@mupt-ai/dari-gateway 1.0.310 → 1.0.312

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 (83) hide show
  1. package/README.md +4 -0
  2. package/dari-gateway.example.yaml +10 -0
  3. package/dist/context/provider_prompt_accounting.js +7 -0
  4. package/dist/context/routing_context.js +4 -1
  5. package/dist/interaction/system_prompt.d.ts +2 -0
  6. package/dist/interaction/system_prompt.js +21 -0
  7. package/dist/models/canonical.d.ts +2 -0
  8. package/dist/models/canonical.js +4 -0
  9. package/dist/models/catalog.js +1 -0
  10. package/dist/models/provider_defaults.js +4 -0
  11. package/dist/models/subscriptions.d.ts +4 -3
  12. package/dist/models/subscriptions.js +13 -9
  13. package/dist/platform/platform.d.ts +3 -0
  14. package/dist/providers/codex_usage.d.ts +13 -0
  15. package/dist/providers/codex_usage.js +46 -2
  16. package/dist/providers/execution.js +62 -9
  17. package/dist/providers/key_check.js +3 -0
  18. package/dist/providers/pi.js +5 -0
  19. package/dist/providers/pi_options.js +8 -0
  20. package/dist/providers/provider_call.d.ts +2 -0
  21. package/dist/providers/provider_call.js +9 -3
  22. package/dist/providers/response_capture.d.ts +4 -1
  23. package/dist/providers/response_capture.js +81 -2
  24. package/dist/providers/subscription_limits.d.ts +20 -2
  25. package/dist/providers/subscription_limits.js +115 -13
  26. package/dist/runtime/explicit_model.js +9 -4
  27. package/dist/runtime/prepare_routed_completion.d.ts +3 -1
  28. package/dist/runtime/prepare_routed_completion.js +7 -2
  29. package/dist/runtime/role_model.d.ts +8 -0
  30. package/dist/runtime/role_model.js +27 -0
  31. package/dist/runtime/routed_runtime.js +3 -1
  32. package/dist/self_host/config.d.ts +9 -1
  33. package/dist/self_host/config.js +44 -1
  34. package/dist/self_host/platform.js +7 -2
  35. package/dist/self_host/resolve.js +18 -3
  36. package/dist/self_host/subscription_test_gateway.d.ts +4 -3
  37. package/dist/self_host/subscription_test_gateway.js +11 -8
  38. package/dist/self_host/subscriptions/access.d.ts +5 -0
  39. package/dist/self_host/subscriptions/access.js +5 -1
  40. package/dist/self_host/subscriptions/http.js +16 -2
  41. package/dist/self_host/subscriptions/index.d.ts +6 -2
  42. package/dist/self_host/subscriptions/index.js +6 -2
  43. package/dist/self_host/subscriptions/oauth.d.ts +8 -4
  44. package/dist/self_host/subscriptions/oauth.js +75 -0
  45. package/dist/self_host/subscriptions/store.d.ts +17 -2
  46. package/dist/self_host/subscriptions/store.js +53 -8
  47. package/dist/self_host/subscriptions/usage.d.ts +7 -0
  48. package/dist/self_host/subscriptions/usage.js +52 -0
  49. package/dist/strategies/route_decision.js +0 -5
  50. package/dist/types.d.ts +6 -1
  51. package/package.json +2 -2
  52. package/src/context/provider_prompt_accounting.ts +7 -0
  53. package/src/context/routing_context.ts +4 -1
  54. package/src/interaction/system_prompt.ts +26 -0
  55. package/src/models/canonical.ts +5 -0
  56. package/src/models/catalog.ts +1 -0
  57. package/src/models/provider_defaults.ts +4 -0
  58. package/src/models/subscriptions.ts +14 -14
  59. package/src/platform/platform.ts +3 -0
  60. package/src/providers/codex_usage.ts +59 -2
  61. package/src/providers/execution.ts +65 -8
  62. package/src/providers/key_check.ts +2 -0
  63. package/src/providers/pi.ts +5 -0
  64. package/src/providers/pi_options.ts +7 -0
  65. package/src/providers/provider_call.ts +12 -3
  66. package/src/providers/response_capture.ts +88 -2
  67. package/src/providers/subscription_limits.ts +131 -14
  68. package/src/runtime/explicit_model.ts +9 -4
  69. package/src/runtime/prepare_routed_completion.ts +13 -3
  70. package/src/runtime/role_model.ts +35 -0
  71. package/src/runtime/routed_runtime.ts +3 -1
  72. package/src/self_host/config.ts +55 -2
  73. package/src/self_host/platform.ts +6 -3
  74. package/src/self_host/resolve.ts +15 -2
  75. package/src/self_host/subscription_test_gateway.ts +14 -8
  76. package/src/self_host/subscriptions/access.ts +10 -1
  77. package/src/self_host/subscriptions/http.ts +23 -2
  78. package/src/self_host/subscriptions/index.ts +7 -1
  79. package/src/self_host/subscriptions/oauth.ts +104 -5
  80. package/src/self_host/subscriptions/store.ts +65 -9
  81. package/src/self_host/subscriptions/usage.ts +64 -0
  82. package/src/strategies/route_decision.ts +0 -9
  83. package/src/types.ts +13 -1
@@ -4,14 +4,18 @@ import { providerFailureMessage } from "../runtime/provider_stream_outcome.js";
4
4
  import type { ProviderKeySource } from "../types.js";
5
5
  import type { CapturedProviderResponse } from "./response_capture.js";
6
6
 
7
- export type SubscriptionOAuthProvider = "anthropic_claude_code" | "openai_codex" | "meta_muse";
7
+ export type SubscriptionOAuthProvider = "anthropic_claude_code" | "openai_codex" | "meta_muse" | "opencode_go";
8
8
 
9
9
  export type SubscriptionUsageLimit = {
10
10
  oauthProvider: SubscriptionOAuthProvider;
11
11
  resetsAt: Date;
12
12
  reason: string;
13
- // The platform made the user's next subscription active, so a retry
14
- // succeeds on it.
13
+ // Set when only this model is at its own limit (such as a weekly cap on one
14
+ // model family): the plan still serves the router's other models.
15
+ model?: string;
16
+ // A retry is served: the platform made the user's next subscription active,
17
+ // or, for a model limit, held only that model so the router's other models
18
+ // serve.
15
19
  switched?: boolean;
16
20
  };
17
21
 
@@ -92,6 +96,59 @@ export function subscriptionUsageFromHeaders(
92
96
  return subscriptionUsageFromWindows(windows, now);
93
97
  }
94
98
 
99
+ /**
100
+ * The plan usage a Muse Code stream reports as its last event,
101
+ * `response.subscription_usage`: `{window: {used_percent, resets_at,
102
+ * window_duration_mins}, weekly: {used_percent, resets_at}, tier}`, the
103
+ * current five hour block and the rolling week, resets in unix seconds and
104
+ * percent that may exceed 100.
105
+ */
106
+ export function museSubscriptionUsage(snapshot: unknown, now: Date): SubscriptionUsage | null {
107
+ if (!isRecord(snapshot)) return null;
108
+ const number = (value: unknown) => typeof value === "number" && Number.isFinite(value) ? value : NaN;
109
+ return subscriptionUsageFromWindows(
110
+ ([["window", FIVE_HOURS], ["weekly", ONE_WEEK]] as const).map(([name, minutes]) => {
111
+ const raw = snapshot[name];
112
+ const window = isRecord(raw) ? raw : {};
113
+ const resetsAt = number(window.resets_at);
114
+ return {
115
+ minutes: number(window.window_duration_mins) > 0 ? Math.round(number(window.window_duration_mins)) : minutes,
116
+ used: number(window.used_percent) / 100,
117
+ resetsAt: Number.isNaN(resetsAt) ? null : new Date(resetsAt * 1000),
118
+ };
119
+ }),
120
+ now,
121
+ );
122
+ }
123
+
124
+ // OpenCode Go's windows by their usage report names; the monthly one follows
125
+ // the billing cycle.
126
+ const OPENCODE_GO_USAGE_WINDOWS = [["rolling", FIVE_HOURS], ["weekly", ONE_WEEK], ["monthly", 30 * 24 * 60]] as const;
127
+
128
+ /**
129
+ * The usage OpenCode Go reports at `GET /zen/go/v1/usage`, which OpenCode's
130
+ * own `/usage` reads: `{usage: {rolling|weekly|monthly: {status: "ok" |
131
+ * "rate-limited", percent, resetsAt}}}`, percent out of 100. A window Go
132
+ * refuses on is at its limit whatever it rounds to.
133
+ */
134
+ export function openCodeGoUsageFromReport(report: unknown, now: Date): SubscriptionUsage | null {
135
+ const usage = isRecord(report) && isRecord(report.usage) ? report.usage : {};
136
+ return subscriptionUsageFromWindows(
137
+ OPENCODE_GO_USAGE_WINDOWS.map(([name, minutes]) => {
138
+ const raw = usage[name];
139
+ const meter = isRecord(raw) ? raw : {};
140
+ const percent = typeof meter.percent === "number" ? meter.percent / 100 : NaN;
141
+ const resetsAt = typeof meter.resetsAt === "string" ? new Date(meter.resetsAt) : null;
142
+ return {
143
+ minutes,
144
+ used: meter.status === "rate-limited" && Number.isFinite(percent) ? 1 : percent,
145
+ resetsAt: resetsAt === null || Number.isNaN(resetsAt.getTime()) ? null : resetsAt,
146
+ };
147
+ }),
148
+ now,
149
+ );
150
+ }
151
+
95
152
  // Neither provider guarantees a reset time on every usage-limit response.
96
153
  // Without one, hold the subscription out for an hour rather than hammering an
97
154
  // exhausted plan on every request.
@@ -103,6 +160,7 @@ const SUBSCRIPTION_LABEL: Record<SubscriptionOAuthProvider, string> = {
103
160
  anthropic_claude_code: "Claude Code",
104
161
  openai_codex: "ChatGPT",
105
162
  meta_muse: "Muse Code",
163
+ opencode_go: "OpenCode Go",
106
164
  };
107
165
 
108
166
  // Providers whose plan page the accounts page links to for buying another.
@@ -116,6 +174,7 @@ export function subscriptionOAuthProviderFor(
116
174
  if (provider === "anthropic") return "anthropic_claude_code";
117
175
  if (provider === "openai" || provider === "openai-codex") return "openai_codex";
118
176
  if (provider === "meta") return "meta_muse";
177
+ if (provider === "opencode-go") return "opencode_go";
119
178
  return null;
120
179
  }
121
180
 
@@ -124,13 +183,16 @@ export function subscriptionOAuthProviderFor(
124
183
  * answers 429 with the unified rate-limit headers; the ChatGPT backend answers
125
184
  * 429 with a structured `error.code` and `resets_at`. Meta documents no
126
185
  * usage-limit signature for Muse Code plans, so any 429 on one holds it until
127
- * the reset Meta gives, if any. The Codex WebSocket
186
+ * the reset Meta gives, if any. OpenCode Go names its refusal
187
+ * `GoUsageLimitError`. The Codex WebSocket
128
188
  * transport bypasses fetch, so its usage-limit error only survives as message
129
189
  * text and is matched there without a reset time.
130
190
  */
131
191
  export function detectSubscriptionUsageLimit(args: {
132
192
  provider: string;
133
193
  keySource: ProviderKeySource;
194
+ // The routed model, named on a limit that covers only it.
195
+ model: string;
134
196
  captured: CapturedProviderResponse | undefined;
135
197
  failure: Record<string, unknown>;
136
198
  now?: Date;
@@ -139,14 +201,22 @@ export function detectSubscriptionUsageLimit(args: {
139
201
  if (oauthProvider === null) return null;
140
202
  const now = args.now ?? new Date();
141
203
  if (oauthProvider === "anthropic_claude_code") {
142
- return anthropicUsageLimit(args.captured, now);
204
+ return anthropicUsageLimit(args.captured, args.model, now);
143
205
  }
144
206
  if (oauthProvider === "meta_muse") return museUsageLimit(args.captured, now);
145
- return codexUsageLimit(args.captured, providerFailureMessage(args.failure), now);
207
+ if (oauthProvider === "opencode_go") return openCodeGoUsageLimit(args.captured, now);
208
+ return codexUsageLimit(args.captured, providerFailureMessage(args.failure), args.model, now);
146
209
  }
147
210
 
211
+ // Claude Code plans also cap some model families on their own
212
+ // (`seven_day_opus`, `seven_day_sonnet`). The representative claim names the
213
+ // window that refused, and `-fallback: available` says another model can still
214
+ // serve; either way the rest of the plan is not exhausted.
215
+ const ANTHROPIC_MODEL_CLAIM = /^(?:five_hour|seven_day)_(?:opus|sonnet|haiku|fable|mythos)(?:_|$)/;
216
+
148
217
  function anthropicUsageLimit(
149
218
  captured: CapturedProviderResponse | undefined,
219
+ model: string,
150
220
  now: Date,
151
221
  ): SubscriptionUsageLimit | null {
152
222
  if (captured === undefined || captured.status !== 429) return null;
@@ -158,10 +228,15 @@ function anthropicUsageLimit(
158
228
  return null;
159
229
  }
160
230
  const claim = captured.headers.get("anthropic-ratelimit-unified-representative-claim");
231
+ const modelLimit = (claim !== null && ANTHROPIC_MODEL_CLAIM.test(claim))
232
+ || captured.headers.get("anthropic-ratelimit-unified-fallback") === "available";
161
233
  return {
162
234
  oauthProvider: "anthropic_claude_code",
163
235
  resetsAt: resetFromUnixSeconds(captured.headers.get("anthropic-ratelimit-unified-reset"), now),
164
- reason: claim ? `Claude Code ${claim.replaceAll("_", " ")} usage limit reached.` : "Claude Code usage limit reached.",
236
+ reason: claim
237
+ ? `Claude Code ${claim.replaceAll("_", " ")} usage limit reached.`
238
+ : modelLimit ? `Claude Code usage limit for ${model} reached.` : "Claude Code usage limit reached.",
239
+ ...(modelLimit ? { model } : {}),
165
240
  };
166
241
  }
167
242
 
@@ -171,6 +246,7 @@ const CODEX_LIMIT_MESSAGE = /usage_limit_reached|usage_not_included|hit your Cha
171
246
  function codexUsageLimit(
172
247
  captured: CapturedProviderResponse | undefined,
173
248
  failureMessage: string,
249
+ model: string,
174
250
  now: Date,
175
251
  ): SubscriptionUsageLimit | null {
176
252
  if (captured !== undefined && captured.status === 429) {
@@ -178,11 +254,10 @@ function codexUsageLimit(
178
254
  const code = typeof error?.code === "string" ? error.code : "";
179
255
  if (error !== null && (CODEX_LIMIT_CODES.has(code) || failureMessage.match(CODEX_LIMIT_MESSAGE))) {
180
256
  const plan = typeof error.plan_type === "string" ? ` (${error.plan_type.toLowerCase()} plan)` : "";
181
- return {
182
- oauthProvider: "openai_codex",
183
- resetsAt: laterReset(error.resets_at, captured.headers, now),
184
- reason: `ChatGPT usage limit reached${plan}.`,
185
- };
257
+ const resetsAt = laterReset(error.resets_at, captured.headers, now);
258
+ return codexModelLimitExhausted(captured.headers)
259
+ ? { oauthProvider: "openai_codex", resetsAt, reason: `ChatGPT usage limit for ${model} reached${plan}.`, model }
260
+ : { oauthProvider: "openai_codex", resetsAt, reason: `ChatGPT usage limit reached${plan}.` };
186
261
  }
187
262
  return null;
188
263
  }
@@ -194,6 +269,21 @@ function codexUsageLimit(
194
269
  };
195
270
  }
196
271
 
272
+ // The ChatGPT backend reports each limit as its own header family,
273
+ // `x-<limit>-primary-used-percent`, the plan's own being `x-codex-*`. A refusal
274
+ // while only another family is spent is that model's own cap.
275
+ function codexModelLimitExhausted(headers: Headers): boolean {
276
+ let plan = false;
277
+ let other = false;
278
+ headers.forEach((value, name) => {
279
+ const family = /^x-(.+)-(?:primary|secondary)-used-percent$/.exec(name.toLowerCase())?.[1];
280
+ if (family === undefined || !(Number(value) >= 100)) return;
281
+ if (family === "codex") plan = true;
282
+ else other = true;
283
+ });
284
+ return other && !plan;
285
+ }
286
+
197
287
  function museUsageLimit(
198
288
  captured: CapturedProviderResponse | undefined,
199
289
  now: Date,
@@ -206,6 +296,25 @@ function museUsageLimit(
206
296
  };
207
297
  }
208
298
 
299
+ // OpenCode Go refuses an exhausted plan with 429 and a `GoUsageLimitError`
300
+ // naming the window ("5 hour", "weekly", "monthly"), as OpenCode's own client
301
+ // recognizes it; an upstream's transient 429 on Go does not hold the plan.
302
+ // The reset is `resetsAt` (ISO) when sent, else Retry-After.
303
+ function openCodeGoUsageLimit(
304
+ captured: CapturedProviderResponse | undefined,
305
+ now: Date,
306
+ ): SubscriptionUsageLimit | null {
307
+ if (captured === undefined || captured.status !== 429) return null;
308
+ if (!captured.bodyText.includes("GoUsageLimitError")) return null;
309
+ const window = /"limitName"\s*:\s*"([^"]+)"/.exec(captured.bodyText)?.[1];
310
+ const resetsAt = Date.parse(/"resetsAt"\s*:\s*"([^"]+)"/.exec(captured.bodyText)?.[1] ?? "");
311
+ return {
312
+ oauthProvider: "opencode_go",
313
+ resetsAt: laterReset(Number.isNaN(resetsAt) ? undefined : resetsAt / 1000, captured.headers, now),
314
+ reason: `OpenCode Go ${window ? `${window} ` : ""}usage limit reached.`,
315
+ };
316
+ }
317
+
209
318
  function codexErrorBody(bodyText: string): Record<string, unknown> | null {
210
319
  try {
211
320
  const parsed: unknown = JSON.parse(bodyText);
@@ -262,6 +371,7 @@ export function failureWithSubscriptionUsageLimit(
262
371
  oauth_provider: limit.oauthProvider,
263
372
  resets_at: limit.resetsAt.toISOString(),
264
373
  reason: limit.reason,
374
+ ...(limit.model !== undefined ? { model: limit.model } : {}),
265
375
  ...(limit.switched === true ? { switched: true } : {}),
266
376
  },
267
377
  };
@@ -284,6 +394,7 @@ export function subscriptionUsageLimitFromFailure(
284
394
  oauthProvider: oauthProvider as SubscriptionOAuthProvider,
285
395
  resetsAt,
286
396
  reason: typeof marker.reason === "string" ? marker.reason : "Subscription usage limit reached.",
397
+ ...(typeof marker.model === "string" ? { model: marker.model } : {}),
287
398
  ...(marker.switched === true ? { switched: true } : {}),
288
399
  };
289
400
  }
@@ -295,7 +406,8 @@ export function subscriptionUsageLimitFromFailure(
295
406
  */
296
407
  export function subscriptionUsageLimitMessage(limit: SubscriptionUsageLimit, accountsUrl?: string): string {
297
408
  const label = SUBSCRIPTION_LABEL[limit.oauthProvider];
298
- const reached = `Your ${label} subscription usage limit is reached. It resets at ${limit.resetsAt.toISOString()}. `;
409
+ const scope = limit.model === undefined ? "" : ` for ${limit.model}`;
410
+ const reached = `Your ${label} subscription usage limit${scope} is reached. It resets at ${limit.resetsAt.toISOString()}. `;
299
411
  if (accountsUrl === undefined) {
300
412
  return reached
301
413
  + `To keep going now, add another ${label} subscription or mark this one available early with \`dari accounts\`.`;
@@ -317,7 +429,8 @@ export function codexUsageLimitError(limit: SubscriptionUsageLimit, accountsUrl?
317
429
  body: Record<string, unknown>;
318
430
  headers: Record<string, string>;
319
431
  } | null {
320
- if (limit.oauthProvider !== "openai_codex") return null;
432
+ // Codex would show a per-model limit as the whole plan's.
433
+ if (limit.oauthProvider !== "openai_codex" || limit.model !== undefined) return null;
321
434
  const promo = accountsUrl === undefined
322
435
  ? "Add another ChatGPT subscription with `dari accounts`"
323
436
  : `Add another ChatGPT subscription at ${accountsUrl}?buy=openai_codex`;
@@ -329,6 +442,10 @@ export function codexUsageLimitError(limit: SubscriptionUsageLimit, accountsUrl?
329
442
 
330
443
  export function subscriptionSwitchedMessage(limit: SubscriptionUsageLimit): string {
331
444
  const label = SUBSCRIPTION_LABEL[limit.oauthProvider];
445
+ if (limit.model !== undefined) {
446
+ return `Your ${label} subscription usage limit for ${limit.model} is reached; it resets at `
447
+ + `${limit.resetsAt.toISOString()}. Dari routes to other models until then; retry the request.`;
448
+ }
332
449
  return `Your ${label} subscription usage limit is reached. `
333
450
  + `Dari switched to your next connected ${label} subscription; retry the request.`;
334
451
  }
@@ -7,15 +7,18 @@ import type { PreparedRoutedCompletion } from "./prepare_routed_completion.js";
7
7
 
8
8
  /* A request for `dari/model/<id>` is served by exactly that enabled model,
9
9
  with no selector or lease: the user chose it, like picking a
10
- model in their agent's /model menu. The client's thinking level is kept
11
- when the model supports it; otherwise the model's default level is used. */
10
+ model in their agent's /model menu, or the router fixed it for the
11
+ request's agent role. Routing rules and switch-cost pruning narrow only
12
+ what the selector may pick, so they never remove it. The client's thinking
13
+ level is kept when the model supports it; otherwise the model's default
14
+ level is used. */
12
15
  export function explicitModelDecision(
13
16
  prepared: PreparedRoutedCompletion,
14
17
  ): RoutedDecision | null {
15
18
  const modelId = explicitModelId(prepared.interaction.model);
16
19
  if (modelId === null) return null;
17
20
  if (!prepared.credentials.enabled_models.includes(modelId)) throw modelNotEnabled(modelId);
18
- const candidates = prepared.routing.candidateResolution.candidates.filter(
21
+ const candidates = prepared.routing.candidateResolution.allCandidates.filter(
19
22
  (candidate) => candidate.model === modelId,
20
23
  );
21
24
  if (candidates.length === 0) {
@@ -30,7 +33,9 @@ export function explicitModelDecision(
30
33
  const decision: RoutingDecision = {
31
34
  selectedModel: candidate.model,
32
35
  reasoningEffort: candidate.reasoningEffort,
33
- reason: `Requested model ${modelId} served without selection.`,
36
+ reason: prepared.role === undefined
37
+ ? `Requested model ${modelId} served without selection.`
38
+ : `The router's ${prepared.role} model ${modelId} served without selection.`,
34
39
  };
35
40
  return { decision };
36
41
  }
@@ -17,8 +17,9 @@ import { gatewayPlatform, type RequestTags, type SessionPin } from "../platform/
17
17
  import { resolveRouter } from "../strategies/routing.js";
18
18
  import { RequestReporter, type ReportedCandidatePruning } from "../telemetry/report.js";
19
19
  import { RoutingBillingFinalization } from "../telemetry/billing_finalization.js";
20
- import type { ClientHarness, ProviderCredential, ResolvedRouter } from "../types.js";
20
+ import type { ClientHarness, ProviderCredential, ResolvedRouter, RouterRole } from "../types.js";
21
21
  import { requestTags } from "./request_tags.js";
22
+ import { rolePrompt, withRoleModel } from "./role_model.js";
22
23
  import { strictProviderAccess } from "./strict_provider_access.js";
23
24
  import type { RoutedRuntimeReporter } from "./runtime_reporter.js";
24
25
  import type { RoutedProtocol } from "./routed_protocol.js";
@@ -43,6 +44,11 @@ export type PreparedRoutedCompletion = {
43
44
  // Present when this request is served by session pinning: the session's
44
45
  // pin key and the pair it pinned, null before its first routed turn.
45
46
  sessionPin?: { key: string; pin: SessionPin | null };
47
+ // The agent role whose fixed router model this request is served.
48
+ role?: RouterRole;
49
+ // The router's prompt for this request's role, appended to the system
50
+ // prompt sent to the provider. Routing and prefix matching never see it.
51
+ rolePrompt?: string;
46
52
  reporter: RoutedRuntimeReporter;
47
53
  };
48
54
 
@@ -136,7 +142,9 @@ export async function prepareRoutedCompletion(args: {
136
142
  }
137
143
  credentials = conversationCredentials;
138
144
  }
139
- const access = strictProviderAccess(credentials, args.interaction);
145
+ const roleModel = withRoleModel(credentials, args.interaction);
146
+ const prompt = rolePrompt(credentials, args.interaction);
147
+ const access = strictProviderAccess(credentials, roleModel.interaction);
140
148
  credentials = access.credentials;
141
149
  args = {
142
150
  ...args,
@@ -227,6 +235,8 @@ export async function prepareRoutedCompletion(args: {
227
235
  harnessConversationIdentity: args.harnessConversationIdentity,
228
236
  routing,
229
237
  ...(sessionPin === undefined ? {} : { sessionPin }),
238
+ ...(roleModel.role === undefined ? {} : { role: roleModel.role }),
239
+ ...(prompt === undefined ? {} : { rolePrompt: prompt }),
230
240
  reporter,
231
241
  };
232
242
  }
@@ -258,7 +268,7 @@ async function withProviderCredentials(
258
268
  for (const [model, credential] of resolved) {
259
269
  if (!credential?.apiKey.trim()) continue;
260
270
  const plan = credential.subscription;
261
- if (plan !== undefined && !subscriptionServes(plan, model, clientHarness)) continue;
271
+ if (plan !== undefined && !subscriptionServes(plan, executionProviderForModel(credentials, model), clientHarness)) continue;
262
272
  provider_credentials[model] = credential;
263
273
  if (plan === "openai_codex") {
264
274
  // Keep the catalog's limits and thinking levels; only the serving
@@ -0,0 +1,35 @@
1
+ import { isBackgroundRequest, type InteractionRequest } from "../interaction/types.js";
2
+ import { EXPLICIT_MODEL_PREFIX } from "../protocol/input/router_model.js";
3
+ import type { ResolvedRouter, RouterRole } from "../types.js";
4
+
5
+ /* The agent role a request comes from: subagents include workflow agents, and
6
+ anything else that is not background work (compaction, auxiliary requests,
7
+ side replies) is the main agent. Background work has no role. */
8
+ export function requestRole(interaction: InteractionRequest): RouterRole | null {
9
+ if (isBackgroundRequest(interaction)) return null;
10
+ const requestClass = interaction.agentContext?.requestClass;
11
+ return requestClass === "subagent" || requestClass === "workflow" ? "subagent" : "main";
12
+ }
13
+
14
+ /* A router can fix the model for an agent role. A request from a fixed role
15
+ is served that model as if it had asked for `dari/model/<id>`, whatever
16
+ model it did ask for. */
17
+ export function withRoleModel(
18
+ credentials: ResolvedRouter,
19
+ interaction: InteractionRequest,
20
+ ): { interaction: InteractionRequest; role?: RouterRole } {
21
+ const role = requestRole(interaction);
22
+ const model = role === null ? null : credentials.role_models?.[role];
23
+ if (!role || !model) return { interaction };
24
+ return { interaction: { ...interaction, model: `${EXPLICIT_MODEL_PREFIX}${model}` }, role };
25
+ }
26
+
27
+ /* The router's prompt for a request's role, or undefined. */
28
+ export function rolePrompt(
29
+ credentials: ResolvedRouter,
30
+ interaction: InteractionRequest,
31
+ ): string | undefined {
32
+ const role = requestRole(interaction);
33
+ const prompt = role === null ? undefined : credentials.role_prompts?.[role]?.trim();
34
+ return prompt || undefined;
35
+ }
@@ -268,10 +268,11 @@ async function prepareRuntimeExecution(args: {
268
268
  if (explicit) {
269
269
  prepared.reporter.attachServingDecision(explicit.decision);
270
270
  prepared.reporter.attachDecisionDetails({
271
- decision_source: "explicit_model",
271
+ decision_source: prepared.role === undefined ? "explicit_model" : "role_model",
272
272
  explicit_model: {
273
273
  model: explicit.decision.selectedModel,
274
274
  reasoning_effort: explicit.decision.reasoningEffort,
275
+ ...(prepared.role === undefined ? {} : { role: prepared.role }),
275
276
  },
276
277
  });
277
278
  return selectedExecutionPlan(prepared, explicit);
@@ -618,6 +619,7 @@ function providerExecution(
618
619
  costEstimates: prepared.routing.reportingCostEstimates,
619
620
  promptCacheKey: prepared.interaction.promptCacheKey,
620
621
  tags: prepared.tags,
622
+ systemPromptSuffix: prepared.rolePrompt,
621
623
  });
622
624
  }
623
625
 
@@ -5,7 +5,7 @@ import {
5
5
  } from "@mupt-ai/dari-router/policy-engine";
6
6
 
7
7
  import { CLIENT_HARNESSES } from "../ingress/client_harness.js";
8
- import type { ClientHarness } from "../types.js";
8
+ import type { ClientHarness, RouterRole, RouterRoleModels, RouterRolePrompts } from "../types.js";
9
9
 
10
10
  /**
11
11
  * The self-hosted gateway's configuration file (YAML or JSON):
@@ -22,6 +22,11 @@ import type { ClientHarness } from "../types.js";
22
22
  * - openai/gpt-6.1-sol
23
23
  * subscriptions: true # serve with connected Claude Code / ChatGPT plans
24
24
  * sessionPinning: false # route each session and subagent once, then keep its model
25
+ * roleModels: # optional: serve an agent role one model, without routing
26
+ * main: anthropic/claude-fable-5-2
27
+ * subagent: openai/gpt-6.1-sol
28
+ * rolePrompts: # optional: append to an agent role's system prompt
29
+ * main: Delegate codebase exploration to subagents.
25
30
  * nativeCompaction: false # let Codex compact server-side with the provider's native compaction
26
31
  * providers: # optional: OpenAI-compatible or self-run endpoints
27
32
  * local:
@@ -60,6 +65,11 @@ export type RouterConfig = {
60
65
  sessionPinning: boolean;
61
66
  nativeCompaction: boolean;
62
67
  zdr: boolean;
68
+ // Fixed models for agent roles (subagents include workflow agents); a role
69
+ // without one is routed.
70
+ roleModels: RouterRoleModels;
71
+ // Text appended to the end of each role's system prompt.
72
+ rolePrompts: RouterRolePrompts;
63
73
  };
64
74
 
65
75
  export type RouterModelConfig = {
@@ -187,9 +197,12 @@ function parseRouter(id: string, raw: unknown): RouterConfig {
187
197
  agentModels[agent as ClientHarness] = parseRouterModels(id, `agentModels.${agent}`, models);
188
198
  }
189
199
  }
200
+ const models = parseRouterModels(id, "models", raw.models);
190
201
  return {
191
- models: parseRouterModels(id, "models", raw.models),
202
+ models,
192
203
  agentModels,
204
+ roleModels: parseRoleModels(id, raw.roleModels, [models, ...Object.values(agentModels)].flat()),
205
+ rolePrompts: parseRolePrompts(id, raw.rolePrompts),
193
206
  retries: optionalRetries(raw.retries, `routers.${id}.retries`) ?? 1,
194
207
  subscriptions: optionalBoolean(raw.subscriptions, `routers.${id}.subscriptions`) ?? true,
195
208
  sessionPinning: optionalBoolean(raw.sessionPinning, `routers.${id}.sessionPinning`) ?? false,
@@ -198,6 +211,46 @@ function parseRouter(id: string, raw: unknown): RouterConfig {
198
211
  };
199
212
  }
200
213
 
214
+ const ROUTER_ROLES: readonly RouterRole[] = ["main", "subagent"];
215
+
216
+ function parseRoleModels(routerId: string, raw: unknown, models: RouterModelConfig[]): RouterRoleModels {
217
+ if (raw === undefined) return {};
218
+ if (!isRecord(raw)) throw new Error(`routers.${routerId}.roleModels must map main and subagent to models.`);
219
+ const roleModels: RouterRoleModels = {};
220
+ for (const [role, model] of Object.entries(raw)) {
221
+ if (!(ROUTER_ROLES as readonly string[]).includes(role)) {
222
+ throw new Error(`routers.${routerId}.roleModels has an unknown role "${role}"; use main or subagent.`);
223
+ }
224
+ if (model === null) continue;
225
+ if (typeof model !== "string" || !models.some((listed) => listed.id === model)) {
226
+ throw new Error(`routers.${routerId}.roleModels.${role} must be one of the router's models.`);
227
+ }
228
+ roleModels[role as RouterRole] = model;
229
+ }
230
+ return roleModels;
231
+ }
232
+
233
+ export const ROLE_PROMPT_MAX_LENGTH = 4000;
234
+
235
+ function parseRolePrompts(routerId: string, raw: unknown): RouterRolePrompts {
236
+ if (raw === undefined) return {};
237
+ if (!isRecord(raw)) throw new Error(`routers.${routerId}.rolePrompts must map main and subagent to text.`);
238
+ const rolePrompts: RouterRolePrompts = {};
239
+ for (const [role, prompt] of Object.entries(raw)) {
240
+ if (!(ROUTER_ROLES as readonly string[]).includes(role)) {
241
+ throw new Error(`routers.${routerId}.rolePrompts has an unknown role "${role}"; use main or subagent.`);
242
+ }
243
+ if (prompt === null) continue;
244
+ if (typeof prompt !== "string" || !prompt.trim() || prompt.length > ROLE_PROMPT_MAX_LENGTH) {
245
+ throw new Error(
246
+ `routers.${routerId}.rolePrompts.${role} must be text of at most ${ROLE_PROMPT_MAX_LENGTH} characters.`,
247
+ );
248
+ }
249
+ rolePrompts[role as RouterRole] = prompt.trim();
250
+ }
251
+ return rolePrompts;
252
+ }
253
+
201
254
  /** Read one model list of a router, naming `field` in what it rejects. */
202
255
  export function parseRouterModels(routerId: string, field: string, raw: unknown): RouterModelConfig[] {
203
256
  if (!Array.isArray(raw) || raw.length === 0) {
@@ -44,9 +44,12 @@ export function createSelfHostedPlatform(deps: Omit<SelfHostedResolverDeps, "pre
44
44
  apiKey: await freshAccessToken(deps.subscriptions, next, { fetch: deps.fetch }),
45
45
  };
46
46
  },
47
- markSubscriptionUnavailable: async (hold) =>
48
- hold.credentialId !== undefined &&
49
- deps.subscriptions.markUnavailable(hold.credentialId, hold.limit.resetsAt, hold.limit.reason),
47
+ async markSubscriptionUnavailable({ credentialId, limit }) {
48
+ if (credentialId === undefined) return false;
49
+ return limit.model === undefined
50
+ ? deps.subscriptions.markUnavailable(credentialId, limit.resetsAt, limit.reason)
51
+ : deps.subscriptions.holdModel(credentialId, limit.model, limit.resetsAt, limit.reason);
52
+ },
50
53
  async recordUsage() {
51
54
  // Resolution never reports a "managed" key source here.
52
55
  throw new Error("The self-hosted gateway has no managed provider keys to account.");
@@ -20,6 +20,7 @@ import {
20
20
  } from "./config.js";
21
21
  import type { RouterModelStore } from "./router_models.js";
22
22
  import {
23
+ activeModelHolds,
23
24
  freshAccessToken,
24
25
  type OAuthFetch,
25
26
  type SubscriptionCredential,
@@ -109,7 +110,15 @@ export async function resolveSelfHostedRouter(
109
110
  credentials.set(provider, apiKey ? { key: apiKey, source: "user" } : null);
110
111
  }
111
112
 
112
- const models = listed.filter((model) => credentials.get(providerForModel(model.id)) != null);
113
+ // A model at its own limit on the serving plan leaves routing until it resets.
114
+ const models = listed.filter((model) => {
115
+ const credential = credentials.get(providerForModel(model.id));
116
+ if (credential == null) return false;
117
+ const plan = credential.subscription;
118
+ if (plan === undefined || !activeModelHolds(plan, now).some((hold) => hold.model === model.id)) return true;
119
+ exhausted.add(plan.provider);
120
+ return false;
121
+ });
113
122
  if (models.length === 0) {
114
123
  const missing = [...credentials].filter(([, credential]) => credential == null).map(([provider]) => provider);
115
124
  throw unavailableRouterError(request.routerId, exhausted, missing);
@@ -132,6 +141,8 @@ export async function resolveSelfHostedRouter(
132
141
  primary_retries: router.retries,
133
142
  routing_strategy: "dari",
134
143
  custom_config: null,
144
+ role_models: router.roleModels,
145
+ role_prompts: router.rolePrompts,
135
146
  evals: [],
136
147
  model_thinking_levels: thinkingLevels(listed),
137
148
  model_prices: {},
@@ -206,6 +217,7 @@ function subscriptionProviderFor(
206
217
  }
207
218
  if (provider === "meta") return clientHarness === "muse_code" ? "meta_muse" : null;
208
219
  if (provider === "openai") return "openai_codex";
220
+ if (provider === "opencode-go") return "opencode_go";
209
221
  return null;
210
222
  }
211
223
 
@@ -227,6 +239,7 @@ const SUBSCRIPTION_PLAN_NAMES: Record<SubscriptionProvider, string> = {
227
239
  anthropic_claude_code: "Claude Code",
228
240
  openai_codex: "ChatGPT",
229
241
  meta_muse: "Muse Code",
242
+ opencode_go: "OpenCode Go",
230
243
  };
231
244
 
232
245
  /**
@@ -264,7 +277,7 @@ function unavailableRouterError(
264
277
  .join(" and ");
265
278
  return new HttpError(
266
279
  424,
267
- `Every connected ${plans} subscription is at its usage limit, and no API key can serve router ${routerId} instead.${missingNote}`,
280
+ `Every connected ${plans} subscription is at its usage limit for the models router ${routerId} lists, and no API key can serve them instead.${missingNote}`,
268
281
  "personal_subscription_unavailable",
269
282
  );
270
283
  }
@@ -11,16 +11,21 @@ import { tokens } from "./subscriptions/test_support.js";
11
11
  * A self-hosted gateway, run through its entrypoint as its own process so no
12
12
  * other test file's module mocks reach it, serving two Claude Code plans
13
13
  * (access tokens `sk-ant-oat01-a` and `-b`) against a local stand-in for
14
- * Anthropic. `upstream` answers each provider call given the plan's token.
14
+ * Anthropic. `upstream` answers each provider call given the plan's token
15
+ * and the native model it asks for. The router lists `models`.
15
16
  */
16
- export async function startSubscriptionGateway(upstream: (token: string) => Response) {
17
+ export async function startSubscriptionGateway(
18
+ upstream: (token: string, model: string) => Response,
19
+ models: string[] = ["anthropic/claude-sonnet-5-5"],
20
+ ) {
17
21
  const served: string[] = [];
18
22
  const provider = Bun.serve({
19
23
  port: 0,
20
- fetch(request) {
24
+ async fetch(request) {
21
25
  const token = (request.headers.get("authorization") ?? "").replace(/^Bearer /, "");
22
26
  served.push(token);
23
- return upstream(token);
27
+ const body = await request.json() as { model?: string };
28
+ return upstream(token, body.model ?? "");
24
29
  },
25
30
  });
26
31
  const dir = mkdtempSync(join(tmpdir(), "dari-gateway-plans-"));
@@ -34,7 +39,7 @@ export async function startSubscriptionGateway(upstream: (token: string) => Resp
34
39
  writeFileSync(configPath, `
35
40
  routers:
36
41
  default:
37
- models: [anthropic/claude-sonnet-5-5]
42
+ models: [${models.join(", ")}]
38
43
  providers:
39
44
  anthropic:
40
45
  baseUrl: http://127.0.0.1:${provider.port}
@@ -60,8 +65,9 @@ providers:
60
65
  planIds: plans.map((plan) => plan.id),
61
66
  // The plans as the gateway stored them.
62
67
  plan: (id: string) => new SubscriptionStore(new Database(dbPath)).get(id),
63
- // One Claude Code request in the conversation `sessionId` starts.
64
- claudeCode: async (sessionId: string, text: string) =>
68
+ // One Claude Code request in the conversation `sessionId` starts, for
69
+ // `model` or, by default, routed.
70
+ claudeCode: async (sessionId: string, text: string, model = "dari/model/anthropic/claude-sonnet-5-5") =>
65
71
  await fetch(`${baseUrl}/v1/messages`, {
66
72
  method: "POST",
67
73
  headers: {
@@ -73,7 +79,7 @@ providers:
73
79
  "x-claude-code-session-id": sessionId,
74
80
  },
75
81
  body: JSON.stringify({
76
- model: "dari/model/anthropic/claude-sonnet-5-5",
82
+ model,
77
83
  max_tokens: 64,
78
84
  stream: true,
79
85
  messages: [{ role: "user", content: text }],
@@ -15,9 +15,18 @@ export async function freshAccessToken(
15
15
  store: SubscriptionStore,
16
16
  credential: SubscriptionCredential,
17
17
  options: { fetch: OAuthFetch; now?: Date },
18
+ ): Promise<string> {
19
+ store.touch(credential.id, options.now ?? new Date());
20
+ return await refreshedAccessToken(store, credential, options);
21
+ }
22
+
23
+ /** A usable access token without recording a use. */
24
+ export async function refreshedAccessToken(
25
+ store: SubscriptionStore,
26
+ credential: SubscriptionCredential,
27
+ options: { fetch: OAuthFetch; now?: Date },
18
28
  ): Promise<string> {
19
29
  const now = options.now ?? new Date();
20
- store.touch(credential.id, now);
21
30
  if (!expiresSoon(credential, now)) return credential.accessToken;
22
31
 
23
32
  const pending = inFlight.get(credential.id);