← All Examples Example 10 / 12 Mycel Token Exchange: Supplier Guarantees & Micro-Dollar Metering
Prompt-First Example 10 · Mycel Exchange · Mycel · Guarantees & Metering

Mycel Exchange:
Guarantees & Micro-Dollars

Boot an in-memory Exchange, publish an on-premise GPU Supplier Offer, authenticate via ES256 JWKS or static Application credentials, stream through @umwelten/pi, and verify integer micro-dollar accounting.

File: examples/mycel-e2e/run.ts Recreate: pnpm tsx examples/mycel-e2e/run.ts Packages: @umwelten/mycel @umwelten/pi jose
01 — The Prompt You Give Pi
“Build a self-contained end-to-end script that boots @umwelten/mycel's Exchange on localhost, registers an 'on-premise' Supplier publishing gemma-4-26b, funds an End User with 10,000,000 micro-dollars ($10), streams a turn from @umwelten/pi's runPiTurn({ provider: 'mycel' }) without importing @umwelten/mycel on the buyer side, verifies exact prompt/completion micro-dollar charges, and proves requests missing X-Mycel-End-User are rejected with HTTP 401.”
Paste directly into pi or your coding agent with @umwelten/* installed. 6 min walkthrough
02 — The Example That Gets Built

Live workspace source: examples/mycel-e2e/run.ts

Read directly from disk at site-build time — byte-for-byte identical to the typechecked script in this repo.

TypeScript examples/mycel-e2e/run.ts
pnpm tsx examples/mycel-e2e/run.ts
1#!/usr/bin/env node
2/**
3 * The whole path, end to end: a Pi turn reaching a Supplier through the Mycel
4 * Token Exchange, metered and charged in integer micro-dollars on the way.
5 *
6 *   @umwelten/pi runPiTurn({ model: { provider: "mycel", name } })
7 *     → OpenAI /v1 HTTP with X-Mycel-End-User (imports nothing from @umwelten/mycel)
8 *       → the Exchange (auth, Guarantee-filtered dispatch, metering, balances)
9 *         → a Supplier
10 *
11 * Run:  pnpm tsx examples/mycel-e2e/run.ts
12 */
13
14import { SignJWT, createLocalJWKSet, exportJWK, generateKeyPair } from "jose";
15import { listMycelModels, runPiTurn } from "@umwelten/pi";
16import { MemoryStore } from "@umwelten/mycel/store/memory-store.js";
17import { Operator } from "@umwelten/mycel/operator.js";
18import { Balances, applicationOwner, endUserOwner } from "@umwelten/mycel/metering/balances.js";
19import { createIdentityVerifier } from "@umwelten/mycel/auth/identity.js";
20import { createExchangeServer } from "@umwelten/mycel/server.js";
21import { startMockUpstream } from "@umwelten/mycel/testing/mock-upstream.js";
22
23const log = (...parts: unknown[]) => console.log(parts.join(" "));
24const MODEL = "gemma-4-26b";
25
26async function main() {
27  // ── A Supplier: a stand-in for a DGX behind a tunnel ────────────────
28  const supplierBox = await startMockUpstream("ok");
29
30  const store = new MemoryStore();
31  await store.setup();
32
33  const operator = new Operator(store);
34  const { credential } = await operator.registerSupplier({
35    id: "office-spark",
36    displayName: "Office DGX Spark",
37    baseUrl: supplierBox.baseUrl,
38    grantedGuarantees: ["on-premise", "no-training"],
39  });
40
41  // ── An Application, with its own signing key ────────────────────────
42  const { publicKey, privateKey } = await generateKeyPair("ES256");
43  const publicJwk = await exportJWK(publicKey);
44
45  // The Application publishes its keys; here we hand the Exchange a local key
46  // set instead of standing up a JWKS endpoint for a demo.
47  const keySet = createLocalJWKSet({ keys: [publicJwk] });
48
49  await store.createClient({ id: "acme", name: "Acme" });
50  await store.createApplication({
51    id: "hairstyle-app",
52    clientId: "acme",
53    jwksUrl: "https://hairstyle.example/.well-known/jwks.json",
54    requiredGuarantees: ["on-premise"],
55    enabled: true,
56    createdAt: new Date(),
57  });
58
59  const exchange = await createExchangeServer({
60    store,
61    port: 0,
62    host: "127.0.0.1",
63    verifyCaller: createIdentityVerifier({ store, makeKeySet: () => keySet }),
64  });
65  log(`Exchange listening at ${exchange.url}`);
66
67  // ── The supplier agent publishes what it probed ─────────────────────
68  const publish = await fetch(`${exchange.url}/suppliers/offers`, {
69    method: "POST",
70    headers: { "content-type": "application/json", authorization: `Bearer ${credential}` },
71    body: JSON.stringify({
72      guarantees: ["on-premise"],
73      offers: [
74        {
75          model: MODEL,
76          capabilities: ["chat", "streaming", "tool-calling"],
77          servingMode: "managed",
78          contextTokens: 131072,
79        },
80      ],
81    }),
82  });
83  log(`Published offers: ${publish.status}`, JSON.stringify(await publish.json()));
84
85  // ── Fund an End User ────────────────────────────────────────────────
86  const balances = new Balances(store);
87  const owner = endUserOwner({
88    application: (await store.getApplication("hairstyle-app"))!,
89    subject: "user-1",
90  });
91  await balances.grant(owner, 10_000_000, "signup");
92  log(`Granted user-1 ${(await balances.get(owner)).microDollars} micro-dollars`);
93
94  // ── umwelten calls it, knowing nothing about Suppliers ──────────────
95  const token = await new SignJWT({})
96    .setProtectedHeader({ alg: "ES256" })
97    .setIssuer("hairstyle-app")
98    .setSubject("user-1")
99    .setIssuedAt()
100    .setExpirationTime("5m")
101    .sign(privateKey);
102
103  const catalogue = await listMycelModels(token, exchange.url);
104  log(`\nCatalogue: ${catalogue.map((m) => m.name).join(", ")}`);
105  log(
106    `  retail $${catalogue[0]?.costs?.promptTokens}/M prompt, ` +
107      `$${catalogue[0]?.costs?.completionTokens}/M completion`,
108  );
109
110  process.env.MYCEL_API_KEY = token;
111  process.env.MYCEL_URL = exchange.url;
112  process.env.MYCEL_END_USER = "user-1";
113
114  const response = await runPiTurn({
115    model: { name: MODEL, provider: "mycel" },
116    systemPrompt: "You are a helpful assistant.",
117    prompt: "Say something brief.",
118  });
119  log(`\nResponse: ${JSON.stringify(response.content.slice(0, 80))}`);
120
121  // ── What the Exchange recorded ──────────────────────────────────────
122  const [record] = await store.listRequests();
123  log(`\nRequest record:`);
124  log(`  application  ${record.applicationId}  subject ${record.subject}`);
125  log(`  served by    ${record.supplierId} (${record.model})`);
126  log(`  tokens       ${record.promptTokens} prompt / ${record.completionTokens} completion`);
127  log(`  cost         ${record.cost} micro-dollars (owned hardware)`);
128  log(`  charge       ${record.charge} micro-dollars`);
129  log(`  balance left ${(await balances.get(owner)).microDollars}`);
130
131  // ── The other way in: a caller that cannot serve a JWKS ─────────────
132  //
133  // A habitat, a script, a small client. It presents a static credential and
134  // states its End User in a header. What must hold is exactly what held for
135  // the JWT — the Application is authenticated and the subject is scoped to it
136  // — because the JWT never authenticated the End User either (ADR 0014).
137  const habitat = await operator.createApplication({
138    id: "help-habitat",
139    clientId: "acme",
140  });
141  // Funding the Application is enough. A charge falls through End User →
142  // Application → Client, stopping at the first that has ever had a ledger
143  // entry, so a subject nobody has granted anything draws from the pool behind
144  // it. Granting a subject directly is how you cap it instead.
145  await balances.grant(applicationOwner("help-habitat"), 5_000_000, "stage-1 float");
146
147  const direct = await fetch(`${exchange.url}/v1/chat/completions`, {
148    method: "POST",
149    headers: {
150      "content-type": "application/json",
151      authorization: `Bearer ${habitat.credential}`,
152      "x-mycel-end-user": "operator",
153    },
154    body: JSON.stringify({ model: MODEL, messages: [{ role: "user", content: "hi" }] }),
155  });
156  log(`
157Static credential: HTTP ${direct.status}`);
158
159  const forHabitat = (await store.listRequests()).filter(
160    (r) => r.applicationId === "help-habitat",
161  );
162  log(`  attributed to  ${forHabitat[0]?.applicationId} / ${forHabitat[0]?.subject}`);
163  log(`  charged        ${forHabitat[0]?.charge} micro-dollars`);
164
165  // Without the header there is no subject, and no implicit fallback to the
166  // Application's own id — otherwise a caller that forgot it would have its
167  // whole estate attributed to one user and per-user caps would quietly stop
168  // being per-user.
169  const noSubject = await fetch(`${exchange.url}/v1/chat/completions`, {
170    method: "POST",
171    headers: {
172      "content-type": "application/json",
173      authorization: `Bearer ${habitat.credential}`,
174    },
175    body: JSON.stringify({ model: MODEL, messages: [{ role: "user", content: "hi" }] }),
176  });
177  log(`  no end-user →  HTTP ${noSubject.status} (refused)`);
178
179  await exchange.close();
180  await supplierBox.close();
181  // Local providers install a global undici dispatcher whose keep-alive sockets
182  // hold the event loop open; everything above has already resolved.
183  process.exit(0);
184}
185
186void main();
03 — Captured Execution Telemetry

Captured stdout from running pnpm tsx examples/mycel-e2e/run.ts

Captured Run Output pnpm tsx examples/mycel-e2e/run.ts
Exchange listening at http://127.0.0.1:<port>
Published offers: 200 {"supplierId":"office-spark","offers":1,"guarantees":["on-premise","no-training"]}
Granted user-1 10000000 micro-dollars

Catalogue: gemma-4-26b
  retail $0.1/M prompt, $0.4/M completion

Response: "The quick brown fox jumps over the lazy dog"

Request record:
  application  hairstyle-app  subject user-1
  served by    office-spark (gemma-4-26b)
  tokens       16 prompt / 14 completion
  cost         0 micro-dollars (owned hardware)
  charge       8 micro-dollars
  balance left 9999992

Static credential: HTTP 200
  attributed to  help-habitat / operator
  charged        4 micro-dollars
  no end-user →  HTTP 401 (refused)
04 — How & Why This Extends Pi

Architectural notes

Guarantees (on-premise, no-training) and probed Capabilities act as hard filters in Dispatch before price and Headroom rank surviving Offers, and missing X-Mycel-End-User headers fail closed with HTTP 401.