@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
@@ -64,7 +64,11 @@ export function buildOptions(request, auth, selectedModel, model, pi, sessionId,
64
64
  }
65
65
  if (isAnthropic(api)) {
66
66
  const budgetTokens = request.reasoning?.budgetTokens;
67
- if (request.reasoning?.enabled === false) {
67
+ const clientReasoning = request.reasoning;
68
+ if (clientReasoning?.clientOnly === true && clientReasoning.effort === undefined) {
69
+ patches.push((payload) => payloadWithClientThinking(payload, clientReasoning));
70
+ }
71
+ else if (request.reasoning?.enabled === false) {
68
72
  patches.push((payload) => ({ ...payload, thinking: { type: "disabled" } }));
69
73
  }
70
74
  else if (budgetTokens !== undefined) {
@@ -144,6 +148,9 @@ export function buildOptions(request, auth, selectedModel, model, pi, sessionId,
144
148
  else if (reasoning === "off" && isCompletions(api) && offRequiresWireNone(selectedModel)) {
145
149
  patches.push((payload) => payloadWithReasoningNone(payload, model));
146
150
  }
151
+ if (reasoning === undefined && request.reasoning?.clientOnly === true && (isOpenAI(api) || isOpenAIResponsesApi(api))) {
152
+ patches.push(payloadWithoutReasoningEffort);
153
+ }
147
154
  if (isOpenAIResponsesApi(api))
148
155
  patches.push(payloadWithDetailedReasoningSummary);
149
156
  // Some clients send the default tool_choice even after omitting tools for
@@ -166,6 +173,16 @@ export function supportedThinkingLevels(model, pi) {
166
173
  }
167
174
  function providerReasoning(request, selectedModel, model, pi, selectedReasoningEffort) {
168
175
  const supportedLevels = supportedThinkingLevels(model, pi);
176
+ if (request.reasoning?.clientOnly === true) {
177
+ // The client's own settings, with no level chosen for it: an unnamed
178
+ // effort stays unsent and the provider's default applies.
179
+ const { effort, baseEffort, hasConfigurationUpdate } = request.reasoning;
180
+ for (const named of [effort, baseEffort]) {
181
+ if (named !== undefined)
182
+ validateReasoningEffortForModel(named, selectedModel, supportedLevels);
183
+ }
184
+ return hasConfigurationUpdate ? baseEffort : effort;
185
+ }
169
186
  const defaultReasoningEffort = isReasoningEffort(model.defaultThinkingLevel) ? model.defaultThinkingLevel : undefined;
170
187
  const effective = effectiveReasoningForModel({
171
188
  request,
@@ -273,6 +290,45 @@ function payloadWithReasoningNone(payload, model) {
273
290
  const { reasoning_effort: _, ...rest } = payload;
274
291
  return { ...rest, reasoning: { ...asRecord(payload.reasoning), effort: "none" } };
275
292
  }
293
+ // The client's own Anthropic thinking and nothing chosen for it: its budget,
294
+ // adaptive thinking or disabled thinking when it asked for that, or no
295
+ // thinking field at all, and never an effort it did not name, top-level or
296
+ // in per-turn effort messages.
297
+ function payloadWithClientThinking(payload, reasoning) {
298
+ const { thinking: chosen, output_config: outputConfig, ...rest } = payload;
299
+ const { effort: _, ...config } = asRecord(outputConfig);
300
+ const { budget_tokens: __, ...display } = asRecord(chosen);
301
+ const thinking = reasoning.budgetTokens !== undefined
302
+ ? { ...display, type: "enabled", budget_tokens: reasoning.budgetTokens }
303
+ : reasoning.enabled === true
304
+ ? { ...display, type: "adaptive" }
305
+ : reasoning.enabled === false
306
+ ? { type: "disabled" }
307
+ : undefined;
308
+ // Pi marks each turn's effort in system messages on per-turn-effort models,
309
+ // at a level of its own when none is named; the client named none.
310
+ const messages = Array.isArray(rest.messages)
311
+ ? { messages: rest.messages.filter((message) => !isEffortMarker(message)) }
312
+ : {};
313
+ return {
314
+ ...rest,
315
+ ...messages,
316
+ ...(Object.keys(config).length === 0 ? {} : { output_config: config }),
317
+ ...(thinking === undefined ? {} : { thinking }),
318
+ };
319
+ }
320
+ function isEffortMarker(message) {
321
+ return isRecord(message) && message.role === "system" && isRecord(message.output_config);
322
+ }
323
+ // Pi names an effort of its own when it is given none. A client that named
324
+ // none is served the provider's default, so the effort is left unsent.
325
+ function payloadWithoutReasoningEffort(payload) {
326
+ const { reasoning_effort: _, reasoning, ...rest } = payload;
327
+ if (!isRecord(reasoning))
328
+ return rest;
329
+ const { effort: __, ...kept } = reasoning;
330
+ return Object.keys(kept).length === 0 ? rest : { ...rest, reasoning: kept };
331
+ }
276
332
  // Pi's default "auto" summary leaves many reasoning items empty (93% on the
277
333
  // ChatGPT Codex backend). Readable summaries are the only reasoning a later
278
334
  // turn on another provider can replay, so ask for detailed ones.
@@ -20,11 +20,14 @@ type ProviderCallConfig = {
20
20
  endpoint?: ProviderEndpoint;
21
21
  systemPromptSuffix?: string;
22
22
  };
23
+ export type ClientThinking = "default" | "off" | `budget:${number}`;
23
24
  export type ProviderExecution = ProviderCallConfig & {
24
25
  provider: Provider;
25
26
  providerKeySource: ProviderKeySource;
26
27
  subscriptionUserId?: string;
27
28
  subscriptionCredentialId?: string;
29
+ subscriptionLinkGrantId?: string;
30
+ thinkingLevel: string;
28
31
  usageContext: RoutingUsageContext | undefined;
29
32
  headers: Record<string, string>;
30
33
  };
@@ -56,6 +59,7 @@ export declare function prepareProviderExecution(args: {
56
59
  costEstimates?: readonly CandidateCostEstimate[];
57
60
  tags?: RequestTags;
58
61
  systemPromptSuffix?: string;
62
+ clientThinking?: ClientThinking;
59
63
  }): ProviderExecution;
60
64
  export declare function startProviderCompletion(args: {
61
65
  interaction: InteractionRequest;
@@ -8,6 +8,7 @@ import { scrubSecretValues } from "../telemetry/scrub.js";
8
8
  import { usageContextFor, } from "../telemetry/usage.js";
9
9
  import { awsRoleCredentials } from "./aws_assume_role.js";
10
10
  import { attachProviderResponseCapture, createProviderResponseCapture, } from "./response_capture.js";
11
+ import { subscriptionOAuthProviderFor } from "./subscription_limits.js";
11
12
  import { completeInteractionModel, streamInteractionModel, } from "./pi.js";
12
13
  import { promptTokenEstimateFor } from "./cancel_estimate.js";
13
14
  import { withSystemPromptSuffix } from "../interaction/system_prompt.js";
@@ -19,6 +20,7 @@ export function prepareProviderExecution(args) {
19
20
  throw new HttpError(400, "The prompt exceeds this model's standard-price context range. Shorten or compact the conversation.", "context_length_exceeded");
20
21
  }
21
22
  const provider = executionProviderForModel(args.credentials, model);
23
+ const thinkingLevel = args.clientThinking ?? args.decision.reasoningEffort;
22
24
  const supplied = args.credentials.provider_credentials?.[model];
23
25
  const providerKeySource = keySourceForModel(args.credentials, model);
24
26
  // A strict router serves a plan only when the platform supplied it for this
@@ -57,8 +59,10 @@ export function prepareProviderExecution(args) {
57
59
  ? {
58
60
  subscriptionUserId: args.credentials.attributed_user_id,
59
61
  subscriptionCredentialId: args.credentials.subscription_credential_ids?.[provider],
62
+ ...(args.credentials.link_grant_id ? { subscriptionLinkGrantId: args.credentials.link_grant_id } : {}),
60
63
  }
61
64
  : {}),
65
+ thinkingLevel,
62
66
  usageContext: usageContextFor({
63
67
  billable: args.billable,
64
68
  credentials: args.credentials,
@@ -69,7 +73,7 @@ export function prepareProviderExecution(args) {
69
73
  }),
70
74
  headers: {
71
75
  "X-Dari-Selected-Model": model,
72
- "X-Dari-Thinking-Level": args.decision.reasoningEffort,
76
+ "X-Dari-Thinking-Level": thinkingLevel,
73
77
  "X-Dari-Provider-Key-Source": providerKeySource,
74
78
  "X-Dari-Conversation-Id": args.conversationId,
75
79
  ...(args.decision.leaseTurnsRemaining === undefined
@@ -99,9 +103,12 @@ export function startProviderCompletion(args) {
99
103
  function responseCaptureFor(execution) {
100
104
  // A subscription's failures carry its usage limit; a customer key's say
101
105
  // whether the provider refused the key itself.
106
+ // Muse Code reports its plan's usage as the stream's last event.
102
107
  return execution.providerKeySource === "managed"
103
108
  ? undefined
104
- : createProviderResponseCapture();
109
+ : createProviderResponseCapture({
110
+ watchSubscriptionUsage: subscriptionOAuthProviderFor(execution.provider, execution.providerKeySource) === "meta_muse",
111
+ });
105
112
  }
106
113
  export async function startProviderStream(args) {
107
114
  const providerStartedMs = Date.now();
@@ -8,6 +8,7 @@ export type ProviderResponseCapture = {
8
8
  fetch: ProviderFetch;
9
9
  last: CapturedProviderResponse | undefined;
10
10
  succeeded: Headers | undefined;
11
+ streamedSubscriptionUsage: Promise<unknown>;
11
12
  };
12
13
  /**
13
14
  * A fetch wrapper that remembers the last failed provider response, and the
@@ -16,7 +17,9 @@ export type ProviderResponseCapture = {
16
17
  * runtime, so this is the only place the status, rate-limit headers, and
17
18
  * structured error body of a rejected call can still be read.
18
19
  */
19
- export declare function createProviderResponseCapture(): ProviderResponseCapture;
20
+ export declare function createProviderResponseCapture(options?: {
21
+ watchSubscriptionUsage?: boolean;
22
+ }): ProviderResponseCapture;
20
23
  /**
21
24
  * A provider call that throws before returning a stream loses its capture with
22
25
  * the started state, so the error carries it to the attempt runner instead.
@@ -1,3 +1,5 @@
1
+ const SUBSCRIPTION_USAGE_EVENT = "response.subscription_usage";
2
+ const MAX_SCANNED_LINE = 64 * 1024;
1
3
  const CAPTURED_BODY_MAX_BYTES = 64 * 1024;
2
4
  /**
3
5
  * A fetch wrapper that remembers the last failed provider response, and the
@@ -6,15 +8,23 @@ const CAPTURED_BODY_MAX_BYTES = 64 * 1024;
6
8
  * runtime, so this is the only place the status, rate-limit headers, and
7
9
  * structured error body of a rejected call can still be read.
8
10
  */
9
- export function createProviderResponseCapture() {
11
+ export function createProviderResponseCapture(options = {}) {
10
12
  const capture = {
11
13
  last: undefined,
12
14
  succeeded: undefined,
15
+ streamedSubscriptionUsage: Promise.resolve(null),
13
16
  fetch: async (input, init) => {
14
17
  const response = await globalThis.fetch(input, init);
15
18
  if (response.ok) {
16
19
  capture.succeeded = response.headers;
17
- return response;
20
+ if (options.watchSubscriptionUsage !== true
21
+ || response.body === null
22
+ || !response.headers.get("content-type")?.includes("text/event-stream")) {
23
+ return response;
24
+ }
25
+ const watched = watchSubscriptionUsage(response.body);
26
+ capture.streamedSubscriptionUsage = watched.usage;
27
+ return new Response(watched.body, response);
18
28
  }
19
29
  const bodyText = await readBodyPrefix(response.clone());
20
30
  capture.last = { status: response.status, headers: response.headers, bodyText };
@@ -23,6 +33,75 @@ export function createProviderResponseCapture() {
23
33
  };
24
34
  return capture;
25
35
  }
36
+ /**
37
+ * Passes a server-sent event stream through unchanged while watching for its
38
+ * subscription usage event. The usage resolves when the stream ends or is
39
+ * cancelled.
40
+ */
41
+ function watchSubscriptionUsage(source) {
42
+ let found = null;
43
+ let settle = () => undefined;
44
+ const usage = new Promise((resolve) => { settle = resolve; });
45
+ const decoder = new TextDecoder();
46
+ const reader = source.getReader();
47
+ // The usage event is small; a longer line (an image, a large output item)
48
+ // is skipped rather than buffered.
49
+ let line = "";
50
+ let skipping = false;
51
+ const take = (complete) => {
52
+ if (!complete.startsWith("data:") || !complete.includes(SUBSCRIPTION_USAGE_EVENT))
53
+ return;
54
+ try {
55
+ const event = JSON.parse(complete.slice(5));
56
+ if (event.type === SUBSCRIPTION_USAGE_EVENT)
57
+ found = event.subscription ?? null;
58
+ }
59
+ catch {
60
+ // Not this event; the stream itself is the client's to parse.
61
+ }
62
+ };
63
+ const scan = (text) => {
64
+ const pieces = text.split("\n");
65
+ for (let index = 0; index < pieces.length; index += 1) {
66
+ if (!skipping)
67
+ line += pieces[index];
68
+ if (line.length > MAX_SCANNED_LINE) {
69
+ line = "";
70
+ skipping = true;
71
+ }
72
+ if (index < pieces.length - 1) {
73
+ if (!skipping)
74
+ take(line.trimEnd());
75
+ line = "";
76
+ skipping = false;
77
+ }
78
+ }
79
+ };
80
+ const body = new ReadableStream({
81
+ async pull(controller) {
82
+ try {
83
+ const { done, value } = await reader.read();
84
+ if (done) {
85
+ scan(decoder.decode() + "\n");
86
+ settle(found);
87
+ controller.close();
88
+ return;
89
+ }
90
+ scan(decoder.decode(value, { stream: true }));
91
+ controller.enqueue(value);
92
+ }
93
+ catch (error) {
94
+ settle(found);
95
+ controller.error(error);
96
+ }
97
+ },
98
+ async cancel(reason) {
99
+ settle(found);
100
+ await reader.cancel(reason);
101
+ },
102
+ });
103
+ return { body, usage };
104
+ }
26
105
  async function readBodyPrefix(response) {
27
106
  try {
28
107
  const text = await response.text();
@@ -10,6 +10,7 @@ type StreamExecutionFacts = {
10
10
  provider: string;
11
11
  model: string;
12
12
  providerKeySource: ProviderKeySource;
13
+ thinkingLevel?: string;
13
14
  conversationId: string;
14
15
  usageContext: RoutingUsageContext | undefined;
15
16
  pricing: ModelPricing | null;
@@ -37,6 +37,21 @@ export declare function subscriptionUsageFromWindows(raw: Array<{
37
37
  * reports none: the most used of the plan's windows.
38
38
  */
39
39
  export declare function subscriptionUsageFromHeaders(provider: string, keySource: ProviderKeySource, headers: Headers, now?: Date): SubscriptionUsage | null;
40
+ /**
41
+ * The plan usage a Muse Code stream reports as its last event,
42
+ * `response.subscription_usage`: `{window: {used_percent, resets_at,
43
+ * window_duration_mins}, weekly: {used_percent, resets_at}, tier}`, the
44
+ * current five hour block and the rolling week, resets in unix seconds and
45
+ * percent that may exceed 100.
46
+ */
47
+ export declare function museSubscriptionUsage(snapshot: unknown, now: Date): SubscriptionUsage | null;
48
+ /**
49
+ * The usage OpenCode Go reports at `GET /zen/go/v1/usage`, which OpenCode's
50
+ * own `/usage` reads: `{usage: {rolling|weekly|monthly: {status: "ok" |
51
+ * "rate-limited", percent, resetsAt}}}`, percent out of 100. A window Go
52
+ * refuses on is at its limit whatever it rounds to.
53
+ */
54
+ export declare function openCodeGoUsageFromReport(report: unknown, now: Date): SubscriptionUsage | null;
40
55
  export declare const DEFAULT_USAGE_LIMIT_WINDOW_MS: number;
41
56
  export declare function subscriptionOAuthProviderFor(provider: string, keySource: ProviderKeySource): SubscriptionOAuthProvider | null;
42
57
  /**
@@ -46,6 +46,51 @@ export function subscriptionUsageFromHeaders(provider, keySource, headers, now =
46
46
  : [];
47
47
  return subscriptionUsageFromWindows(windows, now);
48
48
  }
49
+ /**
50
+ * The plan usage a Muse Code stream reports as its last event,
51
+ * `response.subscription_usage`: `{window: {used_percent, resets_at,
52
+ * window_duration_mins}, weekly: {used_percent, resets_at}, tier}`, the
53
+ * current five hour block and the rolling week, resets in unix seconds and
54
+ * percent that may exceed 100.
55
+ */
56
+ export function museSubscriptionUsage(snapshot, now) {
57
+ if (!isRecord(snapshot))
58
+ return null;
59
+ const number = (value) => typeof value === "number" && Number.isFinite(value) ? value : NaN;
60
+ return subscriptionUsageFromWindows([["window", FIVE_HOURS], ["weekly", ONE_WEEK]].map(([name, minutes]) => {
61
+ const raw = snapshot[name];
62
+ const window = isRecord(raw) ? raw : {};
63
+ const resetsAt = number(window.resets_at);
64
+ return {
65
+ minutes: number(window.window_duration_mins) > 0 ? Math.round(number(window.window_duration_mins)) : minutes,
66
+ used: number(window.used_percent) / 100,
67
+ resetsAt: Number.isNaN(resetsAt) ? null : new Date(resetsAt * 1000),
68
+ };
69
+ }), now);
70
+ }
71
+ // OpenCode Go's windows by their usage report names; the monthly one follows
72
+ // the billing cycle.
73
+ const OPENCODE_GO_USAGE_WINDOWS = [["rolling", FIVE_HOURS], ["weekly", ONE_WEEK], ["monthly", 30 * 24 * 60]];
74
+ /**
75
+ * The usage OpenCode Go reports at `GET /zen/go/v1/usage`, which OpenCode's
76
+ * own `/usage` reads: `{usage: {rolling|weekly|monthly: {status: "ok" |
77
+ * "rate-limited", percent, resetsAt}}}`, percent out of 100. A window Go
78
+ * refuses on is at its limit whatever it rounds to.
79
+ */
80
+ export function openCodeGoUsageFromReport(report, now) {
81
+ const usage = isRecord(report) && isRecord(report.usage) ? report.usage : {};
82
+ return subscriptionUsageFromWindows(OPENCODE_GO_USAGE_WINDOWS.map(([name, minutes]) => {
83
+ const raw = usage[name];
84
+ const meter = isRecord(raw) ? raw : {};
85
+ const percent = typeof meter.percent === "number" ? meter.percent / 100 : NaN;
86
+ const resetsAt = typeof meter.resetsAt === "string" ? new Date(meter.resetsAt) : null;
87
+ return {
88
+ minutes,
89
+ used: meter.status === "rate-limited" && Number.isFinite(percent) ? 1 : percent,
90
+ resetsAt: resetsAt === null || Number.isNaN(resetsAt.getTime()) ? null : resetsAt,
91
+ };
92
+ }), now);
93
+ }
49
94
  // Neither provider guarantees a reset time on every usage-limit response.
50
95
  // Without one, hold the subscription out for an hour rather than hammering an
51
96
  // exhausted plan on every request.
@@ -1,4 +1,5 @@
1
1
  import { HttpError } from "../http/errors.js";
2
+ import { modelNotServed } from "../models/link_errors.js";
2
3
  import { explicitModelId } from "../protocol/input/router_model.js";
3
4
  /* A request for `dari/model/<id>` is served by exactly that enabled model,
4
5
  with no selector or lease: the user chose it, like picking a
@@ -6,18 +7,26 @@ import { explicitModelId } from "../protocol/input/router_model.js";
6
7
  request's agent role. Routing rules and switch-cost pruning narrow only
7
8
  what the selector may pick, so they never remove it. The client's thinking
8
9
  level is kept when the model supports it; otherwise the model's default
9
- level is used. */
10
+ level is used. A Dari Link token's level is never replaced: it is served
11
+ exactly or the request is refused. */
10
12
  export function explicitModelDecision(prepared) {
11
13
  const modelId = explicitModelId(prepared.interaction.model);
12
14
  if (modelId === null)
13
15
  return null;
14
- if (!prepared.credentials.enabled_models.includes(modelId))
15
- throw modelNotEnabled(modelId);
16
+ if (!prepared.credentials.enabled_models.includes(modelId)) {
17
+ throw prepared.credentials.link_grant_id
18
+ ? modelNotServed(prepared.credentials, modelId)
19
+ : modelNotEnabled(modelId);
20
+ }
16
21
  const candidates = prepared.routing.candidateResolution.allCandidates.filter((candidate) => candidate.model === modelId);
17
22
  if (candidates.length === 0) {
18
23
  throw new HttpError(400, `Model '${modelId}' cannot serve this request.`, "model_unavailable", "model");
19
24
  }
20
25
  const candidate = pickCandidate(prepared, modelId, candidates);
26
+ // A Dari Link token's named level is served exactly or refused.
27
+ const named = prepared.interaction.reasoning?.clientOnly === true ? prepared.interaction.reasoning.effort : undefined;
28
+ if (named !== undefined && candidate.reasoningEffort !== named)
29
+ throw thinkingLevelUnavailable(modelId, named);
21
30
  const decision = {
22
31
  selectedModel: candidate.model,
23
32
  reasoningEffort: candidate.reasoningEffort,
@@ -50,10 +59,13 @@ export function strictModelDecision(prepared) {
50
59
  const requested = prepared.interaction.reasoning?.effort
51
60
  ?? prepared.credentials.model_configs?.[modelId]?.default_thinking_level;
52
61
  if (requested !== undefined && requested !== null && decision.reasoningEffort !== requested) {
53
- throw new HttpError(400, `Model '${modelId}' cannot serve thinking level '${requested}' on this router.`, "thinking_level_unavailable", "reasoning_effort");
62
+ throw thinkingLevelUnavailable(modelId, requested);
54
63
  }
55
64
  return { decision };
56
65
  }
66
+ function thinkingLevelUnavailable(modelId, requested) {
67
+ return new HttpError(400, `Model '${modelId}' cannot serve thinking level '${requested}' on this router.`, "thinking_level_unavailable", "reasoning_effort");
68
+ }
57
69
  export function modelNotEnabled(modelId) {
58
70
  return new HttpError(400, `Model '${modelId}' is not enabled on this router.`, "model_not_enabled", "model");
59
71
  }
@@ -63,32 +63,20 @@ export function codexConversationIdentity(headers, payload) {
63
63
  if (turnMetadata.length === 0) {
64
64
  return undefined;
65
65
  }
66
- const candidates = [
67
- ...turnMetadata.map((metadata) => uuidIdentity(metadata.thread_id, "x-codex-turn-metadata.thread_id")),
68
- uuidIdentity(headers.get("thread-id"), "thread-id"),
69
- uuidIdentity(clientMetadata?.thread_id, "client_metadata.thread_id"),
70
- ].filter((value) => value !== undefined);
71
- if (candidates.length === 0) {
66
+ // Clients can carry a stale projection after a resume or fork. Conflicts
67
+ // must not fail the request, and fields must not mix across projections:
68
+ // take thread, turn, and parent from one turn metadata projection, header
69
+ // first, falling back to the standalone thread fields only for the thread.
70
+ const entry = turnMetadata.find((metadata) => metadata.thread_id !== undefined)
71
+ ?? turnMetadata[0];
72
+ const threadId = uuidIdentity(entry.thread_id, "x-codex-turn-metadata.thread_id")
73
+ ?? uuidIdentity(headers.get("thread-id"), "thread-id")
74
+ ?? uuidIdentity(clientMetadata?.thread_id, "client_metadata.thread_id");
75
+ if (threadId === undefined) {
72
76
  return undefined;
73
77
  }
74
- const [threadId] = candidates;
75
- if (candidates.some((candidate) => candidate !== threadId)) {
76
- throw new HttpError(400, "Codex thread identity fields must agree.", "invalid_request_error", "thread-id");
77
- }
78
- const userTurnIds = turnMetadata
79
- .map((metadata) => uuidIdentity(metadata.turn_id, "x-codex-turn-metadata.turn_id"))
80
- .filter((value) => value !== undefined);
81
- const [userTurnId] = userTurnIds;
82
- if (userTurnIds.some((candidate) => candidate !== userTurnId)) {
83
- throw new HttpError(400, "Codex turn identity fields must agree.", "invalid_request_error", "x-codex-turn-metadata.turn_id");
84
- }
85
- const parentThreadIds = turnMetadata
86
- .map((metadata) => uuidIdentity(metadata.parent_thread_id, "x-codex-turn-metadata.parent_thread_id"))
87
- .filter((value) => value !== undefined);
88
- const [parentThreadId] = parentThreadIds;
89
- if (parentThreadIds.some((candidate) => candidate !== parentThreadId)) {
90
- throw new HttpError(400, "Codex parent thread identity fields must agree.", "invalid_request_error", "x-codex-turn-metadata.parent_thread_id");
91
- }
78
+ const userTurnId = uuidIdentity(entry.turn_id, "x-codex-turn-metadata.turn_id");
79
+ const parentThreadId = uuidIdentity(entry.parent_thread_id, "x-codex-turn-metadata.parent_thread_id");
92
80
  return {
93
81
  kind: "codex_thread",
94
82
  value: threadId,
@@ -106,15 +94,12 @@ export function codexRequestContext(headers, payload) {
106
94
  const metadata = codexTurnMetadataCollection(headers, payload);
107
95
  if (metadata.length === 0)
108
96
  return undefined;
109
- // HTTP and body projections must agree before either can classify a turn.
110
- const kinds = new Set(metadata.map((entry) => entry.request_kind));
111
- const agents = new Set(metadata.map((entry) => entry.subagent_kind));
112
- if (kinds.size > 1 || agents.size > 1) {
113
- throw new HttpError(400, "Codex request classification fields must agree.", "invalid_request_error", "x-codex-turn-metadata");
114
- }
115
- const [kind] = kinds;
116
- const [agentKind] = agents;
117
- const entry = metadata[0];
97
+ // Classify from one projection, header first, skipping one that omits the
98
+ // request kind so a partial header falls back to a complete body.
99
+ const entry = metadata.find((candidate) => candidate.request_kind !== undefined)
100
+ ?? metadata[0];
101
+ const kind = entry.request_kind;
102
+ const agentKind = entry.subagent_kind;
118
103
  const agentId = uuidIdentity(entry.thread_id, "x-codex-turn-metadata.thread_id");
119
104
  const requestClass = kind === "compaction" ? "compaction"
120
105
  : kind === "memory" || kind === "prewarm" ? "auxiliary"
@@ -143,10 +128,9 @@ export function claudeCodeConversationIdentity(headers, metadataSessionId) {
143
128
  ].filter((value) => value !== undefined);
144
129
  if (candidates.length === 0)
145
130
  return undefined;
131
+ // Claude Code can carry a stale metadata session after a resume or fork.
132
+ // The header names the live session, so it wins over the metadata.
146
133
  const [sessionId] = candidates;
147
- if (candidates.some((candidate) => candidate !== sessionId)) {
148
- throw new HttpError(400, "Claude Code session identity fields must agree.", "invalid_request_error", "x-claude-code-session-id");
149
- }
150
134
  // Claude Code reuses the parent session UUID for every subagent, but gives
151
135
  // each subagent a stable agent header. Keep the parent thread on the bare
152
136
  // session identity and scope each subagent to its own composite identity.
@@ -0,0 +1,27 @@
1
+ import type { LinkBudget } from "../platform/platform.js";
2
+ /** The windows a budget can cap: five hours and one week. */
3
+ export declare const LINK_BUDGET_WINDOW_MINUTES: readonly [300, 10080];
4
+ /** Tokens one of a grant's requests used, and when it was received. */
5
+ export type BudgetUse = {
6
+ at: Date;
7
+ tokens: number;
8
+ };
9
+ /** A budget window as it stands for a grant; `resetsAt` is set only at the cap. */
10
+ export type BudgetStanding = {
11
+ windowMinutes: number;
12
+ maxTokens: number;
13
+ usedTokens: number;
14
+ resetsAt: Date | null;
15
+ };
16
+ /** Each budget window as it stands, from the grant's uses. */
17
+ export declare function budgetStandings(budget: readonly LinkBudget[], uses: readonly BudgetUse[], now: Date): BudgetStanding[];
18
+ /** Undefined while the grant is within its budget; otherwise when it is back. */
19
+ export declare function overBudgetUntil(standings: readonly BudgetStanding[]): Date | undefined;
20
+ /** How far back a budget's windows reach, in milliseconds; 0 for none. */
21
+ export declare function budgetLookbackMs(budget: readonly LinkBudget[]): number;
22
+ /** A budget from a request: five-hour and weekly windows, each a positive whole token cap. */
23
+ export declare function validBudget(value: unknown): LinkBudget[] | null;
24
+ export declare function budgetBody(budget: readonly LinkBudget[]): {
25
+ window_minutes: number;
26
+ max_tokens: number;
27
+ }[];
@@ -0,0 +1,62 @@
1
+ /* A Dari Link grant's budget: the most tokens its app may use in each rolling
2
+ window, across all of the grant's plans and API keys together.
3
+
4
+ A grant's tokens are what Dari recorded for its requests (child tokens
5
+ included): input + output + cache read + cache write, the same total the
6
+ Connected Apps page shows. A window's used tokens are those of requests
7
+ received in its last `windowMinutes`. Each request is checked before it is
8
+ served, so one in flight may take a window past its cap.
9
+
10
+ A window at its cap is back once enough of its oldest requests roll off to
11
+ bring it under the cap again: `resetsAt` is when that happens. */
12
+ /** The windows a budget can cap: five hours and one week. */
13
+ export const LINK_BUDGET_WINDOW_MINUTES = [300, 10080];
14
+ /** Each budget window as it stands, from the grant's uses. */
15
+ export function budgetStandings(budget, uses, now) {
16
+ return budget.map((entry) => {
17
+ const windowMs = entry.windowMinutes * 60_000;
18
+ const live = uses
19
+ .filter((use) => use.at.getTime() > now.getTime() - windowMs)
20
+ .sort((a, b) => a.at.getTime() - b.at.getTime());
21
+ const usedTokens = live.reduce((sum, use) => sum + use.tokens, 0);
22
+ let resetsAt = null;
23
+ let remaining = usedTokens;
24
+ for (const use of live) {
25
+ if (remaining < entry.maxTokens)
26
+ break;
27
+ remaining -= use.tokens;
28
+ resetsAt = new Date(use.at.getTime() + windowMs);
29
+ }
30
+ return { windowMinutes: entry.windowMinutes, maxTokens: entry.maxTokens, usedTokens, resetsAt };
31
+ });
32
+ }
33
+ /** Undefined while the grant is within its budget; otherwise when it is back. */
34
+ export function overBudgetUntil(standings) {
35
+ const resets = standings.flatMap((standing) => standing.resetsAt === null ? [] : [standing.resetsAt.getTime()]);
36
+ return resets.length === 0 ? undefined : new Date(Math.max(...resets));
37
+ }
38
+ /** How far back a budget's windows reach, in milliseconds; 0 for none. */
39
+ export function budgetLookbackMs(budget) {
40
+ return Math.max(0, ...budget.map((entry) => entry.windowMinutes)) * 60_000;
41
+ }
42
+ /** A budget from a request: five-hour and weekly windows, each a positive whole token cap. */
43
+ export function validBudget(value) {
44
+ if (!Array.isArray(value))
45
+ return null;
46
+ const budget = [];
47
+ for (const entry of value) {
48
+ if (typeof entry !== "object" || entry === null)
49
+ return null;
50
+ const { window_minutes: minutes, max_tokens: tokens } = entry;
51
+ if (!LINK_BUDGET_WINDOW_MINUTES.includes(minutes)
52
+ || typeof tokens !== "number" || !Number.isSafeInteger(tokens) || tokens <= 0
53
+ || budget.some((other) => other.windowMinutes === minutes)) {
54
+ return null;
55
+ }
56
+ budget.push({ windowMinutes: minutes, maxTokens: tokens });
57
+ }
58
+ return budget.sort((a, b) => a.windowMinutes - b.windowMinutes);
59
+ }
60
+ export function budgetBody(budget) {
61
+ return budget.map((entry) => ({ window_minutes: entry.windowMinutes, max_tokens: entry.maxTokens }));
62
+ }
@@ -0,0 +1,7 @@
1
+ import type { InteractionRequest } from "../interaction/types.js";
2
+ import type { ResolvedRouter } from "../types.js";
3
+ export declare function linkGrantAccess(credentials: ResolvedRouter, interaction: InteractionRequest): {
4
+ credentials: ResolvedRouter;
5
+ interaction: InteractionRequest;
6
+ };
7
+ export declare function catalogModelFor(name: string, models: readonly string[]): string | null;