@mupt-ai/dari-gateway 1.0.311 → 1.0.313

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 (127) hide show
  1. package/README.md +279 -2
  2. package/dist/context/provider_prompt_accounting.js +7 -0
  3. package/dist/context/routing_context.js +4 -1
  4. package/dist/http/handler.d.ts +2 -1
  5. package/dist/http/handler.js +12 -2
  6. package/dist/ingress/anthropic_messages.js +15 -3
  7. package/dist/ingress/chat_completions.js +6 -1
  8. package/dist/ingress/codex.js +2 -2
  9. package/dist/ingress/link.d.ts +24 -0
  10. package/dist/ingress/link.js +1519 -0
  11. package/dist/ingress/link_assets.d.ts +14 -0
  12. package/dist/ingress/link_assets.js +49 -0
  13. package/dist/ingress/link_font.d.ts +1 -0
  14. package/dist/ingress/link_font.js +6 -0
  15. package/dist/ingress/models.js +46 -2
  16. package/dist/interaction/types.d.ts +1 -0
  17. package/dist/link_client.d.ts +386 -0
  18. package/dist/link_client.js +579 -0
  19. package/dist/models/gateways.d.ts +2 -0
  20. package/dist/models/gateways.js +2 -0
  21. package/dist/models/link_errors.d.ts +30 -0
  22. package/dist/models/link_errors.js +120 -0
  23. package/dist/models/subscriptions.d.ts +8 -1
  24. package/dist/models/subscriptions.js +13 -2
  25. package/dist/platform/platform.d.ts +303 -1
  26. package/dist/protocol/input/router_model.d.ts +4 -0
  27. package/dist/protocol/input/router_model.js +31 -1
  28. package/dist/providers/execution.js +31 -5
  29. package/dist/providers/pi_options.js +57 -1
  30. package/dist/providers/provider_call.d.ts +4 -0
  31. package/dist/providers/provider_call.js +9 -2
  32. package/dist/providers/response_capture.d.ts +4 -1
  33. package/dist/providers/response_capture.js +81 -2
  34. package/dist/providers/stream_finalization.d.ts +1 -0
  35. package/dist/providers/subscription_limits.d.ts +15 -0
  36. package/dist/providers/subscription_limits.js +45 -0
  37. package/dist/runtime/explicit_model.js +16 -4
  38. package/dist/runtime/harness_identity/extract.js +20 -36
  39. package/dist/runtime/link_budget.d.ts +27 -0
  40. package/dist/runtime/link_budget.js +62 -0
  41. package/dist/runtime/link_grant_access.d.ts +7 -0
  42. package/dist/runtime/link_grant_access.js +99 -0
  43. package/dist/runtime/link_in_flight.d.ts +4 -0
  44. package/dist/runtime/link_in_flight.js +43 -0
  45. package/dist/runtime/prepare_routed_completion.js +5 -1
  46. package/dist/runtime/routed_runtime.js +8 -0
  47. package/dist/runtime/runtime_reporter.d.ts +1 -0
  48. package/dist/runtime/runtime_reporter.js +1 -0
  49. package/dist/self_host/config.d.ts +9 -0
  50. package/dist/self_host/config.js +11 -1
  51. package/dist/self_host/link_store.d.ts +167 -0
  52. package/dist/self_host/link_store.js +564 -0
  53. package/dist/self_host/main.d.ts +10 -3
  54. package/dist/self_host/main.js +19 -4
  55. package/dist/self_host/platform.d.ts +2 -2
  56. package/dist/self_host/platform.js +284 -10
  57. package/dist/self_host/resolve.d.ts +8 -0
  58. package/dist/self_host/resolve.js +146 -15
  59. package/dist/self_host/secret_box.d.ts +23 -0
  60. package/dist/self_host/secret_box.js +105 -0
  61. package/dist/self_host/stub_gateway.d.ts +60 -0
  62. package/dist/self_host/stub_gateway.js +397 -0
  63. package/dist/self_host/stub_main.d.ts +2 -0
  64. package/dist/self_host/stub_main.js +69 -0
  65. package/dist/self_host/subscription_test_gateway.d.ts +12 -9
  66. package/dist/self_host/subscription_test_gateway.js +25 -91
  67. package/dist/self_host/subscriptions/access.d.ts +5 -0
  68. package/dist/self_host/subscriptions/access.js +5 -1
  69. package/dist/self_host/subscriptions/http.js +8 -1
  70. package/dist/self_host/subscriptions/index.d.ts +5 -2
  71. package/dist/self_host/subscriptions/index.js +5 -2
  72. package/dist/self_host/subscriptions/store.d.ts +41 -16
  73. package/dist/self_host/subscriptions/store.js +136 -32
  74. package/dist/self_host/subscriptions/usage.d.ts +7 -0
  75. package/dist/self_host/subscriptions/usage.js +52 -0
  76. package/dist/telemetry/report.js +18 -0
  77. package/dist/types.d.ts +18 -0
  78. package/package.json +4 -3
  79. package/src/context/provider_prompt_accounting.ts +7 -0
  80. package/src/context/routing_context.ts +3 -1
  81. package/src/http/handler.ts +14 -2
  82. package/src/ingress/anthropic_messages.ts +19 -4
  83. package/src/ingress/chat_completions.ts +6 -1
  84. package/src/ingress/codex.ts +2 -2
  85. package/src/ingress/link.ts +1731 -0
  86. package/src/ingress/link_assets.ts +56 -0
  87. package/src/ingress/link_font.ts +9 -0
  88. package/src/ingress/models.ts +48 -2
  89. package/src/interaction/types.ts +4 -0
  90. package/src/link_client.ts +796 -0
  91. package/src/models/gateways.ts +3 -0
  92. package/src/models/link_errors.ts +157 -0
  93. package/src/models/subscriptions.ts +15 -1
  94. package/src/platform/platform.ts +330 -1
  95. package/src/protocol/input/router_model.ts +36 -1
  96. package/src/providers/execution.ts +31 -4
  97. package/src/providers/pi_options.ts +57 -1
  98. package/src/providers/provider_call.ts +20 -2
  99. package/src/providers/response_capture.ts +88 -2
  100. package/src/providers/stream_finalization.ts +1 -0
  101. package/src/providers/subscription_limits.ts +53 -0
  102. package/src/runtime/explicit_model.ts +21 -8
  103. package/src/runtime/harness_identity/extract.ts +21 -60
  104. package/src/runtime/link_budget.ts +75 -0
  105. package/src/runtime/link_grant_access.ts +116 -0
  106. package/src/runtime/link_in_flight.ts +46 -0
  107. package/src/runtime/prepare_routed_completion.ts +6 -1
  108. package/src/runtime/routed_runtime.ts +8 -0
  109. package/src/runtime/runtime_reporter.ts +3 -0
  110. package/src/self_host/config.ts +24 -1
  111. package/src/self_host/link_store.ts +782 -0
  112. package/src/self_host/main.ts +21 -4
  113. package/src/self_host/platform.ts +305 -11
  114. package/src/self_host/resolve.ts +172 -15
  115. package/src/self_host/secret_box.ts +112 -0
  116. package/src/self_host/stub_gateway.ts +497 -0
  117. package/src/self_host/stub_main.ts +72 -0
  118. package/src/self_host/subscription_test_gateway.ts +26 -95
  119. package/src/self_host/subscriptions/access.ts +10 -1
  120. package/src/self_host/subscriptions/http.ts +9 -1
  121. package/src/self_host/subscriptions/index.ts +6 -0
  122. package/src/self_host/subscriptions/store.ts +167 -36
  123. package/src/self_host/subscriptions/usage.ts +64 -0
  124. package/src/telemetry/report.ts +17 -1
  125. package/src/types.ts +26 -0
  126. package/dist/self_host/subscriptions/test_support.d.ts +0 -15
  127. package/dist/self_host/subscriptions/test_support.js +0 -34
@@ -0,0 +1,120 @@
1
+ /* The errors a Dari Link token gets, each with its own code so an app can
2
+ tell its user what to do.
3
+
4
+ 401, the token itself is dead:
5
+ - `link_token_expired`: refresh the access token (or mint a new child
6
+ token) and retry.
7
+ - `grant_revoked`: the grant is gone; `revoked_by` says who ended it
8
+ (`user`, `app`, or `reuse_detected`) and `revoked_at` when. The user must
9
+ link again.
10
+
11
+ 424, the grant's subscriptions cannot serve the request:
12
+ - `subscription_exhausted`: the plans that can serve this client are at
13
+ their usage limits; `resets_at` (and Retry-After) says when the first one
14
+ is back, when that is known.
15
+ - `grant_budget_exhausted`: the grant used the most tokens the user
16
+ allowed it in a window (per five hours or per week); `resets_at` (and
17
+ Retry-After) says when enough of the window rolls off to serve again.
18
+ - `subscription_client_mismatch`: the granted plans serve only another
19
+ client (a Claude Code plan serves only Claude Code itself); the user must
20
+ grant a plan that serves any app, such as a ChatGPT plan.
21
+ - `model_not_granted`: no granted plan serves the model the request named,
22
+ or any model the router lists. */
23
+ import { providerForModel } from "@mupt-ai/dari-router/policy-engine";
24
+ import { HttpError } from "../http/errors.js";
25
+ export const LINK_GRANT_ERROR_CODES = [
26
+ "subscription_exhausted",
27
+ "grant_budget_exhausted",
28
+ "subscription_client_mismatch",
29
+ "model_not_granted",
30
+ ];
31
+ export const LINK_TOKEN_ERROR_CODES = ["link_token_expired", "grant_revoked"];
32
+ /** Who ended a grant. */
33
+ export const LINK_REVOKERS = ["user", "app", "reuse_detected"];
34
+ export const SUBSCRIPTION_PLAN_LABELS = {
35
+ anthropic_claude_code: "Claude Pro/Max/Ultra",
36
+ openai_codex: "ChatGPT Plus/Pro",
37
+ meta_muse: "Meta Muse",
38
+ opencode_go: "OpenCode Go",
39
+ };
40
+ const ONLY_CLIENT = {
41
+ anthropic_claude_code: "Claude Code itself",
42
+ meta_muse: "Muse Code itself",
43
+ };
44
+ export function linkTokenExpired() {
45
+ return new HttpError(401, "This Dari Link token expired. Refresh it and retry.", "link_token_expired");
46
+ }
47
+ export function linkGrantRevoked(revokedBy, revokedAt) {
48
+ const who = revokedBy === "user"
49
+ ? "The user revoked this Dari Link grant."
50
+ : revokedBy === "app"
51
+ ? "The app revoked this Dari Link grant."
52
+ : revokedBy === "reuse_detected"
53
+ ? "This Dari Link grant was revoked because a rotated refresh token was used again."
54
+ : "This Dari Link grant was revoked.";
55
+ return new HttpError(401, `${who} The user must link again.`, "grant_revoked", undefined, undefined, {
56
+ ...(revokedBy === null ? {} : { revoked_by: revokedBy }),
57
+ ...(revokedAt === null ? {} : { revoked_at: revokedAt }),
58
+ });
59
+ }
60
+ /** The granted plans for a provider are all at their usage limits. */
61
+ export function plansExhausted(plans, resetsAt) {
62
+ const until = resetsAt === null ? "" : ` The first is back at ${resetsAt.toISOString()}.`;
63
+ return {
64
+ code: "subscription_exhausted",
65
+ message: `The ${names(plans)} subscriptions this Dari Link grant may use are at their usage limits.${until}`,
66
+ resets_at: resetsAt?.toISOString() ?? null,
67
+ };
68
+ }
69
+ /** The grant used the most tokens the user allowed it in a window. */
70
+ export function budgetExhausted(resetsAt) {
71
+ return {
72
+ code: "grant_budget_exhausted",
73
+ message: `This Dari Link grant used the most tokens the user allowed this app. It is back at ${resetsAt.toISOString()}.`,
74
+ resets_at: resetsAt.toISOString(),
75
+ };
76
+ }
77
+ /** The granted plans for a provider serve only another client. */
78
+ export function plansForAnotherClient(plans) {
79
+ const only = [...new Set(plans.map((plan) => `${SUBSCRIPTION_PLAN_LABELS[plan]} plans serve only ${ONLY_CLIENT[plan] ?? "their own client"}`))];
80
+ return {
81
+ code: "subscription_client_mismatch",
82
+ message: `This Dari Link grant cannot serve this client: ${only.join("; ")}. Ask the user to grant a plan that serves any app, such as a ChatGPT plan.`,
83
+ };
84
+ }
85
+ /**
86
+ * Why a grant serves nothing at all: its plans are at their limits, serve
87
+ * only another client, or serve no model.
88
+ */
89
+ export function linkGrantUnavailableError(unavailable) {
90
+ const entries = Object.values(unavailable);
91
+ const cause = entries.find((entry) => entry.code === "subscription_exhausted")
92
+ ?? entries.find((entry) => entry.code === "subscription_client_mismatch");
93
+ if (cause !== undefined)
94
+ return linkUnavailableError(cause);
95
+ return linkGrantError("model_not_granted", "No subscription this Dari Link grant may use serves a model. GET /v1/link/grant shows the grant's plans and models.");
96
+ }
97
+ /**
98
+ * Why a grant cannot serve one model: its plan is at its limit or serves only
99
+ * another client, or no granted plan serves the model at all.
100
+ */
101
+ export function modelNotServed(credentials, modelId) {
102
+ const cause = credentials.link_unavailable?.[modelId] ?? credentials.link_unavailable?.[providerForModel(modelId)];
103
+ return cause === undefined ? modelNotGranted(modelId) : linkUnavailableError(cause);
104
+ }
105
+ export function modelNotGranted(modelId) {
106
+ return linkGrantError("model_not_granted", `Model '${modelId}' is not available on this Dari Link grant. GET /v1/link/grant lists the models it can use.`);
107
+ }
108
+ export function linkUnavailableError(cause) {
109
+ const resetsAt = typeof cause.resets_at === "string" ? new Date(cause.resets_at) : null;
110
+ return linkGrantError(cause.code, cause.message, resetsAt !== null && !Number.isNaN(resetsAt.getTime()) ? resetsAt : null);
111
+ }
112
+ export function linkGrantError(code, message, resetsAt = null) {
113
+ if (resetsAt === null)
114
+ return new HttpError(424, message, code);
115
+ const retryAfter = Math.max(1, Math.ceil((resetsAt.getTime() - Date.now()) / 1000));
116
+ return new HttpError(424, message, code, undefined, { "Retry-After": String(retryAfter) }, { resets_at: resetsAt.toISOString() });
117
+ }
118
+ function names(plans) {
119
+ return [...new Set(plans.map((plan) => SUBSCRIPTION_PLAN_LABELS[plan]))].join(" and ");
120
+ }
@@ -1,9 +1,16 @@
1
1
  import { type RouterModelPrice } from "@mupt-ai/dari-router/policy-engine";
2
2
  import type { ClientHarness, ResolvedRouterModelConfig, SubscriptionKind } from "../types.js";
3
+ /** The model provider whose models a plan serves, such as `openai`. */
4
+ export declare function subscriptionModelProvider(kind: SubscriptionKind): string;
5
+ /**
6
+ * The only client a plan may serve, or undefined when it serves any client:
7
+ * ChatGPT plans serve any client through the Codex backend.
8
+ */
9
+ export declare function subscriptionClient(kind: SubscriptionKind): ClientHarness | undefined;
3
10
  /**
4
11
  * Whether a plan may serve a model executed by `provider` for this client:
5
12
  * each plan serves only its own provider's models, and only to the client its
6
13
  * provider allows.
7
14
  */
8
15
  export declare function subscriptionServes(kind: SubscriptionKind, provider: string, clientHarness: ClientHarness | undefined): boolean;
9
- export declare function codexModelConfig(modelId: string, price: RouterModelPrice | null): ResolvedRouterModelConfig;
16
+ export declare function codexModelConfig(modelId: string, price: RouterModelPrice | null, baseUrl?: string): ResolvedRouterModelConfig;
@@ -15,6 +15,17 @@ const SUBSCRIPTION_CLIENTS = {
15
15
  anthropic_claude_code: "claude_code",
16
16
  meta_muse: "muse_code",
17
17
  };
18
+ /** The model provider whose models a plan serves, such as `openai`. */
19
+ export function subscriptionModelProvider(kind) {
20
+ return SUBSCRIPTION_MODEL_PROVIDERS[kind][0];
21
+ }
22
+ /**
23
+ * The only client a plan may serve, or undefined when it serves any client:
24
+ * ChatGPT plans serve any client through the Codex backend.
25
+ */
26
+ export function subscriptionClient(kind) {
27
+ return SUBSCRIPTION_CLIENTS[kind];
28
+ }
18
29
  /**
19
30
  * Whether a plan may serve a model executed by `provider` for this client:
20
31
  * each plan serves only its own provider's models, and only to the client its
@@ -28,12 +39,12 @@ export function subscriptionServes(kind, provider, clientHarness) {
28
39
  }
29
40
  // A ChatGPT plan serves OpenAI models as the `openai-codex` provider through
30
41
  // the Codex backend.
31
- export function codexModelConfig(modelId, price) {
42
+ export function codexModelConfig(modelId, price, baseUrl = CODEX_BACKEND_URL) {
32
43
  return {
33
44
  provider: "openai-codex",
34
45
  native_model_id: nativeModelId(modelId),
35
46
  api: "openai-codex-responses",
36
- base_url: CODEX_BACKEND_URL,
47
+ base_url: baseUrl,
37
48
  // A plan bills no tokens; the catalog price only feeds cost estimates.
38
49
  cost: price ?? { input: 0, output: 0 },
39
50
  fast_mode: false,
@@ -2,7 +2,7 @@ import type { Provider, ReasoningEffort, RoutingStrategy } from "@mupt-ai/dari-r
2
2
  import type { HarnessConversationIdentity } from "../runtime/harness_identity/index.js";
3
3
  import type { InteractionRequest, SourceProtocol } from "../interaction/types.js";
4
4
  import type { SubscriptionUsage, SubscriptionUsageLimit } from "../providers/subscription_limits.js";
5
- import type { ClientHarness, ProviderCredential, ProviderKeySource, ResolvedRouter } from "../types.js";
5
+ import type { ClientHarness, ProviderCredential, ProviderKeySource, ResolvedRouter, SubscriptionKind } from "../types.js";
6
6
  /**
7
7
  * Everything the gateway runtime needs from the deployment around it: router
8
8
  * configuration and credentials, durable routing state, accounting sinks, and
@@ -73,6 +73,302 @@ export type GatewayPlatform = {
73
73
  recordRequest(record: RequestRecord): void;
74
74
  captureRequestError(error: unknown, context: RequestErrorContext): void;
75
75
  captureOperationalError(error: unknown, context: OperationalErrorContext): void;
76
+ /**
77
+ * Optional. Dari Link: OAuth grants that let a registered app send one
78
+ * user's requests through the gateway on the subscriptions the user chose,
79
+ * and nothing else. Without it the `/v1/link/...` endpoints answer 404.
80
+ */
81
+ link?: LinkPlatform;
82
+ };
83
+ /**
84
+ * Dari Link storage and authorization. The gateway serves the OAuth protocol
85
+ * (authorization code with PKCE S256) and validates its parameters; the
86
+ * platform authenticates users and clients, stores apps and grants, and
87
+ * issues tokens.
88
+ *
89
+ * Methods throw HttpError(401) for a key that cannot act, HttpError(401,
90
+ * `invalid_client`) for a confidential client without its secret, and
91
+ * HttpError(400) with code `invalid_grant`, `refresh_race`, `invalid_client`,
92
+ * or `invalid_request` for a request the protocol refuses.
93
+ *
94
+ * A link token is a gateway key for `resolveRouter`: the platform serves it
95
+ * the default router on only the grant's subscriptions, never an API key or
96
+ * credits, and sets `link_grant_id` and `link_models`. It fails the request
97
+ * with 424 `subscription_exhausted` (and `resets_at`),
98
+ * `subscription_client_mismatch`, or `model_not_granted` when no granted plan
99
+ * can serve, and with 401 `link_token_expired` or `grant_revoked` (and
100
+ * `revoked_by`) for a dead token. A revoked grant's tokens stop at once.
101
+ */
102
+ export type LinkPlatform = {
103
+ /**
104
+ * How a user approves a grant. A platform with its own signed-in web app
105
+ * names its consent page, and the gateway sends the authorization request
106
+ * there; otherwise the gateway serves the approval page itself.
107
+ */
108
+ approval: LinkConsentPage | LinkApprovalPage;
109
+ /**
110
+ * Hosts, besides loopback, an app may register an http (not https) redirect
111
+ * URI on: exact names, or `*.suffix` for any subdomain. For private dev hosts
112
+ * on a self-hosted gateway; absent or empty allows none.
113
+ */
114
+ httpRedirectHosts?: readonly string[];
115
+ /**
116
+ * Register an app. With `apiKey`, as that user; without, as an open dynamic
117
+ * registration (RFC 7591), which the gateway rate-limits. A confidential
118
+ * app gets a client secret, returned this once.
119
+ */
120
+ registerApp(request: {
121
+ apiKey?: string;
122
+ name: string;
123
+ redirectUris: string[];
124
+ confidential?: boolean;
125
+ }): Promise<LinkApp & {
126
+ clientSecret?: string;
127
+ }>;
128
+ /** The registered app, or null for an unknown client id. */
129
+ app(clientId: string): Promise<LinkApp | null>;
130
+ /** Redeem a code once for the grant's first tokens. */
131
+ exchangeCode(request: LinkCodeExchange): Promise<LinkTokens>;
132
+ /**
133
+ * A new access token. A public client's refresh token rotates: the one
134
+ * presented stops working, presenting it again within a minute is refused
135
+ * with `refresh_race`, and later reuse revokes the grant. A confidential
136
+ * client keeps its refresh token.
137
+ */
138
+ refresh(request: LinkClient & {
139
+ refreshToken: string;
140
+ }): Promise<LinkTokens>;
141
+ /**
142
+ * Trade a grant's access token for a child token (RFC 8693) that serves only
143
+ * its models, cannot refresh, mint, or read the grant, and dies with the grant.
144
+ */
145
+ exchangeToken(request: LinkTokenExchange): Promise<LinkChildToken>;
146
+ /**
147
+ * The live grant an access token belongs to. Throws the 401 a dead token
148
+ * gets, and 403 for a child token.
149
+ */
150
+ grant(accessToken: string): Promise<LinkGrantDetail>;
151
+ /**
152
+ * What a grant's requests used, by every token of it (child tokens
153
+ * included), filtered to requests carrying every given tag and received in
154
+ * the time range. Authenticates like `grant`: a child token gets 403.
155
+ */
156
+ usage(request: LinkUsageQuery): Promise<LinkUsage>;
157
+ /**
158
+ * Revoke the grant a token (access, refresh, or child) belongs to when it
159
+ * is the client's (RFC 7009). Unknown tokens are ignored.
160
+ */
161
+ revokeToken(request: LinkClient & {
162
+ token: string;
163
+ }): Promise<void>;
164
+ /** The user's grants that are not revoked. */
165
+ grants(apiKey: string): Promise<LinkGrant[]>;
166
+ /** Revoke one of the user's grants; false when it has none by that id. */
167
+ revokeGrant(request: {
168
+ apiKey: string;
169
+ grantId: string;
170
+ }): Promise<boolean>;
171
+ /**
172
+ * Replace one of the user's grants' budget (empty removes it); false when
173
+ * the user has no grant by that id.
174
+ */
175
+ setBudget(request: {
176
+ apiKey: string;
177
+ grantId: string;
178
+ budget: LinkBudget[];
179
+ }): Promise<boolean>;
180
+ };
181
+ /**
182
+ * A consent page the platform serves to its signed-in users. The gateway
183
+ * validates the authorization request and redirects to `consentUrl` with the
184
+ * request's query; the page creates the grant and returns the code to the app.
185
+ */
186
+ export type LinkConsentPage = {
187
+ consentUrl: string;
188
+ connectedAppsUrl: string;
189
+ };
190
+ /**
191
+ * What the gateway's own approval page needs from the platform. The page
192
+ * needs no account: a user connects a plan by signing in to its provider, and
193
+ * the gateway remembers them in a signed cookie as an opaque subject, so their
194
+ * plans are there the next time an app asks.
195
+ */
196
+ export type LinkApprovalPage = {
197
+ /**
198
+ * The secret that signs the approval page's cookies. Throws
199
+ * HttpError(503, `link_not_configured`) when the platform has none.
200
+ */
201
+ sessionSecret(): string;
202
+ /** The kinds of plan a user can connect on the page, in the order offered. */
203
+ connectable: readonly SubscriptionKind[];
204
+ /** The providers and gateways a user can add an API key for, in the order offered. */
205
+ keyProviders: readonly LinkKeyProvider[];
206
+ /**
207
+ * Add the user's API key for one of `keyProviders`, replacing their earlier
208
+ * key for it. Throws HttpError(400) for a key the provider refuses.
209
+ */
210
+ addKey(subject: string, provider: string, apiKey: string): Promise<{
211
+ credentialId: string;
212
+ }>;
213
+ /** The plans this user connected and the API keys they added, which an approval chooses among. */
214
+ subscriptions(subject: string): Promise<LinkSubscription[]>;
215
+ /** Start the provider's sign-in for a plan of this kind. */
216
+ startConnect(subject: string, kind: SubscriptionKind): Promise<LinkConnect>;
217
+ /**
218
+ * Finish a sign-in `startConnect` began: with the code the provider showed
219
+ * the user, or for a provider that shows the user a code to enter, with
220
+ * nothing. Null while the provider still waits on the user. Throws
221
+ * HttpError(400) for a code the provider refuses or a sign-in that ended.
222
+ */
223
+ completeConnect(subject: string, session: string, authorizationResponse: string): Promise<{
224
+ credentialId: string;
225
+ } | null>;
226
+ /**
227
+ * Forget one of the user's plans or API keys: its stored tokens or key are
228
+ * deleted, every app loses it, and a grant left with nothing is revoked.
229
+ * False when the user has none by that id.
230
+ */
231
+ remove(subject: string, credentialId: string): Promise<boolean>;
232
+ /**
233
+ * One of the user's live grants for this app, which an update request edits
234
+ * in place; null when the user has none by that id.
235
+ */
236
+ grant(subject: string, grantId: string, clientId: string): Promise<Pick<LinkGrant, "credentialIds" | "budget"> | null>;
237
+ /** Create a grant on the chosen subscriptions and return its one-time code. */
238
+ approve(request: LinkApproval): Promise<{
239
+ code: string;
240
+ }>;
241
+ };
242
+ /** A model provider or gateway whose API key a user can add on the approval page. */
243
+ export type LinkKeyProvider = {
244
+ id: string;
245
+ name: string;
246
+ };
247
+ /** A provider sign-in under way on the approval page. */
248
+ export type LinkConnect = {
249
+ session: string;
250
+ authorizationUrl: string;
251
+ userCode: string | null;
252
+ };
253
+ /**
254
+ * The most tokens a grant's app may use in a rolling window, across all of
255
+ * the grant's plans and API keys. See runtime/link_budget.ts for how tokens
256
+ * are counted.
257
+ */
258
+ export type LinkBudget = {
259
+ windowMinutes: number;
260
+ maxTokens: number;
261
+ };
262
+ /** A budget window as it stands for a grant. */
263
+ export type LinkBudgetStanding = {
264
+ windowMinutes: number;
265
+ maxTokens: number;
266
+ usedTokens: number;
267
+ resetsAt: string | null;
268
+ };
269
+ /** A client as it authenticates at the token and revocation endpoints. */
270
+ export type LinkClient = {
271
+ clientId: string;
272
+ clientSecret?: string;
273
+ };
274
+ export type LinkApp = {
275
+ clientId: string;
276
+ name: string;
277
+ redirectUris: string[];
278
+ confidential: boolean;
279
+ };
280
+ /** One quota window of a plan: its length, share used (0 to 1), and reset. */
281
+ export type LinkUsageWindow = {
282
+ minutes: number;
283
+ utilization: number;
284
+ resetsAt: string;
285
+ };
286
+ export type LinkSubscription = {
287
+ id: string;
288
+ provider: string;
289
+ apiKeyProvider?: string;
290
+ name: string;
291
+ label: string | null;
292
+ accountEmail: string | null;
293
+ unavailableUntil: string | null;
294
+ usage: LinkUsageWindow[];
295
+ };
296
+ export type LinkApproval = {
297
+ subject: string;
298
+ grantId?: string;
299
+ clientId: string;
300
+ redirectUri: string;
301
+ codeChallenge: string;
302
+ credentialIds: string[];
303
+ budget: LinkBudget[];
304
+ };
305
+ export type LinkCodeExchange = LinkClient & {
306
+ code: string;
307
+ redirectUri: string;
308
+ codeChallenge: string;
309
+ };
310
+ export type LinkTokens = {
311
+ accessToken: string;
312
+ refreshToken: string;
313
+ expiresIn: number;
314
+ };
315
+ export type LinkTokenExchange = LinkClient & {
316
+ subjectToken: string;
317
+ models: Array<{
318
+ model: string;
319
+ thinking?: string;
320
+ }>;
321
+ expiresIn: number;
322
+ tags: Record<string, string>;
323
+ };
324
+ export type LinkChildToken = {
325
+ accessToken: string;
326
+ expiresIn: number;
327
+ grantId: string;
328
+ };
329
+ export type LinkGrant = {
330
+ id: string;
331
+ clientId: string;
332
+ appName: string;
333
+ credentialIds: string[];
334
+ createdAt: string;
335
+ budget: LinkBudget[];
336
+ };
337
+ /** A grant as its app sees it: the granted subscriptions themselves. */
338
+ export type LinkUsageQuery = {
339
+ accessToken: string;
340
+ tags: Record<string, string>;
341
+ since?: Date;
342
+ until?: Date;
343
+ groupByTag?: string;
344
+ requestId?: string;
345
+ };
346
+ /** Token counts in one shape for every protocol: input excludes cache reads and writes. */
347
+ export type LinkUsageTotals = {
348
+ requests: number;
349
+ errors: number;
350
+ inputTokens: number;
351
+ outputTokens: number;
352
+ cacheReadTokens: number;
353
+ cacheWriteTokens: number;
354
+ };
355
+ export type LinkUsage = LinkUsageTotals & {
356
+ byModel: Array<LinkUsageTotals & {
357
+ model: string;
358
+ thinking: string | null;
359
+ }>;
360
+ byTag?: Array<LinkUsageTotals & {
361
+ value: string | null;
362
+ }>;
363
+ completeThrough: string | null;
364
+ };
365
+ export type LinkGrantDetail = Omit<LinkGrant, "credentialIds" | "budget"> & {
366
+ budget: LinkBudgetStanding[];
367
+ subscriptions: LinkSubscription[];
368
+ user: {
369
+ email: string | null;
370
+ name: string | null;
371
+ } | null;
76
372
  };
77
373
  export type ResolveRouterRequest = {
78
374
  routerId: string;
@@ -123,11 +419,13 @@ export type SubscriptionHold = {
123
419
  userId: string;
124
420
  credentialId: string | undefined;
125
421
  limit: SubscriptionUsageLimit;
422
+ linkGrantId?: string;
126
423
  };
127
424
  export type NextSubscriptionRequest = {
128
425
  userId: string;
129
426
  provider: Provider;
130
427
  conversationId: string;
428
+ linkGrantId?: string;
131
429
  };
132
430
  export type NextSubscription = {
133
431
  credentialId: string;
@@ -147,6 +445,10 @@ export type RequestRecord = {
147
445
  zdr: boolean;
148
446
  harnessConversationIdentity?: HarnessConversationIdentity;
149
447
  tags: RequestTags;
448
+ link?: {
449
+ grantId: string;
450
+ thinking: string | null;
451
+ };
150
452
  router: RequestRecordRouter;
151
453
  candidates: Array<{
152
454
  model: string;
@@ -4,4 +4,8 @@ export declare function isAnthropicRouterModel(model: string): boolean;
4
4
  export declare const EXPLICIT_MODEL_PREFIX = "dari/model/";
5
5
  export declare function explicitModelId(model: string | undefined): string | null;
6
6
  export declare function explicitModelSlug(modelId: string): string;
7
+ export declare const LINK_ACCESS_TOKEN_PREFIX = "dlk_at_";
8
+ export declare const LINK_CHILD_TOKEN_PREFIX = "dlk_ct_";
9
+ export declare function isLinkToken(token: string): boolean;
10
+ export declare function linkTokenModel<T>(token: string, model: T): T | string;
7
11
  export declare function unsupportedModelMessage(): string;
@@ -24,6 +24,8 @@ const ANTHROPIC_MODEL_ID_PATTERN = /^(anthropic\/)?claude-[a-z0-9][a-z0-9.-]*$/i
24
24
  export function isAnthropicRouterModel(model) {
25
25
  return ANTHROPIC_ROUTER_MODELS.has(model) || ANTHROPIC_MODEL_ID_PATTERN.test(model);
26
26
  }
27
+ // The name the Claude app lists routing under; it names no model.
28
+ const CLAUDE_APP_ROUTER_MODEL = "claude-dari-routing";
27
29
  /* An explicit model, `dari/model/<catalog id>`, serves exactly that enabled
28
30
  model without selection, so a client's model picker can switch models. It
29
31
  is a separate namespace so the synonyms above, which Claude Code subagents
@@ -38,7 +40,35 @@ export function explicitModelId(model) {
38
40
  export function explicitModelSlug(modelId) {
39
41
  return EXPLICIT_MODEL_PREFIX + modelId;
40
42
  }
41
- const UNSUPPORTED_MODEL_MESSAGE = `Only model '${CANONICAL_ROUTER_MODEL}' or '${EXPLICIT_MODEL_PREFIX}<model>' is supported.`;
43
+ // A Dari Link token's access and child tokens, which every platform issues.
44
+ export const LINK_ACCESS_TOKEN_PREFIX = "dlk_at_";
45
+ export const LINK_CHILD_TOKEN_PREFIX = "dlk_ct_";
46
+ export function isLinkToken(token) {
47
+ return token.startsWith(LINK_ACCESS_TOKEN_PREFIX) || token.startsWith(LINK_CHILD_TOKEN_PREFIX);
48
+ }
49
+ /* A Dari Link token is served exactly the model it names, so every name but
50
+ the router's own (`dari/routing`, the Anthropic tier names, the Claude app's
51
+ routing name) names a catalog model: `gpt-5.5`, `claude-sonnet-5-5`,
52
+ `anthropic/claude-sonnet-5-5`, or a dated snapshot such as
53
+ `claude-haiku-4-5-20251001`. It is taken as `dari/model/<name>`, which the
54
+ grant resolves to the catalog model it serves, so an app forwarding Claude
55
+ Code or Codex traffic needs no model map, and the client's thinking settings
56
+ for that model are kept. Any other key is unchanged. */
57
+ export function linkTokenModel(token, model) {
58
+ if (!isLinkToken(token) || typeof model !== "string" || model.length === 0)
59
+ return model;
60
+ if (model === CANONICAL_ROUTER_MODEL
61
+ || model.toLowerCase() === CLAUDE_APP_ROUTER_MODEL
62
+ || explicitModelId(model) !== null
63
+ || ANTHROPIC_ROUTER_MODEL_TIERS.includes(model)) {
64
+ return model;
65
+ }
66
+ return explicitModelSlug(model);
67
+ }
68
+ // Bare catalog ids such as `gpt-5.5` are not model names here: name one as
69
+ // `dari/model/<provider>/<model>`, which GET /v1/models lists.
70
+ const UNSUPPORTED_MODEL_MESSAGE = `Only model '${CANONICAL_ROUTER_MODEL}' or '${EXPLICIT_MODEL_PREFIX}<model>' is supported.`
71
+ + ` Name a catalog model as '${EXPLICIT_MODEL_PREFIX}<provider>/<model>', such as '${EXPLICIT_MODEL_PREFIX}openai/gpt-5.5'; GET /v1/models lists them.`;
42
72
  export function unsupportedModelMessage() {
43
73
  return UNSUPPORTED_MODEL_MESSAGE;
44
74
  }
@@ -13,7 +13,7 @@ import { estimatedCancelUsage, NO_DELIVERED_OUTPUT, observeDeliveredOutput, } fr
13
13
  import { providerResponseCaptureFromError } from "./response_capture.js";
14
14
  import { createStreamFinalizer } from "./stream_finalization.js";
15
15
  import { readCodexModelLimitReset, readCodexUsage } from "./codex_usage.js";
16
- import { detectSubscriptionUsageLimit, codexUsageLimitError, subscriptionOAuthProviderFor, subscriptionUsageFromHeaders, failureWithSubscriptionUsageLimit, retryAfterSeconds, subscriptionUsageLimitFromFailure, subscriptionSwitchedMessage, subscriptionUsageLimitMessage, } from "./subscription_limits.js";
16
+ import { detectSubscriptionUsageLimit, codexUsageLimitError, subscriptionOAuthProviderFor, subscriptionUsageFromHeaders, museSubscriptionUsage, failureWithSubscriptionUsageLimit, retryAfterSeconds, subscriptionUsageLimitFromFailure, subscriptionSwitchedMessage, subscriptionUsageLimitMessage, } from "./subscription_limits.js";
17
17
  export async function executeNonStreaming(args) {
18
18
  const result = await completeNonStreaming(args);
19
19
  if (result.reportBarrierError !== undefined) {
@@ -24,9 +24,25 @@ export async function executeNonStreaming(args) {
24
24
  });
25
25
  }
26
26
  return Response.json(result.responseBody, {
27
- headers: result.choice.execution.headers,
27
+ headers: { ...result.choice.execution.headers, ...linkUsageHeaders(result) },
28
28
  });
29
29
  }
30
+ // One usage shape for a Dari Link app whatever protocol it speaks: the tokens
31
+ // a response used, with `input_tokens` excluding cache reads and writes. A
32
+ // stream carries its usage in the protocol's own final event instead.
33
+ function linkUsageHeaders(result) {
34
+ if (!result.choice.execution.subscriptionLinkGrantId)
35
+ return {};
36
+ const usage = result.output.usage;
37
+ return {
38
+ "X-Dari-Usage": JSON.stringify({
39
+ input_tokens: usage.input,
40
+ output_tokens: usage.output,
41
+ cache_read_tokens: usage.cacheRead,
42
+ cache_write_tokens: usage.cacheWrite,
43
+ }),
44
+ };
45
+ }
30
46
  export async function completeNonStreaming(args) {
31
47
  const result = await completeWithRetries(args);
32
48
  args.reporter.attachServingDecision(result.choice.decision);
@@ -454,6 +470,7 @@ async function providerFailedAttempt(message, latencyMs, execution, responseCapt
454
470
  userId: execution.subscriptionUserId,
455
471
  credentialId: execution.subscriptionCredentialId,
456
472
  limit,
473
+ ...(execution.subscriptionLinkGrantId ? { linkGrantId: execution.subscriptionLinkGrantId } : {}),
457
474
  });
458
475
  // Nothing reached the client yet, so the same request is retried on the
459
476
  // next plan at once when the platform names it. The same plan still serves
@@ -560,6 +577,7 @@ async function nextSubscriptionFor(execution) {
560
577
  userId: execution.subscriptionUserId,
561
578
  provider: execution.provider,
562
579
  conversationId: execution.conversationId,
580
+ ...(execution.subscriptionLinkGrantId ? { linkGrantId: execution.subscriptionLinkGrantId } : {}),
563
581
  });
564
582
  }
565
583
  catch (error) {
@@ -594,18 +612,26 @@ function noteSubscriptionUsage(execution, responseCapture) {
594
612
  const fromHeaders = headers === undefined
595
613
  ? null
596
614
  : subscriptionUsageFromHeaders(execution.provider, execution.providerKeySource, headers);
615
+ const oauthProvider = subscriptionOAuthProviderFor(execution.provider, execution.providerKeySource);
597
616
  // Codex's WebSocket transport carries no headers; its usage report does.
617
+ // Muse Code's usage is the last event of its stream.
598
618
  const usage = fromHeaders !== null
599
619
  ? Promise.resolve(fromHeaders)
600
- : subscriptionOAuthProviderFor(execution.provider, execution.providerKeySource) === "openai_codex"
620
+ : oauthProvider === "openai_codex"
601
621
  ? readCodexUsage({
602
622
  credentialId,
603
623
  accessToken: execution.apiKey,
604
624
  baseUrl: execution.endpoint?.baseUrl ?? execution.config?.base_url ?? undefined,
605
625
  })
606
- : Promise.resolve(null);
626
+ : oauthProvider === "meta_muse" && responseCapture !== undefined
627
+ ? responseCapture.streamedSubscriptionUsage.then((snapshot) => museSubscriptionUsage(snapshot, new Date()))
628
+ : Promise.resolve(null);
607
629
  usage
608
- .then((reported) => reported === null ? undefined : record({ userId, credentialId, usage: reported }))
630
+ .then((reported) => reported === null ? undefined : record({
631
+ userId,
632
+ credentialId,
633
+ usage: reported,
634
+ }))
609
635
  .catch((error) => {
610
636
  console.error("subscription usage record failed", error);
611
637
  captureOperationalError(error, { code: "subscription_usage_record_failed" });