@mupt-ai/dari-gateway 1.0.310 → 1.0.311

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 (72) hide show
  1. package/README.md +4 -0
  2. package/dari-gateway.example.yaml +10 -0
  3. package/dist/context/routing_context.js +4 -1
  4. package/dist/interaction/system_prompt.d.ts +2 -0
  5. package/dist/interaction/system_prompt.js +21 -0
  6. package/dist/models/canonical.d.ts +2 -0
  7. package/dist/models/canonical.js +4 -0
  8. package/dist/models/catalog.js +1 -0
  9. package/dist/models/provider_defaults.js +4 -0
  10. package/dist/models/subscriptions.d.ts +4 -3
  11. package/dist/models/subscriptions.js +13 -9
  12. package/dist/platform/platform.d.ts +3 -0
  13. package/dist/providers/codex_usage.d.ts +13 -0
  14. package/dist/providers/codex_usage.js +46 -2
  15. package/dist/providers/execution.js +55 -6
  16. package/dist/providers/key_check.js +3 -0
  17. package/dist/providers/pi.js +5 -0
  18. package/dist/providers/pi_options.js +8 -0
  19. package/dist/providers/provider_call.d.ts +2 -0
  20. package/dist/providers/provider_call.js +4 -2
  21. package/dist/providers/subscription_limits.d.ts +5 -2
  22. package/dist/providers/subscription_limits.js +70 -13
  23. package/dist/runtime/explicit_model.js +9 -4
  24. package/dist/runtime/prepare_routed_completion.d.ts +3 -1
  25. package/dist/runtime/prepare_routed_completion.js +7 -2
  26. package/dist/runtime/role_model.d.ts +8 -0
  27. package/dist/runtime/role_model.js +27 -0
  28. package/dist/runtime/routed_runtime.js +3 -1
  29. package/dist/self_host/config.d.ts +9 -1
  30. package/dist/self_host/config.js +44 -1
  31. package/dist/self_host/platform.js +7 -2
  32. package/dist/self_host/resolve.js +18 -3
  33. package/dist/self_host/subscription_test_gateway.d.ts +4 -3
  34. package/dist/self_host/subscription_test_gateway.js +11 -8
  35. package/dist/self_host/subscriptions/http.js +9 -1
  36. package/dist/self_host/subscriptions/index.d.ts +3 -2
  37. package/dist/self_host/subscriptions/index.js +3 -2
  38. package/dist/self_host/subscriptions/oauth.d.ts +8 -4
  39. package/dist/self_host/subscriptions/oauth.js +75 -0
  40. package/dist/self_host/subscriptions/store.d.ts +17 -2
  41. package/dist/self_host/subscriptions/store.js +53 -8
  42. package/dist/strategies/route_decision.js +0 -5
  43. package/dist/types.d.ts +6 -1
  44. package/package.json +2 -2
  45. package/src/context/routing_context.ts +4 -1
  46. package/src/interaction/system_prompt.ts +26 -0
  47. package/src/models/canonical.ts +5 -0
  48. package/src/models/catalog.ts +1 -0
  49. package/src/models/provider_defaults.ts +4 -0
  50. package/src/models/subscriptions.ts +14 -14
  51. package/src/platform/platform.ts +3 -0
  52. package/src/providers/codex_usage.ts +59 -2
  53. package/src/providers/execution.ts +58 -6
  54. package/src/providers/key_check.ts +2 -0
  55. package/src/providers/pi.ts +5 -0
  56. package/src/providers/pi_options.ts +7 -0
  57. package/src/providers/provider_call.ts +7 -2
  58. package/src/providers/subscription_limits.ts +78 -14
  59. package/src/runtime/explicit_model.ts +9 -4
  60. package/src/runtime/prepare_routed_completion.ts +13 -3
  61. package/src/runtime/role_model.ts +35 -0
  62. package/src/runtime/routed_runtime.ts +3 -1
  63. package/src/self_host/config.ts +55 -2
  64. package/src/self_host/platform.ts +6 -3
  65. package/src/self_host/resolve.ts +15 -2
  66. package/src/self_host/subscription_test_gateway.ts +14 -8
  67. package/src/self_host/subscriptions/http.ts +15 -1
  68. package/src/self_host/subscriptions/index.ts +4 -1
  69. package/src/self_host/subscriptions/oauth.ts +104 -5
  70. package/src/self_host/subscriptions/store.ts +65 -9
  71. package/src/strategies/route_decision.ts +0 -9
  72. package/src/types.ts +13 -1
@@ -49,7 +49,7 @@ import {
49
49
  import type { NextSubscription } from "../platform/platform.js";
50
50
  import { providerResponseCaptureFromError, type ProviderResponseCapture } from "./response_capture.js";
51
51
  import { createStreamFinalizer } from "./stream_finalization.js";
52
- import { readCodexUsage } from "./codex_usage.js";
52
+ import { readCodexModelLimitReset, readCodexUsage } from "./codex_usage.js";
53
53
  import {
54
54
  detectSubscriptionUsageLimit,
55
55
  codexUsageLimitError,
@@ -60,6 +60,7 @@ import {
60
60
  subscriptionUsageLimitFromFailure,
61
61
  subscriptionSwitchedMessage,
62
62
  subscriptionUsageLimitMessage,
63
+ type SubscriptionUsageLimit,
63
64
  } from "./subscription_limits.js";
64
65
 
65
66
  export type ProviderChoice = {
@@ -718,14 +719,16 @@ async function providerFailedAttempt(
718
719
  execution: ProviderExecution,
719
720
  responseCapture: ProviderResponseCapture | undefined,
720
721
  ): Promise<ProviderAttemptFailure> {
721
- const limit = detectSubscriptionUsageLimit({
722
+ const detected = detectSubscriptionUsageLimit({
722
723
  provider: execution.provider,
723
724
  keySource: execution.providerKeySource,
725
+ model: execution.model,
724
726
  captured: responseCapture?.last,
725
727
  failure: message,
726
728
  });
727
- if (limit === null) {
729
+ if (detected === null) {
728
730
  const status = responseCapture?.last?.status;
731
+ if (execution.providerKeySource === "subscription") logUnclassifiedRefusal(execution, responseCapture);
729
732
  // The customer's own key was refused: theirs to fix, not a gateway fault.
730
733
  const rejected = execution.providerKeySource === "user" && (status === 401 || status === 403);
731
734
  return {
@@ -737,10 +740,15 @@ async function providerFailedAttempt(
737
740
  retryable: !isPromptPolicyRejection(message),
738
741
  };
739
742
  }
743
+ const limit = detected.oauthProvider === "openai_codex" && detected.model === undefined
744
+ && execution.subscriptionUserId !== undefined
745
+ ? await withCodexModelLimit(detected, execution)
746
+ : detected;
740
747
  // Retrying an exhausted plan cannot succeed. The platform learns about it
741
748
  // before this request returns so the next resolve already serves the
742
749
  // user's next subscription, or the model's API credential when the router
743
- // allows subscription API fallback for it.
750
+ // allows subscription API fallback for it. A limit on one model holds only
751
+ // that model, and the next resolve routes to the others.
744
752
  const switched = execution.subscriptionUserId !== undefined
745
753
  && await holdSubscription({
746
754
  userId: execution.subscriptionUserId,
@@ -748,8 +756,9 @@ async function providerFailedAttempt(
748
756
  limit,
749
757
  });
750
758
  // Nothing reached the client yet, so the same request is retried on the
751
- // next plan at once when the platform names it.
752
- const nextSubscription = switched
759
+ // next plan at once when the platform names it. The same plan still serves
760
+ // after a model limit, so there is no next plan to retry on.
761
+ const nextSubscription = switched && limit.model === undefined
753
762
  ? await nextSubscriptionFor(execution)
754
763
  : undefined;
755
764
  return {
@@ -808,6 +817,49 @@ function usageHasTokens(usage: unknown): boolean {
808
817
  });
809
818
  }
810
819
 
820
+ // Codex's WebSocket transport carries no headers, and a refusal over HTTP may
821
+ // carry none of the per-limit families, so the usage report tells whether the
822
+ // plan or only this model's own cap is spent. Unknown keeps the plan hold.
823
+ async function withCodexModelLimit(
824
+ limit: SubscriptionUsageLimit,
825
+ execution: ProviderExecution,
826
+ ): Promise<SubscriptionUsageLimit> {
827
+ try {
828
+ const resetsAt = await readCodexModelLimitReset({
829
+ accessToken: execution.apiKey,
830
+ baseUrl: execution.endpoint?.baseUrl ?? execution.config?.base_url ?? undefined,
831
+ });
832
+ if (resetsAt === null) return limit;
833
+ return { ...limit, model: execution.model, resetsAt, reason: `ChatGPT usage limit for ${execution.model} reached.` };
834
+ } catch (error) {
835
+ console.error("codex usage report for a usage limit failed", error);
836
+ return limit;
837
+ }
838
+ }
839
+
840
+ // A subscription refusal no rule recognizes may be a usage limit in a shape
841
+ // not seen yet (a new per-model cap). Log what identifies one, never content.
842
+ function logUnclassifiedRefusal(
843
+ execution: ProviderExecution,
844
+ responseCapture: ProviderResponseCapture | undefined,
845
+ ): void {
846
+ const captured = responseCapture?.last;
847
+ if (captured === undefined || (captured.status !== 403 && captured.status !== 429)) return;
848
+ // Claude Code's per-minute limit, a known transient refusal.
849
+ if (captured.headers.get("anthropic-ratelimit-unified-status")?.startsWith("allowed")) return;
850
+ const headers: Record<string, string> = {};
851
+ captured.headers.forEach((value, name) => {
852
+ if (/ratelimit|rate-limit|used-percent|reset|retry-after|limit-name/i.test(name)) headers[name] = value;
853
+ });
854
+ console.warn("unclassified subscription refusal", JSON.stringify({
855
+ provider: execution.provider,
856
+ model: execution.model,
857
+ status: captured.status,
858
+ headers,
859
+ body: captured.bodyText.slice(0, 500),
860
+ }));
861
+ }
862
+
811
863
  function isPromptPolicyRejection(message: Record<string, unknown>): boolean {
812
864
  const text = providerFailureMessage(message).toLowerCase();
813
865
  return text.includes("invalid prompt") && text.includes("usage policy");
@@ -55,6 +55,8 @@ function keyCheckRequest(
55
55
  if (endpoint === undefined) {
56
56
  if (provider === "openrouter") return { url: "https://openrouter.ai/api/v1/key", headers: bearer };
57
57
  if (provider === "vercel-ai-gateway") return { url: "https://ai-gateway.vercel.sh/v1/credits", headers: bearer };
58
+ // OpenCode Go's models list is public, so it cannot tell a bad key.
59
+ if (provider === "opencode-go") return null;
58
60
  }
59
61
  const target = endpoint
60
62
  ?? (getBuiltinModels(provider as never) as unknown as ProviderKeyEndpoint[] | undefined)?.[0];
@@ -114,6 +114,11 @@ function piStreamSimple(
114
114
  ): AssistantMessageEventStream {
115
115
  const api = PI_APIS[String(model.api)];
116
116
  if (!api) throw new Error(`No Pi API implementation for ${String(model.api)}.`);
117
+ // The Anthropic SDK adds ANTHROPIC_CUSTOM_HEADERS from the process
118
+ // environment to every request. A gateway started from a Claude Code
119
+ // session inherits Dari's own `Authorization` there, which would replace
120
+ // the credential the gateway resolved; upstream headers are the gateway's.
121
+ delete process.env.ANTHROPIC_CUSTOM_HEADERS;
117
122
  return api.streamSimple(model as unknown as Model<Api>, normalizeContext(context as unknown as Context), options);
118
123
  }
119
124
 
@@ -77,6 +77,13 @@ export function buildOptions(
77
77
  if (model.provider === "meta" && request.museCodeClientId !== undefined) {
78
78
  headers["x-client-id"] = request.museCodeClientId;
79
79
  }
80
+ // OpenCode Go serves coding agents that name themselves and send a stable
81
+ // session id; a generic SDK user agent reads as abuse.
82
+ // https://opencode.ai/docs/go/
83
+ if (model.provider === "opencode-go") {
84
+ headers["user-agent"] = "dari-gateway";
85
+ if (sessionId) headers["x-opencode-session"] = sessionId;
86
+ }
80
87
  // Pi's Anthropic transport honors compat.supportsTemperature; the OpenAI
81
88
  // transports forward temperature regardless, so drop it here for models
82
89
  // that reject it instead of failing the whole request.
@@ -49,6 +49,7 @@ import {
49
49
  type ProviderEventStream,
50
50
  } from "./pi.js";
51
51
  import { promptTokenEstimateFor, type PromptTokenEstimate } from "./cancel_estimate.js";
52
+ import { withSystemPromptSuffix } from "../interaction/system_prompt.js";
52
53
 
53
54
  type ProviderCallConfig = {
54
55
  model: string;
@@ -62,6 +63,8 @@ type ProviderCallConfig = {
62
63
  promptEstimate: PromptTokenEstimate | undefined;
63
64
  // A platform-supplied endpoint replacing the model's configured one.
64
65
  endpoint?: ProviderEndpoint;
66
+ // Appended to the end of the system prompt sent to the provider.
67
+ systemPromptSuffix?: string;
65
68
  };
66
69
 
67
70
  export type ProviderExecution = ProviderCallConfig & {
@@ -107,6 +110,7 @@ export function prepareProviderExecution(args: {
107
110
  promptCacheKey?: string;
108
111
  costEstimates?: readonly CandidateCostEstimate[];
109
112
  tags?: RequestTags;
113
+ systemPromptSuffix?: string;
110
114
  }): ProviderExecution {
111
115
  const model = args.decision.selectedModel;
112
116
  const promptEstimate = promptTokenEstimateFor(args.costEstimates, model, args.decision.reasoningEffort);
@@ -146,6 +150,7 @@ export function prepareProviderExecution(args: {
146
150
  : args.conversationId,
147
151
  reasoningEffort: args.decision.reasoningEffort,
148
152
  promptEstimate,
153
+ ...(args.systemPromptSuffix ? { systemPromptSuffix: args.systemPromptSuffix } : {}),
149
154
  ...(supplied?.baseUrl || supplied?.headers
150
155
  ? { endpoint: { baseUrl: supplied.baseUrl, headers: supplied.headers } }
151
156
  : {}),
@@ -230,7 +235,7 @@ export async function startProviderStream(args: {
230
235
  try {
231
236
  const providerStream = await streamInteractionModel({
232
237
  model: args.execution.model,
233
- request: args.interaction,
238
+ request: withSystemPromptSuffix(args.interaction, args.execution.systemPromptSuffix),
234
239
  apiKey: args.execution.apiKey,
235
240
  auth: await awsRoleCredentials.resolve(args.execution.auth),
236
241
  pricing: args.execution.pricing,
@@ -325,7 +330,7 @@ async function completeProvider(args: {
325
330
  const providerStartedAt = new Date();
326
331
  const completion = await completeInteractionModel({
327
332
  model: args.execution.model,
328
- request: args.interaction,
333
+ request: withSystemPromptSuffix(args.interaction, args.execution.systemPromptSuffix),
329
334
  apiKey: args.execution.apiKey,
330
335
  auth: await awsRoleCredentials.resolve(args.execution.auth),
331
336
  pricing: args.execution.pricing,
@@ -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
 
@@ -103,6 +107,7 @@ const SUBSCRIPTION_LABEL: Record<SubscriptionOAuthProvider, string> = {
103
107
  anthropic_claude_code: "Claude Code",
104
108
  openai_codex: "ChatGPT",
105
109
  meta_muse: "Muse Code",
110
+ opencode_go: "OpenCode Go",
106
111
  };
107
112
 
108
113
  // Providers whose plan page the accounts page links to for buying another.
@@ -116,6 +121,7 @@ export function subscriptionOAuthProviderFor(
116
121
  if (provider === "anthropic") return "anthropic_claude_code";
117
122
  if (provider === "openai" || provider === "openai-codex") return "openai_codex";
118
123
  if (provider === "meta") return "meta_muse";
124
+ if (provider === "opencode-go") return "opencode_go";
119
125
  return null;
120
126
  }
121
127
 
@@ -124,13 +130,16 @@ export function subscriptionOAuthProviderFor(
124
130
  * answers 429 with the unified rate-limit headers; the ChatGPT backend answers
125
131
  * 429 with a structured `error.code` and `resets_at`. Meta documents no
126
132
  * 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
133
+ * the reset Meta gives, if any. OpenCode Go names its refusal
134
+ * `GoUsageLimitError`. The Codex WebSocket
128
135
  * transport bypasses fetch, so its usage-limit error only survives as message
129
136
  * text and is matched there without a reset time.
130
137
  */
131
138
  export function detectSubscriptionUsageLimit(args: {
132
139
  provider: string;
133
140
  keySource: ProviderKeySource;
141
+ // The routed model, named on a limit that covers only it.
142
+ model: string;
134
143
  captured: CapturedProviderResponse | undefined;
135
144
  failure: Record<string, unknown>;
136
145
  now?: Date;
@@ -139,14 +148,22 @@ export function detectSubscriptionUsageLimit(args: {
139
148
  if (oauthProvider === null) return null;
140
149
  const now = args.now ?? new Date();
141
150
  if (oauthProvider === "anthropic_claude_code") {
142
- return anthropicUsageLimit(args.captured, now);
151
+ return anthropicUsageLimit(args.captured, args.model, now);
143
152
  }
144
153
  if (oauthProvider === "meta_muse") return museUsageLimit(args.captured, now);
145
- return codexUsageLimit(args.captured, providerFailureMessage(args.failure), now);
154
+ if (oauthProvider === "opencode_go") return openCodeGoUsageLimit(args.captured, now);
155
+ return codexUsageLimit(args.captured, providerFailureMessage(args.failure), args.model, now);
146
156
  }
147
157
 
158
+ // Claude Code plans also cap some model families on their own
159
+ // (`seven_day_opus`, `seven_day_sonnet`). The representative claim names the
160
+ // window that refused, and `-fallback: available` says another model can still
161
+ // serve; either way the rest of the plan is not exhausted.
162
+ const ANTHROPIC_MODEL_CLAIM = /^(?:five_hour|seven_day)_(?:opus|sonnet|haiku|fable|mythos)(?:_|$)/;
163
+
148
164
  function anthropicUsageLimit(
149
165
  captured: CapturedProviderResponse | undefined,
166
+ model: string,
150
167
  now: Date,
151
168
  ): SubscriptionUsageLimit | null {
152
169
  if (captured === undefined || captured.status !== 429) return null;
@@ -158,10 +175,15 @@ function anthropicUsageLimit(
158
175
  return null;
159
176
  }
160
177
  const claim = captured.headers.get("anthropic-ratelimit-unified-representative-claim");
178
+ const modelLimit = (claim !== null && ANTHROPIC_MODEL_CLAIM.test(claim))
179
+ || captured.headers.get("anthropic-ratelimit-unified-fallback") === "available";
161
180
  return {
162
181
  oauthProvider: "anthropic_claude_code",
163
182
  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.",
183
+ reason: claim
184
+ ? `Claude Code ${claim.replaceAll("_", " ")} usage limit reached.`
185
+ : modelLimit ? `Claude Code usage limit for ${model} reached.` : "Claude Code usage limit reached.",
186
+ ...(modelLimit ? { model } : {}),
165
187
  };
166
188
  }
167
189
 
@@ -171,6 +193,7 @@ const CODEX_LIMIT_MESSAGE = /usage_limit_reached|usage_not_included|hit your Cha
171
193
  function codexUsageLimit(
172
194
  captured: CapturedProviderResponse | undefined,
173
195
  failureMessage: string,
196
+ model: string,
174
197
  now: Date,
175
198
  ): SubscriptionUsageLimit | null {
176
199
  if (captured !== undefined && captured.status === 429) {
@@ -178,11 +201,10 @@ function codexUsageLimit(
178
201
  const code = typeof error?.code === "string" ? error.code : "";
179
202
  if (error !== null && (CODEX_LIMIT_CODES.has(code) || failureMessage.match(CODEX_LIMIT_MESSAGE))) {
180
203
  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
- };
204
+ const resetsAt = laterReset(error.resets_at, captured.headers, now);
205
+ return codexModelLimitExhausted(captured.headers)
206
+ ? { oauthProvider: "openai_codex", resetsAt, reason: `ChatGPT usage limit for ${model} reached${plan}.`, model }
207
+ : { oauthProvider: "openai_codex", resetsAt, reason: `ChatGPT usage limit reached${plan}.` };
186
208
  }
187
209
  return null;
188
210
  }
@@ -194,6 +216,21 @@ function codexUsageLimit(
194
216
  };
195
217
  }
196
218
 
219
+ // The ChatGPT backend reports each limit as its own header family,
220
+ // `x-<limit>-primary-used-percent`, the plan's own being `x-codex-*`. A refusal
221
+ // while only another family is spent is that model's own cap.
222
+ function codexModelLimitExhausted(headers: Headers): boolean {
223
+ let plan = false;
224
+ let other = false;
225
+ headers.forEach((value, name) => {
226
+ const family = /^x-(.+)-(?:primary|secondary)-used-percent$/.exec(name.toLowerCase())?.[1];
227
+ if (family === undefined || !(Number(value) >= 100)) return;
228
+ if (family === "codex") plan = true;
229
+ else other = true;
230
+ });
231
+ return other && !plan;
232
+ }
233
+
197
234
  function museUsageLimit(
198
235
  captured: CapturedProviderResponse | undefined,
199
236
  now: Date,
@@ -206,6 +243,25 @@ function museUsageLimit(
206
243
  };
207
244
  }
208
245
 
246
+ // OpenCode Go refuses an exhausted plan with 429 and a `GoUsageLimitError`
247
+ // naming the window ("5 hour", "weekly", "monthly"), as OpenCode's own client
248
+ // recognizes it; an upstream's transient 429 on Go does not hold the plan.
249
+ // The reset is `resetsAt` (ISO) when sent, else Retry-After.
250
+ function openCodeGoUsageLimit(
251
+ captured: CapturedProviderResponse | undefined,
252
+ now: Date,
253
+ ): SubscriptionUsageLimit | null {
254
+ if (captured === undefined || captured.status !== 429) return null;
255
+ if (!captured.bodyText.includes("GoUsageLimitError")) return null;
256
+ const window = /"limitName"\s*:\s*"([^"]+)"/.exec(captured.bodyText)?.[1];
257
+ const resetsAt = Date.parse(/"resetsAt"\s*:\s*"([^"]+)"/.exec(captured.bodyText)?.[1] ?? "");
258
+ return {
259
+ oauthProvider: "opencode_go",
260
+ resetsAt: laterReset(Number.isNaN(resetsAt) ? undefined : resetsAt / 1000, captured.headers, now),
261
+ reason: `OpenCode Go ${window ? `${window} ` : ""}usage limit reached.`,
262
+ };
263
+ }
264
+
209
265
  function codexErrorBody(bodyText: string): Record<string, unknown> | null {
210
266
  try {
211
267
  const parsed: unknown = JSON.parse(bodyText);
@@ -262,6 +318,7 @@ export function failureWithSubscriptionUsageLimit(
262
318
  oauth_provider: limit.oauthProvider,
263
319
  resets_at: limit.resetsAt.toISOString(),
264
320
  reason: limit.reason,
321
+ ...(limit.model !== undefined ? { model: limit.model } : {}),
265
322
  ...(limit.switched === true ? { switched: true } : {}),
266
323
  },
267
324
  };
@@ -284,6 +341,7 @@ export function subscriptionUsageLimitFromFailure(
284
341
  oauthProvider: oauthProvider as SubscriptionOAuthProvider,
285
342
  resetsAt,
286
343
  reason: typeof marker.reason === "string" ? marker.reason : "Subscription usage limit reached.",
344
+ ...(typeof marker.model === "string" ? { model: marker.model } : {}),
287
345
  ...(marker.switched === true ? { switched: true } : {}),
288
346
  };
289
347
  }
@@ -295,7 +353,8 @@ export function subscriptionUsageLimitFromFailure(
295
353
  */
296
354
  export function subscriptionUsageLimitMessage(limit: SubscriptionUsageLimit, accountsUrl?: string): string {
297
355
  const label = SUBSCRIPTION_LABEL[limit.oauthProvider];
298
- const reached = `Your ${label} subscription usage limit is reached. It resets at ${limit.resetsAt.toISOString()}. `;
356
+ const scope = limit.model === undefined ? "" : ` for ${limit.model}`;
357
+ const reached = `Your ${label} subscription usage limit${scope} is reached. It resets at ${limit.resetsAt.toISOString()}. `;
299
358
  if (accountsUrl === undefined) {
300
359
  return reached
301
360
  + `To keep going now, add another ${label} subscription or mark this one available early with \`dari accounts\`.`;
@@ -317,7 +376,8 @@ export function codexUsageLimitError(limit: SubscriptionUsageLimit, accountsUrl?
317
376
  body: Record<string, unknown>;
318
377
  headers: Record<string, string>;
319
378
  } | null {
320
- if (limit.oauthProvider !== "openai_codex") return null;
379
+ // Codex would show a per-model limit as the whole plan's.
380
+ if (limit.oauthProvider !== "openai_codex" || limit.model !== undefined) return null;
321
381
  const promo = accountsUrl === undefined
322
382
  ? "Add another ChatGPT subscription with `dari accounts`"
323
383
  : `Add another ChatGPT subscription at ${accountsUrl}?buy=openai_codex`;
@@ -329,6 +389,10 @@ export function codexUsageLimitError(limit: SubscriptionUsageLimit, accountsUrl?
329
389
 
330
390
  export function subscriptionSwitchedMessage(limit: SubscriptionUsageLimit): string {
331
391
  const label = SUBSCRIPTION_LABEL[limit.oauthProvider];
392
+ if (limit.model !== undefined) {
393
+ return `Your ${label} subscription usage limit for ${limit.model} is reached; it resets at `
394
+ + `${limit.resetsAt.toISOString()}. Dari routes to other models until then; retry the request.`;
395
+ }
332
396
  return `Your ${label} subscription usage limit is reached. `
333
397
  + `Dari switched to your next connected ${label} subscription; retry the request.`;
334
398
  }
@@ -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) {