@mupt-ai/dari-gateway 1.0.312 → 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 (113) hide show
  1. package/README.md +279 -2
  2. package/dist/context/routing_context.js +4 -1
  3. package/dist/http/handler.d.ts +2 -1
  4. package/dist/http/handler.js +12 -2
  5. package/dist/ingress/anthropic_messages.js +15 -3
  6. package/dist/ingress/chat_completions.js +6 -1
  7. package/dist/ingress/codex.js +2 -2
  8. package/dist/ingress/link.d.ts +24 -0
  9. package/dist/ingress/link.js +1519 -0
  10. package/dist/ingress/link_assets.d.ts +14 -0
  11. package/dist/ingress/link_assets.js +49 -0
  12. package/dist/ingress/link_font.d.ts +1 -0
  13. package/dist/ingress/link_font.js +6 -0
  14. package/dist/ingress/models.js +46 -2
  15. package/dist/interaction/types.d.ts +1 -0
  16. package/dist/link_client.d.ts +386 -0
  17. package/dist/link_client.js +579 -0
  18. package/dist/models/gateways.d.ts +2 -0
  19. package/dist/models/gateways.js +2 -0
  20. package/dist/models/link_errors.d.ts +30 -0
  21. package/dist/models/link_errors.js +120 -0
  22. package/dist/models/subscriptions.d.ts +8 -1
  23. package/dist/models/subscriptions.js +13 -2
  24. package/dist/platform/platform.d.ts +303 -1
  25. package/dist/protocol/input/router_model.d.ts +4 -0
  26. package/dist/protocol/input/router_model.js +31 -1
  27. package/dist/providers/execution.js +24 -2
  28. package/dist/providers/pi_options.js +57 -1
  29. package/dist/providers/provider_call.d.ts +4 -0
  30. package/dist/providers/provider_call.js +4 -1
  31. package/dist/providers/stream_finalization.d.ts +1 -0
  32. package/dist/runtime/explicit_model.js +16 -4
  33. package/dist/runtime/harness_identity/extract.js +20 -36
  34. package/dist/runtime/link_budget.d.ts +27 -0
  35. package/dist/runtime/link_budget.js +62 -0
  36. package/dist/runtime/link_grant_access.d.ts +7 -0
  37. package/dist/runtime/link_grant_access.js +99 -0
  38. package/dist/runtime/link_in_flight.d.ts +4 -0
  39. package/dist/runtime/link_in_flight.js +43 -0
  40. package/dist/runtime/prepare_routed_completion.js +5 -1
  41. package/dist/runtime/routed_runtime.js +8 -0
  42. package/dist/runtime/runtime_reporter.d.ts +1 -0
  43. package/dist/runtime/runtime_reporter.js +1 -0
  44. package/dist/self_host/config.d.ts +9 -0
  45. package/dist/self_host/config.js +11 -1
  46. package/dist/self_host/link_store.d.ts +167 -0
  47. package/dist/self_host/link_store.js +564 -0
  48. package/dist/self_host/main.d.ts +10 -3
  49. package/dist/self_host/main.js +19 -4
  50. package/dist/self_host/platform.d.ts +2 -2
  51. package/dist/self_host/platform.js +284 -10
  52. package/dist/self_host/resolve.d.ts +8 -0
  53. package/dist/self_host/resolve.js +146 -15
  54. package/dist/self_host/secret_box.d.ts +23 -0
  55. package/dist/self_host/secret_box.js +105 -0
  56. package/dist/self_host/stub_gateway.d.ts +60 -0
  57. package/dist/self_host/stub_gateway.js +397 -0
  58. package/dist/self_host/stub_main.d.ts +2 -0
  59. package/dist/self_host/stub_main.js +69 -0
  60. package/dist/self_host/subscription_test_gateway.d.ts +12 -9
  61. package/dist/self_host/subscription_test_gateway.js +25 -91
  62. package/dist/self_host/subscriptions/http.js +1 -0
  63. package/dist/self_host/subscriptions/index.d.ts +2 -2
  64. package/dist/self_host/subscriptions/index.js +2 -2
  65. package/dist/self_host/subscriptions/store.d.ts +41 -16
  66. package/dist/self_host/subscriptions/store.js +136 -32
  67. package/dist/telemetry/report.js +18 -0
  68. package/dist/types.d.ts +18 -0
  69. package/package.json +4 -3
  70. package/src/context/routing_context.ts +3 -1
  71. package/src/http/handler.ts +14 -2
  72. package/src/ingress/anthropic_messages.ts +19 -4
  73. package/src/ingress/chat_completions.ts +6 -1
  74. package/src/ingress/codex.ts +2 -2
  75. package/src/ingress/link.ts +1731 -0
  76. package/src/ingress/link_assets.ts +56 -0
  77. package/src/ingress/link_font.ts +9 -0
  78. package/src/ingress/models.ts +48 -2
  79. package/src/interaction/types.ts +4 -0
  80. package/src/link_client.ts +796 -0
  81. package/src/models/gateways.ts +3 -0
  82. package/src/models/link_errors.ts +157 -0
  83. package/src/models/subscriptions.ts +15 -1
  84. package/src/platform/platform.ts +330 -1
  85. package/src/protocol/input/router_model.ts +36 -1
  86. package/src/providers/execution.ts +24 -2
  87. package/src/providers/pi_options.ts +57 -1
  88. package/src/providers/provider_call.ts +15 -1
  89. package/src/providers/stream_finalization.ts +1 -0
  90. package/src/runtime/explicit_model.ts +21 -8
  91. package/src/runtime/harness_identity/extract.ts +21 -60
  92. package/src/runtime/link_budget.ts +75 -0
  93. package/src/runtime/link_grant_access.ts +116 -0
  94. package/src/runtime/link_in_flight.ts +46 -0
  95. package/src/runtime/prepare_routed_completion.ts +6 -1
  96. package/src/runtime/routed_runtime.ts +8 -0
  97. package/src/runtime/runtime_reporter.ts +3 -0
  98. package/src/self_host/config.ts +24 -1
  99. package/src/self_host/link_store.ts +782 -0
  100. package/src/self_host/main.ts +21 -4
  101. package/src/self_host/platform.ts +305 -11
  102. package/src/self_host/resolve.ts +172 -15
  103. package/src/self_host/secret_box.ts +112 -0
  104. package/src/self_host/stub_gateway.ts +497 -0
  105. package/src/self_host/stub_main.ts +72 -0
  106. package/src/self_host/subscription_test_gateway.ts +26 -95
  107. package/src/self_host/subscriptions/http.ts +1 -0
  108. package/src/self_host/subscriptions/index.ts +3 -0
  109. package/src/self_host/subscriptions/store.ts +167 -36
  110. package/src/telemetry/report.ts +17 -1
  111. package/src/types.ts +26 -0
  112. package/dist/self_host/subscriptions/test_support.d.ts +0 -15
  113. 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;
@@ -20,6 +20,7 @@ export function prepareProviderExecution(args) {
20
20
  throw new HttpError(400, "The prompt exceeds this model's standard-price context range. Shorten or compact the conversation.", "context_length_exceeded");
21
21
  }
22
22
  const provider = executionProviderForModel(args.credentials, model);
23
+ const thinkingLevel = args.clientThinking ?? args.decision.reasoningEffort;
23
24
  const supplied = args.credentials.provider_credentials?.[model];
24
25
  const providerKeySource = keySourceForModel(args.credentials, model);
25
26
  // A strict router serves a plan only when the platform supplied it for this
@@ -58,8 +59,10 @@ export function prepareProviderExecution(args) {
58
59
  ? {
59
60
  subscriptionUserId: args.credentials.attributed_user_id,
60
61
  subscriptionCredentialId: args.credentials.subscription_credential_ids?.[provider],
62
+ ...(args.credentials.link_grant_id ? { subscriptionLinkGrantId: args.credentials.link_grant_id } : {}),
61
63
  }
62
64
  : {}),
65
+ thinkingLevel,
63
66
  usageContext: usageContextFor({
64
67
  billable: args.billable,
65
68
  credentials: args.credentials,
@@ -70,7 +73,7 @@ export function prepareProviderExecution(args) {
70
73
  }),
71
74
  headers: {
72
75
  "X-Dari-Selected-Model": model,
73
- "X-Dari-Thinking-Level": args.decision.reasoningEffort,
76
+ "X-Dari-Thinking-Level": thinkingLevel,
74
77
  "X-Dari-Provider-Key-Source": providerKeySource,
75
78
  "X-Dari-Conversation-Id": args.conversationId,
76
79
  ...(args.decision.leaseTurnsRemaining === undefined
@@ -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;
@@ -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;
@@ -0,0 +1,99 @@
1
+ import { linkGrantError, modelNotServed } from "../models/link_errors.js";
2
+ import { CANONICAL_MODELS } from "../models/canonical.js";
3
+ import { explicitModelId, explicitModelSlug } from "../protocol/input/router_model.js";
4
+ import { modelMetadataLookup } from "../providers/pi.js";
5
+ /* A Dari Link token is served exactly what its request names, never a
6
+ substitute. `dari/routing` chooses among the router's models the grant
7
+ serves. A named model (`dari/model/<id>`; the ingress names every other
8
+ model a link token asks for this way, see `linkTokenModel`) is the catalog
9
+ model it names, by its full id, its bare id, or a dated snapshot of it. It
10
+ is served as that model when a granted plan serves it, at any level the
11
+ model supports, with the client's own thinking settings and no level chosen
12
+ for it; otherwise the request fails with the reason. A grant with an API
13
+ key for a gateway (OpenRouter, Vercel AI Gateway) is also served any model
14
+ of that gateway by its full id, `openrouter/<id>`, which no catalog lists. A
15
+ child token serves only its models, each at its pinned thinking level when
16
+ it has one. */
17
+ export function linkGrantAccess(credentials, interaction) {
18
+ if (!credentials.link_grant_id)
19
+ return { credentials, interaction };
20
+ const pins = credentials.link_pins ?? null;
21
+ const name = explicitModelId(interaction.model);
22
+ // The grant's own models first; a catalog model it does not serve still
23
+ // names the reason it cannot.
24
+ // A gateway's model is named by its full id, which starts with the gateway.
25
+ const gateway = name?.toLowerCase().split("/")[0];
26
+ const viaGateway = gateway !== undefined && credentials.link_key_gateways !== undefined && Object.hasOwn(credentials.link_key_gateways, gateway);
27
+ const named = name === null
28
+ ? null
29
+ : catalogModelFor(name, credentials.link_models ?? [])
30
+ ?? catalogModelFor(name, CANONICAL_MODELS.map((model) => model.id))
31
+ ?? (viaGateway ? name.toLowerCase() : null);
32
+ if (name !== null && named === null) {
33
+ throw linkGrantError("model_not_granted", `Model '${name}' is not a catalog model this Dari Link grant can use. GET /v1/link/grant lists them.`);
34
+ }
35
+ const pin = pins === null ? null : pins.find((candidate) => candidate.model === named) ?? null;
36
+ if (pins !== null && pin === null) {
37
+ throw linkGrantError("model_not_granted", `This Dari Link child token serves only ${pins.map((candidate) => `'${explicitModelSlug(candidate.model)}'`).join(", ")}.`);
38
+ }
39
+ if (named === null) {
40
+ if (credentials.enabled_models.length > 0)
41
+ return { credentials, interaction };
42
+ throw linkGrantError("model_not_granted", "No subscription this Dari Link grant may use serves a model its router lists. Name one of the grant's models as 'dari/model/<id>'; GET /v1/link/grant lists them.");
43
+ }
44
+ if (!credentials.link_models?.includes(named) && !viaGateway)
45
+ throw modelNotServed(credentials, named);
46
+ // The router's own choice of thinking levels narrows only what it routes.
47
+ const { [named]: _routed, ...thinkingLevels } = credentials.model_thinking_levels ?? {};
48
+ const endpoint = viaGateway ? credentials.link_key_gateways[gateway] : null;
49
+ return {
50
+ credentials: {
51
+ ...credentials,
52
+ enabled_models: [...new Set([...credentials.enabled_models, named])],
53
+ model_thinking_levels: thinkingLevels,
54
+ // A gateway the platform points elsewhere is called there.
55
+ ...(endpoint == null
56
+ ? {}
57
+ : {
58
+ model_configs: {
59
+ ...credentials.model_configs,
60
+ [named]: { provider: gateway, native_model_id: named.slice(gateway.length + 1), ...endpoint, cost: { input: 0, output: 0 } },
61
+ },
62
+ }),
63
+ },
64
+ interaction: {
65
+ ...interaction,
66
+ model: explicitModelSlug(named),
67
+ reasoning: pin?.thinking
68
+ ? { effort: pin.thinking, enabled: pin.thinking !== "off", clientOnly: true }
69
+ : clientReasoning(credentials, named, interaction.reasoning),
70
+ },
71
+ };
72
+ }
73
+ // The client's own thinking settings. Anthropic takes `thinking: disabled` on
74
+ // every model, so a model with no "off" level is still served it exactly
75
+ // rather than refused.
76
+ function clientReasoning(credentials, model, reasoning) {
77
+ if (reasoning?.enabled === false && reasoning.effort === "off") {
78
+ const metadata = modelMetadataLookup(credentials.model_configs)(model);
79
+ if (metadata.model.api === "anthropic-messages" && !metadata.supportedThinkingLevels.includes("off")) {
80
+ return { enabled: false, clientOnly: true };
81
+ }
82
+ }
83
+ return { ...reasoning, clientOnly: true };
84
+ }
85
+ // A snapshot date: Anthropic's `-20251001`, OpenAI's `-2025-08-07`.
86
+ const SNAPSHOT_DATE = /-(?:\d{8}|\d{4}-\d{2}-\d{2})$/;
87
+ /* The model id in `models` a name means: the id itself, the one id it is the
88
+ bare form of (`claude-haiku-4-5` is `anthropic/claude-haiku-4-5`), or either
89
+ of those for a dated snapshot of it. A name two models share means neither. */
90
+ export function catalogModelFor(name, models) {
91
+ for (const candidate of new Set([name.toLowerCase(), name.toLowerCase().replace(SNAPSHOT_DATE, "")])) {
92
+ if (models.includes(candidate))
93
+ return candidate;
94
+ const matches = models.filter((id) => id.endsWith(`/${candidate}`));
95
+ if (matches.length === 1)
96
+ return matches[0];
97
+ }
98
+ return null;
99
+ }
@@ -0,0 +1,4 @@
1
+ export declare function linkRequestStarted(grantId: string, requestId: string, receivedAt: Date): void;
2
+ export declare function linkRequestRecorded(grantId: string, requestId: string): void;
3
+ /** Every request of the grant received before this time has been recorded. */
4
+ export declare function linkCompleteThrough(grantId: string, now?: Date): Date;
@@ -0,0 +1,43 @@
1
+ /* The Dari Link requests this gateway process is serving and has not yet
2
+ recorded, so a usage read can say up to when its counts are complete.
3
+
4
+ A request is counted from its report (RequestReporter) until its usage is
5
+ recorded. Before its report exists a request is still resolving, so the
6
+ answer also stays RESOLVE_SLACK_MS behind now. An entry older than
7
+ STALE_MS (a child token's longest life) is taken as lost and dropped.
8
+
9
+ This is exact only where one process serves and records every request of
10
+ a grant: the self-hosted gateway. */
11
+ const RESOLVE_SLACK_MS = 30_000;
12
+ const STALE_MS = 12 * 60 * 60_000;
13
+ // Grant id -> request id -> when the request was received (ms).
14
+ const inFlight = new Map();
15
+ export function linkRequestStarted(grantId, requestId, receivedAt) {
16
+ let requests = inFlight.get(grantId);
17
+ if (requests === undefined) {
18
+ requests = new Map();
19
+ inFlight.set(grantId, requests);
20
+ }
21
+ requests.set(requestId, receivedAt.getTime());
22
+ }
23
+ export function linkRequestRecorded(grantId, requestId) {
24
+ const requests = inFlight.get(grantId);
25
+ if (requests === undefined)
26
+ return;
27
+ requests.delete(requestId);
28
+ if (requests.size === 0)
29
+ inFlight.delete(grantId);
30
+ }
31
+ /** Every request of the grant received before this time has been recorded. */
32
+ export function linkCompleteThrough(grantId, now = new Date()) {
33
+ let through = now.getTime() - RESOLVE_SLACK_MS;
34
+ const requests = inFlight.get(grantId);
35
+ for (const [requestId, receivedAt] of requests ?? []) {
36
+ if (receivedAt < now.getTime() - STALE_MS) {
37
+ requests.delete(requestId);
38
+ continue;
39
+ }
40
+ through = Math.min(through, receivedAt);
41
+ }
42
+ return new Date(through);
43
+ }
@@ -11,6 +11,7 @@ import { resolveRouter } from "../strategies/routing.js";
11
11
  import { RequestReporter } from "../telemetry/report.js";
12
12
  import { RoutingBillingFinalization } from "../telemetry/billing_finalization.js";
13
13
  import { requestTags } from "./request_tags.js";
14
+ import { linkGrantAccess } from "./link_grant_access.js";
14
15
  import { rolePrompt, withRoleModel } from "./role_model.js";
15
16
  import { strictProviderAccess } from "./strict_provider_access.js";
16
17
  import { scopedHarnessAgentId, scopedHarnessConversationId, scopedHarnessSessionId, } from "./harness_identity/index.js";
@@ -89,8 +90,11 @@ export async function prepareRoutedCompletion(args) {
89
90
  }
90
91
  const roleModel = withRoleModel(credentials, args.interaction);
91
92
  const prompt = rolePrompt(credentials, args.interaction);
92
- const access = strictProviderAccess(credentials, roleModel.interaction);
93
+ const strictAccess = strictProviderAccess(credentials, roleModel.interaction);
94
+ const access = linkGrantAccess(strictAccess.credentials, strictAccess.interaction);
93
95
  credentials = access.credentials;
96
+ // A child token's tags label every request it makes, whatever the request says.
97
+ Object.assign(tags, credentials.link_tags);
94
98
  args = {
95
99
  ...args,
96
100
  interaction: clampRequestedEffort(access.interaction, credentials, modelMetadataLookup(credentials.model_configs)),
@@ -443,8 +443,16 @@ function providerExecution(prepared, decision) {
443
443
  promptCacheKey: prepared.interaction.promptCacheKey,
444
444
  tags: prepared.tags,
445
445
  systemPromptSuffix: prepared.rolePrompt,
446
+ clientThinking: clientThinking(prepared.interaction.reasoning),
446
447
  });
447
448
  }
449
+ function clientThinking(reasoning) {
450
+ if (reasoning?.clientOnly !== true || reasoning.effort !== undefined)
451
+ return undefined;
452
+ if (reasoning.enabled === false)
453
+ return "off";
454
+ return reasoning.budgetTokens === undefined ? "default" : `budget:${reasoning.budgetTokens}`;
455
+ }
448
456
  function tokenCount(value) {
449
457
  return typeof value === "number" && Number.isFinite(value)
450
458
  ? Math.max(0, Math.trunc(value))
@@ -6,6 +6,7 @@ export type ReportedProviderExecution = {
6
6
  provider: string;
7
7
  model: string;
8
8
  providerKeySource: ProviderKeySource;
9
+ thinkingLevel?: string;
9
10
  };
10
11
  export declare function reportedExecution(execution: ReportedProviderExecution): ReportedProviderExecution;
11
12
  export type ReportableProviderOutcome = {
@@ -3,6 +3,7 @@ export function reportedExecution(execution) {
3
3
  provider: execution.provider,
4
4
  model: execution.model,
5
5
  providerKeySource: execution.providerKeySource,
6
+ ...(execution.thinkingLevel === undefined ? {} : { thinkingLevel: execution.thinkingLevel }),
6
7
  };
7
8
  }
8
9
  export function createExperimentRoutedRuntimeReporter() {
@@ -21,10 +21,15 @@ import type { ClientHarness, RouterRoleModels, RouterRolePrompts } from "../type
21
21
  * rolePrompts: # optional: append to an agent role's system prompt
22
22
  * main: Delegate codebase exploration to subagents.
23
23
  * nativeCompaction: false # let Codex compact server-side with the provider's native compaction
24
+ * link: # optional: Dari Link
25
+ * allowHttpRedirectHosts: # http (not https) redirect URIs allowed on these
26
+ * - "*.example.ts.net" # private dev hosts; `*.` matches any subdomain
24
27
  * providers: # optional: OpenAI-compatible or self-run endpoints
25
28
  * local:
26
29
  * baseUrl: http://localhost:8000/v1
27
30
  * apiKeyEnv: LOCAL_API_KEY
31
+ * openai-codex: # optional: where ChatGPT plan requests go (a proxy)
32
+ * baseUrl: https://chatgpt.com/backend-api
28
33
  * ```
29
34
  *
30
35
  * Secrets never live here: gateway keys come from `DARI_GATEWAY_KEYS`,
@@ -36,6 +41,10 @@ import type { ClientHarness, RouterRoleModels, RouterRolePrompts } from "../type
36
41
  export type GatewayConfig = {
37
42
  routers: Record<string, RouterConfig>;
38
43
  providers: Record<string, ProviderEndpointConfig>;
44
+ link?: LinkConfig;
45
+ };
46
+ export type LinkConfig = {
47
+ allowHttpRedirectHosts: string[];
39
48
  };
40
49
  export type ProviderEndpointConfig = {
41
50
  baseUrl: string;
@@ -1,5 +1,6 @@
1
1
  import { isReasoningEffort, isRecord, } from "@mupt-ai/dari-router/policy-engine";
2
2
  import { CLIENT_HARNESSES } from "../ingress/client_harness.js";
3
+ const REDIRECT_HOST_PATTERN = /^(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;
3
4
  const ROUTER_ID_PATTERN = /^[A-Za-z0-9_-]+$/;
4
5
  const PROVIDER_ID_PATTERN = /^[a-z0-9][a-z0-9.-]*$/;
5
6
  const MODEL_ID_PATTERN = /^[a-z0-9][a-z0-9.-]*\/\S+$/;
@@ -67,7 +68,16 @@ export function parseGatewayConfig(raw) {
67
68
  providers[id] = parseProvider(id, provider);
68
69
  }
69
70
  }
70
- return { routers, providers };
71
+ return { routers, providers, ...(raw.link === undefined ? {} : { link: parseLink(raw.link) }) };
72
+ }
73
+ function parseLink(raw) {
74
+ if (!isRecord(raw))
75
+ throw new Error("`link` must be a map.");
76
+ const hosts = raw.allowHttpRedirectHosts ?? [];
77
+ if (!Array.isArray(hosts) || !hosts.every((host) => typeof host === "string" && REDIRECT_HOST_PATTERN.test(host.toLowerCase()))) {
78
+ throw new Error("link.allowHttpRedirectHosts must list host names, each optionally starting with `*.`.");
79
+ }
80
+ return { allowHttpRedirectHosts: hosts.map((host) => host.toLowerCase()) };
71
81
  }
72
82
  function parseProvider(id, raw) {
73
83
  if (!isRecord(raw) || typeof raw.baseUrl !== "string" || !URL.canParse(raw.baseUrl)) {