@kaperkunde/tokens 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +415 -2
  2. package/dist/browser-api.d.mts +56 -0
  3. package/dist/browser-api.mjs +75 -0
  4. package/dist/errors.d.mts +41 -0
  5. package/dist/errors.mjs +97 -0
  6. package/dist/index.d.mts +5 -0
  7. package/dist/index.mjs +5 -0
  8. package/dist/react/autorefill.d.mts +21 -0
  9. package/dist/react/autorefill.mjs +269 -0
  10. package/dist/react/balance.d.mts +23 -0
  11. package/dist/react/balance.mjs +116 -0
  12. package/dist/react/buy.d.mts +27 -0
  13. package/dist/react/buy.mjs +175 -0
  14. package/dist/react/history.d.mts +23 -0
  15. package/dist/react/history.mjs +102 -0
  16. package/dist/react/hooks.d.mts +52 -0
  17. package/dist/react/hooks.mjs +150 -0
  18. package/dist/react/index.d.mts +11 -0
  19. package/dist/react/index.mjs +10 -0
  20. package/dist/react/labels.d.mts +114 -0
  21. package/dist/react/labels.mjs +125 -0
  22. package/dist/react/own-model.d.mts +31 -0
  23. package/dist/react/own-model.mjs +358 -0
  24. package/dist/react/ui.d.mts +61 -0
  25. package/dist/react/ui.mjs +128 -0
  26. package/dist/react/usage.d.mts +21 -0
  27. package/dist/react/usage.mjs +137 -0
  28. package/dist/server/client.d.mts +76 -0
  29. package/dist/server/client.mjs +137 -0
  30. package/dist/server/error-of.d.mts +12 -0
  31. package/dist/server/error-of.mjs +63 -0
  32. package/dist/server/gateway.d.mts +62 -0
  33. package/dist/server/gateway.mjs +110 -0
  34. package/dist/server/index.d.mts +7 -0
  35. package/dist/server/index.mjs +7 -0
  36. package/dist/server/node.d.mts +23 -0
  37. package/dist/server/node.mjs +81 -0
  38. package/dist/server/routes.d.mts +56 -0
  39. package/dist/server/routes.mjs +257 -0
  40. package/dist/server/webhook.d.mts +47 -0
  41. package/dist/server/webhook.mjs +99 -0
  42. package/dist/styles.css +380 -0
  43. package/dist/types.d.mts +635 -0
  44. package/dist/types.mjs +142 -0
  45. package/dist/units.d.mts +37 -0
  46. package/dist/units.mjs +76 -0
  47. package/package.json +73 -4
  48. package/stub/cli.mjs +8 -0
  49. package/stub/server.d.mts +36 -0
  50. package/stub/server.mjs +1385 -0
@@ -0,0 +1,1385 @@
1
+ // Token Center contract stub (contract v1). Plain Node >= 22, no dependencies.
2
+ // In-memory wallet; canned or forwarded provider answers; signed webhooks. Not the center.
3
+ // `startStub(options)` starts one; `tokens-stub` (cli.mjs) is the command line. Kept in sync with
4
+ // the contract (types.ts / openapi.yaml): see the package README, "Testing against the stub".
5
+ import { createServer } from "node:http"
6
+ import { createHmac, randomBytes } from "node:crypto"
7
+
8
+ /**
9
+ * Start a stand-in Token Center. Options map onto the `TOKENS_STUB_*` environment variables
10
+ * (an option wins over its variable): port (0 = any free port), key, webhookUrl, webhookSecret,
11
+ * upstream {anthropic, openai, own}, extraModels, startMicros, feeBps, unitOne, unitMany, reply.
12
+ * Resolves to {url, port, close(), reset()}.
13
+ */
14
+ export function startStub(options = {}) {
15
+ const set = (name, value) =>
16
+ value === undefined || value === null
17
+ ? {}
18
+ : { [name]: Array.isArray(value) ? value.join(",") : String(value) }
19
+ const env = {
20
+ ...process.env,
21
+ ...set("TOKENS_STUB_PORT", options.port),
22
+ ...set("TOKENS_STUB_KEY", options.key),
23
+ ...set("TOKENS_STUB_WEBHOOK_URL", options.webhookUrl),
24
+ ...set("TOKENS_STUB_WEBHOOK_SECRET", options.webhookSecret),
25
+ ...set("TOKENS_STUB_ANTHROPIC_UPSTREAM", options.upstream?.anthropic),
26
+ ...set("TOKENS_STUB_OPENAI_UPSTREAM", options.upstream?.openai),
27
+ ...set("TOKENS_STUB_OWN_UPSTREAM", options.upstream?.own),
28
+ ...set("TOKENS_STUB_EXTRA_MODELS", options.extraModels),
29
+ ...set("TOKENS_STUB_START_MICROS", options.startMicros),
30
+ ...set("TOKENS_STUB_FEE_BPS", options.feeBps),
31
+ ...set("TOKENS_STUB_UNIT_ONE", options.unitOne),
32
+ ...set("TOKENS_STUB_UNIT_MANY", options.unitMany),
33
+ ...set("TOKENS_STUB_REPLY", options.reply),
34
+ ...set("TOKENS_STUB_PACKS", options.packsCents),
35
+ ...set("TOKENS_STUB_PACKS_ONLY", options.packsOnly),
36
+ }
37
+ const timers = new Set()
38
+ let PORT = Number(env.TOKENS_STUB_PORT ?? 4100)
39
+ const KEY = env.TOKENS_STUB_KEY || null // unset: any non-empty key is accepted
40
+ const HOOK_URL = env.TOKENS_STUB_WEBHOOK_URL || null
41
+ const HOOK_SECRET = env.TOKENS_STUB_WEBHOOK_SECRET ?? "whsec_stub"
42
+ const UP = {
43
+ anthropic: env.TOKENS_STUB_ANTHROPIC_UPSTREAM,
44
+ openai: env.TOKENS_STUB_OPENAI_UPSTREAM,
45
+ }
46
+ const START = Number(env.TOKENS_STUB_START_MICROS ?? 5_000_000)
47
+ const FEE_BPS = Number(env.TOKENS_STUB_FEE_BPS ?? 2000)
48
+ const UNIT = {
49
+ one: env.TOKENS_STUB_UNIT_ONE ?? "token",
50
+ many: env.TOKENS_STUB_UNIT_MANY ?? "tokens",
51
+ perDollar: 1_000_000,
52
+ }
53
+ const PRICE = {
54
+ inputUsdPerM: "3",
55
+ outputUsdPerM: "15",
56
+ cacheReadUsdPerM: "0.3",
57
+ cacheWriteUsdPerM: "3.75",
58
+ cacheWrite1hUsdPerM: "6",
59
+ longPromptTokens: null,
60
+ longPromptFactor: null,
61
+ fastFactor: null,
62
+ effectiveFrom: "2026-01-01T00:00:00.000Z",
63
+ }
64
+ const MODELS = [
65
+ {
66
+ id: "claude-sonnet-5-5",
67
+ displayName: "Claude Sonnet 5.5",
68
+ provider: "anthropic",
69
+ protocol: "anthropic",
70
+ },
71
+ {
72
+ id: "claude-haiku-5-5",
73
+ displayName: "Claude Haiku 5.5",
74
+ provider: "anthropic",
75
+ protocol: "anthropic",
76
+ },
77
+ {
78
+ id: "gpt-5.5-mini",
79
+ displayName: "GPT-5.5 mini",
80
+ provider: "openai",
81
+ protocol: "openai",
82
+ },
83
+ ...(env.TOKENS_STUB_EXTRA_MODELS ?? "")
84
+ .split(",")
85
+ .filter(Boolean)
86
+ .map((id) => ({
87
+ id,
88
+ displayName: id,
89
+ provider: "openai",
90
+ protocol: "openai",
91
+ })),
92
+ ].map((m) => ({
93
+ ...m,
94
+ capabilities: ["tools", "streaming", "json"],
95
+ contextTokens: 200000,
96
+ price: PRICE,
97
+ }))
98
+ const VOICES = [
99
+ {
100
+ id: "stub-voice",
101
+ name: "Stub voice",
102
+ provider: "openai",
103
+ usdPerMChars: "15",
104
+ isDefault: true,
105
+ },
106
+ ]
107
+ const SALE = [
108
+ {
109
+ currency: "eur",
110
+ centsPerDollar: 121,
111
+ taxBehavior: "inclusive",
112
+ minimumCents: 500,
113
+ effectiveFrom: PRICE.effectiveFrom,
114
+ },
115
+ {
116
+ currency: "usd",
117
+ centsPerDollar: 100,
118
+ taxBehavior: "exclusive",
119
+ minimumCents: 500,
120
+ effectiveFrom: PRICE.effectiveFrom,
121
+ },
122
+ ]
123
+ // Purchase options (contract PurchaseOptions): TOKENS_STUB_PACKS (cents, comma-separated, default
124
+ // AJ's 500,1000,2500,5000) and TOKENS_STUB_PACKS_ONLY=true to allow only those.
125
+ const OPTIONS = {
126
+ packsCents: (env.TOKENS_STUB_PACKS ?? "500,1000,2500,5000")
127
+ .split(",")
128
+ .filter(Boolean)
129
+ .map(Number),
130
+ packsOnly: env.TOKENS_STUB_PACKS_ONLY === "true",
131
+ minimumCents: 500,
132
+ maximumCents: 100000,
133
+ }
134
+ const STATUS = {
135
+ unauthenticated: 401,
136
+ forbidden: 403,
137
+ invalid_request: 400,
138
+ unknown_user: 404,
139
+ not_found: 404,
140
+ unknown_model: 404,
141
+ model_not_priced: 409,
142
+ wrong_protocol: 400,
143
+ insufficient_balance: 402,
144
+ capability_unavailable: 402,
145
+ byo_not_configured: 409,
146
+ byo_failed: 502,
147
+ byo_limit_reached: 402,
148
+ provider_error: 502,
149
+ provider_timeout: 504,
150
+ rate_limited: 429,
151
+ payments_unavailable: 503,
152
+ purchase_too_small: 400,
153
+ no_card: 409,
154
+ conflict: 409,
155
+ center_unavailable: 503,
156
+ internal_error: 500,
157
+ }
158
+
159
+ let state
160
+ const reset = () => {
161
+ state = {
162
+ users: new Map(),
163
+ calls: [],
164
+ purchases: new Map(),
165
+ mode: { down: false, providerError: false },
166
+ }
167
+ }
168
+ reset()
169
+ const now = () => new Date().toISOString()
170
+ const id = (p) => `${p}_${randomBytes(12).toString("hex")}`
171
+
172
+ // ------------------------------------------------------------------ wallet
173
+ const user = (userId, email) => {
174
+ let u = state.users.get(userId)
175
+ if (!u) {
176
+ u = {
177
+ userId,
178
+ email: null,
179
+ displayName: null,
180
+ createdAt: now(),
181
+ lastSeenAt: null,
182
+ purchased: START,
183
+ lots: [],
184
+ own: null,
185
+ order: "tokens_only",
186
+ autoRefill: {
187
+ enabled: false,
188
+ thresholdMicros: 1_000_000,
189
+ amountCents: 1000,
190
+ currency: "eur",
191
+ monthlyMaxCents: 5000,
192
+ card: null,
193
+ pending: false,
194
+ failedAt: null,
195
+ },
196
+ history: [],
197
+ low: false,
198
+ empty: false,
199
+ }
200
+ state.users.set(userId, u)
201
+ }
202
+ if (email) u.email = email
203
+ u.lastSeenAt = now()
204
+ return u
205
+ }
206
+ const live = (lot) =>
207
+ lot.remainingMicros > 0 && (!lot.expiresAt || lot.expiresAt > now())
208
+ // Every lot is locked to one provider; soonest expiry first, none last, then by id.
209
+ const lotsFor = (u, provider) =>
210
+ u.lots
211
+ .filter((l) => live(l) && l.provider === provider)
212
+ .sort(
213
+ (a, b) =>
214
+ (a.expiresAt ?? "9").localeCompare(b.expiresAt ?? "9") ||
215
+ a.id.localeCompare(b.id),
216
+ )
217
+ const grantsOf = (u) =>
218
+ u.lots.filter(live).reduce((s, l) => s + l.remainingMicros, 0)
219
+ const summary = (u) => ({
220
+ availableMicros: u.purchased + grantsOf(u),
221
+ purchasedMicros: u.purchased,
222
+ grantsMicros: grantsOf(u),
223
+ })
224
+ const available = (u, provider) =>
225
+ u.purchased +
226
+ lotsFor(u, provider).reduce((s, l) => s + l.remainingMicros, 0)
227
+ const balance = (u, known = true) => {
228
+ const lots = u.lots.filter(live)
229
+ const next = lots
230
+ .filter((l) => l.expiresAt)
231
+ .sort((a, b) => a.expiresAt.localeCompare(b.expiresAt))[0]
232
+ return {
233
+ userId: u.userId,
234
+ known,
235
+ ...summary(u),
236
+ byProvider: Object.fromEntries(
237
+ ["anthropic", "openai", "elevenlabs"].map((p) => [p, available(u, p)]),
238
+ ),
239
+ lots,
240
+ nextExpiry: next
241
+ ? { at: next.expiresAt, micros: next.remainingMicros }
242
+ : null,
243
+ unit: UNIT,
244
+ feeBps: FEE_BPS,
245
+ autoRefill: { enabled: u.autoRefill.enabled, pending: false },
246
+ }
247
+ }
248
+ const crossings = (u) => {
249
+ const a = summary(u).availableMicros
250
+ if (a < 500_000 && !u.low) {
251
+ u.low = true
252
+ emit("balance.low", {
253
+ userId: u.userId,
254
+ thresholdMicros: 500_000,
255
+ balance: summary(u),
256
+ })
257
+ } else if (a >= 500_000) u.low = false
258
+ if (a <= 0 && !u.empty) {
259
+ u.empty = true
260
+ emit("balance.empty", { userId: u.userId, balance: summary(u) })
261
+ } else if (a > 0) u.empty = false
262
+ }
263
+ const charge = (u, call, provider, costMicros) => {
264
+ let rest = costMicros,
265
+ fromGrants = 0
266
+ for (const lot of call.source === "own" ? [] : lotsFor(u, provider)) {
267
+ const take = Math.min(lot.remainingMicros, rest)
268
+ lot.remainingMicros -= take
269
+ lot.spentMicros += take
270
+ fromGrants += take
271
+ rest -= take
272
+ if (!rest) break
273
+ }
274
+ const fee = Math.ceil((rest * FEE_BPS) / 10000)
275
+ // Shortfall: absorbed by the center; purchased never goes below zero.
276
+ const shortfall = Math.max(0, rest + fee - u.purchased)
277
+ u.purchased = Math.max(0, u.purchased - rest - fee)
278
+ Object.assign(call, {
279
+ status: "charged",
280
+ costMicros,
281
+ feeMicros: fee,
282
+ chargedMicros: fromGrants + rest + fee,
283
+ fromGrantsMicros: fromGrants,
284
+ fromPurchasedMicros: rest + fee,
285
+ shortfallMicros: shortfall,
286
+ balanceAfterMicros: summary(u).availableMicros,
287
+ finishedAt: now(),
288
+ latencyMs: Date.now() - call.t0,
289
+ })
290
+ crossings(u)
291
+ return call
292
+ }
293
+ const usd = (usage) =>
294
+ (usage.inputTokens - usage.cacheReadTokens - usage.cacheWriteTokens) * 3 +
295
+ usage.cacheReadTokens * 0.3 +
296
+ (usage.cacheWriteTokens - usage.cacheWrite1hTokens) * 3.75 +
297
+ usage.cacheWrite1hTokens * 6 +
298
+ usage.outputTokens * 15 +
299
+ (usage.units?.tts_chars ?? 0) * 15
300
+ const costOf = (usage) => Math.ceil(usd(usage)) // $/M × tokens = micros
301
+ // Calls are keyed `callId` on the wire (CallCharge / CallRecord), never `id`.
302
+ const publicCall = ({ t0: _t0, id: callId, ...c }) => ({ callId, ...c })
303
+
304
+ // ------------------------------------------------------------------ webhooks
305
+ const sign = (body, t = Math.floor(Date.now() / 1000)) =>
306
+ `t=${t},v1=${createHmac("sha256", HOOK_SECRET).update(`${t}.${body}`).digest("hex")}`
307
+ function emit(type, data) {
308
+ const event = {
309
+ id: id("evt"),
310
+ type,
311
+ createdAt: now(),
312
+ appId: "app_stub",
313
+ livemode: false,
314
+ data,
315
+ }
316
+ if (!HOOK_URL) return event
317
+ const body = JSON.stringify(event)
318
+ const send = (attempt) =>
319
+ fetch(HOOK_URL, {
320
+ method: "POST",
321
+ headers: {
322
+ "content-type": "application/json",
323
+ "token-signature": sign(body),
324
+ "token-event-id": event.id,
325
+ },
326
+ body,
327
+ signal: AbortSignal.timeout(10_000),
328
+ })
329
+ .then((r) => {
330
+ if (!r.ok) throw new Error(String(r.status))
331
+ })
332
+ .catch((e) => {
333
+ if (attempt < 3) {
334
+ const t = setTimeout(
335
+ () => {
336
+ timers.delete(t)
337
+ send(attempt + 1)
338
+ },
339
+ 1000 * 2 ** attempt,
340
+ )
341
+ t.unref?.()
342
+ timers.add(t)
343
+ } else console.error(`[stub] webhook ${type} dead: ${e.message}`)
344
+ })
345
+ send(0)
346
+ return event
347
+ }
348
+
349
+ // ------------------------------------------------------------------ http helpers
350
+ const readBody = (req) =>
351
+ new Promise((ok, no) => {
352
+ const b = []
353
+ req.on("data", (c) => b.push(c))
354
+ req.on("end", () => ok(Buffer.concat(b).toString("utf8")))
355
+ req.on("error", no)
356
+ })
357
+ const json = (res, status, body, headers = {}) => {
358
+ res.writeHead(status, { "content-type": "application/json", ...headers })
359
+ res.end(body === undefined ? "" : JSON.stringify(body))
360
+ }
361
+ const fail = (res, code, message, shape = "api", extra = {}) => {
362
+ const detail = { code, message, ...extra }
363
+ const body =
364
+ shape === "anthropic"
365
+ ? {
366
+ type: "error",
367
+ error: {
368
+ type:
369
+ code === "insufficient_balance"
370
+ ? "permission_error"
371
+ : "api_error",
372
+ message,
373
+ },
374
+ token_center: detail,
375
+ }
376
+ : shape === "openai"
377
+ ? { error: { message, type: code, code }, token_center: detail }
378
+ : { error: detail }
379
+ json(res, STATUS[code], body, {
380
+ "x-token-error": code,
381
+ ...(extra.callId ? { "x-token-call-id": extra.callId } : {}),
382
+ })
383
+ }
384
+ const attribution = (req) =>
385
+ Object.fromEntries(
386
+ ["purpose", "activity", "scope", "job", "subject", "correlation"]
387
+ .map((k) => [k, req.headers[`x-token-${k}`]])
388
+ .filter(([, v]) => v)
389
+ .map(([k, v]) => [k, decodeURIComponent(v).slice(0, 200)]),
390
+ )
391
+ const chargeHeaders = (c) => ({
392
+ "x-token-call-id": c.id,
393
+ "x-token-source": c.source,
394
+ "x-token-model": c.model,
395
+ "x-token-cost-micros": String(c.costMicros),
396
+ "x-token-fee-micros": String(c.feeMicros),
397
+ "x-token-charged-micros": String(c.chargedMicros),
398
+ "x-token-balance-micros": String(c.balanceAfterMicros),
399
+ })
400
+ const zeroUsage = () => ({
401
+ inputTokens: 0,
402
+ outputTokens: 0,
403
+ cacheReadTokens: 0,
404
+ cacheWriteTokens: 0,
405
+ cacheWrite1hTokens: 0,
406
+ cacheWrite5mTokens: 0,
407
+ totalTokens: 0,
408
+ })
409
+ const fromAnthropic = (u, x = {}) => {
410
+ const read = x.cache_read_input_tokens ?? u.cacheReadTokens,
411
+ write = x.cache_creation_input_tokens ?? u.cacheWriteTokens
412
+ const input =
413
+ x.input_tokens !== undefined
414
+ ? x.input_tokens + read + write
415
+ : u.inputTokens
416
+ const output = x.output_tokens ?? u.outputTokens
417
+ const write1h =
418
+ x.cache_creation?.ephemeral_1h_input_tokens ?? u.cacheWrite1hTokens
419
+ return {
420
+ inputTokens: input,
421
+ outputTokens: output,
422
+ cacheReadTokens: read,
423
+ cacheWriteTokens: write,
424
+ cacheWrite1hTokens: write1h,
425
+ cacheWrite5mTokens: write - write1h,
426
+ totalTokens: input + output,
427
+ }
428
+ }
429
+ const fromOpenAI = (x) => ({
430
+ inputTokens: x.prompt_tokens ?? 0,
431
+ outputTokens: x.completion_tokens ?? 0,
432
+ cacheReadTokens: x.prompt_tokens_details?.cached_tokens ?? 0,
433
+ cacheWriteTokens: 0,
434
+ cacheWrite1hTokens: 0,
435
+ cacheWrite5mTokens: 0,
436
+ totalTokens: x.total_tokens ?? 0,
437
+ })
438
+
439
+ // ------------------------------------------------------------------ canned provider
440
+ const sse = (res, events) => {
441
+ for (const [event, data] of events)
442
+ res.write(
443
+ `${event ? `event: ${event}\n` : ""}data: ${typeof data === "string" ? data : JSON.stringify(data)}\n\n`,
444
+ )
445
+ }
446
+ const TEXT = env.TOKENS_STUB_REPLY ?? "Stub reply."
447
+ const cannedAnthropic = (body) => ({
448
+ id: id("msg"),
449
+ type: "message",
450
+ role: "assistant",
451
+ model: body.model,
452
+ content: [{ type: "text", text: TEXT }],
453
+ stop_reason: "end_turn",
454
+ stop_sequence: null,
455
+ usage: {
456
+ input_tokens: 100,
457
+ output_tokens: 20,
458
+ cache_read_input_tokens: 0,
459
+ cache_creation_input_tokens: 0,
460
+ },
461
+ })
462
+ const cannedAnthropicStream = (m) => [
463
+ [
464
+ "message_start",
465
+ {
466
+ type: "message_start",
467
+ message: {
468
+ ...m,
469
+ content: [],
470
+ stop_reason: null,
471
+ usage: { ...m.usage, output_tokens: 1 },
472
+ },
473
+ },
474
+ ],
475
+ [
476
+ "content_block_start",
477
+ {
478
+ type: "content_block_start",
479
+ index: 0,
480
+ content_block: { type: "text", text: "" },
481
+ },
482
+ ],
483
+ [
484
+ "content_block_delta",
485
+ {
486
+ type: "content_block_delta",
487
+ index: 0,
488
+ delta: { type: "text_delta", text: TEXT },
489
+ },
490
+ ],
491
+ ["content_block_stop", { type: "content_block_stop", index: 0 }],
492
+ [
493
+ "message_delta",
494
+ {
495
+ type: "message_delta",
496
+ delta: { stop_reason: "end_turn", stop_sequence: null },
497
+ usage: { output_tokens: 20 },
498
+ },
499
+ ],
500
+ ["message_stop", { type: "message_stop" }],
501
+ ]
502
+ const cannedOpenAI = (body) => ({
503
+ id: id("chatcmpl"),
504
+ object: "chat.completion",
505
+ created: Math.floor(Date.now() / 1000),
506
+ model: body.model,
507
+ choices: [
508
+ {
509
+ index: 0,
510
+ message: { role: "assistant", content: TEXT },
511
+ finish_reason: "stop",
512
+ },
513
+ ],
514
+ usage: { prompt_tokens: 100, completion_tokens: 20, total_tokens: 120 },
515
+ })
516
+ const cannedOpenAIStream = (c) => {
517
+ const base = {
518
+ id: c.id,
519
+ object: "chat.completion.chunk",
520
+ created: c.created,
521
+ model: c.model,
522
+ }
523
+ return [
524
+ [
525
+ null,
526
+ {
527
+ ...base,
528
+ choices: [
529
+ {
530
+ index: 0,
531
+ delta: { role: "assistant", content: TEXT },
532
+ finish_reason: null,
533
+ },
534
+ ],
535
+ },
536
+ ],
537
+ [
538
+ null,
539
+ { ...base, choices: [{ index: 0, delta: {}, finish_reason: "stop" }] },
540
+ ],
541
+ [null, { ...base, choices: [], usage: c.usage }],
542
+ [null, "[DONE]"],
543
+ ]
544
+ }
545
+
546
+ // Forward to an upstream fake (or real) provider; meter what it reports. Returns usage.
547
+ async function forward(
548
+ req,
549
+ res,
550
+ upstream,
551
+ path,
552
+ raw,
553
+ protocol,
554
+ stream,
555
+ headers,
556
+ ) {
557
+ const up = await fetch(upstream.replace(/\/$/, "") + path, {
558
+ method: "POST",
559
+ headers: {
560
+ "content-type": "application/json",
561
+ authorization: "Bearer stub",
562
+ "x-api-key": "stub",
563
+ "anthropic-version": req.headers["anthropic-version"] ?? "2023-06-01",
564
+ },
565
+ body: raw,
566
+ })
567
+ if (!stream || !up.ok) {
568
+ const text = await up.text()
569
+ let usage = zeroUsage()
570
+ try {
571
+ const j = JSON.parse(text)
572
+ usage =
573
+ protocol === "anthropic"
574
+ ? fromAnthropic(usage, j.usage)
575
+ : fromOpenAI(j.usage ?? {})
576
+ } catch {
577
+ /* not JSON or no usage: stays zero */
578
+ }
579
+ return { status: up.status, text, usage, ok: up.ok }
580
+ }
581
+ res.writeHead(200, {
582
+ "content-type": "text/event-stream",
583
+ "cache-control": "no-cache",
584
+ ...headers,
585
+ })
586
+ let usage = zeroUsage(),
587
+ buf = ""
588
+ for await (const chunk of up.body) {
589
+ res.write(chunk)
590
+ buf += Buffer.from(chunk).toString()
591
+ const lines = buf.split("\n")
592
+ buf = lines.pop()
593
+ for (const line of lines)
594
+ if (line.startsWith("data:")) {
595
+ try {
596
+ const j = JSON.parse(line.slice(5))
597
+ if (protocol === "anthropic")
598
+ usage = fromAnthropic(usage, j.message?.usage ?? j.usage)
599
+ else if (j.usage) usage = fromOpenAI(j.usage)
600
+ } catch {
601
+ /* not JSON or no usage: stays zero */
602
+ }
603
+ }
604
+ }
605
+ return { status: 200, usage, ok: true, streamed: true }
606
+ }
607
+
608
+ // Real, playable audio: 12 MPEG-1 Layer III frames (128 kbps, 44.1 kHz, stereo, all-zero payload =
609
+ // silence), about 0.3 s. Every decoder plays it; the length does not follow the text.
610
+ const silentMp3 = () =>
611
+ Buffer.concat(
612
+ Array.from({ length: 12 }, () =>
613
+ Buffer.concat([
614
+ Buffer.from([0xff, 0xfb, 0x90, 0x00]),
615
+ Buffer.alloc(413),
616
+ ]),
617
+ ),
618
+ )
619
+
620
+ // ------------------------------------------------------------------ gateway
621
+ async function gateway(req, res, url, raw) {
622
+ const shape = url.pathname === "/v1/messages" ? "anthropic" : "openai"
623
+ const userId = req.headers["x-token-user"]
624
+ if (!userId)
625
+ return fail(res, "invalid_request", "x-token-user is required.", shape, {
626
+ path: "x-token-user",
627
+ })
628
+ const u = user(
629
+ decodeURIComponent(userId),
630
+ req.headers["x-token-email"] &&
631
+ decodeURIComponent(req.headers["x-token-email"]),
632
+ )
633
+ let body
634
+ try {
635
+ body = JSON.parse(raw || "{}")
636
+ } catch {
637
+ return fail(res, "invalid_request", "Body is not JSON.", shape)
638
+ }
639
+ const speech = url.pathname === "/v1/audio/speech"
640
+ const backend = req.headers["x-token-backend"] === "own" ? "own" : "tokens"
641
+ let model = speech
642
+ ? VOICES.find((v) => v.id === (body.voice ?? "stub-voice")) &&
643
+ "tts-stub-voice"
644
+ : body.model
645
+ const known = MODELS.find((m) => m.id === model)
646
+ if (speech && !model) return fail(res, "not_found", "No such voice.", shape)
647
+ if (!speech && backend === "tokens") {
648
+ if (/unpriced/.test(model ?? ""))
649
+ return fail(res, "model_not_priced", `${model} has no price.`, shape)
650
+ if (!known)
651
+ return fail(res, "unknown_model", `${model} is not offered.`, shape)
652
+ if (known.protocol !== shape)
653
+ return fail(
654
+ res,
655
+ "wrong_protocol",
656
+ `${model} is served on the other endpoint.`,
657
+ shape,
658
+ )
659
+ }
660
+ if (backend === "own") {
661
+ if (shape !== "openai" || speech)
662
+ return fail(
663
+ res,
664
+ "wrong_protocol",
665
+ "Own endpoints speak chat completions.",
666
+ shape,
667
+ )
668
+ if (!u.own)
669
+ return fail(
670
+ res,
671
+ "byo_not_configured",
672
+ "No own endpoint saved.",
673
+ shape,
674
+ { action: "configure_own" },
675
+ )
676
+ if (!u.own.models.includes(model)) model = u.own.defaultModel
677
+ }
678
+ const provider = speech
679
+ ? "openai"
680
+ : backend === "own"
681
+ ? "own"
682
+ : known.provider
683
+ if (backend === "tokens" && available(u, provider) <= 0)
684
+ return fail(res, "insufficient_balance", "Out of tokens.", shape, {
685
+ action: "buy_tokens",
686
+ provider,
687
+ })
688
+ const endpoint = speech
689
+ ? "speech"
690
+ : shape === "anthropic"
691
+ ? "messages"
692
+ : "chat_completions"
693
+ const call = {
694
+ id: id("call"),
695
+ t0: Date.now(),
696
+ userId: u.userId,
697
+ status: "admitted",
698
+ endpoint,
699
+ provider,
700
+ source: backend,
701
+ requestedModel: body.model ?? model,
702
+ model,
703
+ stream: !!body.stream,
704
+ attribution: attribution(req),
705
+ error: null,
706
+ createdAt: now(),
707
+ finishedAt: null,
708
+ latencyMs: null,
709
+ usage: zeroUsage(),
710
+ costMicros: 0,
711
+ feeMicros: 0,
712
+ chargedMicros: 0,
713
+ fromGrantsMicros: 0,
714
+ fromPurchasedMicros: 0,
715
+ shortfallMicros: 0,
716
+ balanceAfterMicros: 0,
717
+ }
718
+ state.calls.push(call)
719
+ if (state.mode.providerError) {
720
+ Object.assign(call, {
721
+ status: "failed",
722
+ finishedAt: now(),
723
+ error: {
724
+ code: "provider_error",
725
+ message: "Stub provider error.",
726
+ status: 529,
727
+ },
728
+ })
729
+ return fail(res, "provider_error", "The provider failed.", shape, {
730
+ status: 529,
731
+ callId: call.id,
732
+ })
733
+ }
734
+ if (speech) {
735
+ const chars = [...String(body.input ?? "")].length
736
+ if (!chars || chars > 4096) {
737
+ call.status = "failed"
738
+ return fail(
739
+ res,
740
+ "invalid_request",
741
+ "input must be 1..4096 characters.",
742
+ shape,
743
+ { path: "input" },
744
+ )
745
+ }
746
+ call.usage = { ...zeroUsage(), units: { tts_chars: chars } }
747
+ charge(u, call, "openai", costOf(call.usage))
748
+ const audio = silentMp3()
749
+ res.writeHead(200, {
750
+ "content-type": "audio/mpeg",
751
+ "x-token-chars": String(chars),
752
+ ...chargeHeaders(call),
753
+ })
754
+ return res.end(audio)
755
+ }
756
+ if (shape === "openai" && body.stream) {
757
+ body.stream_options = { ...body.stream_options, include_usage: true }
758
+ raw = JSON.stringify(body)
759
+ }
760
+ const upstream =
761
+ backend === "own" ? (u.own.upstream ?? UP.openai) : UP[shape]
762
+ const head = {
763
+ "x-token-call-id": call.id,
764
+ "x-token-source": call.source,
765
+ "x-token-model": call.model,
766
+ }
767
+ const trailer = () => {
768
+ if (req.headers["x-token-trailer"] === "event")
769
+ sse(res, [["token_center", publicCall(call)]])
770
+ }
771
+ if (upstream) {
772
+ const out = await forward(
773
+ req,
774
+ res,
775
+ upstream,
776
+ url.pathname.replace(/^\/v1/, ""),
777
+ raw,
778
+ shape,
779
+ !!body.stream,
780
+ head,
781
+ )
782
+ call.usage = out.usage
783
+ if (!out.ok) {
784
+ charge(u, call, provider, backend === "own" ? 0 : costOf(out.usage))
785
+ call.status = "failed"
786
+ return fail(
787
+ res,
788
+ backend === "own" ? "byo_failed" : "provider_error",
789
+ `Upstream answered ${out.status}.`,
790
+ shape,
791
+ { status: out.status, callId: call.id },
792
+ )
793
+ }
794
+ charge(u, call, provider, backend === "own" ? 0 : costOf(out.usage))
795
+ if (out.streamed) {
796
+ trailer()
797
+ return res.end()
798
+ }
799
+ res.writeHead(200, {
800
+ "content-type": "application/json",
801
+ ...chargeHeaders(call),
802
+ })
803
+ return res.end(out.text)
804
+ }
805
+ const message =
806
+ shape === "anthropic"
807
+ ? cannedAnthropic({ ...body, model })
808
+ : cannedOpenAI({ ...body, model })
809
+ call.usage =
810
+ shape === "anthropic"
811
+ ? fromAnthropic(zeroUsage(), message.usage)
812
+ : fromOpenAI(message.usage)
813
+ if (!body.stream) {
814
+ charge(u, call, provider, backend === "own" ? 0 : costOf(call.usage))
815
+ return json(res, 200, message, chargeHeaders(call))
816
+ }
817
+ res.writeHead(200, {
818
+ "content-type": "text/event-stream",
819
+ "cache-control": "no-cache",
820
+ ...head,
821
+ })
822
+ sse(
823
+ res,
824
+ shape === "anthropic"
825
+ ? cannedAnthropicStream(message)
826
+ : cannedOpenAIStream(message),
827
+ )
828
+ charge(u, call, provider, backend === "own" ? 0 : costOf(call.usage))
829
+ trailer()
830
+ res.end()
831
+ }
832
+
833
+ // ------------------------------------------------------------------ app API
834
+ const page = (calls, q) => {
835
+ const f = calls
836
+ .filter(
837
+ (c) =>
838
+ (!q.get("userId") || c.userId === q.get("userId")) &&
839
+ ["scope", "job", "correlation", "purpose"].every(
840
+ (k) => !q.get(k) || c.attribution[k] === q.get(k),
841
+ ) &&
842
+ (!q.get("source") || c.source === q.get("source")) &&
843
+ (!q.get("since") || c.createdAt >= q.get("since")),
844
+ )
845
+ .reverse()
846
+ const start = Number(q.get("cursor") ?? 0),
847
+ limit = Math.min(Number(q.get("limit") ?? 50), 200)
848
+ const sum = (k) => f.reduce((s, c) => s + (c[k] ?? c.usage[k] ?? 0), 0)
849
+ return {
850
+ calls: f.slice(start, start + limit).map(publicCall),
851
+ nextCursor: start + limit < f.length ? String(start + limit) : null,
852
+ totals: {
853
+ count: f.length,
854
+ ...Object.fromEntries(
855
+ [
856
+ "costMicros",
857
+ "feeMicros",
858
+ "chargedMicros",
859
+ "inputTokens",
860
+ "outputTokens",
861
+ "cacheReadTokens",
862
+ "cacheWriteTokens",
863
+ "cacheWrite5mTokens",
864
+ "cacheWrite1hTokens",
865
+ "totalTokens",
866
+ ].map((k) => [k, sum(k)]),
867
+ ),
868
+ },
869
+ }
870
+ }
871
+ const ownView = (u) =>
872
+ u.own && {
873
+ ...u.own,
874
+ apiKey: undefined,
875
+ upstream: undefined,
876
+ order: u.order,
877
+ }
878
+ async function api(req, res, url, raw) {
879
+ const p = url.pathname,
880
+ m = req.method,
881
+ q = url.searchParams
882
+ let body = {}
883
+ try {
884
+ body = raw ? JSON.parse(raw) : {}
885
+ } catch {
886
+ return fail(res, "invalid_request", "Body is not JSON.")
887
+ }
888
+ if (p === "/api/v1/app")
889
+ return json(res, 200, {
890
+ id: "app_stub",
891
+ name: "Stub app",
892
+ unit: UNIT,
893
+ purchaseOptions: OPTIONS,
894
+ feeBps: FEE_BPS,
895
+ lowBalanceMicros: 500_000,
896
+ maxInFlightPerUser: 4,
897
+ livemode: false,
898
+ returnOrigins: ["http://localhost", "http://127.0.0.1"],
899
+ })
900
+ if (p === "/api/v1/models") return json(res, 200, { models: MODELS })
901
+ if (p === "/api/v1/voices") return json(res, 200, { voices: VOICES })
902
+ if (p === "/api/v1/sale-prices")
903
+ return json(res, 200, {
904
+ prices: SALE,
905
+ feeBps: FEE_BPS,
906
+ paymentsAvailable: true,
907
+ options: OPTIONS,
908
+ })
909
+ if (p === "/api/v1/calls") return json(res, 200, page(state.calls, q))
910
+ let r = p.match(/^\/api\/v1\/calls\/([^/]+)$/)
911
+ if (r) {
912
+ const c = state.calls.find((x) => x.id === r[1])
913
+ return c
914
+ ? json(res, 200, publicCall(c))
915
+ : fail(res, "not_found", "No such call.")
916
+ }
917
+ if (p === "/api/v1/route") {
918
+ if (!body.userId || !body.model)
919
+ return fail(
920
+ res,
921
+ "invalid_request",
922
+ "userId and model are needed.",
923
+ "api",
924
+ { path: body.userId ? "model" : "userId" },
925
+ )
926
+ const u = user(body.userId),
927
+ needs = body.needs ?? [],
928
+ own =
929
+ u.own &&
930
+ u.order !== "tokens_only" &&
931
+ needs.every((n) => n !== "voice" && u.own.capabilities.includes(n))
932
+ const ownFirst =
933
+ own &&
934
+ (u.order === "own_only" ||
935
+ u.order === "own_then_tokens" ||
936
+ (u.order === "tokens_then_own" &&
937
+ available(
938
+ u,
939
+ MODELS.find((x) => x.id === body.model)?.provider ?? "anthropic",
940
+ ) <= 0))
941
+ const known = MODELS.find((x) => x.id === body.model)
942
+ if (ownFirst)
943
+ return json(res, 200, {
944
+ source: "own",
945
+ protocol: "openai",
946
+ model: u.own.models.includes(body.model)
947
+ ? body.model
948
+ : u.own.defaultModel,
949
+ backend: "own",
950
+ fallback: null,
951
+ availableMicros: summary(u).availableMicros,
952
+ })
953
+ if (!known)
954
+ return fail(
955
+ res,
956
+ /unpriced/.test(body.model ?? "")
957
+ ? "model_not_priced"
958
+ : "unknown_model",
959
+ `${body.model} is not offered.`,
960
+ )
961
+ const missing =
962
+ u.own &&
963
+ u.order !== "tokens_only" &&
964
+ needs.find((n) => n === "voice" || !u.own.capabilities.includes(n))
965
+ if (available(u, known.provider) <= 0)
966
+ return fail(
967
+ res,
968
+ missing ? "capability_unavailable" : "insufficient_balance",
969
+ missing ? `Your own service can't do ${missing}.` : "Out of tokens.",
970
+ "api",
971
+ { action: "buy_tokens", ...(missing ? { capability: missing } : {}) },
972
+ )
973
+ return json(res, 200, {
974
+ source: "tokens",
975
+ protocol: known.protocol,
976
+ model: known.id,
977
+ backend: "tokens",
978
+ fallback:
979
+ missing && u.order !== "tokens_then_own"
980
+ ? { reason: "capability", capability: missing }
981
+ : null,
982
+ availableMicros: available(u, known.provider),
983
+ })
984
+ }
985
+ r = p.match(/^\/api\/v1\/users\/([^/]+)(\/.*)?$/)
986
+ if (!r) return fail(res, "not_found", "No such endpoint.")
987
+ const userId = decodeURIComponent(r[1]),
988
+ rest = r[2] ?? "",
989
+ seen = state.users.has(userId),
990
+ u = user(userId)
991
+ if (rest === "" && m === "PUT") {
992
+ if (body.email !== undefined) u.email = body.email
993
+ if (body.displayName !== undefined) u.displayName = body.displayName
994
+ const { userId: i, email, displayName, createdAt, lastSeenAt } = u
995
+ return json(res, 200, {
996
+ userId: i,
997
+ email,
998
+ displayName,
999
+ createdAt,
1000
+ lastSeenAt,
1001
+ })
1002
+ }
1003
+ if (rest === "/balance") return json(res, 200, balance(u, seen))
1004
+ if (rest === "/calls") {
1005
+ q.set("userId", userId)
1006
+ return json(res, 200, page(state.calls, q))
1007
+ }
1008
+ if (rest === "/history")
1009
+ return json(res, 200, {
1010
+ entries: [...u.history].reverse(),
1011
+ nextCursor: null,
1012
+ })
1013
+ if (rest === "/checkout" && m === "POST") {
1014
+ const price = SALE.find((s) => s.currency === body.currency)
1015
+ if (!price)
1016
+ return fail(res, "invalid_request", "Unknown currency.", "api", {
1017
+ path: "currency",
1018
+ })
1019
+ if (!(body.amountCents >= OPTIONS.minimumCents))
1020
+ return fail(
1021
+ res,
1022
+ "purchase_too_small",
1023
+ "The smallest amount is 5.",
1024
+ "api",
1025
+ { minimumCents: OPTIONS.minimumCents },
1026
+ )
1027
+ if (
1028
+ body.amountCents > OPTIONS.maximumCents ||
1029
+ (OPTIONS.packsOnly && !OPTIONS.packsCents.includes(body.amountCents))
1030
+ )
1031
+ return fail(
1032
+ res,
1033
+ "invalid_request",
1034
+ "That amount is not offered.",
1035
+ "api",
1036
+ { path: "amountCents" },
1037
+ )
1038
+ const purchase = {
1039
+ id: id("pur"),
1040
+ kind: "checkout",
1041
+ status: "open",
1042
+ currency: body.currency,
1043
+ amountCents: body.amountCents,
1044
+ taxCents: null,
1045
+ totalCents: null,
1046
+ creditMicros: Math.floor(
1047
+ (body.amountCents * 1_000_000) / price.centsPerDollar,
1048
+ ),
1049
+ failure: null,
1050
+ createdAt: now(),
1051
+ paidAt: null,
1052
+ }
1053
+ state.purchases.set(purchase.id, {
1054
+ purchase,
1055
+ userId,
1056
+ successUrl: body.successUrl,
1057
+ saveCard: !!body.saveCard,
1058
+ })
1059
+ return json(res, 201, {
1060
+ purchaseId: purchase.id,
1061
+ url: `http://localhost:${PORT}/stub/checkout/${purchase.id}`,
1062
+ expiresAt: new Date(Date.now() + 86400e3).toISOString(),
1063
+ creditMicros: purchase.creditMicros,
1064
+ })
1065
+ }
1066
+ r = rest.match(/^\/purchases\/([^/]+)$/)
1067
+ if (r) {
1068
+ const x = state.purchases.get(r[1])
1069
+ return x && x.userId === userId
1070
+ ? json(res, 200, x.purchase)
1071
+ : fail(res, "not_found", "No such purchase.")
1072
+ }
1073
+ if (rest === "/autorefill") {
1074
+ if (m === "PUT") {
1075
+ // Only the settings: a card or payment method is never accepted here.
1076
+ const fields = [
1077
+ "enabled",
1078
+ "thresholdMicros",
1079
+ "amountCents",
1080
+ "currency",
1081
+ "monthlyMaxCents",
1082
+ ]
1083
+ const unknown = Object.keys(body).filter((k) => !fields.includes(k))
1084
+ if (unknown.length)
1085
+ return fail(
1086
+ res,
1087
+ "invalid_request",
1088
+ `Auto-refill takes only its settings; ${unknown.join(", ")} is not one.`,
1089
+ "api",
1090
+ { path: unknown[0] },
1091
+ )
1092
+ if (body.enabled && !u.autoRefill.card)
1093
+ return fail(res, "no_card", "Save a card first.")
1094
+ for (const k of fields)
1095
+ if (body[k] !== undefined) u.autoRefill[k] = body[k]
1096
+ }
1097
+ return json(res, 200, u.autoRefill)
1098
+ }
1099
+ if (rest === "/card" && m === "POST")
1100
+ return json(res, 201, {
1101
+ url: `http://localhost:${PORT}/stub/card/${encodeURIComponent(userId)}?to=${encodeURIComponent(body.successUrl)}`,
1102
+ expiresAt: new Date(Date.now() + 86400e3).toISOString(),
1103
+ })
1104
+ if (rest === "/card" && m === "DELETE") {
1105
+ u.autoRefill.card = null
1106
+ u.autoRefill.enabled = false
1107
+ return json(res, 204)
1108
+ }
1109
+ if (rest === "/own-endpoint") {
1110
+ if (m === "GET") return json(res, 200, u.own ? ownView(u) : null)
1111
+ if (m === "DELETE") {
1112
+ u.own = null
1113
+ u.order = "tokens_only"
1114
+ return json(res, 204)
1115
+ }
1116
+ if (!/^https?:\/\//.test(body.baseUrl ?? "") || !body.models?.length)
1117
+ return fail(
1118
+ res,
1119
+ "invalid_request",
1120
+ "baseUrl and models are needed.",
1121
+ "api",
1122
+ { path: "baseUrl" },
1123
+ )
1124
+ const key = body.apiKey === undefined ? u.own?.apiKey : body.apiKey
1125
+ u.own = {
1126
+ baseUrl: body.baseUrl,
1127
+ apiKey: key,
1128
+ hasKey: !!key,
1129
+ keyHint: key ? key.slice(-4) : null,
1130
+ models: body.models,
1131
+ defaultModel: body.defaultModel ?? body.models[0],
1132
+ capabilities: body.capabilities ?? [],
1133
+ toolChoice: body.toolChoice === "required" ? "required" : "auto",
1134
+ monthlyTokenLimit: body.monthlyTokenLimit ?? null,
1135
+ usedThisMonth: 0,
1136
+ periodEndsAt: new Date(
1137
+ Date.UTC(new Date().getUTCFullYear(), new Date().getUTCMonth() + 1),
1138
+ ).toISOString(),
1139
+ lastTest: null,
1140
+ upstream: env.TOKENS_STUB_OWN_UPSTREAM || null,
1141
+ }
1142
+ u.order = body.order ?? "own_then_tokens"
1143
+ return json(res, 200, ownView(u))
1144
+ }
1145
+ if (rest === "/own-endpoint/test") {
1146
+ if (!u.own)
1147
+ return fail(res, "byo_not_configured", "No own endpoint saved.")
1148
+ u.own.lastTest = {
1149
+ ok: !/fail/.test(u.own.baseUrl),
1150
+ at: now(),
1151
+ latencyMs: 42,
1152
+ models: u.own.models,
1153
+ error: /fail/.test(u.own.baseUrl)
1154
+ ? {
1155
+ code: "byo_failed",
1156
+ message: "The endpoint answered 401.",
1157
+ status: 401,
1158
+ }
1159
+ : null,
1160
+ }
1161
+ return json(res, 200, u.own.lastTest)
1162
+ }
1163
+ if (rest === "/backend-order" && m === "PUT") {
1164
+ if (!u.own && body.order !== "tokens_only")
1165
+ return fail(res, "byo_not_configured", "Save an own endpoint first.")
1166
+ u.order = body.order
1167
+ return json(res, 200, { order: u.order })
1168
+ }
1169
+ return fail(res, "not_found", "No such endpoint.")
1170
+ }
1171
+
1172
+ // ------------------------------------------------------------------ stub controls (no auth)
1173
+ async function control(req, res, url, raw) {
1174
+ const body = raw ? JSON.parse(raw) : {}
1175
+ if (url.pathname === "/stub/reset") {
1176
+ reset()
1177
+ return json(res, 200, { ok: true })
1178
+ }
1179
+ if (url.pathname === "/stub/mode") {
1180
+ Object.assign(state.mode, body)
1181
+ return json(res, 200, state.mode)
1182
+ }
1183
+ if (url.pathname === "/stub/state")
1184
+ return json(res, 200, {
1185
+ users: [...state.users.values()].map((u) => balance(u)),
1186
+ calls: state.calls.map(publicCall),
1187
+ mode: state.mode,
1188
+ })
1189
+ if (url.pathname === "/stub/balance") {
1190
+ const u = user(body.userId)
1191
+ u.purchased = body.purchasedMicros
1192
+ crossings(u)
1193
+ return json(res, 200, balance(u))
1194
+ }
1195
+ if (url.pathname === "/stub/grant") {
1196
+ const u = user(body.userId)
1197
+ if (body.provider === null)
1198
+ return fail(
1199
+ res,
1200
+ "invalid_request",
1201
+ "Every lot is locked to one provider.",
1202
+ "api",
1203
+ { path: "provider" },
1204
+ )
1205
+ const lot = {
1206
+ id: id("lot"),
1207
+ kind: body.kind ?? "airdrop",
1208
+ provider: body.provider ?? "anthropic",
1209
+ grantedMicros: body.micros,
1210
+ spentMicros: 0,
1211
+ remainingMicros: body.micros,
1212
+ expiresAt: body.expiresAt ?? null,
1213
+ reason: body.reason ?? null,
1214
+ createdAt: now(),
1215
+ }
1216
+ u.lots.push(lot)
1217
+ u.history.push({ type: "grant", at: lot.createdAt, lot })
1218
+ crossings(u)
1219
+ return json(
1220
+ res,
1221
+ 200,
1222
+ emit("grant.received", {
1223
+ userId: u.userId,
1224
+ source: lot.kind,
1225
+ lot,
1226
+ airdropId: lot.kind === "airdrop" ? id("drop") : null,
1227
+ balance: summary(u),
1228
+ }),
1229
+ )
1230
+ }
1231
+ if (url.pathname === "/stub/expire") {
1232
+ for (const u of state.users.values())
1233
+ for (const lot of u.lots)
1234
+ if (lot.id === body.lotId && lot.remainingMicros > 0) {
1235
+ const expiredMicros = lot.remainingMicros
1236
+ lot.remainingMicros = 0
1237
+ lot.expiresAt = now()
1238
+ u.history.push({
1239
+ type: "expiry",
1240
+ at: now(),
1241
+ lotId: lot.id,
1242
+ expiredMicros,
1243
+ })
1244
+ crossings(u)
1245
+ return json(
1246
+ res,
1247
+ 200,
1248
+ emit("grant.expired", {
1249
+ userId: u.userId,
1250
+ lot,
1251
+ expiredMicros,
1252
+ balance: summary(u),
1253
+ }),
1254
+ )
1255
+ }
1256
+ return fail(res, "not_found", "No such live lot.")
1257
+ }
1258
+ if (url.pathname === "/stub/autorefill-fail") {
1259
+ const u = user(body.userId)
1260
+ u.autoRefill.enabled = false
1261
+ u.autoRefill.failedAt = now()
1262
+ return json(
1263
+ res,
1264
+ 200,
1265
+ emit("autorefill.failed", {
1266
+ userId: u.userId,
1267
+ purchaseId: null,
1268
+ reason: "Your card was declined.",
1269
+ }),
1270
+ )
1271
+ }
1272
+ let r = url.pathname.match(/^\/stub\/checkout\/([^/]+)$/)
1273
+ if (r) {
1274
+ const x = state.purchases.get(r[1])
1275
+ if (!x) return fail(res, "not_found", "No such purchase.")
1276
+ if (x.purchase.status === "open") {
1277
+ const u = user(x.userId)
1278
+ Object.assign(x.purchase, {
1279
+ status: "paid",
1280
+ paidAt: now(),
1281
+ taxCents: 0,
1282
+ totalCents: x.purchase.amountCents,
1283
+ })
1284
+ u.purchased += x.purchase.creditMicros
1285
+ if (x.saveCard) u.autoRefill.card = { label: "Visa ending 4242" }
1286
+ u.history.push({ type: "purchase", at: now(), purchase: x.purchase })
1287
+ crossings(u)
1288
+ emit("purchase.completed", {
1289
+ userId: u.userId,
1290
+ purchase: x.purchase,
1291
+ balance: summary(u),
1292
+ })
1293
+ }
1294
+ res.writeHead(303, {
1295
+ location: (x.successUrl ?? "/").replace("{PURCHASE_ID}", x.purchase.id),
1296
+ })
1297
+ return res.end()
1298
+ }
1299
+ r = url.pathname.match(/^\/stub\/card\/([^/]+)$/)
1300
+ if (r) {
1301
+ user(decodeURIComponent(r[1])).autoRefill.card = {
1302
+ label: "Visa ending 4242",
1303
+ }
1304
+ res.writeHead(303, { location: url.searchParams.get("to") ?? "/" })
1305
+ return res.end()
1306
+ }
1307
+ return fail(res, "not_found", "No such stub control.")
1308
+ }
1309
+
1310
+ // ------------------------------------------------------------------ server
1311
+ const server = createServer(async (req, res) => {
1312
+ const url = new URL(req.url, `http://localhost:${PORT}`)
1313
+ try {
1314
+ const raw = await readBody(req)
1315
+ if (url.pathname.startsWith("/stub/"))
1316
+ return await control(req, res, url, raw)
1317
+ const shape =
1318
+ url.pathname === "/v1/messages"
1319
+ ? "anthropic"
1320
+ : url.pathname.startsWith("/v1/")
1321
+ ? "openai"
1322
+ : "api"
1323
+ if (state.mode.down)
1324
+ return fail(
1325
+ res,
1326
+ "center_unavailable",
1327
+ "The token center is unavailable.",
1328
+ shape,
1329
+ )
1330
+ const key =
1331
+ req.headers["x-api-key"] ??
1332
+ (req.headers.authorization ?? "").replace(/^Bearer\s+/i, "")
1333
+ if (!key || (KEY && key !== KEY))
1334
+ return fail(res, "unauthenticated", "Unknown app key.", shape)
1335
+ if (url.pathname === "/v1/models")
1336
+ return json(res, 200, {
1337
+ object: "list",
1338
+ data: MODELS.map((x) => ({
1339
+ id: x.id,
1340
+ object: "model",
1341
+ type: "model",
1342
+ display_name: x.displayName,
1343
+ created: 1767225600,
1344
+ created_at: PRICE.effectiveFrom,
1345
+ owned_by: x.provider,
1346
+ })),
1347
+ has_more: false,
1348
+ first_id: MODELS[0].id,
1349
+ last_id: MODELS.at(-1).id,
1350
+ })
1351
+ if (
1352
+ req.method === "POST" &&
1353
+ ["/v1/messages", "/v1/chat/completions", "/v1/audio/speech"].includes(
1354
+ url.pathname,
1355
+ )
1356
+ )
1357
+ return await gateway(req, res, url, raw)
1358
+ if (url.pathname.startsWith("/api/v1/"))
1359
+ return await api(req, res, url, raw)
1360
+ fail(res, "not_found", "No such endpoint.", shape)
1361
+ } catch (e) {
1362
+ console.error("[stub]", e)
1363
+ if (!res.headersSent) fail(res, "internal_error", "Stub error.")
1364
+ else res.end()
1365
+ }
1366
+ })
1367
+ return new Promise((resolve, reject) => {
1368
+ server.once("error", reject)
1369
+ server.listen(PORT, () => {
1370
+ PORT = server.address().port
1371
+ resolve({
1372
+ url: `http://localhost:${PORT}`,
1373
+ port: PORT,
1374
+ reset,
1375
+ close: () =>
1376
+ new Promise((done) => {
1377
+ for (const t of timers) clearTimeout(t)
1378
+ timers.clear()
1379
+ server.closeAllConnections?.()
1380
+ server.close(() => done())
1381
+ }),
1382
+ })
1383
+ })
1384
+ })
1385
+ }