@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
@@ -1,12 +1,16 @@
1
1
  /**
2
2
  * OAuth protocols for personal subscriptions: Claude Code (PKCE, the user
3
3
  * pastes back the `code#state` Anthropic shows), ChatGPT/Codex (device code,
4
- * the gateway polls for approval), and Muse Code (Meta's device code, then the
5
- * subscription's Model API key minted from the sign-in token). Every network
6
- * call goes through the injected `fetch`.
4
+ * the gateway polls for approval), Muse Code (Meta's device code, then the
5
+ * subscription's Model API key minted from the sign-in token), and OpenCode Go
6
+ * (the OpenCode Console device sign-in `opencode auth login` runs, scoped to
7
+ * the workspace that holds the plan).
8
+ * Every network call goes through the injected `fetch`.
7
9
  */
8
- export type SubscriptionProvider = "anthropic_claude_code" | "openai_codex" | "meta_muse";
10
+ export type SubscriptionProvider = "anthropic_claude_code" | "openai_codex" | "meta_muse" | "opencode_go";
9
11
  export declare const SUBSCRIPTION_PROVIDERS: readonly SubscriptionProvider[];
12
+ export declare const OPENCODE_CLIENT_ID = "opencode-cli";
13
+ export declare const OPENCODE_APPROVAL_PENDING = "OpenCode approval is still pending. Enter the code in the OpenCode console, finish approval, then try again.";
10
14
  export type OAuthFetch = (url: string, init: RequestInit) => Promise<Response>;
11
15
  export type OAuthOptions = {
12
16
  fetch: OAuthFetch;
@@ -3,7 +3,12 @@ export const SUBSCRIPTION_PROVIDERS = [
3
3
  "anthropic_claude_code",
4
4
  "openai_codex",
5
5
  "meta_muse",
6
+ "opencode_go",
6
7
  ];
8
+ const OPENCODE_CONSOLE_URL = "https://opencode.ai/console";
9
+ export const OPENCODE_CLIENT_ID = "opencode-cli";
10
+ const OPENCODE_TOKEN_URL = `${OPENCODE_CONSOLE_URL}/auth/device/token`;
11
+ export const OPENCODE_APPROVAL_PENDING = "OpenCode approval is still pending. Enter the code in the OpenCode console, finish approval, then try again.";
7
12
  /** The provider refused or could not be reached (HTTP 502 at the edge). */
8
13
  export class SubscriptionOAuthProviderError extends Error {
9
14
  status;
@@ -56,6 +61,16 @@ const MUSE_SIGN_IN_REFRESH_PREFIX = "refresh:";
56
61
  export const META_APPROVAL_PENDING = "Meta approval is still pending. Enter the code at Meta, finish approval, then try again.";
57
62
  export async function startOAuth(provider, options) {
58
63
  const expiresAt = new Date((options.now ?? new Date()).getTime() + FLOW_TIMEOUT_MS);
64
+ if (provider === "opencode_go") {
65
+ const device = await postJson(options.fetch, `${OPENCODE_CONSOLE_URL}/auth/device/code`, { client_id: OPENCODE_CLIENT_ID, supports_org_scope: true }, "OpenCode device code request");
66
+ const verification = requiredString(device, "verification_uri_complete");
67
+ return {
68
+ authorizationUrl: verification.startsWith("/") ? `https://opencode.ai${verification}` : verification,
69
+ expiresAt,
70
+ userCode: requiredString(device, "user_code"),
71
+ flow: { device_code: requiredString(device, "device_code") },
72
+ };
73
+ }
59
74
  if (provider === "anthropic_claude_code") {
60
75
  const verifier = randomUrlSafe(32);
61
76
  const challenge = base64Url(createHash("sha256").update(verifier).digest());
@@ -105,6 +120,31 @@ export async function startOAuth(provider, options) {
105
120
  */
106
121
  export async function completeOAuth(provider, flow, authorizationResponse, options) {
107
122
  const now = options.now ?? new Date();
123
+ if (provider === "opencode_go") {
124
+ let token;
125
+ try {
126
+ token = await postJson(options.fetch, OPENCODE_TOKEN_URL, {
127
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
128
+ device_code: requiredString(flow, "device_code"),
129
+ client_id: OPENCODE_CLIENT_ID,
130
+ }, "OpenCode device approval check");
131
+ }
132
+ catch (error) {
133
+ if (error instanceof SubscriptionOAuthProviderError) {
134
+ if (error.errorCode === "authorization_pending" || error.errorCode === "slow_down") {
135
+ throw new SubscriptionOAuthInputError(OPENCODE_APPROVAL_PENDING);
136
+ }
137
+ if (error.errorCode === "access_denied") {
138
+ throw new SubscriptionOAuthInputError("The sign-in was declined on OpenCode. Start again to retry.");
139
+ }
140
+ if (error.errorCode === "expired_token") {
141
+ throw new SubscriptionOAuthInputError("The OpenCode sign-in code expired. Start again.");
142
+ }
143
+ }
144
+ throw error;
145
+ }
146
+ return await opencodeGoTokens(token, null, options.fetch, now);
147
+ }
108
148
  if (provider === "anthropic_claude_code") {
109
149
  const verifier = requiredString(flow, "code_verifier");
110
150
  const expectedState = requiredString(flow, "state");
@@ -175,6 +215,10 @@ export async function completeOAuth(provider, flow, authorizationResponse, optio
175
215
  }
176
216
  export async function refreshOAuth(credential, options) {
177
217
  const now = options.now ?? new Date();
218
+ if (credential.provider === "opencode_go") {
219
+ const token = await postJson(options.fetch, OPENCODE_TOKEN_URL, { grant_type: "refresh_token", refresh_token: credential.refreshToken, client_id: OPENCODE_CLIENT_ID }, "OpenCode sign-in refresh");
220
+ return await opencodeGoTokens(token, credential.accountId, options.fetch, now);
221
+ }
178
222
  if (credential.provider === "anthropic_claude_code") {
179
223
  const token = await postJson(options.fetch, CLAUDE_TOKEN_URL, {
180
224
  grant_type: "refresh_token",
@@ -374,3 +418,34 @@ function base64Url(value) {
374
418
  function isRecord(value) {
375
419
  return typeof value === "object" && value !== null && !Array.isArray(value);
376
420
  }
421
+ // A Console token is scoped to the workspace the sign-in chose, which holds
422
+ // the Go plan; a refresh that omits it keeps the stored one.
423
+ async function opencodeGoTokens(token, workspace, fetch, now) {
424
+ const accessToken = requiredString(token, "access_token");
425
+ const orgId = typeof token.org_id === "string" && token.org_id ? token.org_id : workspace;
426
+ return {
427
+ provider: "opencode_go",
428
+ accessToken,
429
+ refreshToken: requiredString(token, "refresh_token"),
430
+ expiresAt: new Date(now.getTime() + positiveInt(token.expires_in) * 1000),
431
+ accountId: orgId,
432
+ accountEmail: await opencodeEmail(fetch, accessToken),
433
+ };
434
+ }
435
+ // The signed-in member's email, shown with the subscription; best effort.
436
+ async function opencodeEmail(fetch, accessToken) {
437
+ try {
438
+ const response = await fetch(`${OPENCODE_CONSOLE_URL}/api/user`, {
439
+ method: "GET",
440
+ headers: { Accept: "application/json", Authorization: `Bearer ${accessToken}`, "User-Agent": "Dari/1.0" },
441
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
442
+ });
443
+ if (!response.ok)
444
+ return null;
445
+ const user = await response.json();
446
+ return isRecord(user) && typeof user.email === "string" && user.email ? user.email : null;
447
+ }
448
+ catch {
449
+ return null;
450
+ }
451
+ }
@@ -19,7 +19,8 @@
19
19
  * used last.
20
20
  * - When every subscription is past the threshold, the least used serves.
21
21
  * A hold ends on its own once `unavailable_until` passes; reported usage
22
- * stops counting once its window resets.
22
+ * stops counting once its window resets. A model hold (one model at its own
23
+ * limit) leaves the subscription serving its other models.
23
24
  */
24
25
  import type { Database } from "bun:sqlite";
25
26
  import type { SubscriptionUsage } from "../../providers/subscription_limits.js";
@@ -37,6 +38,7 @@ export type SubscriptionCredential = {
37
38
  expiresAt: Date;
38
39
  unavailableUntil: Date | null;
39
40
  unavailableReason: string | null;
41
+ modelHolds: SubscriptionModelHold[];
40
42
  usage: (SubscriptionUsage & {
41
43
  observedAt: Date;
42
44
  }) | null;
@@ -45,6 +47,11 @@ export type SubscriptionCredential = {
45
47
  updatedAt: Date;
46
48
  lastUsedAt: Date | null;
47
49
  };
50
+ export type SubscriptionModelHold = {
51
+ model: string;
52
+ until: Date;
53
+ reason: string;
54
+ };
48
55
  export type PendingOAuthSession = {
49
56
  token: string;
50
57
  provider: SubscriptionProvider;
@@ -94,7 +101,13 @@ export declare class SubscriptionStore {
94
101
  * a subscription for the same provider is available now.
95
102
  */
96
103
  markUnavailable(id: string, until: Date, reason: string, now?: Date): boolean;
97
- /** Clear a usage-limit hold. Null when the subscription is not connected. */
104
+ /**
105
+ * Hold one model at its own usage limit on a subscription, which keeps
106
+ * serving its other models. A hold only grows, like the plan's. Returns
107
+ * whether the subscription is connected.
108
+ */
109
+ holdModel(id: string, model: string, until: Date, reason: string, now?: Date): boolean;
110
+ /** Clear a subscription's usage-limit holds. Null when it is not connected. */
98
111
  markAvailable(name: string, now?: Date): SubscriptionCredential | null;
99
112
  createSession(session: Omit<PendingOAuthSession, "token">, now?: Date): PendingOAuthSession;
100
113
  /** A pending session, including an expired one so callers can say it expired. */
@@ -103,6 +116,8 @@ export declare class SubscriptionStore {
103
116
  private freeName;
104
117
  }
105
118
  export declare function isHeld(credential: SubscriptionCredential, now: Date): boolean;
119
+ /** The models held at their own limit on a subscription now, by model. */
120
+ export declare function activeModelHolds(credential: SubscriptionCredential, now: Date): SubscriptionModelHold[];
106
121
  /** The usage a subscription last reported, while its window has not reset. */
107
122
  /**
108
123
  * The last reported usage of every window that has not reset. A short window
@@ -8,14 +8,16 @@ const BASE_NAMES = {
8
8
  anthropic_claude_code: "ANTHROPIC_CLAUDE_CODE_OAUTH_TOKEN",
9
9
  openai_codex: "OPENAI_CODEX_OAUTH_TOKEN",
10
10
  meta_muse: "META_MUSE_OAUTH_TOKEN",
11
+ opencode_go: "OPENCODE_GO_OAUTH_TOKEN",
11
12
  };
12
- // Usage columns added after the table first shipped; existing databases gain
13
- // them on open.
14
- const USAGE_COLUMNS = {
13
+ // Columns added after the table first shipped; existing databases gain them
14
+ // on open.
15
+ const ADDED_COLUMNS = {
15
16
  usage_utilization: "REAL",
16
17
  usage_resets_at: "INTEGER",
17
18
  usage_observed_at: "INTEGER",
18
19
  usage_windows: "TEXT",
20
+ model_holds: "TEXT",
19
21
  };
20
22
  export class SubscriptionStore {
21
23
  db;
@@ -37,13 +39,14 @@ export class SubscriptionStore {
37
39
  usage_resets_at INTEGER,
38
40
  usage_observed_at INTEGER,
39
41
  usage_windows TEXT,
42
+ model_holds TEXT,
40
43
  position INTEGER NOT NULL,
41
44
  created_at INTEGER NOT NULL,
42
45
  updated_at INTEGER NOT NULL,
43
46
  last_used_at INTEGER
44
47
  )`);
45
48
  const columns = new Set(db.query("PRAGMA table_info(subscription_credentials)").all().map((column) => column.name));
46
- for (const [column, type] of Object.entries(USAGE_COLUMNS)) {
49
+ for (const [column, type] of Object.entries(ADDED_COLUMNS)) {
47
50
  if (!columns.has(column))
48
51
  db.run(`ALTER TABLE subscription_credentials ADD COLUMN ${column} ${type}`);
49
52
  }
@@ -147,13 +150,14 @@ export class SubscriptionStore {
147
150
  return null;
148
151
  if (existing !== null) {
149
152
  // Another (or an unidentified) account must not inherit the previous
150
- // account's hold, reported usage, or conversations (whose cache is
153
+ // account's holds, reported usage, or conversations (whose cache is
151
154
  // the previous account's).
152
155
  const sameAccount = tokens.accountEmail !== null && tokens.accountEmail === existing.accountEmail;
153
156
  const usage = sameAccount ? existing.usage : null;
154
157
  this.db.run(`UPDATE subscription_credentials SET access_token = ?, refresh_token = ?, expires_at = ?,
155
158
  account_id = ?, account_email = ?, unavailable_until = ?, unavailable_reason = ?,
156
- usage_utilization = ?, usage_resets_at = ?, usage_observed_at = ?, usage_windows = ?, updated_at = ?
159
+ usage_utilization = ?, usage_resets_at = ?, usage_observed_at = ?, usage_windows = ?, model_holds = ?,
160
+ updated_at = ?
157
161
  WHERE id = ?`, [
158
162
  tokens.accessToken,
159
163
  tokens.refreshToken,
@@ -166,6 +170,7 @@ export class SubscriptionStore {
166
170
  usage?.resetsAt.getTime() ?? null,
167
171
  usage?.observedAt.getTime() ?? null,
168
172
  usage === null ? null : windowsJson(usage),
173
+ sameAccount ? modelHoldsJson(existing.modelHolds) : null,
169
174
  now.getTime(),
170
175
  existing.id,
171
176
  ]);
@@ -243,12 +248,34 @@ export class SubscriptionStore {
243
248
  }
244
249
  return this.activeCredential(credential.provider, now) !== null;
245
250
  }
246
- /** Clear a usage-limit hold. Null when the subscription is not connected. */
251
+ /**
252
+ * Hold one model at its own usage limit on a subscription, which keeps
253
+ * serving its other models. A hold only grows, like the plan's. Returns
254
+ * whether the subscription is connected.
255
+ */
256
+ holdModel(id, model, until, reason, now = new Date()) {
257
+ const credential = this.get(id);
258
+ if (credential === null)
259
+ return false;
260
+ const current = activeModelHolds(credential, now);
261
+ const existing = current.find((hold) => hold.model === model);
262
+ if (existing === undefined || until > existing.until) {
263
+ const holds = [...current.filter((hold) => hold.model !== model), { model, until, reason }];
264
+ this.db.run("UPDATE subscription_credentials SET model_holds = ?, updated_at = ? WHERE id = ?", [
265
+ modelHoldsJson(holds),
266
+ now.getTime(),
267
+ id,
268
+ ]);
269
+ }
270
+ return true;
271
+ }
272
+ /** Clear a subscription's usage-limit holds. Null when it is not connected. */
247
273
  markAvailable(name, now = new Date()) {
248
274
  const credential = this.getByName(name);
249
275
  if (credential === null)
250
276
  return null;
251
- this.db.run("UPDATE subscription_credentials SET unavailable_until = NULL, unavailable_reason = NULL, updated_at = ? WHERE id = ?", [now.getTime(), credential.id]);
277
+ this.db.run(`UPDATE subscription_credentials SET unavailable_until = NULL, unavailable_reason = NULL, model_holds = NULL,
278
+ updated_at = ? WHERE id = ?`, [now.getTime(), credential.id]);
252
279
  return this.get(credential.id);
253
280
  }
254
281
  createSession(session, now = new Date()) {
@@ -285,6 +312,12 @@ export class SubscriptionStore {
285
312
  export function isHeld(credential, now) {
286
313
  return credential.unavailableUntil !== null && credential.unavailableUntil > now;
287
314
  }
315
+ /** The models held at their own limit on a subscription now, by model. */
316
+ export function activeModelHolds(credential, now) {
317
+ return credential.modelHolds
318
+ .filter((hold) => hold.until > now)
319
+ .sort((a, b) => a.model.localeCompare(b.model));
320
+ }
288
321
  /** The usage a subscription last reported, while its window has not reset. */
289
322
  /**
290
323
  * The last reported usage of every window that has not reset. A short window
@@ -360,6 +393,7 @@ function credentialFromRow(row) {
360
393
  observedAt: new Date(row.usage_observed_at),
361
394
  windows: parseWindows(row.usage_windows),
362
395
  },
396
+ modelHolds: parseModelHolds(row.model_holds),
363
397
  position: row.position,
364
398
  createdAt: new Date(row.created_at),
365
399
  updatedAt: new Date(row.updated_at),
@@ -369,6 +403,17 @@ function credentialFromRow(row) {
369
403
  function windowsJson(usage) {
370
404
  return JSON.stringify(usage.windows.map((window) => ({ ...window, resetsAt: window.resetsAt.getTime() })));
371
405
  }
406
+ function modelHoldsJson(holds) {
407
+ if (holds.length === 0)
408
+ return null;
409
+ return JSON.stringify(holds.map((hold) => ({ ...hold, until: hold.until.getTime() })));
410
+ }
411
+ function parseModelHolds(value) {
412
+ if (value === null)
413
+ return [];
414
+ return JSON.parse(value)
415
+ .map((hold) => ({ ...hold, until: new Date(hold.until) }));
416
+ }
372
417
  // Rows recorded before windows were stored have none.
373
418
  function parseWindows(value) {
374
419
  if (value === null)
@@ -11,11 +11,6 @@ export async function routeDecision(args) {
11
11
  if (custom === null) {
12
12
  throw new HttpError(502, "Router custom rule configuration is missing.", "custom_config_missing");
13
13
  }
14
- if (custom && resolution.candidates.length === 0) {
15
- const error = new HttpError(502, "No custom routing rule or default model/thinking-level pair is routable for this request.", "custom_no_routable_candidates");
16
- error.decisionDetails = { custom_rules: custom.audit };
17
- throw error;
18
- }
19
14
  const relevance = args.selectorBackend.evalRelevance !== undefined
20
15
  && resolution.candidates.length > 1
21
16
  ? await relevantEvals({
package/dist/types.d.ts CHANGED
@@ -18,7 +18,7 @@ export type AwsAssumeRoleProviderAuth = {
18
18
  region: string;
19
19
  };
20
20
  export type ResolvedProviderAuth = BearerProviderAuth | AwsSigV4ProviderAuth;
21
- export type SubscriptionKind = "openai_codex" | "anthropic_claude_code" | "meta_muse";
21
+ export type SubscriptionKind = "openai_codex" | "anthropic_claude_code" | "meta_muse" | "opencode_go";
22
22
  export type ProviderCredential = {
23
23
  apiKey: string;
24
24
  baseUrl?: string;
@@ -63,6 +63,9 @@ export type ResolvedRouterModelConfig = {
63
63
  fast_mode_cost?: RouterModelPrice | null;
64
64
  zdr?: boolean;
65
65
  };
66
+ export type RouterRole = "main" | "subagent";
67
+ export type RouterRoleModels = Partial<Record<RouterRole, string | null>>;
68
+ export type RouterRolePrompts = Partial<Record<RouterRole, string | null>>;
66
69
  export type ResolvedRouter = {
67
70
  router_id: string;
68
71
  organization_id: string;
@@ -91,6 +94,8 @@ export type ResolvedRouter = {
91
94
  prefix_hits?: RouterPrefixHit[];
92
95
  routing_strategy?: RoutingStrategy;
93
96
  custom_config?: CustomRouterConfig | null;
97
+ role_models?: RouterRoleModels;
98
+ role_prompts?: RouterRolePrompts;
94
99
  model_thinking_levels?: Record<string, ReasoningEffort[]>;
95
100
  fast_models?: string[];
96
101
  model_prices?: Record<string, RouterModelPrice>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.310",
3
+ "version": "1.0.311",
4
4
  "description": "Self-hostable LLM gateway for coding agents and APIs: one endpoint for Anthropic Messages, OpenAI Chat Completions, and OpenAI Responses, with subscription pooling, failover, and prompt-cache-aware routing.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -51,7 +51,7 @@
51
51
  },
52
52
  "dependencies": {
53
53
  "@aws-sdk/client-sts": "3.1063.0",
54
- "@mupt-ai/dari-router": "1.0.310",
54
+ "@mupt-ai/dari-router": "1.0.311",
55
55
  "@mupt-ai/pi-ai": "1.5.2-mupt.1"
56
56
  },
57
57
  "devDependencies": {
@@ -193,7 +193,10 @@ export async function buildRoutingContext(args: {
193
193
  thinkingEnabled: args.interaction.reasoning?.enabled === true,
194
194
  toolChoice: args.interaction.toolChoice,
195
195
  modelThinkingLevels: args.credentials.model_thinking_levels,
196
- strategy: args.credentials.routing_strategy === "custom" ? "custom" : "dari",
196
+ // Routing rules steer what the selector picks; an explicit model is
197
+ // served as requested, so they do not narrow its candidates.
198
+ strategy: args.credentials.routing_strategy === "custom"
199
+ && explicitModelId(args.interaction.model) === null ? "custom" : "dari",
197
200
  customConfig: args.credentials.custom_config,
198
201
  modelPrices: args.credentials.model_prices ?? {},
199
202
  pricing,
@@ -0,0 +1,26 @@
1
+ import type { InteractionItem, InteractionRequest } from "./types.js";
2
+
3
+ /* Appends text to the end of the system prompt: after the client's
4
+ instructions and its leading system or developer messages, before the
5
+ conversation. The text is the same on every turn, so the provider's cached
6
+ prefix stays stable. */
7
+ export function withSystemPromptSuffix(
8
+ interaction: InteractionRequest,
9
+ suffix: string | undefined,
10
+ ): InteractionRequest {
11
+ if (!suffix) return interaction;
12
+ const isPreamble = (item: InteractionItem) =>
13
+ item.type === "message" && (item.role === "system" || item.role === "developer");
14
+ const at = interaction.items.findIndex((item) => !isPreamble(item));
15
+ const index = at === -1 ? interaction.items.length : at;
16
+ const message: InteractionItem = {
17
+ type: "message",
18
+ role: "system",
19
+ content: [{ type: "text", text: suffix }],
20
+ contentShape: "string",
21
+ };
22
+ return {
23
+ ...interaction,
24
+ items: [...interaction.items.slice(0, index), message, ...interaction.items.slice(index)],
25
+ };
26
+ }
@@ -9,3 +9,8 @@ export type CanonicalModel = {
9
9
 
10
10
  /** The canonical models Dari serves, from the monorepo's router catalog. */
11
11
  export const CANONICAL_MODELS: readonly CanonicalModel[] = canonicalModels;
12
+
13
+ /** A model's catalog name; a model the catalog does not list keeps its id. */
14
+ export function canonicalModelName(id: string): string {
15
+ return CANONICAL_MODELS.find((model) => model.id === id)?.name ?? id;
16
+ }
@@ -67,6 +67,7 @@ export const DEFAULT_CATALOG_PROVIDERS: readonly string[] = [
67
67
  "meta",
68
68
  "xai",
69
69
  "fireworks",
70
+ "opencode-go",
70
71
  "openrouter",
71
72
  "vercel-ai-gateway",
72
73
  ];
@@ -10,6 +10,7 @@ const PROVIDER_LABELS: Record<string, string> = {
10
10
  fireworks: "Fireworks",
11
11
  meta: "Meta",
12
12
  xai: "xAI",
13
+ "opencode-go": "OpenCode Go",
13
14
  dari: "Dari",
14
15
  "amazon-bedrock": "Amazon Bedrock",
15
16
  azure: "Microsoft Azure",
@@ -33,6 +34,9 @@ const PROVIDER_BASE_URLS: Record<string, string> = {
33
34
  anthropic: "https://api.anthropic.com",
34
35
  fireworks: "https://api.fireworks.ai/inference/v1",
35
36
  xai: "https://api.x.ai/v1",
37
+ // A flat-rate plan for open models; each model keeps its own API path
38
+ // under https://opencode.ai/inference/go/, and this is chat completions.
39
+ "opencode-go": "https://opencode.ai/inference/go/openai/v1",
36
40
  // Meta's Model API serves OpenAI Responses and Chat Completions here, and
37
41
  // Anthropic Messages at https://api.meta.ai.
38
42
  meta: "https://api.meta.ai/v1",
@@ -1,18 +1,17 @@
1
- import {
2
- nativeModelId,
3
- providerForModel,
4
- type RouterModelPrice,
5
- } from "@mupt-ai/dari-router/policy-engine";
1
+ import { nativeModelId, type RouterModelPrice } from "@mupt-ai/dari-router/policy-engine";
6
2
 
7
3
  import type { ClientHarness, ResolvedRouterModelConfig, SubscriptionKind } from "../types.js";
8
4
 
9
5
  const CODEX_BACKEND_URL = "https://chatgpt.com/backend-api";
10
6
 
11
- // The model provider whose models each kind of plan serves.
12
- const SUBSCRIPTION_MODEL_PROVIDERS: Record<SubscriptionKind, string> = {
13
- openai_codex: "openai",
14
- anthropic_claude_code: "anthropic",
15
- meta_muse: "meta",
7
+ // The execution providers whose models each kind of plan serves; a ChatGPT
8
+ // plan's OpenAI models execute as `openai-codex` once resolve points them at
9
+ // the Codex backend.
10
+ const SUBSCRIPTION_MODEL_PROVIDERS: Record<SubscriptionKind, readonly string[]> = {
11
+ openai_codex: ["openai", "openai-codex"],
12
+ anthropic_claude_code: ["anthropic"],
13
+ meta_muse: ["meta"],
14
+ opencode_go: ["opencode-go"],
16
15
  };
17
16
 
18
17
  // The client each plan is limited to, as its provider limits it: a Claude Code
@@ -23,15 +22,16 @@ const SUBSCRIPTION_CLIENTS: Partial<Record<SubscriptionKind, ClientHarness>> = {
23
22
  };
24
23
 
25
24
  /**
26
- * Whether a plan may serve a model for this client: each plan serves only its
27
- * own provider's models, and only to the client its provider allows.
25
+ * Whether a plan may serve a model executed by `provider` for this client:
26
+ * each plan serves only its own provider's models, and only to the client its
27
+ * provider allows.
28
28
  */
29
29
  export function subscriptionServes(
30
30
  kind: SubscriptionKind,
31
- model: string,
31
+ provider: string,
32
32
  clientHarness: ClientHarness | undefined,
33
33
  ): boolean {
34
- if (SUBSCRIPTION_MODEL_PROVIDERS[kind] !== providerForModel(model)) return false;
34
+ if (!SUBSCRIPTION_MODEL_PROVIDERS[kind].includes(provider)) return false;
35
35
  const client = SUBSCRIPTION_CLIENTS[kind];
36
36
  return client === undefined || clientHarness === client;
37
37
  }
@@ -58,6 +58,9 @@ export type GatewayPlatform = {
58
58
  /**
59
59
  * Hold an exhausted personal subscription until it resets. Resolves whether
60
60
  * another connected subscription for the same provider can serve a retry.
61
+ * A limit naming a `model` holds only that model on the subscription, which
62
+ * keeps serving the router's other models; it resolves whether the hold
63
+ * landed, since those models then serve a retry.
61
64
  */
62
65
  markSubscriptionUnavailable(hold: SubscriptionHold): Promise<boolean>;
63
66
  /**
@@ -1,4 +1,9 @@
1
- import { CODEX_USAGE_WINDOWS, type SubscriptionUsage, subscriptionUsageFromWindows } from "./subscription_limits.js";
1
+ import {
2
+ CODEX_USAGE_WINDOWS,
3
+ DEFAULT_USAGE_LIMIT_WINDOW_MS,
4
+ type SubscriptionUsage,
5
+ subscriptionUsageFromWindows,
6
+ } from "./subscription_limits.js";
2
7
 
3
8
  // Codex calls run over a WebSocket that bypasses fetch, so a ChatGPT plan's
4
9
  // usage never reaches the gateway as response headers. The ChatGPT backend's
@@ -22,7 +27,59 @@ export async function readCodexUsage(args: {
22
27
  const last = readAt.get(args.credentialId);
23
28
  if (last !== undefined && now - last < CODEX_USAGE_INTERVAL_MS) return null;
24
29
  readAt.set(args.credentialId, now);
30
+ return codexUsageFromReport(await fetchCodexUsageReport(args), new Date(now));
31
+ }
32
+
33
+ /**
34
+ * When a ChatGPT usage-limit refusal came from a per-model cap rather than the
35
+ * plan's own limit, that cap's reset; null when the plan itself is spent or
36
+ * the report names no spent cap. The report lists those caps as
37
+ * `additional_rate_limits` beside the plan's `rate_limit`.
38
+ */
39
+ export async function readCodexModelLimitReset(args: {
40
+ accessToken: string;
41
+ baseUrl?: string;
42
+ now?: Date;
43
+ fetch?: typeof fetch;
44
+ }): Promise<Date | null> {
45
+ return codexModelLimitResetFromReport(await fetchCodexUsageReport(args), args.now ?? new Date());
46
+ }
47
+
48
+ export function codexModelLimitResetFromReport(report: unknown, now: Date): Date | null {
49
+ if (!isRecord(report) || limitSpent(report.rate_limit)) return null;
50
+ const spent = (Array.isArray(report.additional_rate_limits) ? report.additional_rate_limits : [])
51
+ .map((limit) => isRecord(limit) ? limit.rate_limit : undefined)
52
+ .filter(limitSpent);
53
+ if (spent.length === 0) return null;
54
+ const resets = spent.flatMap((limit) => limitWindows(limit))
55
+ .filter((window) => window.used >= 100 && window.resetAt !== null && window.resetAt > now)
56
+ .map((window) => window.resetAt!.getTime());
57
+ return new Date(resets.length > 0 ? Math.max(...resets) : now.getTime() + DEFAULT_USAGE_LIMIT_WINDOW_MS);
58
+ }
25
59
 
60
+ function limitSpent(limit: unknown): boolean {
61
+ if (!isRecord(limit)) return false;
62
+ return limit.limit_reached === true || limit.allowed === false
63
+ || limitWindows(limit).some((window) => window.used >= 100);
64
+ }
65
+
66
+ function limitWindows(limit: unknown): Array<{ used: number; resetAt: Date | null }> {
67
+ if (!isRecord(limit)) return [];
68
+ return CODEX_USAGE_WINDOWS.flatMap(([name]) => {
69
+ const window = limit[`${name}_window`];
70
+ if (!isRecord(window) || typeof window.used_percent !== "number") return [];
71
+ return [{
72
+ used: window.used_percent,
73
+ resetAt: typeof window.reset_at === "number" ? new Date(window.reset_at * 1000) : null,
74
+ }];
75
+ });
76
+ }
77
+
78
+ async function fetchCodexUsageReport(args: {
79
+ accessToken: string;
80
+ baseUrl?: string;
81
+ fetch?: typeof fetch;
82
+ }): Promise<unknown> {
26
83
  const accountId = codexAccountId(args.accessToken);
27
84
  const response = await (args.fetch ?? globalThis.fetch)(
28
85
  `${(args.baseUrl ?? DEFAULT_CODEX_BASE_URL).replace(/\/$/, "")}/wham/usage`,
@@ -36,7 +93,7 @@ export async function readCodexUsage(args: {
36
93
  },
37
94
  );
38
95
  if (!response.ok) throw new Error(`Codex usage report failed with status ${response.status}.`);
39
- return codexUsageFromReport(await response.json(), new Date(now));
96
+ return await response.json();
40
97
  }
41
98
 
42
99
  /** Every Codex window with a future reset, or null when the report has none. */