@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,635 @@
1
+ /**
2
+ * Token Center contract types, contract version 1.
3
+ *
4
+ * The single source of truth shared by the center and `@kaperkunde/tokens` (each carries a copy). openapi.yaml says the same thing
5
+ * over HTTP; if the two ever disagree, this file wins and openapi.yaml is fixed.
6
+ *
7
+ * Conventions:
8
+ * - Money is integer **micro-dollars** (`Micros`, 1 USD = 1_000_000). JSON carries it as a
9
+ * number (safe up to 9e15, i.e. $9bn). Never floats for balances.
10
+ * - Fiat amounts for Stripe are integer **cents** in the named currency.
11
+ * - Times are ISO 8601 strings in UTC (`2026-12-01T00:00:00.000Z`).
12
+ * - `userId` is always the **app's own user id** (opaque string, 1..128 chars). The center never
13
+ * sees one app's users from another app (`appId` comes from the key, never from the body).
14
+ */
15
+ export declare const CONTRACT_VERSION: 1;
16
+ /** Integer micro-dollars. */
17
+ export type Micros = number;
18
+ /** Integer cents of a currency. */
19
+ export type Cents = number;
20
+ export type IsoTime = string;
21
+ /**
22
+ * Header names (lower case; HTTP is case-insensitive). Request values that carry user text --
23
+ * `x-token-user`, `x-token-email` and every attribution header -- are
24
+ * `encodeURIComponent`-encoded by the client (the package always encodes them) and decoded by
25
+ * the center (a value that is not valid percent-encoding is taken as it is). A decoded
26
+ * attribution value is at most 200 characters, longer is cut; a decoded user id is 1..128.
27
+ */
28
+ export declare const TOKEN_HEADERS: {
29
+ /** The app's user id, URI-encoded. Required on every gateway request. */
30
+ readonly user: "x-token-user";
31
+ /** The user's **verified** email, URI-encoded. Optional; stored/updated on the center's user row. */
32
+ readonly email: "x-token-email";
33
+ /** What the call is for, a small closed set per app (e.g. storyteller, player, voice). */
34
+ readonly purpose: "x-token-purpose";
35
+ /** A human line ("Telling Ash"). */
36
+ readonly activity: "x-token-activity";
37
+ /** The app's grouping (e.g. a party or a world id). */
38
+ readonly scope: "x-token-scope";
39
+ /** The app's job id (a job id in the app's own queue). */
40
+ readonly job: "x-token-job";
41
+ /** What the call is about (e.g. a character or chapter id). */
42
+ readonly subject: "x-token-subject";
43
+ /** Groups several gateway requests into one app-level call (the app's own ledger row id). */
44
+ readonly correlation: "x-token-correlation";
45
+ /** `tokens` (default) or `own`. `own` sends a chat-completions request to the user's own endpoint. */
46
+ readonly backend: "x-token-backend";
47
+ /** `event`: append a final `event: token_center` SSE event carrying the CallCharge. Off by default. */
48
+ readonly trailer: "x-token-trailer";
49
+ /** Idempotency for app API POSTs that create something (checkout, card setup). */
50
+ readonly idempotencyKey: "idempotency-key";
51
+ readonly callId: "x-token-call-id";
52
+ /** `tokens` | `own` */
53
+ readonly source: "x-token-source";
54
+ /** The model that actually ran (may differ from the requested one on `own`). */
55
+ readonly model: "x-token-model";
56
+ /** Provider cost of the call at the price in force, micros. Absent on streams (use GET /api/v1/calls/:id or the trailer). */
57
+ readonly costMicros: "x-token-cost-micros";
58
+ /** Fee charged on the purchased portion, micros. */
59
+ readonly feeMicros: "x-token-fee-micros";
60
+ /** What the call came to, cost + fee, micros (the wallet lost this less any absorbed shortfall). */
61
+ readonly chargedMicros: "x-token-charged-micros";
62
+ /** Total spendable after the charge (all lots, all providers), micros. */
63
+ readonly balanceMicros: "x-token-balance-micros";
64
+ /** Characters metered on a speech call. */
65
+ readonly chars: "x-token-chars";
66
+ /** On every error response: the stable ErrorCode. */
67
+ readonly error: "x-token-error";
68
+ /** Rate limited / in-flight cap: seconds to wait (standard header). */
69
+ readonly retryAfter: "retry-after";
70
+ /** `t=<unix seconds>,v1=<hex HMAC-SHA256(secret, `${t}.${rawBody}`)>` */
71
+ readonly signature: "token-signature";
72
+ readonly eventId: "token-event-id";
73
+ };
74
+ /** The keys the gateway accepts for the app key: Anthropic SDKs send `x-api-key`, OpenAI SDKs `authorization: Bearer`. */
75
+ export declare const APP_KEY_HEADERS: readonly ["x-api-key", "authorization"];
76
+ /** App key format: `tk_<live|test>_<keyId 12 chars>_<secret 40 chars base62>`. Only sha256(secret) is stored. */
77
+ export declare const APP_KEY_PATTERN: RegExp;
78
+ /** Webhook signature tolerance. */
79
+ export declare const WEBHOOK_TOLERANCE_SECONDS = 300;
80
+ export declare const ERROR_CODES: readonly ["unauthenticated", "forbidden", "invalid_request", "unknown_user", "not_found", "unknown_model", "model_not_priced", "wrong_protocol", "insufficient_balance", "capability_unavailable", "byo_not_configured", "byo_failed", "byo_limit_reached", "provider_error", "provider_timeout", "rate_limited", "payments_unavailable", "purchase_too_small", "no_card", "conflict", "center_unavailable", "internal_error"];
81
+ export type ErrorCode = (typeof ERROR_CODES)[number];
82
+ export declare const ERROR_STATUS: Record<ErrorCode, number>;
83
+ export type Capability = "tools" | "streaming" | "vision" | "json" | "voice";
84
+ export type TokenErrorDetail = {
85
+ code: ErrorCode;
86
+ /** English sentence safe to show a user; never contains keys, provider bodies or other users. */
87
+ message: string;
88
+ /** insufficient_balance / capability_unavailable: what the app should offer. */
89
+ action?: "buy_tokens" | "configure_own" | "wait";
90
+ capability?: Capability;
91
+ provider?: ProviderId;
92
+ minimumCents?: Cents;
93
+ retryAfterSeconds?: number;
94
+ /** Upstream HTTP status for provider_error / byo_failed. */
95
+ status?: number;
96
+ /** invalid_request: JSON path of the offending field. */
97
+ path?: string;
98
+ callId?: string;
99
+ };
100
+ /** App API (`/api/v1/*`) error body. */
101
+ export type TokenErrorBody = {
102
+ error: TokenErrorDetail;
103
+ };
104
+ /**
105
+ * Gateway error bodies keep the provider's shape so provider SDKs parse them, plus
106
+ * `token_center`. `x-token-error` header carries the code too.
107
+ * - /v1/messages: { type: "error", error: { type, message }, token_center }
108
+ * - /v1/chat/completions: { error: { message, type, code }, token_center }
109
+ * A provider's own error (4xx from Anthropic/OpenAI) is passed through with its status and body,
110
+ * and `token_center: { code: "provider_error", status }` added.
111
+ */
112
+ export type GatewayAnthropicError = {
113
+ type: "error";
114
+ error: {
115
+ type: string;
116
+ message: string;
117
+ };
118
+ token_center: TokenErrorDetail;
119
+ };
120
+ export type GatewayOpenAIError = {
121
+ error: {
122
+ message: string;
123
+ type: string;
124
+ code: string | null;
125
+ };
126
+ token_center: TokenErrorDetail;
127
+ };
128
+ /** Providers the center talks to with its own keys. Airdrops/grants lock to one of these. */
129
+ export type ProviderId = "anthropic" | "openai" | "elevenlabs";
130
+ export type Protocol = "anthropic" | "openai";
131
+ export type Source = "tokens" | "own";
132
+ /** Per user, as apps with a bring-your-own model have it. Default for a user with an own endpoint: own_then_tokens. */
133
+ export type BackendOrder = "tokens_then_own" | "own_then_tokens" | "tokens_only" | "own_only";
134
+ export type Currency = "eur" | "usd";
135
+ export type Attribution = {
136
+ purpose?: string;
137
+ activity?: string;
138
+ scope?: string;
139
+ job?: string;
140
+ subject?: string;
141
+ correlation?: string;
142
+ };
143
+ /** A restricted bucket: an airdrop share or an admin grant. Fee-free, always locked to one provider. */
144
+ export type GrantLot = {
145
+ id: string;
146
+ kind: "airdrop" | "grant";
147
+ /** The one provider this lot pays for (airdrops and grants alike; there is no "any provider" lot). */
148
+ provider: ProviderId;
149
+ grantedMicros: Micros;
150
+ spentMicros: Micros;
151
+ remainingMicros: Micros;
152
+ expiresAt: IsoTime | null;
153
+ /** Admin's reason/note, shown to the user only if the app chooses to. */
154
+ reason: string | null;
155
+ createdAt: IsoTime;
156
+ };
157
+ export type BalanceSummary = {
158
+ /** Everything spendable now on some provider: unexpired lots + purchased. May be <= 0. */
159
+ availableMicros: Micros;
160
+ /** General purchased credit. Never negative: a shortfall is absorbed by the center (README "Shortfall"). */
161
+ purchasedMicros: Micros;
162
+ /** Sum of unexpired lot remainders. */
163
+ grantsMicros: Micros;
164
+ };
165
+ export type Balance = BalanceSummary & {
166
+ userId: string;
167
+ /** Whether the center has seen this user yet (false → all zeros). */
168
+ known: boolean;
169
+ /** Spendable per provider: lots locked to it + purchased. */
170
+ byProvider: Record<ProviderId, Micros>;
171
+ lots: GrantLot[];
172
+ /** Earliest expiry among lots with something left. */
173
+ nextExpiry: {
174
+ at: IsoTime;
175
+ micros: Micros;
176
+ } | null;
177
+ /** The app's display unit (e.g. "credits" at 1_000_000 per dollar). */
178
+ unit: AppUnit;
179
+ /** Fee now in force, basis points (2000 = 20%), for "a token buys less than a dollar of model" copy. */
180
+ feeBps: number;
181
+ autoRefill: {
182
+ enabled: boolean;
183
+ pending: boolean;
184
+ } | null;
185
+ };
186
+ export type AppUnit = {
187
+ one: string;
188
+ many: string;
189
+ perDollar: number;
190
+ };
191
+ export type UpsertUserRequest = {
192
+ /** Verified email only. */
193
+ email?: string | null;
194
+ displayName?: string | null;
195
+ };
196
+ export type AppUser = {
197
+ userId: string;
198
+ email: string | null;
199
+ displayName: string | null;
200
+ createdAt: IsoTime;
201
+ lastSeenAt: IsoTime | null;
202
+ };
203
+ export type CallUsage = {
204
+ /** The whole prompt, cache included (Anthropic: input + cache_read + cache_creation). */
205
+ inputTokens: number;
206
+ outputTokens: number;
207
+ /** Part of inputTokens served from cache. */
208
+ cacheReadTokens: number;
209
+ /** Part of inputTokens written to cache (5m + 1h). */
210
+ cacheWriteTokens: number;
211
+ /** Part of cacheWriteTokens kept an hour. */
212
+ cacheWrite1hTokens: number;
213
+ /** Part of cacheWriteTokens kept five minutes (cacheWriteTokens - cacheWrite1hTokens). The center always fills it. */
214
+ cacheWrite5mTokens?: number;
215
+ reasoningTokens?: number;
216
+ totalTokens: number;
217
+ /** Non-token units: speech is metered in characters. */
218
+ units?: {
219
+ tts_chars?: number;
220
+ };
221
+ inferenceGeo?: string;
222
+ speed?: string;
223
+ serviceTier?: string;
224
+ };
225
+ export type CallStatus = "admitted" | "charged" | "failed" | "lost";
226
+ export type CallEndpoint = "messages" | "chat_completions" | "speech";
227
+ /** What a finished call took. Also the trailer event's data. */
228
+ export type CallCharge = {
229
+ callId: string;
230
+ status: CallStatus;
231
+ source: Source;
232
+ model: string;
233
+ usage: CallUsage;
234
+ costMicros: Micros;
235
+ feeMicros: Micros;
236
+ /** cost + fee: what the call came to. */
237
+ chargedMicros: Micros;
238
+ /** Taken from lots (fee-free). */
239
+ fromGrantsMicros: Micros;
240
+ /** Asked of purchased, fee included. */
241
+ fromPurchasedMicros: Micros;
242
+ /**
243
+ * Part of fromPurchasedMicros the user did not have, written off by the center as house loss
244
+ * (purchased stops at zero). What the wallet actually lost is chargedMicros - shortfallMicros.
245
+ */
246
+ shortfallMicros: Micros;
247
+ balanceAfterMicros: Micros;
248
+ /**
249
+ * Present and true when the usage was estimated because the provider's final usage never
250
+ * arrived (a stream cut short, an answer that broke off): the prompt from what the provider
251
+ * reported or the request's size, the answer from the text relayed, or max_tokens at worst.
252
+ */
253
+ estimated?: boolean;
254
+ };
255
+ /**
256
+ * The charge as a non-streamed gateway response's headers carry it (`x-token-call-id`,
257
+ * `-source`, `-model`, `-cost-micros`, `-fee-micros`, `-charged-micros`, `-balance-micros`):
258
+ * what `chargeFromHeaders` in `@kaperkunde/tokens/server` returns. For the full `CallCharge`
259
+ * (usage, the split between lots and purchased, the shortfall) read `GET /api/v1/calls/:id`.
260
+ */
261
+ export type HeaderCharge = Pick<CallCharge, "callId" | "source" | "model" | "costMicros" | "feeMicros" | "chargedMicros" | "balanceAfterMicros">;
262
+ /** A call as the app API answers it: always keyed `callId` (there is no `id` field). */
263
+ export type CallRecord = CallCharge & {
264
+ userId: string;
265
+ endpoint: CallEndpoint;
266
+ provider: ProviderId | "own";
267
+ requestedModel: string;
268
+ stream: boolean;
269
+ attribution: Attribution;
270
+ /** For own calls: the user's endpoint host (never the key). */
271
+ ownHost?: string;
272
+ error: TokenErrorDetail | null;
273
+ createdAt: IsoTime;
274
+ finishedAt: IsoTime | null;
275
+ latencyMs: number | null;
276
+ };
277
+ export type CallsQuery = {
278
+ limit?: number;
279
+ cursor?: string;
280
+ since?: IsoTime;
281
+ scope?: string;
282
+ job?: string;
283
+ correlation?: string;
284
+ purpose?: string;
285
+ source?: Source;
286
+ };
287
+ export type CallsPage = {
288
+ calls: CallRecord[];
289
+ nextCursor: string | null;
290
+ /** Sums over the whole filter, not just the page. */
291
+ totals: {
292
+ count: number;
293
+ costMicros: Micros;
294
+ feeMicros: Micros;
295
+ chargedMicros: Micros;
296
+ inputTokens: number;
297
+ outputTokens: number;
298
+ cacheReadTokens: number;
299
+ cacheWriteTokens: number;
300
+ /** Of cacheWriteTokens, kept five minutes / an hour. The center always fills both. */
301
+ cacheWrite5mTokens?: number;
302
+ cacheWrite1hTokens?: number;
303
+ totalTokens: number;
304
+ };
305
+ };
306
+ export type RouteRequest = {
307
+ userId: string;
308
+ /** The center model id the app would use on tokens (its role's model). */
309
+ model: string;
310
+ /** What the call needs; an own endpoint lacking one falls back to tokens. */
311
+ needs?: Capability[];
312
+ };
313
+ export type RouteDecision = {
314
+ source: Source;
315
+ /** `anthropic` → use /v1/messages; `openai` → /v1/chat/completions. Own is always `openai`. */
316
+ protocol: Protocol;
317
+ /** The model to send: the requested one, or on `own` the requested one if listed there, else the endpoint's default. */
318
+ model: string;
319
+ /** Value for x-token-backend. */
320
+ backend: Source;
321
+ /** Set when the user's order was not followed as written. */
322
+ fallback: null | {
323
+ reason: "capability" | "own_limit" | "own_unusable" | "no_balance";
324
+ capability?: Capability;
325
+ };
326
+ availableMicros: Micros;
327
+ };
328
+ export type ModelPrice = {
329
+ /** USD per million tokens. Decimal strings to keep sub-cent precision exact ("3", "0.30"). */
330
+ inputUsdPerM: string;
331
+ outputUsdPerM: string;
332
+ cacheReadUsdPerM: string;
333
+ cacheWriteUsdPerM: string;
334
+ cacheWrite1hUsdPerM: string;
335
+ longPromptTokens: number | null;
336
+ longPromptFactor: string | null;
337
+ fastFactor: string | null;
338
+ effectiveFrom: IsoTime;
339
+ };
340
+ export type ModelInfo = {
341
+ id: string;
342
+ displayName: string;
343
+ provider: ProviderId;
344
+ protocol: Protocol;
345
+ capabilities: Capability[];
346
+ contextTokens: number | null;
347
+ /** Always present: unpriced models are not listed (and are refused). */
348
+ price: ModelPrice;
349
+ };
350
+ export type VoiceInfo = {
351
+ id: string;
352
+ name: string;
353
+ provider: ProviderId;
354
+ /** USD per million characters. */
355
+ usdPerMChars: string;
356
+ /** The app's default voice, used when a speech request names none. */
357
+ isDefault: boolean;
358
+ };
359
+ /**
360
+ * What an app lets its users buy (set per app on the center): suggested packs, whether only
361
+ * the packs may be bought, and the bounds checkout enforces. Amounts are cents of whichever
362
+ * currency the user pays in (e.g. packs [500, 1000, 2500, 5000] with packsOnly true).
363
+ */
364
+ export type PurchaseOptions = {
365
+ packsCents: Cents[];
366
+ packsOnly: boolean;
367
+ /** The larger of the app's own minimum and the sale price's (500 by default). */
368
+ minimumCents: Cents;
369
+ maximumCents: Cents;
370
+ };
371
+ export type AppInfo = {
372
+ id: string;
373
+ name: string;
374
+ unit: AppUnit;
375
+ purchaseOptions: PurchaseOptions;
376
+ feeBps: number;
377
+ lowBalanceMicros: Micros;
378
+ maxInFlightPerUser: number;
379
+ livemode: boolean;
380
+ /** Origins checkout/card success and cancel URLs must start with. */
381
+ returnOrigins: string[];
382
+ };
383
+ export type SalePrice = {
384
+ currency: Currency;
385
+ /** Cents that buy one dollar of credit (1_000_000 micros). EUR includes VAT; USD is before sales tax. */
386
+ centsPerDollar: number;
387
+ taxBehavior: "inclusive" | "exclusive";
388
+ minimumCents: Cents;
389
+ effectiveFrom: IsoTime;
390
+ };
391
+ export type SalePrices = {
392
+ prices: SalePrice[];
393
+ feeBps: number;
394
+ paymentsAvailable: boolean;
395
+ /** This app's packs and bounds; checkout refuses an amount outside them. */
396
+ options: PurchaseOptions;
397
+ };
398
+ export type CheckoutRequest = {
399
+ currency: Currency;
400
+ /**
401
+ * Within the app's PurchaseOptions: below `minimumCents` is `purchase_too_small`; above
402
+ * `maximumCents`, or not one of `packsCents` when `packsOnly`, is `invalid_request` (path
403
+ * `amountCents`).
404
+ */
405
+ amountCents: Cents;
406
+ /** Must start with one of the app's returnOrigins. `{PURCHASE_ID}` is substituted. */
407
+ successUrl: string;
408
+ cancelUrl: string;
409
+ /** Save the card for auto-refill (setup_future_usage off_session). */
410
+ saveCard?: boolean;
411
+ locale?: string;
412
+ };
413
+ export type CheckoutSession = {
414
+ purchaseId: string;
415
+ /**
416
+ * Where to send the browser: the center's own start page (`/checkout/<purchaseId>`), which
417
+ * redirects to Stripe Checkout, and to which Stripe returns before the center sends the
418
+ * browser on to `successUrl` / `cancelUrl`.
419
+ */
420
+ url: string;
421
+ expiresAt: IsoTime;
422
+ /** Micros the purchase will credit, worked out at the price in force now. */
423
+ creditMicros: Micros;
424
+ };
425
+ export type PurchaseStatus = "open" | "paid" | "failed" | "expired";
426
+ export type Purchase = {
427
+ id: string;
428
+ kind: "checkout" | "refill";
429
+ status: PurchaseStatus;
430
+ currency: Currency;
431
+ amountCents: Cents;
432
+ taxCents: Cents | null;
433
+ totalCents: Cents | null;
434
+ creditMicros: Micros;
435
+ failure: string | null;
436
+ createdAt: IsoTime;
437
+ paidAt: IsoTime | null;
438
+ };
439
+ export type AutoRefill = {
440
+ enabled: boolean;
441
+ /** Refill when a charge that took from purchased leaves purchased below this. */
442
+ thresholdMicros: Micros;
443
+ amountCents: Cents;
444
+ currency: Currency;
445
+ /** Cap per calendar month (UTC), counted at amountCents before US sales tax. */
446
+ monthlyMaxCents: Cents;
447
+ card: {
448
+ label: string;
449
+ } | null;
450
+ pending: boolean;
451
+ failedAt: IsoTime | null;
452
+ };
453
+ /** The only fields `PUT autorefill` accepts; anything else (a card, a payment method) is `invalid_request`. */
454
+ export type AutoRefillInput = Pick<AutoRefill, "enabled" | "thresholdMicros" | "amountCents" | "currency" | "monthlyMaxCents">;
455
+ export type CardSetupRequest = {
456
+ successUrl: string;
457
+ cancelUrl: string;
458
+ currency?: Currency;
459
+ };
460
+ export type CardSetupSession = {
461
+ url: string;
462
+ expiresAt: IsoTime;
463
+ };
464
+ /**
465
+ * How the center treats `tool_choice` when proxying to the user's endpoint (an app's
466
+ * own-key setting): `auto` passes the request through as sent; `required` turns a request
467
+ * that carries `tools` with `tool_choice` absent or "auto" into `tool_choice: "required"`, for
468
+ * endpoints whose models only call a tool when told to.
469
+ */
470
+ export type ToolChoice = "auto" | "required";
471
+ export type OwnEndpoint = {
472
+ /** https, OpenAI-compatible, ending before /chat/completions (e.g. https://openrouter.ai/api/v1). */
473
+ baseUrl: string;
474
+ hasKey: boolean;
475
+ /** Last 4 characters of the key, for "sk-…a1b2". */
476
+ keyHint: string | null;
477
+ models: string[];
478
+ defaultModel: string;
479
+ capabilities: Capability[];
480
+ toolChoice: ToolChoice;
481
+ /** Tokens per calendar month (UTC); null = no limit. */
482
+ monthlyTokenLimit: number | null;
483
+ usedThisMonth: number;
484
+ periodEndsAt: IsoTime;
485
+ order: BackendOrder;
486
+ lastTest: OwnEndpointTest | null;
487
+ };
488
+ export type OwnEndpointInput = {
489
+ baseUrl: string;
490
+ /** Omit to keep the stored key; null to remove it. Write-only: never returned. */
491
+ apiKey?: string | null;
492
+ models: string[];
493
+ defaultModel?: string;
494
+ capabilities: Capability[];
495
+ /** Omitted: "auto". */
496
+ toolChoice?: ToolChoice;
497
+ monthlyTokenLimit: number | null;
498
+ order: BackendOrder;
499
+ };
500
+ /** GET own-endpoint answers 200 with the JSON `null` for a user with none (never 404). */
501
+ export type OwnEndpointResponse = OwnEndpoint | null;
502
+ export type OwnEndpointTest = {
503
+ ok: boolean;
504
+ at: IsoTime;
505
+ latencyMs: number | null;
506
+ /** Models the endpoint's GET /models listed, where it has one. */
507
+ models: string[] | null;
508
+ error: {
509
+ code: "byo_failed";
510
+ message: string;
511
+ status?: number;
512
+ } | null;
513
+ };
514
+ /** Set just the order (also for users with no own endpoint: only tokens_only is then accepted). */
515
+ export type BackendOrderInput = {
516
+ order: BackendOrder;
517
+ };
518
+ export type HistoryEntry = {
519
+ type: "purchase";
520
+ at: IsoTime;
521
+ purchase: Purchase;
522
+ } | {
523
+ type: "grant";
524
+ at: IsoTime;
525
+ lot: GrantLot;
526
+ } | {
527
+ type: "expiry";
528
+ at: IsoTime;
529
+ lotId: string;
530
+ expiredMicros: Micros;
531
+ } | {
532
+ type: "adjustment";
533
+ at: IsoTime;
534
+ micros: Micros;
535
+ reason: string;
536
+ };
537
+ export type HistoryPage = {
538
+ entries: HistoryEntry[];
539
+ nextCursor: string | null;
540
+ };
541
+ /** POST /v1/messages: Anthropic Messages API, passed through byte-for-byte except `model` is checked. */
542
+ export type AnthropicMessagesRequest = {
543
+ model: string;
544
+ max_tokens: number;
545
+ stream?: boolean;
546
+ [key: string]: unknown;
547
+ };
548
+ /** POST /v1/chat/completions: OpenAI Chat Completions. On streams the center forces stream_options.include_usage. */
549
+ export type ChatCompletionsRequest = {
550
+ model: string;
551
+ stream?: boolean;
552
+ stream_options?: {
553
+ include_usage?: boolean;
554
+ };
555
+ tools?: unknown[];
556
+ [key: string]: unknown;
557
+ };
558
+ /** POST /v1/audio/speech: OpenAI speech shape. Returns audio bytes. */
559
+ export type SpeechRequest = {
560
+ /** Text, 1..4096 characters; metered per character (Unicode code points). */
561
+ input: string;
562
+ /** A center voice id (GET /api/v1/voices); omitted = the app's default voice. */
563
+ voice?: string;
564
+ /** Ignored unless the voice allows a choice; the voice carries its provider model. */
565
+ model?: string;
566
+ response_format?: "mp3" | "opus" | "wav";
567
+ speed?: number;
568
+ };
569
+ /** GET /v1/models: one list both SDK families can read. */
570
+ export type GatewayModelList = {
571
+ object: "list";
572
+ data: Array<{
573
+ id: string;
574
+ object: "model";
575
+ type: "model";
576
+ display_name: string;
577
+ created: number;
578
+ created_at: IsoTime;
579
+ owned_by: ProviderId | "own";
580
+ }>;
581
+ has_more: false;
582
+ first_id: string | null;
583
+ last_id: string | null;
584
+ };
585
+ export type WebhookEnvelope<TYPE extends string, DATA> = {
586
+ /** `evt_…`, unique; deliveries of one event share it. Dedupe on it. */
587
+ id: string;
588
+ type: TYPE;
589
+ createdAt: IsoTime;
590
+ appId: string;
591
+ livemode: boolean;
592
+ data: DATA;
593
+ };
594
+ export type GrantReceivedEvent = WebhookEnvelope<"grant.received", {
595
+ userId: string;
596
+ source: "airdrop" | "grant";
597
+ lot: GrantLot;
598
+ /** Airdrop id when source = airdrop. */
599
+ airdropId: string | null;
600
+ balance: BalanceSummary;
601
+ }>;
602
+ export type PurchaseCompletedEvent = WebhookEnvelope<"purchase.completed", {
603
+ userId: string;
604
+ purchase: Purchase;
605
+ balance: BalanceSummary;
606
+ }>;
607
+ /** A charge or expiry took availableMicros from >= app.lowBalanceMicros to below it (once per crossing). */
608
+ export type BalanceLowEvent = WebhookEnvelope<"balance.low", {
609
+ userId: string;
610
+ thresholdMicros: Micros;
611
+ balance: BalanceSummary;
612
+ }>;
613
+ /** availableMicros went to <= 0 (once per crossing). Apps pause work. */
614
+ export type BalanceEmptyEvent = WebhookEnvelope<"balance.empty", {
615
+ userId: string;
616
+ balance: BalanceSummary;
617
+ }>;
618
+ /** An off-session refill failed; auto-refill has been turned off. */
619
+ export type AutoRefillFailedEvent = WebhookEnvelope<"autorefill.failed", {
620
+ userId: string;
621
+ purchaseId: string | null;
622
+ reason: string;
623
+ }>;
624
+ /** A lot passed its expiry with something left. */
625
+ export type GrantExpiredEvent = WebhookEnvelope<"grant.expired", {
626
+ userId: string;
627
+ lot: GrantLot;
628
+ expiredMicros: Micros;
629
+ balance: BalanceSummary;
630
+ }>;
631
+ export type WebhookEvent = GrantReceivedEvent | PurchaseCompletedEvent | BalanceLowEvent | BalanceEmptyEvent | AutoRefillFailedEvent | GrantExpiredEvent;
632
+ export type WebhookEventType = WebhookEvent["type"];
633
+ export declare const WEBHOOK_EVENT_TYPES: readonly WebhookEventType[];
634
+ /** Retry schedule after a non-2xx or a timeout (10 s): then the delivery is dead (admin may replay). */
635
+ export declare const WEBHOOK_RETRY_SECONDS: readonly [60, 300, 1800, 7200, 21600, 43200, 86400];