@kaperkunde/tokens 0.0.0-stage → 0.1.1

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 (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +425 -2
  3. package/dist/browser-api.d.mts +56 -0
  4. package/dist/browser-api.mjs +75 -0
  5. package/dist/errors.d.mts +47 -0
  6. package/dist/errors.mjs +105 -0
  7. package/dist/index.d.mts +5 -0
  8. package/dist/index.mjs +5 -0
  9. package/dist/react/autorefill.d.mts +21 -0
  10. package/dist/react/autorefill.mjs +269 -0
  11. package/dist/react/balance.d.mts +23 -0
  12. package/dist/react/balance.mjs +116 -0
  13. package/dist/react/buy.d.mts +27 -0
  14. package/dist/react/buy.mjs +175 -0
  15. package/dist/react/history.d.mts +23 -0
  16. package/dist/react/history.mjs +102 -0
  17. package/dist/react/hooks.d.mts +52 -0
  18. package/dist/react/hooks.mjs +150 -0
  19. package/dist/react/index.d.mts +11 -0
  20. package/dist/react/index.mjs +10 -0
  21. package/dist/react/labels.d.mts +114 -0
  22. package/dist/react/labels.mjs +125 -0
  23. package/dist/react/own-model.d.mts +31 -0
  24. package/dist/react/own-model.mjs +358 -0
  25. package/dist/react/ui.d.mts +61 -0
  26. package/dist/react/ui.mjs +128 -0
  27. package/dist/react/usage.d.mts +21 -0
  28. package/dist/react/usage.mjs +137 -0
  29. package/dist/server/client.d.mts +78 -0
  30. package/dist/server/client.mjs +138 -0
  31. package/dist/server/error-of.d.mts +12 -0
  32. package/dist/server/error-of.mjs +63 -0
  33. package/dist/server/gateway.d.mts +64 -0
  34. package/dist/server/gateway.mjs +114 -0
  35. package/dist/server/index.d.mts +7 -0
  36. package/dist/server/index.mjs +7 -0
  37. package/dist/server/node.d.mts +23 -0
  38. package/dist/server/node.mjs +81 -0
  39. package/dist/server/routes.d.mts +56 -0
  40. package/dist/server/routes.mjs +257 -0
  41. package/dist/server/webhook.d.mts +47 -0
  42. package/dist/server/webhook.mjs +99 -0
  43. package/dist/styles.css +380 -0
  44. package/dist/types.d.mts +645 -0
  45. package/dist/types.mjs +162 -0
  46. package/dist/units.d.mts +37 -0
  47. package/dist/units.mjs +76 -0
  48. package/package.json +72 -3
  49. package/stub/cli.mjs +8 -0
  50. package/stub/server.d.mts +38 -0
  51. package/stub/server.mjs +1465 -0
@@ -0,0 +1,128 @@
1
+ "use client";
2
+ import { TokenCenterError, centerUnavailable } from "../errors.mjs";
3
+ import { fill } from "./labels.mjs";
4
+ import { useCallback, useEffect, useId, useRef, useState } from "react";
5
+ import { jsx, jsxs } from "react/jsx-runtime";
6
+ // src/react/ui.tsx
7
+ const cx = (...parts) => parts.filter(Boolean).join(" ");
8
+ /** The class for a part: its stable `tk-*` name plus the consumer's. */
9
+ const part = (styling, name, ...extra) => cx(`tk-${name}`, ...extra, styling.classNames?.[name]);
10
+ /** Anything thrown, as a sentence a user can read. */
11
+ function messageOf(error, labels) {
12
+ if (error instanceof TokenCenterError) return error.code === "center_unavailable" ? labels.unavailable : error.message;
13
+ return labels.somethingWrong;
14
+ }
15
+ const asTokenError = (error) => error instanceof TokenCenterError ? error : centerUnavailable(error);
16
+ /** "Still needed: A, B." for the fields not yet filled in, or `null`. */
17
+ function stillNeeded(labels, fields) {
18
+ const missing = fields.filter((f) => !f.filled).map((f) => f.label);
19
+ return missing.length ? fill(labels.stillNeeded, { fields: missing.join(", ") }) : null;
20
+ }
21
+ /** One async action's state: pending, the error as words, and a way to clear it. */
22
+ function useAction(labels) {
23
+ const [pending, setPending] = useState(false);
24
+ const [error, setError] = useState(null);
25
+ const alive = useRef(true);
26
+ useEffect(() => {
27
+ alive.current = true;
28
+ return () => {
29
+ alive.current = false;
30
+ };
31
+ }, []);
32
+ return {
33
+ pending,
34
+ error,
35
+ setError,
36
+ run: useCallback(async (action) => {
37
+ setPending(true);
38
+ setError(null);
39
+ try {
40
+ return await action();
41
+ } catch (e) {
42
+ if (alive.current) setError(messageOf(e, labels));
43
+ return;
44
+ } finally {
45
+ if (alive.current) setPending(false);
46
+ }
47
+ }, [labels])
48
+ };
49
+ }
50
+ function Notice({ kind = "error", children, styling }) {
51
+ return /* @__PURE__ */ jsx("p", {
52
+ className: part(styling, "notice", `tk-notice--${kind}`),
53
+ role: kind === "error" ? "alert" : "status",
54
+ children
55
+ });
56
+ }
57
+ /** A labelled field: the label, the control (given its id), a hint beneath, and "(needed)" when required. */
58
+ function Field({ label, hint, required, children, styling }) {
59
+ const id = useId();
60
+ const hintId = `${id}-hint`;
61
+ return /* @__PURE__ */ jsxs("div", {
62
+ className: part(styling, "field"),
63
+ children: [
64
+ /* @__PURE__ */ jsxs("label", {
65
+ className: part(styling, "label"),
66
+ htmlFor: id,
67
+ children: [label, required ? /* @__PURE__ */ jsx("span", {
68
+ className: "tk-needed",
69
+ children: " (needed)"
70
+ }) : null]
71
+ }),
72
+ children({
73
+ id,
74
+ "aria-describedby": hint ? hintId : void 0
75
+ }),
76
+ hint ? /* @__PURE__ */ jsx("p", {
77
+ className: part(styling, "hint"),
78
+ id: hintId,
79
+ children: hint
80
+ }) : null
81
+ ]
82
+ });
83
+ }
84
+ /** Two to four exclusive choices as one row of real buttons. */
85
+ function Segmented({ label, value, options, onChange, styling }) {
86
+ const id = useId();
87
+ return /* @__PURE__ */ jsxs("div", {
88
+ className: part(styling, "field"),
89
+ children: [/* @__PURE__ */ jsx("span", {
90
+ className: part(styling, "label"),
91
+ id,
92
+ children: label
93
+ }), /* @__PURE__ */ jsx("div", {
94
+ className: part(styling, "segmented"),
95
+ role: "group",
96
+ "aria-labelledby": id,
97
+ children: options.map((o) => /* @__PURE__ */ jsx("button", {
98
+ type: "button",
99
+ className: part(styling, "segment"),
100
+ "aria-pressed": o.value === value,
101
+ onClick: () => onChange(o.value),
102
+ children: o.label
103
+ }, String(o.value)))
104
+ })]
105
+ });
106
+ }
107
+ function Panel({ title, styling, children, as: Tag = "section" }) {
108
+ const id = useId();
109
+ return /* @__PURE__ */ jsxs(Tag, {
110
+ className: part(styling, "panel", styling.className),
111
+ "aria-labelledby": title ? id : void 0,
112
+ children: [title ? /* @__PURE__ */ jsx("h2", {
113
+ className: part(styling, "title"),
114
+ id,
115
+ children: title
116
+ }) : null, children]
117
+ });
118
+ }
119
+ function dateText(iso, locale) {
120
+ return new Intl.DateTimeFormat(locale, { dateStyle: "medium" }).format(new Date(iso));
121
+ }
122
+ function dateTimeText(iso, locale) {
123
+ return new Intl.DateTimeFormat(locale, {
124
+ dateStyle: "medium",
125
+ timeStyle: "short"
126
+ }).format(new Date(iso));
127
+ }
128
+ export { Field, Notice, Panel, Segmented, asTokenError, cx, dateText, dateTimeText, messageOf, part, stillNeeded, useAction };
@@ -0,0 +1,21 @@
1
+ import { AppUnit, CallRecord, CallsPage, CallsQuery } from "../types.mjs";
2
+ import { LabelOverrides } from "./labels.mjs";
3
+ import { Styling } from "./ui.mjs";
4
+ export type UsageListProps = Styling & {
5
+ /** Which calls (scope, job, purpose, since …). Default: the user's newest. */
6
+ query?: CallsQuery;
7
+ /** A page you already hold. */
8
+ page?: CallsPage;
9
+ pageSize?: number;
10
+ unit?: AppUnit;
11
+ /** Poll the first page, in ms. Off by default. */
12
+ refreshMs?: number;
13
+ labels?: LabelOverrides;
14
+ basePath?: string;
15
+ };
16
+ /** Share of the prompt served from cache, 0..100. */
17
+ export declare const cacheShare: (call: Pick<CallRecord, "usage">) => number;
18
+ /** What the user is shown a call as: its activity, else its purpose, else the model. */
19
+ export declare const callTitle: (call: CallRecord) => string;
20
+ /** The user's calls with what each cost, how much of its prompt came from cache, and what it was for. */
21
+ export declare function UsageList(props: UsageListProps): import("react").JSX.Element;
@@ -0,0 +1,137 @@
1
+ "use client";
2
+ import { formatCompact, formatUnits } from "../units.mjs";
3
+ import { useAppInfo, useCalls, useLabels, useLocale, useTokenApi } from "./hooks.mjs";
4
+ import { fill } from "./labels.mjs";
5
+ import { Notice, Panel, dateTimeText, messageOf, part } from "./ui.mjs";
6
+ import { useState } from "react";
7
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
8
+ // src/react/usage.tsx
9
+ /** Share of the prompt served from cache, 0..100. */
10
+ const cacheShare = (call) => call.usage.inputTokens > 0 ? Math.round(call.usage.cacheReadTokens / call.usage.inputTokens * 100) : 0;
11
+ /** What the user is shown a call as: its activity, else its purpose, else the model. */
12
+ const callTitle = (call) => call.attribution.activity || call.attribution.purpose || call.model;
13
+ /** The user's calls with what each cost, how much of its prompt came from cache, and what it was for. */
14
+ function UsageList(props) {
15
+ const labels = useLabels(props.labels);
16
+ const locale = useLocale();
17
+ const api = useTokenApi(props.basePath);
18
+ const styling = props;
19
+ const query = {
20
+ limit: props.pageSize ?? 25,
21
+ ...props.query
22
+ };
23
+ const first = useCalls(query, {
24
+ basePath: props.basePath,
25
+ refreshMs: props.refreshMs,
26
+ skip: props.page !== void 0
27
+ });
28
+ const app = useAppInfo({
29
+ basePath: props.basePath,
30
+ skip: props.unit !== void 0
31
+ });
32
+ const unit = props.unit ?? app.data?.unit ?? {
33
+ one: "token",
34
+ many: "tokens",
35
+ perDollar: 1e6
36
+ };
37
+ const [more, setMore] = useState([]);
38
+ const [cursor, setCursor] = useState(void 0);
39
+ const [error, setError] = useState(null);
40
+ const [loadingMore, setLoadingMore] = useState(false);
41
+ const page = props.page ?? first.data;
42
+ const calls = [...page?.calls ?? [], ...more];
43
+ const next = cursor === void 0 ? page?.nextCursor ?? null : cursor;
44
+ async function loadMore() {
45
+ if (!next) return;
46
+ setLoadingMore(true);
47
+ setError(null);
48
+ try {
49
+ const out = await api.calls({
50
+ ...query,
51
+ cursor: next
52
+ });
53
+ setMore((m) => [...m, ...out.calls]);
54
+ setCursor(out.nextCursor);
55
+ } catch (e) {
56
+ setError(messageOf(e, labels));
57
+ } finally {
58
+ setLoadingMore(false);
59
+ }
60
+ }
61
+ return /* @__PURE__ */ jsx(Panel, {
62
+ title: labels.usageTitle,
63
+ styling,
64
+ children: !page ? first.error ? /* @__PURE__ */ jsx(Notice, {
65
+ styling,
66
+ children: labels.unavailable
67
+ }) : /* @__PURE__ */ jsx("p", {
68
+ className: "tk-muted",
69
+ children: labels.loading
70
+ }) : calls.length === 0 ? /* @__PURE__ */ jsx("p", {
71
+ className: "tk-muted",
72
+ children: labels.usageEmpty
73
+ }) : /* @__PURE__ */ jsxs(Fragment, { children: [
74
+ /* @__PURE__ */ jsx("p", {
75
+ className: "tk-muted",
76
+ children: fill(labels.totals, {
77
+ count: page.totals.count,
78
+ amount: formatUnits(page.totals.chargedMicros, unit, {
79
+ locale,
80
+ compact: true
81
+ })
82
+ })
83
+ }),
84
+ /* @__PURE__ */ jsx("ul", {
85
+ className: part(styling, "list"),
86
+ children: calls.map((call) => /* @__PURE__ */ jsxs("li", {
87
+ className: part(styling, "row"),
88
+ children: [/* @__PURE__ */ jsxs("span", {
89
+ className: "tk-row__main",
90
+ children: [
91
+ /* @__PURE__ */ jsx("span", {
92
+ className: "tk-row__title",
93
+ children: callTitle(call)
94
+ }),
95
+ /* @__PURE__ */ jsxs("span", {
96
+ className: "tk-row__meta",
97
+ children: [
98
+ dateTimeText(call.createdAt, locale),
99
+ call.source === "own" ? ` · ${labels.yourOwn}` : ` · ${call.model}`,
100
+ call.status === "failed" ? ` · ${labels.failedCall}` : ""
101
+ ]
102
+ }),
103
+ /* @__PURE__ */ jsxs("span", {
104
+ className: "tk-row__meta",
105
+ children: [fill(labels.tokensInOut, {
106
+ input: formatCompact(call.usage.inputTokens),
107
+ output: formatCompact(call.usage.outputTokens)
108
+ }), call.usage.inputTokens > 0 && call.usage.cacheReadTokens > 0 ? ` · ${fill(labels.cached, { percent: cacheShare(call) })}` : ""]
109
+ })
110
+ ]
111
+ }), /* @__PURE__ */ jsx("span", {
112
+ className: "tk-row__amount",
113
+ children: call.source === "own" ? "—" : formatUnits(call.chargedMicros, unit, {
114
+ locale,
115
+ bare: true
116
+ })
117
+ })]
118
+ }, call.callId))
119
+ }),
120
+ error ? /* @__PURE__ */ jsx(Notice, {
121
+ styling,
122
+ children: error
123
+ }) : null,
124
+ next ? /* @__PURE__ */ jsx("div", {
125
+ className: part(styling, "actions"),
126
+ children: /* @__PURE__ */ jsx("button", {
127
+ type: "button",
128
+ className: part(styling, "button"),
129
+ onClick: loadMore,
130
+ "aria-busy": loadingMore,
131
+ children: labels.loadMore
132
+ })
133
+ }) : null
134
+ ] })
135
+ });
136
+ }
137
+ export { UsageList, cacheShare, callTitle };
@@ -0,0 +1,78 @@
1
+ import { AppInfo, AppUser, Attribution, AutoRefill, AutoRefillInput, BackendOrderInput, Balance, CallRecord, CallsPage, CallsQuery, CardSetupRequest, CardSetupSession, CheckoutRequest, CheckoutSession, HeaderCharge, HistoryPage, ModelInfo, OwnEndpoint, OwnEndpointInput, OwnEndpointResponse, OwnEndpointTest, Purchase, RouteDecision, RouteRequest, SalePrices, SpeechRequest, UpsertUserRequest, VoiceInfo } from "../types.mjs";
2
+ export type TokenCenterOptions = {
3
+ /** The center, e.g. `https://tokens.example.com` (configuration: nothing here knows it). */
4
+ baseUrl: string;
5
+ /** The app key `tk_<live|test>_<keyId>_<secret>`. Server side only. */
6
+ apiKey: string;
7
+ fetch?: typeof fetch;
8
+ /** Per request; default 10 s. A `wait` on a call lengthens that request's. */
9
+ timeoutMs?: number;
10
+ };
11
+ export type CallsFilter = CallsQuery & {
12
+ userId?: string;
13
+ };
14
+ export type SpeechResult = {
15
+ audio: Uint8Array;
16
+ contentType: string;
17
+ /** What the call took, from the response headers. */
18
+ charge: HeaderCharge | null;
19
+ /** Characters metered. */
20
+ chars: number | null;
21
+ /** The voice that actually spoke, when the center used another than the one asked for (`x-token-voice-fallback`). */
22
+ voiceFallback: string | null;
23
+ };
24
+ /** Every `/api/v1` path as a typed method. See {@link createTokenCenter}. */
25
+ export type TokenCenter = ReturnType<typeof createTokenCenter>;
26
+ /**
27
+ * The app-API client. Fetch-based, one timeout per request, and every
28
+ * failure a `TokenCenterError`: an answer with an error body keeps the
29
+ * contract's code; no answer at all (refused, DNS, timeout, a 5xx with no
30
+ * body) is `center_unavailable`, which an app treats as **fail closed**.
31
+ */
32
+ export declare function createTokenCenter(options: TokenCenterOptions): {
33
+ baseUrl: string;
34
+ app: () => Promise<AppInfo>;
35
+ models: () => Promise<ModelInfo[]>;
36
+ voices: () => Promise<VoiceInfo[]>;
37
+ salePrices: () => Promise<SalePrices>;
38
+ /** Which backend (own endpoint or tokens) and model a call should use for this user. */
39
+ route: (request: RouteRequest) => Promise<RouteDecision>;
40
+ upsertUser: (userId: string, request: UpsertUserRequest) => Promise<AppUser>;
41
+ balance: (userId: string) => Promise<Balance>;
42
+ history: (userId: string, query?: {
43
+ limit?: number;
44
+ cursor?: string;
45
+ }) => Promise<HistoryPage>;
46
+ calls: (userId: string, query?: CallsQuery) => Promise<CallsPage>;
47
+ /** Across all of the app's users. */
48
+ allCalls: (query?: CallsFilter) => Promise<CallsPage>;
49
+ /**
50
+ * One call. A streamed call's charge is known only once it ends: pass
51
+ * `wait` (seconds, ≤ 30) to long-poll until it is no longer `admitted`.
52
+ */
53
+ call: (callId: string, options?: {
54
+ wait?: number;
55
+ }) => Promise<CallRecord>;
56
+ checkout: (userId: string, request: CheckoutRequest, options?: {
57
+ idempotencyKey?: string;
58
+ }) => Promise<CheckoutSession>;
59
+ purchase: (userId: string, purchaseId: string) => Promise<Purchase>;
60
+ autoRefill: (userId: string) => Promise<AutoRefill>;
61
+ setAutoRefill: (userId: string, input: AutoRefillInput) => Promise<AutoRefill>;
62
+ setupCard: (userId: string, request: CardSetupRequest, options?: {
63
+ idempotencyKey?: string;
64
+ }) => Promise<CardSetupSession>;
65
+ removeCard: (userId: string) => Promise<void>;
66
+ /** The saved endpoint, or `null` (the center answers 404 `not_found`). */
67
+ ownEndpoint: (userId: string) => Promise<OwnEndpointResponse>;
68
+ saveOwnEndpoint: (userId: string, input: OwnEndpointInput) => Promise<OwnEndpoint>;
69
+ removeOwnEndpoint: (userId: string) => Promise<void>;
70
+ testOwnEndpoint: (userId: string) => Promise<OwnEndpointTest>;
71
+ setBackendOrder: (userId: string, input: BackendOrderInput) => Promise<BackendOrderInput>;
72
+ /** `POST /v1/audio/speech`: audio bytes plus what it cost, from the headers. */
73
+ speech: (who: {
74
+ user: string;
75
+ email?: string | null;
76
+ attribution?: Attribution;
77
+ }, request: SpeechRequest) => Promise<SpeechResult>;
78
+ };
@@ -0,0 +1,138 @@
1
+ import { centerUnavailable, errorFromResponse } from "../errors.mjs";
2
+ import { chargeFromHeaders, gatewayHeaders, trimBaseUrl, voiceFallbackFromHeaders } from "./gateway.mjs";
3
+ // src/server/client.ts
4
+ /**
5
+ * The app-API client. Fetch-based, one timeout per request, and every
6
+ * failure a `TokenCenterError`: an answer with an error body keeps the
7
+ * contract's code; no answer at all (refused, DNS, timeout, a 5xx with no
8
+ * body) is `center_unavailable`, which an app treats as **fail closed**.
9
+ */
10
+ function createTokenCenter(options) {
11
+ const base = trimBaseUrl(options.baseUrl);
12
+ const doFetch = options.fetch ?? fetch;
13
+ const defaultTimeout = options.timeoutMs ?? 1e4;
14
+ if (!options.apiKey) throw new Error("createTokenCenter: apiKey is required.");
15
+ const authHeaders = { authorization: `Bearer ${options.apiKey}` };
16
+ async function raw(method, path, init = {}) {
17
+ const search = new URLSearchParams();
18
+ for (const [k, v] of Object.entries(init.query ?? {})) if (v !== void 0 && v !== null && v !== "") search.set(k, String(v));
19
+ const url = `${base}${path}${search.size ? `?${search}` : ""}`;
20
+ const headers = {
21
+ accept: "application/json",
22
+ ...authHeaders,
23
+ ...init.headers
24
+ };
25
+ let body;
26
+ if (init.body !== void 0) {
27
+ body = JSON.stringify(init.body);
28
+ headers["content-type"] = "application/json";
29
+ }
30
+ try {
31
+ return await doFetch(url, {
32
+ method,
33
+ headers,
34
+ body,
35
+ signal: AbortSignal.timeout(init.timeoutMs ?? defaultTimeout)
36
+ });
37
+ } catch (cause) {
38
+ const timedOut = cause instanceof Error && (cause.name === "TimeoutError" || cause.name === "AbortError");
39
+ throw centerUnavailable(cause, timedOut ? "The token center did not answer in time." : "The token center could not be reached.");
40
+ }
41
+ }
42
+ async function failure(response) {
43
+ let body = null;
44
+ try {
45
+ body = await response.json();
46
+ } catch {}
47
+ throw errorFromResponse(response.status, body, {
48
+ code: response.headers.get("x-token-error"),
49
+ retryAfter: response.headers.get("retry-after"),
50
+ callId: response.headers.get("x-token-call-id")
51
+ });
52
+ }
53
+ async function json(method, path, init) {
54
+ const response = await raw(method, path, init);
55
+ if (!response.ok) return failure(response);
56
+ if (response.status === 204) return void 0;
57
+ try {
58
+ return await response.json();
59
+ } catch (cause) {
60
+ throw centerUnavailable(cause, "The token center answered nothing readable.");
61
+ }
62
+ }
63
+ const user = (id) => {
64
+ if (!id) throw new Error("userId is required.");
65
+ return `/api/v1/users/${encodeURIComponent(id)}`;
66
+ };
67
+ const idem = (key) => key ? { "idempotency-key": key } : void 0;
68
+ return {
69
+ baseUrl: base,
70
+ app: () => json("GET", "/api/v1/app"),
71
+ models: async () => (await json("GET", "/api/v1/models")).models,
72
+ voices: async () => (await json("GET", "/api/v1/voices")).voices,
73
+ salePrices: () => json("GET", "/api/v1/sale-prices"),
74
+ /** Which backend (own endpoint or tokens) and model a call should use for this user. */
75
+ route: (request) => json("POST", "/api/v1/route", { body: request }),
76
+ upsertUser: (userId, request) => json("PUT", user(userId), { body: request }),
77
+ balance: (userId) => json("GET", `${user(userId)}/balance`),
78
+ history: (userId, query = {}) => json("GET", `${user(userId)}/history`, { query }),
79
+ calls: (userId, query = {}) => json("GET", `${user(userId)}/calls`, { query }),
80
+ /** Across all of the app's users. */
81
+ allCalls: (query = {}) => json("GET", "/api/v1/calls", { query }),
82
+ /**
83
+ * One call. A streamed call's charge is known only once it ends: pass
84
+ * `wait` (seconds, ≤ 30) to long-poll until it is no longer `admitted`.
85
+ */
86
+ call: (callId, options = {}) => {
87
+ const wait = Math.max(0, Math.min(30, Math.floor(options.wait ?? 0)));
88
+ return json("GET", `/api/v1/calls/${encodeURIComponent(callId)}`, {
89
+ query: wait ? { wait } : void 0,
90
+ timeoutMs: defaultTimeout + wait * 1e3
91
+ });
92
+ },
93
+ checkout: (userId, request, options = {}) => json("POST", `${user(userId)}/checkout`, {
94
+ body: request,
95
+ headers: idem(options.idempotencyKey)
96
+ }),
97
+ purchase: (userId, purchaseId) => json("GET", `${user(userId)}/purchases/${encodeURIComponent(purchaseId)}`),
98
+ autoRefill: (userId) => json("GET", `${user(userId)}/autorefill`),
99
+ setAutoRefill: (userId, input) => json("PUT", `${user(userId)}/autorefill`, { body: input }),
100
+ setupCard: (userId, request, options = {}) => json("POST", `${user(userId)}/card`, {
101
+ body: request,
102
+ headers: idem(options.idempotencyKey)
103
+ }),
104
+ removeCard: (userId) => json("DELETE", `${user(userId)}/card`),
105
+ /** The saved endpoint, or `null` (the center answers 404 `not_found`). */
106
+ ownEndpoint: async (userId) => {
107
+ const response = await raw("GET", `${user(userId)}/own-endpoint`);
108
+ if (response.status === 404) return null;
109
+ if (!response.ok) return failure(response);
110
+ return await response.json();
111
+ },
112
+ saveOwnEndpoint: (userId, input) => json("PUT", `${user(userId)}/own-endpoint`, { body: input }),
113
+ removeOwnEndpoint: (userId) => json("DELETE", `${user(userId)}/own-endpoint`),
114
+ testOwnEndpoint: (userId) => json("POST", `${user(userId)}/own-endpoint/test`),
115
+ setBackendOrder: (userId, input) => json("PUT", `${user(userId)}/backend-order`, { body: input }),
116
+ /** `POST /v1/audio/speech`: audio bytes plus what it cost, from the headers. */
117
+ speech: async (who, request) => {
118
+ const response = await raw("POST", "/v1/audio/speech", {
119
+ body: request,
120
+ headers: gatewayHeaders({
121
+ user: who.user,
122
+ email: who.email,
123
+ attribution: who.attribution
124
+ })
125
+ });
126
+ if (!response.ok) return failure(response);
127
+ const chars = Number(response.headers.get("x-token-chars"));
128
+ return {
129
+ audio: new Uint8Array(await response.arrayBuffer()),
130
+ contentType: response.headers.get("content-type") ?? "audio/mpeg",
131
+ charge: chargeFromHeaders(response.headers),
132
+ chars: Number.isFinite(chars) && chars > 0 ? chars : null,
133
+ voiceFallback: voiceFallbackFromHeaders(response.headers)
134
+ };
135
+ }
136
+ };
137
+ }
138
+ export { createTokenCenter };
@@ -0,0 +1,12 @@
1
+ import { TokenCenterError } from "../errors.mjs";
2
+ /**
3
+ * The `TokenCenterError` behind anything a gateway call threw, or `null` when
4
+ * the error is not the center's at all.
5
+ *
6
+ * Reads, on the error and then down its `cause` chain: an AI SDK
7
+ * `APICallError` (`statusCode`, `responseHeaders` with `x-token-error`,
8
+ * `responseBody` / `data` with `token_center`), a `TokenCenterError`, and a
9
+ * failed fetch (`TypeError: fetch failed`, `ECONNREFUSED`, "Cannot connect to
10
+ * API") which is `center_unavailable`: the caller **fails closed**.
11
+ */
12
+ export declare function tokenErrorOf(error: unknown): TokenCenterError | null;
@@ -0,0 +1,63 @@
1
+ import { TokenCenterError, centerUnavailable, detailOf, errorFromResponse } from "../errors.mjs";
2
+ // src/server/error-of.ts
3
+ const NETWORK_CODES = /* @__PURE__ */ new Set([
4
+ "ECONNREFUSED",
5
+ "ECONNRESET",
6
+ "ENOTFOUND",
7
+ "EAI_AGAIN",
8
+ "ETIMEDOUT",
9
+ "EHOSTUNREACH",
10
+ "ENETUNREACH",
11
+ "UND_ERR_CONNECT_TIMEOUT",
12
+ "UND_ERR_SOCKET",
13
+ "UND_ERR_HEADERS_TIMEOUT"
14
+ ]);
15
+ const record = (v) => typeof v === "object" && v !== null ? v : null;
16
+ function headerFrom(headers, name) {
17
+ const r = record(headers);
18
+ if (!r) return null;
19
+ if (typeof r.get === "function") return r.get(name);
20
+ for (const key of Object.keys(r)) if (key.toLowerCase() === name) return String(r[key]);
21
+ return null;
22
+ }
23
+ function parseBody(value) {
24
+ if (typeof value !== "string") return value ?? null;
25
+ try {
26
+ return JSON.parse(value);
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+ /**
32
+ * The `TokenCenterError` behind anything a gateway call threw, or `null` when
33
+ * the error is not the center's at all.
34
+ *
35
+ * Reads, on the error and then down its `cause` chain: an AI SDK
36
+ * `APICallError` (`statusCode`, `responseHeaders` with `x-token-error`,
37
+ * `responseBody` / `data` with `token_center`), a `TokenCenterError`, and a
38
+ * failed fetch (`TypeError: fetch failed`, `ECONNREFUSED`, "Cannot connect to
39
+ * API") which is `center_unavailable`: the caller **fails closed**.
40
+ */
41
+ function tokenErrorOf(error) {
42
+ let current = error;
43
+ for (let depth = 0; depth < 5 && current; depth++) {
44
+ if (current instanceof TokenCenterError) return current;
45
+ const e = record(current);
46
+ if (!e) return null;
47
+ const status = typeof e.statusCode === "number" ? e.statusCode : typeof e.status === "number" ? e.status : null;
48
+ const body = parseBody(e.responseBody ?? e.data ?? e.body);
49
+ const code = headerFrom(e.responseHeaders ?? e.headers, "x-token-error");
50
+ if (status !== null && (detailOf(record(body)?.token_center) || detailOf(record(body)?.error) || code)) return errorFromResponse(status, body, {
51
+ code,
52
+ retryAfter: headerFrom(e.responseHeaders ?? e.headers, "retry-after"),
53
+ callId: headerFrom(e.responseHeaders ?? e.headers, "x-token-call-id")
54
+ });
55
+ const cause = record(e.cause);
56
+ const errCode = typeof e.code === "string" ? e.code : cause && typeof cause.code === "string" ? cause.code : null;
57
+ const message = typeof e.message === "string" ? e.message : "";
58
+ if (errCode && NETWORK_CODES.has(errCode) || e.name === "TypeError" && /fetch failed/i.test(message) || /^Cannot connect to API/i.test(message)) return centerUnavailable(current);
59
+ current = e.cause;
60
+ }
61
+ return null;
62
+ }
63
+ export { tokenErrorOf };
@@ -0,0 +1,64 @@
1
+ import { Attribution, CallCharge, HeaderCharge, Source } from "../types.mjs";
2
+ export type GatewayHeaderInput = {
3
+ /** The payer: the app's own user id. Required. */
4
+ user: string;
5
+ /** The app's **verified** email for that user. */
6
+ email?: string | null;
7
+ attribution?: Attribution;
8
+ /** `own` sends a chat-completions call to the user's own endpoint. Default `tokens`. */
9
+ backend?: Source;
10
+ /** `true`: append a final `event: token_center` SSE event carrying the charge. */
11
+ trailer?: boolean;
12
+ };
13
+ /** `https://center/` and `https://center/v1` both mean `https://center`. */
14
+ export declare const trimBaseUrl: (baseUrl: string) => string;
15
+ /**
16
+ * The `x-token-*` request headers: who pays and what the call is for. Values
17
+ * are `encodeURIComponent`-encoded (an activity line names characters) and cut
18
+ * to 200 characters, as the center decodes them. Merge per call into the AI
19
+ * SDK's `headers` option; the app key rides on the provider, not here.
20
+ */
21
+ export declare function gatewayHeaders(input: GatewayHeaderInput): Record<string, string>;
22
+ export type GatewayConfigInput = GatewayHeaderInput & {
23
+ baseUrl: string;
24
+ apiKey: string;
25
+ };
26
+ export type GatewayConfig = {
27
+ /** `<center>/v1`: both `@ai-sdk/anthropic` (`/messages`) and OpenAI-compatible providers (`/chat/completions`, `/audio/speech`) add their paths to it. */
28
+ baseURL: string;
29
+ apiKey: string;
30
+ headers: Record<string, string>;
31
+ };
32
+ /**
33
+ * Provider settings pointing an AI SDK provider at the center:
34
+ *
35
+ * ```ts
36
+ * createAnthropic(gatewayConfig({ baseUrl, apiKey, user: host.id }))
37
+ * createOpenAICompatible({ name: "tokens", ...gatewayConfig({ … }) })
38
+ * ```
39
+ *
40
+ * Providers are cheap to make, so make one per payer. For attribution that
41
+ * changes per call (purpose, activity, job) pass `gatewayHeaders({ … })` as
42
+ * the call's `headers` instead, or build the provider per call.
43
+ */
44
+ export declare function gatewayConfig(input: GatewayConfigInput): GatewayConfig;
45
+ type HeadersLike = Headers | {
46
+ get(name: string): string | null | undefined;
47
+ } | Record<string, string | string[] | undefined>;
48
+ /** The voice a speech answer used in place of the one asked for (`x-token-voice-fallback`), or `null` when it was the asked one. */
49
+ export declare function voiceFallbackFromHeaders(headers: HeadersLike): string | null;
50
+ /** The call id a gateway response carries up front (streams have it before any cost is known), or `null`. */
51
+ export declare function callIdFromHeaders(headers: HeadersLike): string | null;
52
+ /**
53
+ * The charge from a non-streamed response's headers (`x-token-call-id`,
54
+ * `-source`, `-model`, `-cost-micros`, `-fee-micros`, `-charged-micros`,
55
+ * `-balance-micros`), or `null` when the answer did not come through the
56
+ * gateway or carries no cost yet (a stream: take the id with
57
+ * {@link callIdFromHeaders}, then `center.call(id, { wait })` or the opt-in
58
+ * trailer, {@link parseTrailer}). Accepts `Headers`, a Node header record, or
59
+ * the AI SDK's `response.headers`.
60
+ */
61
+ export declare function chargeFromHeaders(headers: HeadersLike): HeaderCharge | null;
62
+ /** The `event: token_center` trailer of a stream read as text, parsed; `null` when absent. */
63
+ export declare function parseTrailer<T = CallCharge>(sse: string): T | null;
64
+ export {};