@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
@@ -1,10 +1,11 @@
1
1
  import type { ProviderKeySource } from "../types.js";
2
2
  import type { CapturedProviderResponse } from "./response_capture.js";
3
- export type SubscriptionOAuthProvider = "anthropic_claude_code" | "openai_codex" | "meta_muse";
3
+ export type SubscriptionOAuthProvider = "anthropic_claude_code" | "openai_codex" | "meta_muse" | "opencode_go";
4
4
  export type SubscriptionUsageLimit = {
5
5
  oauthProvider: SubscriptionOAuthProvider;
6
6
  resetsAt: Date;
7
7
  reason: string;
8
+ model?: string;
8
9
  switched?: boolean;
9
10
  };
10
11
  /** One quota window of a plan: its length, share used (0 to 1), and reset. */
@@ -36,6 +37,21 @@ export declare function subscriptionUsageFromWindows(raw: Array<{
36
37
  * reports none: the most used of the plan's windows.
37
38
  */
38
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;
39
55
  export declare const DEFAULT_USAGE_LIMIT_WINDOW_MS: number;
40
56
  export declare function subscriptionOAuthProviderFor(provider: string, keySource: ProviderKeySource): SubscriptionOAuthProvider | null;
41
57
  /**
@@ -43,13 +59,15 @@ export declare function subscriptionOAuthProviderFor(provider: string, keySource
43
59
  * answers 429 with the unified rate-limit headers; the ChatGPT backend answers
44
60
  * 429 with a structured `error.code` and `resets_at`. Meta documents no
45
61
  * usage-limit signature for Muse Code plans, so any 429 on one holds it until
46
- * the reset Meta gives, if any. The Codex WebSocket
62
+ * the reset Meta gives, if any. OpenCode Go names its refusal
63
+ * `GoUsageLimitError`. The Codex WebSocket
47
64
  * transport bypasses fetch, so its usage-limit error only survives as message
48
65
  * text and is matched there without a reset time.
49
66
  */
50
67
  export declare function detectSubscriptionUsageLimit(args: {
51
68
  provider: string;
52
69
  keySource: ProviderKeySource;
70
+ model: string;
53
71
  captured: CapturedProviderResponse | undefined;
54
72
  failure: Record<string, unknown>;
55
73
  now?: Date;
@@ -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.
@@ -55,6 +100,7 @@ const SUBSCRIPTION_LABEL = {
55
100
  anthropic_claude_code: "Claude Code",
56
101
  openai_codex: "ChatGPT",
57
102
  meta_muse: "Muse Code",
103
+ opencode_go: "OpenCode Go",
58
104
  };
59
105
  // Providers whose plan page the accounts page links to for buying another.
60
106
  const BUYABLE_SUBSCRIPTIONS = new Set(["anthropic_claude_code", "openai_codex"]);
@@ -67,6 +113,8 @@ export function subscriptionOAuthProviderFor(provider, keySource) {
67
113
  return "openai_codex";
68
114
  if (provider === "meta")
69
115
  return "meta_muse";
116
+ if (provider === "opencode-go")
117
+ return "opencode_go";
70
118
  return null;
71
119
  }
72
120
  /**
@@ -74,7 +122,8 @@ export function subscriptionOAuthProviderFor(provider, keySource) {
74
122
  * answers 429 with the unified rate-limit headers; the ChatGPT backend answers
75
123
  * 429 with a structured `error.code` and `resets_at`. Meta documents no
76
124
  * usage-limit signature for Muse Code plans, so any 429 on one holds it until
77
- * the reset Meta gives, if any. The Codex WebSocket
125
+ * the reset Meta gives, if any. OpenCode Go names its refusal
126
+ * `GoUsageLimitError`. The Codex WebSocket
78
127
  * transport bypasses fetch, so its usage-limit error only survives as message
79
128
  * text and is matched there without a reset time.
80
129
  */
@@ -84,13 +133,20 @@ export function detectSubscriptionUsageLimit(args) {
84
133
  return null;
85
134
  const now = args.now ?? new Date();
86
135
  if (oauthProvider === "anthropic_claude_code") {
87
- return anthropicUsageLimit(args.captured, now);
136
+ return anthropicUsageLimit(args.captured, args.model, now);
88
137
  }
89
138
  if (oauthProvider === "meta_muse")
90
139
  return museUsageLimit(args.captured, now);
91
- return codexUsageLimit(args.captured, providerFailureMessage(args.failure), now);
140
+ if (oauthProvider === "opencode_go")
141
+ return openCodeGoUsageLimit(args.captured, now);
142
+ return codexUsageLimit(args.captured, providerFailureMessage(args.failure), args.model, now);
92
143
  }
93
- function anthropicUsageLimit(captured, now) {
144
+ // Claude Code plans also cap some model families on their own
145
+ // (`seven_day_opus`, `seven_day_sonnet`). The representative claim names the
146
+ // window that refused, and `-fallback: available` says another model can still
147
+ // serve; either way the rest of the plan is not exhausted.
148
+ const ANTHROPIC_MODEL_CLAIM = /^(?:five_hour|seven_day)_(?:opus|sonnet|haiku|fable|mythos)(?:_|$)/;
149
+ function anthropicUsageLimit(captured, model, now) {
94
150
  if (captured === undefined || captured.status !== 429)
95
151
  return null;
96
152
  const status = captured.headers.get("anthropic-ratelimit-unified-status");
@@ -101,25 +157,29 @@ function anthropicUsageLimit(captured, now) {
101
157
  return null;
102
158
  }
103
159
  const claim = captured.headers.get("anthropic-ratelimit-unified-representative-claim");
160
+ const modelLimit = (claim !== null && ANTHROPIC_MODEL_CLAIM.test(claim))
161
+ || captured.headers.get("anthropic-ratelimit-unified-fallback") === "available";
104
162
  return {
105
163
  oauthProvider: "anthropic_claude_code",
106
164
  resetsAt: resetFromUnixSeconds(captured.headers.get("anthropic-ratelimit-unified-reset"), now),
107
- reason: claim ? `Claude Code ${claim.replaceAll("_", " ")} usage limit reached.` : "Claude Code usage limit reached.",
165
+ reason: claim
166
+ ? `Claude Code ${claim.replaceAll("_", " ")} usage limit reached.`
167
+ : modelLimit ? `Claude Code usage limit for ${model} reached.` : "Claude Code usage limit reached.",
168
+ ...(modelLimit ? { model } : {}),
108
169
  };
109
170
  }
110
171
  const CODEX_LIMIT_CODES = new Set(["usage_limit_reached", "usage_not_included"]);
111
172
  const CODEX_LIMIT_MESSAGE = /usage_limit_reached|usage_not_included|hit your ChatGPT usage limit|the usage limit has been reached/i;
112
- function codexUsageLimit(captured, failureMessage, now) {
173
+ function codexUsageLimit(captured, failureMessage, model, now) {
113
174
  if (captured !== undefined && captured.status === 429) {
114
175
  const error = codexErrorBody(captured.bodyText);
115
176
  const code = typeof error?.code === "string" ? error.code : "";
116
177
  if (error !== null && (CODEX_LIMIT_CODES.has(code) || failureMessage.match(CODEX_LIMIT_MESSAGE))) {
117
178
  const plan = typeof error.plan_type === "string" ? ` (${error.plan_type.toLowerCase()} plan)` : "";
118
- return {
119
- oauthProvider: "openai_codex",
120
- resetsAt: laterReset(error.resets_at, captured.headers, now),
121
- reason: `ChatGPT usage limit reached${plan}.`,
122
- };
179
+ const resetsAt = laterReset(error.resets_at, captured.headers, now);
180
+ return codexModelLimitExhausted(captured.headers)
181
+ ? { oauthProvider: "openai_codex", resetsAt, reason: `ChatGPT usage limit for ${model} reached${plan}.`, model }
182
+ : { oauthProvider: "openai_codex", resetsAt, reason: `ChatGPT usage limit reached${plan}.` };
123
183
  }
124
184
  return null;
125
185
  }
@@ -131,6 +191,23 @@ function codexUsageLimit(captured, failureMessage, now) {
131
191
  reason: "ChatGPT usage limit reached.",
132
192
  };
133
193
  }
194
+ // The ChatGPT backend reports each limit as its own header family,
195
+ // `x-<limit>-primary-used-percent`, the plan's own being `x-codex-*`. A refusal
196
+ // while only another family is spent is that model's own cap.
197
+ function codexModelLimitExhausted(headers) {
198
+ let plan = false;
199
+ let other = false;
200
+ headers.forEach((value, name) => {
201
+ const family = /^x-(.+)-(?:primary|secondary)-used-percent$/.exec(name.toLowerCase())?.[1];
202
+ if (family === undefined || !(Number(value) >= 100))
203
+ return;
204
+ if (family === "codex")
205
+ plan = true;
206
+ else
207
+ other = true;
208
+ });
209
+ return other && !plan;
210
+ }
134
211
  function museUsageLimit(captured, now) {
135
212
  if (captured === undefined || captured.status !== 429)
136
213
  return null;
@@ -140,6 +217,23 @@ function museUsageLimit(captured, now) {
140
217
  reason: "Muse Code usage limit reached.",
141
218
  };
142
219
  }
220
+ // OpenCode Go refuses an exhausted plan with 429 and a `GoUsageLimitError`
221
+ // naming the window ("5 hour", "weekly", "monthly"), as OpenCode's own client
222
+ // recognizes it; an upstream's transient 429 on Go does not hold the plan.
223
+ // The reset is `resetsAt` (ISO) when sent, else Retry-After.
224
+ function openCodeGoUsageLimit(captured, now) {
225
+ if (captured === undefined || captured.status !== 429)
226
+ return null;
227
+ if (!captured.bodyText.includes("GoUsageLimitError"))
228
+ return null;
229
+ const window = /"limitName"\s*:\s*"([^"]+)"/.exec(captured.bodyText)?.[1];
230
+ const resetsAt = Date.parse(/"resetsAt"\s*:\s*"([^"]+)"/.exec(captured.bodyText)?.[1] ?? "");
231
+ return {
232
+ oauthProvider: "opencode_go",
233
+ resetsAt: laterReset(Number.isNaN(resetsAt) ? undefined : resetsAt / 1000, captured.headers, now),
234
+ reason: `OpenCode Go ${window ? `${window} ` : ""}usage limit reached.`,
235
+ };
236
+ }
143
237
  function codexErrorBody(bodyText) {
144
238
  try {
145
239
  const parsed = JSON.parse(bodyText);
@@ -191,6 +285,7 @@ export function failureWithSubscriptionUsageLimit(failure, limit) {
191
285
  oauth_provider: limit.oauthProvider,
192
286
  resets_at: limit.resetsAt.toISOString(),
193
287
  reason: limit.reason,
288
+ ...(limit.model !== undefined ? { model: limit.model } : {}),
194
289
  ...(limit.switched === true ? { switched: true } : {}),
195
290
  },
196
291
  };
@@ -209,6 +304,7 @@ export function subscriptionUsageLimitFromFailure(failure) {
209
304
  oauthProvider: oauthProvider,
210
305
  resetsAt,
211
306
  reason: typeof marker.reason === "string" ? marker.reason : "Subscription usage limit reached.",
307
+ ...(typeof marker.model === "string" ? { model: marker.model } : {}),
212
308
  ...(marker.switched === true ? { switched: true } : {}),
213
309
  };
214
310
  }
@@ -219,7 +315,8 @@ export function subscriptionUsageLimitFromFailure(failure) {
219
315
  */
220
316
  export function subscriptionUsageLimitMessage(limit, accountsUrl) {
221
317
  const label = SUBSCRIPTION_LABEL[limit.oauthProvider];
222
- const reached = `Your ${label} subscription usage limit is reached. It resets at ${limit.resetsAt.toISOString()}. `;
318
+ const scope = limit.model === undefined ? "" : ` for ${limit.model}`;
319
+ const reached = `Your ${label} subscription usage limit${scope} is reached. It resets at ${limit.resetsAt.toISOString()}. `;
223
320
  if (accountsUrl === undefined) {
224
321
  return reached
225
322
  + `To keep going now, add another ${label} subscription or mark this one available early with \`dari accounts\`.`;
@@ -237,7 +334,8 @@ export function subscriptionUsageLimitMessage(limit, accountsUrl) {
237
334
  * at <reset>."
238
335
  */
239
336
  export function codexUsageLimitError(limit, accountsUrl) {
240
- if (limit.oauthProvider !== "openai_codex")
337
+ // Codex would show a per-model limit as the whole plan's.
338
+ if (limit.oauthProvider !== "openai_codex" || limit.model !== undefined)
241
339
  return null;
242
340
  const promo = accountsUrl === undefined
243
341
  ? "Add another ChatGPT subscription with `dari accounts`"
@@ -249,6 +347,10 @@ export function codexUsageLimitError(limit, accountsUrl) {
249
347
  }
250
348
  export function subscriptionSwitchedMessage(limit) {
251
349
  const label = SUBSCRIPTION_LABEL[limit.oauthProvider];
350
+ if (limit.model !== undefined) {
351
+ return `Your ${label} subscription usage limit for ${limit.model} is reached; it resets at `
352
+ + `${limit.resetsAt.toISOString()}. Dari routes to other models until then; retry the request.`;
353
+ }
252
354
  return `Your ${label} subscription usage limit is reached. `
253
355
  + `Dari switched to your next connected ${label} subscription; retry the request.`;
254
356
  }
@@ -2,15 +2,18 @@ import { HttpError } from "../http/errors.js";
2
2
  import { explicitModelId } from "../protocol/input/router_model.js";
3
3
  /* A request for `dari/model/<id>` is served by exactly that enabled model,
4
4
  with no selector or lease: the user chose it, like picking a
5
- model in their agent's /model menu. The client's thinking level is kept
6
- when the model supports it; otherwise the model's default level is used. */
5
+ model in their agent's /model menu, or the router fixed it for the
6
+ request's agent role. Routing rules and switch-cost pruning narrow only
7
+ what the selector may pick, so they never remove it. The client's thinking
8
+ level is kept when the model supports it; otherwise the model's default
9
+ level is used. */
7
10
  export function explicitModelDecision(prepared) {
8
11
  const modelId = explicitModelId(prepared.interaction.model);
9
12
  if (modelId === null)
10
13
  return null;
11
14
  if (!prepared.credentials.enabled_models.includes(modelId))
12
15
  throw modelNotEnabled(modelId);
13
- const candidates = prepared.routing.candidateResolution.candidates.filter((candidate) => candidate.model === modelId);
16
+ const candidates = prepared.routing.candidateResolution.allCandidates.filter((candidate) => candidate.model === modelId);
14
17
  if (candidates.length === 0) {
15
18
  throw new HttpError(400, `Model '${modelId}' cannot serve this request.`, "model_unavailable", "model");
16
19
  }
@@ -18,7 +21,9 @@ export function explicitModelDecision(prepared) {
18
21
  const decision = {
19
22
  selectedModel: candidate.model,
20
23
  reasoningEffort: candidate.reasoningEffort,
21
- reason: `Requested model ${modelId} served without selection.`,
24
+ reason: prepared.role === undefined
25
+ ? `Requested model ${modelId} served without selection.`
26
+ : `The router's ${prepared.role} model ${modelId} served without selection.`,
22
27
  };
23
28
  return { decision };
24
29
  }
@@ -1,7 +1,7 @@
1
1
  import { type RoutingContext } from "../context/routing_context.js";
2
2
  import { type InteractionRequest } from "../interaction/types.js";
3
3
  import { type RequestTags, type SessionPin } from "../platform/platform.js";
4
- import type { ClientHarness, ResolvedRouter } from "../types.js";
4
+ import type { ClientHarness, ResolvedRouter, RouterRole } from "../types.js";
5
5
  import type { RoutedRuntimeReporter } from "./runtime_reporter.js";
6
6
  import type { RoutedProtocol } from "./routed_protocol.js";
7
7
  import { type HarnessConversationIdentity } from "./harness_identity/index.js";
@@ -20,6 +20,8 @@ export type PreparedRoutedCompletion = {
20
20
  key: string;
21
21
  pin: SessionPin | null;
22
22
  };
23
+ role?: RouterRole;
24
+ rolePrompt?: string;
23
25
  reporter: RoutedRuntimeReporter;
24
26
  };
25
27
  export declare function prepareRoutedCompletion(args: {
@@ -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 { rolePrompt, withRoleModel } from "./role_model.js";
14
15
  import { strictProviderAccess } from "./strict_provider_access.js";
15
16
  import { scopedHarnessAgentId, scopedHarnessConversationId, scopedHarnessSessionId, } from "./harness_identity/index.js";
16
17
  export async function prepareRoutedCompletion(args) {
@@ -86,7 +87,9 @@ export async function prepareRoutedCompletion(args) {
86
87
  }
87
88
  credentials = conversationCredentials;
88
89
  }
89
- const access = strictProviderAccess(credentials, args.interaction);
90
+ const roleModel = withRoleModel(credentials, args.interaction);
91
+ const prompt = rolePrompt(credentials, args.interaction);
92
+ const access = strictProviderAccess(credentials, roleModel.interaction);
90
93
  credentials = access.credentials;
91
94
  args = {
92
95
  ...args,
@@ -167,6 +170,8 @@ export async function prepareRoutedCompletion(args) {
167
170
  harnessConversationIdentity: args.harnessConversationIdentity,
168
171
  routing,
169
172
  ...(sessionPin === undefined ? {} : { sessionPin }),
173
+ ...(roleModel.role === undefined ? {} : { role: roleModel.role }),
174
+ ...(prompt === undefined ? {} : { rolePrompt: prompt }),
170
175
  reporter,
171
176
  };
172
177
  }
@@ -193,7 +198,7 @@ async function withProviderCredentials(credentials, apiKey, clientHarness) {
193
198
  if (!credential?.apiKey.trim())
194
199
  continue;
195
200
  const plan = credential.subscription;
196
- if (plan !== undefined && !subscriptionServes(plan, model, clientHarness))
201
+ if (plan !== undefined && !subscriptionServes(plan, executionProviderForModel(credentials, model), clientHarness))
197
202
  continue;
198
203
  provider_credentials[model] = credential;
199
204
  if (plan === "openai_codex") {
@@ -0,0 +1,8 @@
1
+ import { type InteractionRequest } from "../interaction/types.js";
2
+ import type { ResolvedRouter, RouterRole } from "../types.js";
3
+ export declare function requestRole(interaction: InteractionRequest): RouterRole | null;
4
+ export declare function withRoleModel(credentials: ResolvedRouter, interaction: InteractionRequest): {
5
+ interaction: InteractionRequest;
6
+ role?: RouterRole;
7
+ };
8
+ export declare function rolePrompt(credentials: ResolvedRouter, interaction: InteractionRequest): string | undefined;
@@ -0,0 +1,27 @@
1
+ import { isBackgroundRequest } from "../interaction/types.js";
2
+ import { EXPLICIT_MODEL_PREFIX } from "../protocol/input/router_model.js";
3
+ /* The agent role a request comes from: subagents include workflow agents, and
4
+ anything else that is not background work (compaction, auxiliary requests,
5
+ side replies) is the main agent. Background work has no role. */
6
+ export function requestRole(interaction) {
7
+ if (isBackgroundRequest(interaction))
8
+ return null;
9
+ const requestClass = interaction.agentContext?.requestClass;
10
+ return requestClass === "subagent" || requestClass === "workflow" ? "subagent" : "main";
11
+ }
12
+ /* A router can fix the model for an agent role. A request from a fixed role
13
+ is served that model as if it had asked for `dari/model/<id>`, whatever
14
+ model it did ask for. */
15
+ export function withRoleModel(credentials, interaction) {
16
+ const role = requestRole(interaction);
17
+ const model = role === null ? null : credentials.role_models?.[role];
18
+ if (!role || !model)
19
+ return { interaction };
20
+ return { interaction: { ...interaction, model: `${EXPLICIT_MODEL_PREFIX}${model}` }, role };
21
+ }
22
+ /* The router's prompt for a request's role, or undefined. */
23
+ export function rolePrompt(credentials, interaction) {
24
+ const role = requestRole(interaction);
25
+ const prompt = role === null ? undefined : credentials.role_prompts?.[role]?.trim();
26
+ return prompt || undefined;
27
+ }
@@ -145,10 +145,11 @@ async function prepareRuntimeExecution(args) {
145
145
  if (explicit) {
146
146
  prepared.reporter.attachServingDecision(explicit.decision);
147
147
  prepared.reporter.attachDecisionDetails({
148
- decision_source: "explicit_model",
148
+ decision_source: prepared.role === undefined ? "explicit_model" : "role_model",
149
149
  explicit_model: {
150
150
  model: explicit.decision.selectedModel,
151
151
  reasoning_effort: explicit.decision.reasoningEffort,
152
+ ...(prepared.role === undefined ? {} : { role: prepared.role }),
152
153
  },
153
154
  });
154
155
  return selectedExecutionPlan(prepared, explicit);
@@ -441,6 +442,7 @@ function providerExecution(prepared, decision) {
441
442
  costEstimates: prepared.routing.reportingCostEstimates,
442
443
  promptCacheKey: prepared.interaction.promptCacheKey,
443
444
  tags: prepared.tags,
445
+ systemPromptSuffix: prepared.rolePrompt,
444
446
  });
445
447
  }
446
448
  function tokenCount(value) {
@@ -1,5 +1,5 @@
1
1
  import { type ReasoningEffort } from "@mupt-ai/dari-router/policy-engine";
2
- import type { ClientHarness } from "../types.js";
2
+ import type { ClientHarness, RouterRoleModels, RouterRolePrompts } from "../types.js";
3
3
  /**
4
4
  * The self-hosted gateway's configuration file (YAML or JSON):
5
5
  *
@@ -15,6 +15,11 @@ import type { ClientHarness } from "../types.js";
15
15
  * - openai/gpt-6.1-sol
16
16
  * subscriptions: true # serve with connected Claude Code / ChatGPT plans
17
17
  * sessionPinning: false # route each session and subagent once, then keep its model
18
+ * roleModels: # optional: serve an agent role one model, without routing
19
+ * main: anthropic/claude-fable-5-2
20
+ * subagent: openai/gpt-6.1-sol
21
+ * rolePrompts: # optional: append to an agent role's system prompt
22
+ * main: Delegate codebase exploration to subagents.
18
23
  * nativeCompaction: false # let Codex compact server-side with the provider's native compaction
19
24
  * providers: # optional: OpenAI-compatible or self-run endpoints
20
25
  * local:
@@ -45,6 +50,8 @@ export type RouterConfig = {
45
50
  sessionPinning: boolean;
46
51
  nativeCompaction: boolean;
47
52
  zdr: boolean;
53
+ roleModels: RouterRoleModels;
54
+ rolePrompts: RouterRolePrompts;
48
55
  };
49
56
  export type RouterModelConfig = {
50
57
  id: string;
@@ -62,5 +69,6 @@ export declare function parseGatewayConfig(raw: unknown): GatewayConfig;
62
69
  export declare function routerModelsFor(router: RouterConfig, clientHarness?: ClientHarness): RouterModelConfig[];
63
70
  /** Every model a router can serve, to any client. */
64
71
  export declare function allRouterModels(router: RouterConfig): RouterModelConfig[];
72
+ export declare const ROLE_PROMPT_MAX_LENGTH = 4000;
65
73
  /** Read one model list of a router, naming `field` in what it rejects. */
66
74
  export declare function parseRouterModels(routerId: string, field: string, raw: unknown): RouterModelConfig[];
@@ -108,9 +108,12 @@ function parseRouter(id, raw) {
108
108
  agentModels[agent] = parseRouterModels(id, `agentModels.${agent}`, models);
109
109
  }
110
110
  }
111
+ const models = parseRouterModels(id, "models", raw.models);
111
112
  return {
112
- models: parseRouterModels(id, "models", raw.models),
113
+ models,
113
114
  agentModels,
115
+ roleModels: parseRoleModels(id, raw.roleModels, [models, ...Object.values(agentModels)].flat()),
116
+ rolePrompts: parseRolePrompts(id, raw.rolePrompts),
114
117
  retries: optionalRetries(raw.retries, `routers.${id}.retries`) ?? 1,
115
118
  subscriptions: optionalBoolean(raw.subscriptions, `routers.${id}.subscriptions`) ?? true,
116
119
  sessionPinning: optionalBoolean(raw.sessionPinning, `routers.${id}.sessionPinning`) ?? false,
@@ -118,6 +121,46 @@ function parseRouter(id, raw) {
118
121
  zdr: optionalBoolean(raw.zdr, `routers.${id}.zdr`) ?? false,
119
122
  };
120
123
  }
124
+ const ROUTER_ROLES = ["main", "subagent"];
125
+ function parseRoleModels(routerId, raw, models) {
126
+ if (raw === undefined)
127
+ return {};
128
+ if (!isRecord(raw))
129
+ throw new Error(`routers.${routerId}.roleModels must map main and subagent to models.`);
130
+ const roleModels = {};
131
+ for (const [role, model] of Object.entries(raw)) {
132
+ if (!ROUTER_ROLES.includes(role)) {
133
+ throw new Error(`routers.${routerId}.roleModels has an unknown role "${role}"; use main or subagent.`);
134
+ }
135
+ if (model === null)
136
+ continue;
137
+ if (typeof model !== "string" || !models.some((listed) => listed.id === model)) {
138
+ throw new Error(`routers.${routerId}.roleModels.${role} must be one of the router's models.`);
139
+ }
140
+ roleModels[role] = model;
141
+ }
142
+ return roleModels;
143
+ }
144
+ export const ROLE_PROMPT_MAX_LENGTH = 4000;
145
+ function parseRolePrompts(routerId, raw) {
146
+ if (raw === undefined)
147
+ return {};
148
+ if (!isRecord(raw))
149
+ throw new Error(`routers.${routerId}.rolePrompts must map main and subagent to text.`);
150
+ const rolePrompts = {};
151
+ for (const [role, prompt] of Object.entries(raw)) {
152
+ if (!ROUTER_ROLES.includes(role)) {
153
+ throw new Error(`routers.${routerId}.rolePrompts has an unknown role "${role}"; use main or subagent.`);
154
+ }
155
+ if (prompt === null)
156
+ continue;
157
+ if (typeof prompt !== "string" || !prompt.trim() || prompt.length > ROLE_PROMPT_MAX_LENGTH) {
158
+ throw new Error(`routers.${routerId}.rolePrompts.${role} must be text of at most ${ROLE_PROMPT_MAX_LENGTH} characters.`);
159
+ }
160
+ rolePrompts[role] = prompt.trim();
161
+ }
162
+ return rolePrompts;
163
+ }
121
164
  /** Read one model list of a router, naming `field` in what it rejects. */
122
165
  export function parseRouterModels(routerId, field, raw) {
123
166
  if (!Array.isArray(raw) || raw.length === 0) {
@@ -37,8 +37,13 @@ export function createSelfHostedPlatform(deps) {
37
37
  apiKey: await freshAccessToken(deps.subscriptions, next, { fetch: deps.fetch }),
38
38
  };
39
39
  },
40
- markSubscriptionUnavailable: async (hold) => hold.credentialId !== undefined &&
41
- deps.subscriptions.markUnavailable(hold.credentialId, hold.limit.resetsAt, hold.limit.reason),
40
+ async markSubscriptionUnavailable({ credentialId, limit }) {
41
+ if (credentialId === undefined)
42
+ return false;
43
+ return limit.model === undefined
44
+ ? deps.subscriptions.markUnavailable(credentialId, limit.resetsAt, limit.reason)
45
+ : deps.subscriptions.holdModel(credentialId, limit.model, limit.resetsAt, limit.reason);
46
+ },
42
47
  async recordUsage() {
43
48
  // Resolution never reports a "managed" key source here.
44
49
  throw new Error("The self-hosted gateway has no managed provider keys to account.");
@@ -4,7 +4,7 @@ import { HttpError } from "../http/errors.js";
4
4
  import { codexModelConfig } from "../models/subscriptions.js";
5
5
  import { registeredModelPrice } from "../providers/pi.js";
6
6
  import { allRouterModels, routerModelsFor, } from "./config.js";
7
- import { freshAccessToken, } from "./subscriptions/index.js";
7
+ import { activeModelHolds, freshAccessToken, } from "./subscriptions/index.js";
8
8
  // A self-hosted gateway is one tenant; these stand in for the hosted
9
9
  // organization and the user a personal subscription belongs to.
10
10
  export const SELF_HOSTED_ORGANIZATION_ID = "self-hosted";
@@ -55,7 +55,17 @@ export async function resolveSelfHostedRouter(deps, request) {
55
55
  const apiKey = await configuredProviderApiKey(deps, provider);
56
56
  credentials.set(provider, apiKey ? { key: apiKey, source: "user" } : null);
57
57
  }
58
- const models = listed.filter((model) => credentials.get(providerForModel(model.id)) != null);
58
+ // A model at its own limit on the serving plan leaves routing until it resets.
59
+ const models = listed.filter((model) => {
60
+ const credential = credentials.get(providerForModel(model.id));
61
+ if (credential == null)
62
+ return false;
63
+ const plan = credential.subscription;
64
+ if (plan === undefined || !activeModelHolds(plan, now).some((hold) => hold.model === model.id))
65
+ return true;
66
+ exhausted.add(plan.provider);
67
+ return false;
68
+ });
59
69
  if (models.length === 0) {
60
70
  const missing = [...credentials].filter(([, credential]) => credential == null).map(([provider]) => provider);
61
71
  throw unavailableRouterError(request.routerId, exhausted, missing);
@@ -77,6 +87,8 @@ export async function resolveSelfHostedRouter(deps, request) {
77
87
  primary_retries: router.retries,
78
88
  routing_strategy: "dari",
79
89
  custom_config: null,
90
+ role_models: router.roleModels,
91
+ role_prompts: router.rolePrompts,
80
92
  evals: [],
81
93
  model_thinking_levels: thinkingLevels(listed),
82
94
  model_prices: {},
@@ -149,6 +161,8 @@ function subscriptionProviderFor(provider, clientHarness) {
149
161
  return clientHarness === "muse_code" ? "meta_muse" : null;
150
162
  if (provider === "openai")
151
163
  return "openai_codex";
164
+ if (provider === "opencode-go")
165
+ return "opencode_go";
152
166
  return null;
153
167
  }
154
168
  // A ChatGPT plan serves OpenAI models as the `openai-codex` provider, and the
@@ -165,6 +179,7 @@ const SUBSCRIPTION_PLAN_NAMES = {
165
179
  anthropic_claude_code: "Claude Code",
166
180
  openai_codex: "ChatGPT",
167
181
  meta_muse: "Muse Code",
182
+ opencode_go: "OpenCode Go",
168
183
  };
169
184
  /**
170
185
  * Providers a router lists that no credential can serve: no API key and no
@@ -193,7 +208,7 @@ function unavailableRouterError(routerId, exhausted, missing) {
193
208
  const plans = [...exhausted]
194
209
  .map((provider) => SUBSCRIPTION_PLAN_NAMES[provider])
195
210
  .join(" and ");
196
- return new HttpError(424, `Every connected ${plans} subscription is at its usage limit, and no API key can serve router ${routerId} instead.${missingNote}`, "personal_subscription_unavailable");
211
+ return new HttpError(424, `Every connected ${plans} subscription is at its usage limit for the models router ${routerId} lists, and no API key can serve them instead.${missingNote}`, "personal_subscription_unavailable");
197
212
  }
198
213
  return new HttpError(424, `No credentials can serve router ${routerId}.${missingNote} Set each provider's API key or connect a subscription that can serve it.`, "provider_credentials_missing");
199
214
  }
@@ -2,13 +2,14 @@
2
2
  * A self-hosted gateway, run through its entrypoint as its own process so no
3
3
  * other test file's module mocks reach it, serving two Claude Code plans
4
4
  * (access tokens `sk-ant-oat01-a` and `-b`) against a local stand-in for
5
- * Anthropic. `upstream` answers each provider call given the plan's token.
5
+ * Anthropic. `upstream` answers each provider call given the plan's token
6
+ * and the native model it asks for. The router lists `models`.
6
7
  */
7
- export declare function startSubscriptionGateway(upstream: (token: string) => Response): Promise<{
8
+ export declare function startSubscriptionGateway(upstream: (token: string, model: string) => Response, models?: string[]): Promise<{
8
9
  served: string[];
9
10
  planIds: string[];
10
11
  plan: (id: string) => import("./subscriptions/store.js").SubscriptionCredential | null;
11
- claudeCode: (sessionId: string, text: string) => Promise<Response>;
12
+ claudeCode: (sessionId: string, text: string, model?: string) => Promise<Response>;
12
13
  stop: () => Promise<void>;
13
14
  }>;
14
15
  /** A streamed Anthropic reply with the given response headers. */