@mupt-ai/dari-gateway 1.0.300 → 1.0.302

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.
@@ -1,4 +1,4 @@
1
- import type { SubscriptionUsage } from "./subscription_limits.js";
1
+ import { type SubscriptionUsage } from "./subscription_limits.js";
2
2
  export declare function readCodexUsage(args: {
3
3
  credentialId: string;
4
4
  accessToken: string;
@@ -6,5 +6,5 @@ export declare function readCodexUsage(args: {
6
6
  now?: number;
7
7
  fetch?: typeof fetch;
8
8
  }): Promise<SubscriptionUsage | null>;
9
- /** The most used window with a future reset, or null when the report has none. */
9
+ /** Every Codex window with a future reset, or null when the report has none. */
10
10
  export declare function codexUsageFromReport(report: unknown, now: Date): SubscriptionUsage | null;
@@ -1,3 +1,4 @@
1
+ import { CODEX_USAGE_WINDOWS, subscriptionUsageFromWindows } from "./subscription_limits.js";
1
2
  // Codex calls run over a WebSocket that bypasses fetch, so a ChatGPT plan's
2
3
  // usage never reaches the gateway as response headers. The ChatGPT backend's
3
4
  // usage report (the endpoint behind the Codex CLI's /status) has the same
@@ -26,26 +27,18 @@ export async function readCodexUsage(args) {
26
27
  throw new Error(`Codex usage report failed with status ${response.status}.`);
27
28
  return codexUsageFromReport(await response.json(), new Date(now));
28
29
  }
29
- /** The most used window with a future reset, or null when the report has none. */
30
+ /** Every Codex window with a future reset, or null when the report has none. */
30
31
  export function codexUsageFromReport(report, now) {
31
32
  const rateLimit = isRecord(report) && isRecord(report.rate_limit) ? report.rate_limit : {};
32
- let binding = null;
33
- for (const name of ["primary_window", "secondary_window"]) {
34
- const window = rateLimit[name];
35
- if (!isRecord(window))
36
- continue;
37
- const used = window.used_percent;
38
- const resetAt = window.reset_at;
39
- if (typeof used !== "number" || !Number.isFinite(used) || typeof resetAt !== "number")
40
- continue;
41
- const resetsAt = new Date(resetAt * 1000);
42
- if (resetsAt <= now)
43
- continue;
44
- const utilization = Math.max(0, Math.min(1, used / 100));
45
- if (binding === null || utilization > binding.utilization)
46
- binding = { utilization, resetsAt };
47
- }
48
- return binding;
33
+ return subscriptionUsageFromWindows(CODEX_USAGE_WINDOWS.map(([name, minutes]) => {
34
+ const window = isRecord(rateLimit[`${name}_window`]) ? rateLimit[`${name}_window`] : {};
35
+ const { used_percent: used, reset_at: resetAt, limit_window_seconds: seconds } = window;
36
+ return {
37
+ minutes: typeof seconds === "number" && seconds > 0 ? Math.round(seconds / 60) : minutes,
38
+ used: typeof used === "number" ? used / 100 : NaN,
39
+ resetsAt: typeof resetAt === "number" ? new Date(resetAt * 1000) : null,
40
+ };
41
+ }), now);
49
42
  }
50
43
  function codexAccountId(token) {
51
44
  const [, payload] = token.split(".");
@@ -197,7 +197,7 @@ export function buildModel(pi, modelId, pricing, config) {
197
197
  throw new HttpError(502, `No base URL is configured for provider ${provider}.`, "provider_configuration_error");
198
198
  }
199
199
  const contextWindow = contextWindowForModel(modelId, registered, config) ?? 128000;
200
- const compat = responsesToolContract(api, runtimeCompat(provider, registered, modelId));
200
+ const compat = gatewayRuntimeCompat(api, runtimeCompat(provider, registered, modelId));
201
201
  return {
202
202
  ...(registered ?? {}),
203
203
  ...(compat !== undefined ? { compat } : {}),
@@ -273,7 +273,13 @@ function contextWindowForModel(modelId, registered, config) {
273
273
  // `tools` field, when a model supports mid-conversation system messages. The gateway
274
274
  // keeps tools at the request level until that native tool-change path is validated.
275
275
  const RESPONSES_APIS = new Set(["openai-responses", "azure-openai-responses", "openai-codex-responses"]);
276
- function responsesToolContract(api, compat) {
276
+ function gatewayRuntimeCompat(api, compat) {
277
+ // Pi 1.5 enables server-side message threads whenever sessionId is set.
278
+ // Gateway sessions serve affinity, not permission to retain a conversation
279
+ // remotely; keep full-history requests, including on ZDR routes.
280
+ if (api === "anthropic-messages") {
281
+ return { ...(isRecord(compat) ? compat : {}), supportsMessageThreads: false };
282
+ }
277
283
  if (typeof api !== "string" || !RESPONSES_APIS.has(api))
278
284
  return compat;
279
285
  if (!isRecord(compat) || compat.supportsMidConvoSystemMessages !== true)
@@ -7,15 +7,30 @@ export type SubscriptionUsageLimit = {
7
7
  reason: string;
8
8
  switched?: boolean;
9
9
  };
10
+ /** One quota window of a plan: its length, share used (0 to 1), and reset. */
11
+ export type SubscriptionUsageWindow = {
12
+ minutes: number;
13
+ utilization: number;
14
+ resetsAt: Date;
15
+ };
10
16
  /**
11
17
  * How much of a subscription's quota is used, from a successful response.
12
- * `utilization` is the binding window's share used (0 to 1): the window
13
- * closest to its limit, whose reset is `resetsAt`.
18
+ * `windows` lists every window with a future reset, shortest first;
19
+ * `utilization` and `resetsAt` are the binding window's: the one closest to
20
+ * its limit.
14
21
  */
15
22
  export type SubscriptionUsage = {
16
23
  utilization: number;
17
24
  resetsAt: Date;
25
+ windows: SubscriptionUsageWindow[];
18
26
  };
27
+ export declare const CODEX_USAGE_WINDOWS: readonly [readonly ["primary", number], readonly ["secondary", number]];
28
+ /** Usage from raw windows, dropping malformed or already-reset ones. */
29
+ export declare function subscriptionUsageFromWindows(raw: Array<{
30
+ minutes: number;
31
+ used: number;
32
+ resetsAt: Date | null;
33
+ }>, now: Date): SubscriptionUsage | null;
19
34
  /**
20
35
  * The quota a successful subscription response reports used, or null when it
21
36
  * reports none: the most used of the plan's windows.
@@ -1,13 +1,30 @@
1
1
  import { isRecord } from "@mupt-ai/dari-router/policy-engine";
2
2
  import { providerFailureMessage } from "../runtime/provider_stream_outcome.js";
3
+ const FIVE_HOURS = 5 * 60;
4
+ const ONE_WEEK = 7 * 24 * 60;
3
5
  // Claude Code's unified limiter reports each window on every response, the
4
6
  // same headers Claude Code itself reads: `-utilization` as a fraction of the
5
7
  // window and `-reset` in unix seconds.
6
- const CLAUDE_CODE_USAGE_WINDOWS = ["5h", "7d"];
8
+ const CLAUDE_CODE_USAGE_WINDOWS = [["5h", FIVE_HOURS], ["7d", ONE_WEEK]];
7
9
  // The ChatGPT backend reports each Codex window on every response, the same
8
- // headers the Codex CLI reads: `-used-percent` out of 100 and `-reset-at` in
9
- // unix seconds.
10
- const CODEX_USAGE_WINDOWS = ["primary", "secondary"];
10
+ // headers the Codex CLI reads: `-used-percent` out of 100, `-reset-at` in
11
+ // unix seconds, and `-window-minutes`. The defaults are a ChatGPT plan's.
12
+ export const CODEX_USAGE_WINDOWS = [["primary", FIVE_HOURS], ["secondary", ONE_WEEK]];
13
+ /** Usage from raw windows, dropping malformed or already-reset ones. */
14
+ export function subscriptionUsageFromWindows(raw, now) {
15
+ const windows = raw
16
+ .filter((window) => Number.isFinite(window.used) && window.resetsAt !== null && window.resetsAt > now)
17
+ .map((window) => ({
18
+ minutes: window.minutes,
19
+ utilization: Math.max(0, Math.min(1, window.used)),
20
+ resetsAt: window.resetsAt,
21
+ }))
22
+ .sort((a, b) => a.minutes - b.minutes);
23
+ if (windows.length === 0)
24
+ return null;
25
+ const binding = windows.reduce((a, b) => (b.utilization > a.utilization ? b : a));
26
+ return { utilization: binding.utilization, resetsAt: binding.resetsAt, windows };
27
+ }
11
28
  /**
12
29
  * The quota a successful subscription response reports used, or null when it
13
30
  * reports none: the most used of the plan's windows.
@@ -15,26 +32,19 @@ const CODEX_USAGE_WINDOWS = ["primary", "secondary"];
15
32
  export function subscriptionUsageFromHeaders(provider, keySource, headers, now = new Date()) {
16
33
  const oauthProvider = subscriptionOAuthProviderFor(provider, keySource);
17
34
  const windows = oauthProvider === "anthropic_claude_code"
18
- ? CLAUDE_CODE_USAGE_WINDOWS.map((window) => ({
35
+ ? CLAUDE_CODE_USAGE_WINDOWS.map(([window, minutes]) => ({
36
+ minutes,
19
37
  used: Number(headers.get(`anthropic-ratelimit-unified-${window}-utilization`) ?? NaN),
20
- reset: headers.get(`anthropic-ratelimit-unified-${window}-reset`),
38
+ resetsAt: unixSecondsDeadline(headers.get(`anthropic-ratelimit-unified-${window}-reset`), now),
21
39
  }))
22
40
  : oauthProvider === "openai_codex"
23
- ? CODEX_USAGE_WINDOWS.map((window) => ({
41
+ ? CODEX_USAGE_WINDOWS.map(([window, minutes]) => ({
42
+ minutes: Number(headers.get(`x-codex-${window}-window-minutes`)) || minutes,
24
43
  used: Number(headers.get(`x-codex-${window}-used-percent`) ?? NaN) / 100,
25
- reset: headers.get(`x-codex-${window}-reset-at`),
44
+ resetsAt: unixSecondsDeadline(headers.get(`x-codex-${window}-reset-at`), now),
26
45
  }))
27
46
  : [];
28
- let binding = null;
29
- for (const { used, reset } of windows) {
30
- const resetsAt = unixSecondsDeadline(reset, now);
31
- if (!Number.isFinite(used) || resetsAt === null)
32
- continue;
33
- const utilization = Math.max(0, Math.min(1, used));
34
- if (binding === null || utilization > binding.utilization)
35
- binding = { utilization, resetsAt };
36
- }
37
- return binding;
47
+ return subscriptionUsageFromWindows(windows, now);
38
48
  }
39
49
  // Neither provider guarantees a reset time on every usage-limit response.
40
50
  // Without one, hold the subscription out for an hour rather than hammering an
@@ -70,7 +70,6 @@ export async function resolveSelfHostedRouter(deps, request) {
70
70
  speculative_routing: false,
71
71
  session_pinning: router.sessionPinning,
72
72
  primary_retries: router.retries,
73
- lease_context_enabled: false,
74
73
  routing_strategy: "dari",
75
74
  custom_config: null,
76
75
  evals: [],
@@ -146,7 +146,15 @@ function summary(store, credential, now) {
146
146
  /** The fields the CLI reads from a credential, never its tokens. */
147
147
  function usageBody(credential, now) {
148
148
  const usage = currentUsage(credential, now);
149
- return usage === null ? null : { utilization: usage.utilization, resets_at: usage.resetsAt.toISOString() };
149
+ return usage === null ? null : {
150
+ utilization: usage.utilization,
151
+ resets_at: usage.resetsAt.toISOString(),
152
+ windows: usage.windows.map((window) => ({
153
+ minutes: window.minutes,
154
+ utilization: window.utilization,
155
+ resets_at: window.resetsAt.toISOString(),
156
+ })),
157
+ };
150
158
  }
151
159
  function credentialBody(credential, active, now) {
152
160
  const held = isHeld(credential, now);
@@ -104,6 +104,11 @@ export declare class SubscriptionStore {
104
104
  }
105
105
  export declare function isHeld(credential: SubscriptionCredential, now: Date): boolean;
106
106
  /** The usage a subscription last reported, while its window has not reset. */
107
+ /**
108
+ * The last reported usage of every window that has not reset. A short window
109
+ * resetting leaves the longer ones in force, so the binding window is the
110
+ * most used of those still running.
111
+ */
107
112
  export declare function currentUsage(credential: SubscriptionCredential, now: Date): SubscriptionUsage | null;
108
113
  /** Subscription names are env-var-style identifiers; matching is case-insensitive. */
109
114
  export declare function normalizeName(name: string): string;
@@ -15,6 +15,7 @@ const USAGE_COLUMNS = {
15
15
  usage_utilization: "REAL",
16
16
  usage_resets_at: "INTEGER",
17
17
  usage_observed_at: "INTEGER",
18
+ usage_windows: "TEXT",
18
19
  };
19
20
  export class SubscriptionStore {
20
21
  db;
@@ -35,6 +36,7 @@ export class SubscriptionStore {
35
36
  usage_utilization REAL,
36
37
  usage_resets_at INTEGER,
37
38
  usage_observed_at INTEGER,
39
+ usage_windows TEXT,
38
40
  position INTEGER NOT NULL,
39
41
  created_at INTEGER NOT NULL,
40
42
  updated_at INTEGER NOT NULL,
@@ -113,7 +115,8 @@ export class SubscriptionStore {
113
115
  }
114
116
  /** Record the usage a response reported for a subscription. */
115
117
  recordUsage(id, usage, now = new Date()) {
116
- this.db.run("UPDATE subscription_credentials SET usage_utilization = ?, usage_resets_at = ?, usage_observed_at = ? WHERE id = ?", [usage.utilization, usage.resetsAt.getTime(), now.getTime(), id]);
118
+ this.db.run(`UPDATE subscription_credentials SET usage_utilization = ?, usage_resets_at = ?, usage_observed_at = ?,
119
+ usage_windows = ? WHERE id = ?`, [usage.utilization, usage.resetsAt.getTime(), now.getTime(), windowsJson(usage), id]);
117
120
  }
118
121
  // A pin idle past CONVERSATION_PIN_TTL_MS is forgotten: the conversation is
119
122
  // assigned like a new one.
@@ -150,7 +153,7 @@ export class SubscriptionStore {
150
153
  const usage = sameAccount ? existing.usage : null;
151
154
  this.db.run(`UPDATE subscription_credentials SET access_token = ?, refresh_token = ?, expires_at = ?,
152
155
  account_id = ?, account_email = ?, unavailable_until = ?, unavailable_reason = ?,
153
- usage_utilization = ?, usage_resets_at = ?, usage_observed_at = ?, updated_at = ?
156
+ usage_utilization = ?, usage_resets_at = ?, usage_observed_at = ?, usage_windows = ?, updated_at = ?
154
157
  WHERE id = ?`, [
155
158
  tokens.accessToken,
156
159
  tokens.refreshToken,
@@ -162,6 +165,7 @@ export class SubscriptionStore {
162
165
  usage?.utilization ?? null,
163
166
  usage?.resetsAt.getTime() ?? null,
164
167
  usage?.observedAt.getTime() ?? null,
168
+ usage === null ? null : windowsJson(usage),
165
169
  now.getTime(),
166
170
  existing.id,
167
171
  ]);
@@ -282,8 +286,23 @@ export function isHeld(credential, now) {
282
286
  return credential.unavailableUntil !== null && credential.unavailableUntil > now;
283
287
  }
284
288
  /** The usage a subscription last reported, while its window has not reset. */
289
+ /**
290
+ * The last reported usage of every window that has not reset. A short window
291
+ * resetting leaves the longer ones in force, so the binding window is the
292
+ * most used of those still running.
293
+ */
285
294
  export function currentUsage(credential, now) {
286
- return credential.usage !== null && credential.usage.resetsAt > now ? credential.usage : null;
295
+ const usage = credential.usage;
296
+ if (usage === null)
297
+ return null;
298
+ // Usage recorded before per-window reports has only the binding window.
299
+ if (usage.windows.length === 0)
300
+ return usage.resetsAt > now ? usage : null;
301
+ const windows = usage.windows.filter((window) => window.resetsAt > now);
302
+ if (windows.length === 0)
303
+ return null;
304
+ const binding = windows.reduce((a, b) => (b.utilization > a.utilization ? b : a));
305
+ return { utilization: binding.utilization, resetsAt: binding.resetsAt, windows };
287
306
  }
288
307
  function hasHeadroom(credential, now) {
289
308
  return (currentUsage(credential, now)?.utilization ?? 0) < SWITCH_AT_UTILIZATION;
@@ -339,6 +358,7 @@ function credentialFromRow(row) {
339
358
  utilization: row.usage_utilization,
340
359
  resetsAt: new Date(row.usage_resets_at),
341
360
  observedAt: new Date(row.usage_observed_at),
361
+ windows: parseWindows(row.usage_windows),
342
362
  },
343
363
  position: row.position,
344
364
  createdAt: new Date(row.created_at),
@@ -346,3 +366,13 @@ function credentialFromRow(row) {
346
366
  lastUsedAt: row.last_used_at === null ? null : new Date(row.last_used_at),
347
367
  };
348
368
  }
369
+ function windowsJson(usage) {
370
+ return JSON.stringify(usage.windows.map((window) => ({ ...window, resetsAt: window.resetsAt.getTime() })));
371
+ }
372
+ // Rows recorded before windows were stored have none.
373
+ function parseWindows(value) {
374
+ if (value === null)
375
+ return [];
376
+ return JSON.parse(value)
377
+ .map((window) => ({ ...window, resetsAt: new Date(window.resetsAt) }));
378
+ }
@@ -1,4 +1,4 @@
1
- import { parseSelectorDecision } from "@mupt-ai/dari-router/policy-engine";
1
+ import { parseSelectorDecision, SELECTOR_LEASE_TURNS } from "@mupt-ai/dari-router/policy-engine";
2
2
  import { HttpError } from "../http/errors.js";
3
3
  export const DARI_AUTO_ROUTING_ENDPOINT = "https://routing.dari.dev/v1/auto-router";
4
4
  // Same selector identity and input budget as `createAutoRouter` in
@@ -23,6 +23,9 @@ export function createAutoRoutingSelectorBackend(config) {
23
23
  return {
24
24
  selectorModel: AUTO_ROUTER_MODEL,
25
25
  contextWindowChars: async () => AUTO_ROUTER_CONTEXT_WINDOW_CHARS,
26
+ // Dari's routing policy grants leases, so an expired lease goes back to
27
+ // the policy rather than the runtime's stateless hold.
28
+ negotiatedLeaseTurns: async () => SELECTOR_LEASE_TURNS,
26
29
  select: async (args) => {
27
30
  let response;
28
31
  try {
@@ -43,11 +46,8 @@ export function createAutoRoutingSelectorBackend(config) {
43
46
  throw new HttpError(502, `Dari Auto Routing returned HTTP ${response.status}.`, "selector_execution_failed");
44
47
  }
45
48
  const outputText = await response.text();
46
- // The gateway applies its own stateless hold; drop any lease the
47
- // policy stamps so it is not mistaken for a negotiated one.
48
- const { leaseTurnsRemaining: _leaseTurnsRemaining, ...decision } = parseSelectorDecision(outputText).decision;
49
49
  return {
50
- decision,
50
+ decision: parseSelectorDecision(outputText).decision,
51
51
  selectorModel: args.selectorModel,
52
52
  candidates: args.candidates,
53
53
  selectorInput: args.selectorInput,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.300",
3
+ "version": "1.0.302",
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,8 +51,8 @@
51
51
  },
52
52
  "dependencies": {
53
53
  "@aws-sdk/client-sts": "3.1063.0",
54
- "@mupt-ai/dari-router": "1.0.300",
55
- "@mupt-ai/pi-ai": "1.4.0-mupt.3"
54
+ "@mupt-ai/dari-router": "1.0.302",
55
+ "@mupt-ai/pi-ai": "1.5.2-mupt.1"
56
56
  },
57
57
  "devDependencies": {
58
58
  "@types/bun": "^1.3.4",
@@ -1,4 +1,4 @@
1
- import type { SubscriptionUsage } from "./subscription_limits.js";
1
+ import { CODEX_USAGE_WINDOWS, type SubscriptionUsage, subscriptionUsageFromWindows } from "./subscription_limits.js";
2
2
 
3
3
  // Codex calls run over a WebSocket that bypasses fetch, so a ChatGPT plan's
4
4
  // usage never reaches the gateway as response headers. The ChatGPT backend's
@@ -39,22 +39,18 @@ export async function readCodexUsage(args: {
39
39
  return codexUsageFromReport(await response.json(), new Date(now));
40
40
  }
41
41
 
42
- /** The most used window with a future reset, or null when the report has none. */
42
+ /** Every Codex window with a future reset, or null when the report has none. */
43
43
  export function codexUsageFromReport(report: unknown, now: Date): SubscriptionUsage | null {
44
44
  const rateLimit = isRecord(report) && isRecord(report.rate_limit) ? report.rate_limit : {};
45
- let binding: SubscriptionUsage | null = null;
46
- for (const name of ["primary_window", "secondary_window"]) {
47
- const window = rateLimit[name];
48
- if (!isRecord(window)) continue;
49
- const used = window.used_percent;
50
- const resetAt = window.reset_at;
51
- if (typeof used !== "number" || !Number.isFinite(used) || typeof resetAt !== "number") continue;
52
- const resetsAt = new Date(resetAt * 1000);
53
- if (resetsAt <= now) continue;
54
- const utilization = Math.max(0, Math.min(1, used / 100));
55
- if (binding === null || utilization > binding.utilization) binding = { utilization, resetsAt };
56
- }
57
- return binding;
45
+ return subscriptionUsageFromWindows(CODEX_USAGE_WINDOWS.map(([name, minutes]) => {
46
+ const window = isRecord(rateLimit[`${name}_window`]) ? rateLimit[`${name}_window`] as Record<string, unknown> : {};
47
+ const { used_percent: used, reset_at: resetAt, limit_window_seconds: seconds } = window;
48
+ return {
49
+ minutes: typeof seconds === "number" && seconds > 0 ? Math.round(seconds / 60) : minutes,
50
+ used: typeof used === "number" ? used / 100 : NaN,
51
+ resetsAt: typeof resetAt === "number" ? new Date(resetAt * 1000) : null,
52
+ };
53
+ }), now);
58
54
  }
59
55
 
60
56
  function codexAccountId(token: string): string | null {
@@ -364,7 +364,7 @@ export function buildModel(
364
364
  throw new HttpError(502, `No base URL is configured for provider ${provider}.`, "provider_configuration_error");
365
365
  }
366
366
  const contextWindow = contextWindowForModel(modelId, registered, config) ?? 128000;
367
- const compat = responsesToolContract(api, runtimeCompat(provider, registered, modelId));
367
+ const compat = gatewayRuntimeCompat(api, runtimeCompat(provider, registered, modelId));
368
368
  return {
369
369
  ...(registered ?? {}),
370
370
  ...(compat !== undefined ? { compat } : {}),
@@ -460,7 +460,13 @@ function contextWindowForModel(
460
460
  // keeps tools at the request level until that native tool-change path is validated.
461
461
  const RESPONSES_APIS: ReadonlySet<string> = new Set(["openai-responses", "azure-openai-responses", "openai-codex-responses"]);
462
462
 
463
- function responsesToolContract(api: unknown, compat: unknown): unknown {
463
+ function gatewayRuntimeCompat(api: unknown, compat: unknown): unknown {
464
+ // Pi 1.5 enables server-side message threads whenever sessionId is set.
465
+ // Gateway sessions serve affinity, not permission to retain a conversation
466
+ // remotely; keep full-history requests, including on ZDR routes.
467
+ if (api === "anthropic-messages") {
468
+ return { ...(isRecord(compat) ? compat : {}), supportsMessageThreads: false };
469
+ }
464
470
  if (typeof api !== "string" || !RESPONSES_APIS.has(api)) return compat;
465
471
  if (!isRecord(compat) || compat.supportsMidConvoSystemMessages !== true) return compat;
466
472
  return { ...compat, supportsMidConvoSystemMessages: false };
@@ -15,25 +15,55 @@ export type SubscriptionUsageLimit = {
15
15
  switched?: boolean;
16
16
  };
17
17
 
18
+ /** One quota window of a plan: its length, share used (0 to 1), and reset. */
19
+ export type SubscriptionUsageWindow = {
20
+ minutes: number;
21
+ utilization: number;
22
+ resetsAt: Date;
23
+ };
24
+
18
25
  /**
19
26
  * How much of a subscription's quota is used, from a successful response.
20
- * `utilization` is the binding window's share used (0 to 1): the window
21
- * closest to its limit, whose reset is `resetsAt`.
27
+ * `windows` lists every window with a future reset, shortest first;
28
+ * `utilization` and `resetsAt` are the binding window's: the one closest to
29
+ * its limit.
22
30
  */
23
31
  export type SubscriptionUsage = {
24
32
  utilization: number;
25
33
  resetsAt: Date;
34
+ windows: SubscriptionUsageWindow[];
26
35
  };
27
36
 
37
+ const FIVE_HOURS = 5 * 60;
38
+ const ONE_WEEK = 7 * 24 * 60;
39
+
28
40
  // Claude Code's unified limiter reports each window on every response, the
29
41
  // same headers Claude Code itself reads: `-utilization` as a fraction of the
30
42
  // window and `-reset` in unix seconds.
31
- const CLAUDE_CODE_USAGE_WINDOWS = ["5h", "7d"] as const;
43
+ const CLAUDE_CODE_USAGE_WINDOWS = [["5h", FIVE_HOURS], ["7d", ONE_WEEK]] as const;
32
44
 
33
45
  // The ChatGPT backend reports each Codex window on every response, the same
34
- // headers the Codex CLI reads: `-used-percent` out of 100 and `-reset-at` in
35
- // unix seconds.
36
- const CODEX_USAGE_WINDOWS = ["primary", "secondary"] as const;
46
+ // headers the Codex CLI reads: `-used-percent` out of 100, `-reset-at` in
47
+ // unix seconds, and `-window-minutes`. The defaults are a ChatGPT plan's.
48
+ export const CODEX_USAGE_WINDOWS = [["primary", FIVE_HOURS], ["secondary", ONE_WEEK]] as const;
49
+
50
+ /** Usage from raw windows, dropping malformed or already-reset ones. */
51
+ export function subscriptionUsageFromWindows(
52
+ raw: Array<{ minutes: number; used: number; resetsAt: Date | null }>,
53
+ now: Date,
54
+ ): SubscriptionUsage | null {
55
+ const windows = raw
56
+ .filter((window) => Number.isFinite(window.used) && window.resetsAt !== null && window.resetsAt > now)
57
+ .map((window) => ({
58
+ minutes: window.minutes,
59
+ utilization: Math.max(0, Math.min(1, window.used)),
60
+ resetsAt: window.resetsAt as Date,
61
+ }))
62
+ .sort((a, b) => a.minutes - b.minutes);
63
+ if (windows.length === 0) return null;
64
+ const binding = windows.reduce((a, b) => (b.utilization > a.utilization ? b : a));
65
+ return { utilization: binding.utilization, resetsAt: binding.resetsAt, windows };
66
+ }
37
67
 
38
68
  /**
39
69
  * The quota a successful subscription response reports used, or null when it
@@ -47,24 +77,19 @@ export function subscriptionUsageFromHeaders(
47
77
  ): SubscriptionUsage | null {
48
78
  const oauthProvider = subscriptionOAuthProviderFor(provider, keySource);
49
79
  const windows = oauthProvider === "anthropic_claude_code"
50
- ? CLAUDE_CODE_USAGE_WINDOWS.map((window) => ({
80
+ ? CLAUDE_CODE_USAGE_WINDOWS.map(([window, minutes]) => ({
81
+ minutes,
51
82
  used: Number(headers.get(`anthropic-ratelimit-unified-${window}-utilization`) ?? NaN),
52
- reset: headers.get(`anthropic-ratelimit-unified-${window}-reset`),
83
+ resetsAt: unixSecondsDeadline(headers.get(`anthropic-ratelimit-unified-${window}-reset`), now),
53
84
  }))
54
85
  : oauthProvider === "openai_codex"
55
- ? CODEX_USAGE_WINDOWS.map((window) => ({
86
+ ? CODEX_USAGE_WINDOWS.map(([window, minutes]) => ({
87
+ minutes: Number(headers.get(`x-codex-${window}-window-minutes`)) || minutes,
56
88
  used: Number(headers.get(`x-codex-${window}-used-percent`) ?? NaN) / 100,
57
- reset: headers.get(`x-codex-${window}-reset-at`),
89
+ resetsAt: unixSecondsDeadline(headers.get(`x-codex-${window}-reset-at`), now),
58
90
  }))
59
91
  : [];
60
- let binding: SubscriptionUsage | null = null;
61
- for (const { used, reset } of windows) {
62
- const resetsAt = unixSecondsDeadline(reset, now);
63
- if (!Number.isFinite(used) || resetsAt === null) continue;
64
- const utilization = Math.max(0, Math.min(1, used));
65
- if (binding === null || utilization > binding.utilization) binding = { utilization, resetsAt };
66
- }
67
- return binding;
92
+ return subscriptionUsageFromWindows(windows, now);
68
93
  }
69
94
 
70
95
  // Neither provider guarantees a reset time on every usage-limit response.
@@ -117,7 +117,6 @@ export async function resolveSelfHostedRouter(
117
117
  speculative_routing: false,
118
118
  session_pinning: router.sessionPinning,
119
119
  primary_retries: router.retries,
120
- lease_context_enabled: false,
121
120
  routing_strategy: "dari",
122
121
  custom_config: null,
123
122
  evals: [],
@@ -162,7 +162,15 @@ function summary(store: SubscriptionStore, credential: SubscriptionCredential, n
162
162
  /** The fields the CLI reads from a credential, never its tokens. */
163
163
  function usageBody(credential: SubscriptionCredential, now: Date) {
164
164
  const usage = currentUsage(credential, now);
165
- return usage === null ? null : { utilization: usage.utilization, resets_at: usage.resetsAt.toISOString() };
165
+ return usage === null ? null : {
166
+ utilization: usage.utilization,
167
+ resets_at: usage.resetsAt.toISOString(),
168
+ windows: usage.windows.map((window) => ({
169
+ minutes: window.minutes,
170
+ utilization: window.utilization,
171
+ resets_at: window.resetsAt.toISOString(),
172
+ })),
173
+ };
166
174
  }
167
175
 
168
176
  function credentialBody(credential: SubscriptionCredential, active: boolean, now: Date) {
@@ -86,6 +86,7 @@ type CredentialRow = {
86
86
  usage_utilization: number | null;
87
87
  usage_resets_at: number | null;
88
88
  usage_observed_at: number | null;
89
+ usage_windows: string | null;
89
90
  position: number;
90
91
  created_at: number;
91
92
  updated_at: number;
@@ -98,6 +99,7 @@ const USAGE_COLUMNS = {
98
99
  usage_utilization: "REAL",
99
100
  usage_resets_at: "INTEGER",
100
101
  usage_observed_at: "INTEGER",
102
+ usage_windows: "TEXT",
101
103
  } as const;
102
104
 
103
105
  type SessionRow = {
@@ -125,6 +127,7 @@ export class SubscriptionStore {
125
127
  usage_utilization REAL,
126
128
  usage_resets_at INTEGER,
127
129
  usage_observed_at INTEGER,
130
+ usage_windows TEXT,
128
131
  position INTEGER NOT NULL,
129
132
  created_at INTEGER NOT NULL,
130
133
  updated_at INTEGER NOT NULL,
@@ -214,8 +217,9 @@ export class SubscriptionStore {
214
217
  /** Record the usage a response reported for a subscription. */
215
218
  recordUsage(id: string, usage: SubscriptionUsage, now = new Date()): void {
216
219
  this.db.run(
217
- "UPDATE subscription_credentials SET usage_utilization = ?, usage_resets_at = ?, usage_observed_at = ? WHERE id = ?",
218
- [usage.utilization, usage.resetsAt.getTime(), now.getTime(), id],
220
+ `UPDATE subscription_credentials SET usage_utilization = ?, usage_resets_at = ?, usage_observed_at = ?,
221
+ usage_windows = ? WHERE id = ?`,
222
+ [usage.utilization, usage.resetsAt.getTime(), now.getTime(), windowsJson(usage), id],
219
223
  );
220
224
  }
221
225
 
@@ -269,7 +273,7 @@ export class SubscriptionStore {
269
273
  this.db.run(
270
274
  `UPDATE subscription_credentials SET access_token = ?, refresh_token = ?, expires_at = ?,
271
275
  account_id = ?, account_email = ?, unavailable_until = ?, unavailable_reason = ?,
272
- usage_utilization = ?, usage_resets_at = ?, usage_observed_at = ?, updated_at = ?
276
+ usage_utilization = ?, usage_resets_at = ?, usage_observed_at = ?, usage_windows = ?, updated_at = ?
273
277
  WHERE id = ?`,
274
278
  [
275
279
  tokens.accessToken,
@@ -282,6 +286,7 @@ export class SubscriptionStore {
282
286
  usage?.utilization ?? null,
283
287
  usage?.resetsAt.getTime() ?? null,
284
288
  usage?.observedAt.getTime() ?? null,
289
+ usage === null ? null : windowsJson(usage),
285
290
  now.getTime(),
286
291
  existing.id,
287
292
  ],
@@ -428,8 +433,20 @@ export function isHeld(credential: SubscriptionCredential, now: Date): boolean {
428
433
  }
429
434
 
430
435
  /** The usage a subscription last reported, while its window has not reset. */
436
+ /**
437
+ * The last reported usage of every window that has not reset. A short window
438
+ * resetting leaves the longer ones in force, so the binding window is the
439
+ * most used of those still running.
440
+ */
431
441
  export function currentUsage(credential: SubscriptionCredential, now: Date): SubscriptionUsage | null {
432
- return credential.usage !== null && credential.usage.resetsAt > now ? credential.usage : null;
442
+ const usage = credential.usage;
443
+ if (usage === null) return null;
444
+ // Usage recorded before per-window reports has only the binding window.
445
+ if (usage.windows.length === 0) return usage.resetsAt > now ? usage : null;
446
+ const windows = usage.windows.filter((window) => window.resetsAt > now);
447
+ if (windows.length === 0) return null;
448
+ const binding = windows.reduce((a, b) => (b.utilization > a.utilization ? b : a));
449
+ return { utilization: binding.utilization, resetsAt: binding.resetsAt, windows };
433
450
  }
434
451
 
435
452
  function hasHeadroom(credential: SubscriptionCredential, now: Date): boolean {
@@ -493,6 +510,7 @@ function credentialFromRow(row: CredentialRow): SubscriptionCredential {
493
510
  utilization: row.usage_utilization,
494
511
  resetsAt: new Date(row.usage_resets_at),
495
512
  observedAt: new Date(row.usage_observed_at),
513
+ windows: parseWindows(row.usage_windows),
496
514
  },
497
515
  position: row.position,
498
516
  createdAt: new Date(row.created_at),
@@ -500,3 +518,14 @@ function credentialFromRow(row: CredentialRow): SubscriptionCredential {
500
518
  lastUsedAt: row.last_used_at === null ? null : new Date(row.last_used_at),
501
519
  };
502
520
  }
521
+
522
+ function windowsJson(usage: SubscriptionUsage): string {
523
+ return JSON.stringify(usage.windows.map((window) => ({ ...window, resetsAt: window.resetsAt.getTime() })));
524
+ }
525
+
526
+ // Rows recorded before windows were stored have none.
527
+ function parseWindows(value: string | null): SubscriptionUsage["windows"] {
528
+ if (value === null) return [];
529
+ return (JSON.parse(value) as Array<{ minutes: number; utilization: number; resetsAt: number }>)
530
+ .map((window) => ({ ...window, resetsAt: new Date(window.resetsAt) }));
531
+ }
@@ -1,4 +1,4 @@
1
- import { parseSelectorDecision } from "@mupt-ai/dari-router/policy-engine";
1
+ import { parseSelectorDecision, SELECTOR_LEASE_TURNS } from "@mupt-ai/dari-router/policy-engine";
2
2
  import { HttpError } from "../http/errors.js";
3
3
  import type { SelectorBackend } from "./routing.js";
4
4
 
@@ -30,6 +30,9 @@ export function createAutoRoutingSelectorBackend(config: {
30
30
  return {
31
31
  selectorModel: AUTO_ROUTER_MODEL,
32
32
  contextWindowChars: async () => AUTO_ROUTER_CONTEXT_WINDOW_CHARS,
33
+ // Dari's routing policy grants leases, so an expired lease goes back to
34
+ // the policy rather than the runtime's stateless hold.
35
+ negotiatedLeaseTurns: async () => SELECTOR_LEASE_TURNS,
33
36
  select: async (args) => {
34
37
  let response: Response;
35
38
  try {
@@ -53,12 +56,8 @@ export function createAutoRoutingSelectorBackend(config: {
53
56
  );
54
57
  }
55
58
  const outputText = await response.text();
56
- // The gateway applies its own stateless hold; drop any lease the
57
- // policy stamps so it is not mistaken for a negotiated one.
58
- const { leaseTurnsRemaining: _leaseTurnsRemaining, ...decision } =
59
- parseSelectorDecision(outputText).decision;
60
59
  return {
61
- decision,
60
+ decision: parseSelectorDecision(outputText).decision,
62
61
  selectorModel: args.selectorModel,
63
62
  candidates: args.candidates,
64
63
  selectorInput: args.selectorInput,