@mupt-ai/dari-gateway 1.0.315 → 1.0.317

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.
@@ -61,6 +61,7 @@ export type LinkPlan = {
61
61
  window_minutes: number;
62
62
  utilization: number;
63
63
  resets_at: string;
64
+ model_family?: "fable";
64
65
  }>;
65
66
  state: "ready" | "plan_limit";
66
67
  available_at: string | null;
@@ -706,6 +706,7 @@ async function grantBody(platform, request, accessToken, detail) {
706
706
  serves: client === undefined ? "any_app" : `${client}_only`,
707
707
  unavailable_until: subscription.unavailableUntil,
708
708
  usage: subscription.usage.map((window) => ({
709
+ ...(window.modelFamily === undefined ? {} : { model_family: window.modelFamily }),
709
710
  window_minutes: window.minutes,
710
711
  utilization: window.utilization,
711
712
  resets_at: window.resetsAt,
@@ -731,7 +732,7 @@ function latest(times) {
731
732
  function planState(subscription, now) {
732
733
  const planTimes = [
733
734
  ...(subscription.unavailableUntil !== null && Date.parse(subscription.unavailableUntil) > now ? [subscription.unavailableUntil] : []),
734
- ...subscription.usage.filter((window) => window.utilization >= 1 && Date.parse(window.resetsAt) > now).map((window) => window.resetsAt),
735
+ ...subscription.usage.filter((window) => window.modelFamily === undefined && window.utilization >= 1 && Date.parse(window.resetsAt) > now).map((window) => window.resetsAt),
735
736
  ];
736
737
  return planTimes.length > 0 ? { state: "plan_limit", available_at: latest(planTimes) } : { state: "ready", available_at: null };
737
738
  }
@@ -1407,7 +1408,7 @@ function planOption(authorize, subscription, ticked) {
1407
1408
  const kind = subscription.provider;
1408
1409
  const only = subscriptionClient(kind);
1409
1410
  const purpose = authorize.purposes[only === "claude_code" || only === "muse_code" ? only : "any_app"];
1410
- const binding = subscription.usage.reduce((most, window) => most === null || window.utilization > most.utilization ? window : most, null);
1411
+ const binding = subscription.usage.filter((window) => window.modelFamily === undefined).reduce((most, window) => most === null || window.utilization > most.utilization ? window : most, null);
1411
1412
  const notes = [
1412
1413
  planLabel(subscription),
1413
1414
  ...(subscription.unavailableUntil
@@ -158,6 +158,7 @@ function linkSubscription(credential) {
158
158
  ? credential.unavailableUntil.toISOString()
159
159
  : null,
160
160
  usage: (currentUsage(credential, now)?.windows ?? []).map((window) => ({
161
+ ...(window.modelFamily === undefined ? {} : { modelFamily: window.modelFamily }),
161
162
  minutes: window.minutes,
162
163
  utilization: window.utilization,
163
164
  resetsAt: window.resetsAt.toISOString(),
@@ -278,6 +278,7 @@ export type LinkApp = {
278
278
  };
279
279
  /** One quota window of a plan: its length, share used (0 to 1), and reset. */
280
280
  export type LinkUsageWindow = {
281
+ modelFamily?: "fable";
281
282
  minutes: number;
282
283
  utilization: number;
283
284
  resetsAt: string;
@@ -10,6 +10,7 @@ export type SubscriptionUsageLimit = {
10
10
  };
11
11
  /** One quota window of a plan: its length, share used (0 to 1), and reset. */
12
12
  export type SubscriptionUsageWindow = {
13
+ modelFamily?: "fable";
13
14
  minutes: number;
14
15
  utilization: number;
15
16
  resetsAt: Date;
@@ -17,7 +18,8 @@ export type SubscriptionUsageWindow = {
17
18
  /**
18
19
  * How much of a subscription's quota is used, from a successful response.
19
20
  * `windows` lists every window with a future reset, shortest first;
20
- * `utilization` and `resetsAt` are the binding window's: the one closest to
21
+ * Model-family windows are separate meters and never bind the whole plan.
22
+ * `utilization` and `resetsAt` are the shared binding window's: the one closest to
21
23
  * its limit.
22
24
  */
23
25
  export type SubscriptionUsage = {
@@ -31,6 +33,7 @@ export declare function subscriptionUsageFromWindows(raw: Array<{
31
33
  minutes: number;
32
34
  used: number;
33
35
  resetsAt: Date | null;
36
+ modelFamily?: "fable";
34
37
  }>, now: Date): SubscriptionUsage | null;
35
38
  /**
36
39
  * The quota a successful subscription response reports used, or null when it
@@ -5,7 +5,7 @@ const ONE_WEEK = 7 * 24 * 60;
5
5
  // Claude Code's unified limiter reports each window on every response, the
6
6
  // same headers Claude Code itself reads: `-utilization` as a fraction of the
7
7
  // window and `-reset` in unix seconds.
8
- const CLAUDE_CODE_USAGE_WINDOWS = [["5h", FIVE_HOURS], ["7d", ONE_WEEK]];
8
+ const CLAUDE_CODE_USAGE_WINDOWS = [["5h", FIVE_HOURS], ["7d", ONE_WEEK], ["7d_oi", ONE_WEEK]];
9
9
  // The ChatGPT backend reports each Codex window on every response, the same
10
10
  // headers the Codex CLI reads: `-used-percent` out of 100, `-reset-at` in
11
11
  // unix seconds, and `-window-minutes`. The defaults are a ChatGPT plan's.
@@ -15,15 +15,18 @@ export function subscriptionUsageFromWindows(raw, now) {
15
15
  const windows = raw
16
16
  .filter((window) => Number.isFinite(window.used) && window.resetsAt !== null && window.resetsAt > now)
17
17
  .map((window) => ({
18
+ ...(window.modelFamily === undefined ? {} : { modelFamily: window.modelFamily }),
18
19
  minutes: window.minutes,
19
20
  utilization: Math.max(0, Math.min(1, window.used)),
20
21
  resetsAt: window.resetsAt,
21
22
  }))
22
- .sort((a, b) => a.minutes - b.minutes);
23
+ .sort((a, b) => a.minutes - b.minutes || (a.modelFamily ?? "").localeCompare(b.modelFamily ?? ""));
23
24
  if (windows.length === 0)
24
25
  return null;
25
- const binding = windows.reduce((a, b) => (b.utilization > a.utilization ? b : a));
26
- return { utilization: binding.utilization, resetsAt: binding.resetsAt, windows };
26
+ const binding = windows.filter((window) => window.modelFamily === undefined)
27
+ .reduce((a, b) => a === null || b.utilization > a.utilization ? b : a, null);
28
+ // Family-only reports still carry useful meters, but no shared-plan usage.
29
+ return { utilization: binding?.utilization ?? 0, resetsAt: binding?.resetsAt ?? windows[0].resetsAt, windows };
27
30
  }
28
31
  /**
29
32
  * The quota a successful subscription response reports used, or null when it
@@ -33,6 +36,7 @@ export function subscriptionUsageFromHeaders(provider, keySource, headers, now =
33
36
  const oauthProvider = subscriptionOAuthProviderFor(provider, keySource);
34
37
  const windows = oauthProvider === "anthropic_claude_code"
35
38
  ? CLAUDE_CODE_USAGE_WINDOWS.map(([window, minutes]) => ({
39
+ ...(window === "7d_oi" ? { modelFamily: "fable" } : {}),
36
40
  minutes,
37
41
  used: Number(headers.get(`anthropic-ratelimit-unified-${window}-utilization`) ?? NaN),
38
42
  resetsAt: unixSecondsDeadline(headers.get(`anthropic-ratelimit-unified-${window}-reset`), now),
@@ -143,7 +147,9 @@ export function detectSubscriptionUsageLimit(args) {
143
147
  }
144
148
  // Claude Code plans also cap some model families on their own
145
149
  // (`seven_day_opus`, `seven_day_sonnet`). The representative claim names the
146
- // window that refused, and `-fallback: available` says another model can still
150
+ // window that refused. Fable uses `seven_day_overage_included` (the separate
151
+ // included Fable allowance), not the shared `seven_day` window.
152
+ // `-fallback: available` also says another model can still
147
153
  // serve; either way the rest of the plan is not exhausted.
148
154
  const ANTHROPIC_MODEL_CLAIM = /^(?:five_hour|seven_day)_(?:opus|sonnet|haiku|fable|mythos)(?:_|$)/;
149
155
  function anthropicUsageLimit(captured, model, now) {
@@ -157,12 +163,13 @@ function anthropicUsageLimit(captured, model, now) {
157
163
  return null;
158
164
  }
159
165
  const claim = captured.headers.get("anthropic-ratelimit-unified-representative-claim");
160
- const modelLimit = (claim !== null && ANTHROPIC_MODEL_CLAIM.test(claim))
166
+ const fableLimit = claim === "seven_day_overage_included";
167
+ const modelLimit = fableLimit || (claim !== null && ANTHROPIC_MODEL_CLAIM.test(claim))
161
168
  || captured.headers.get("anthropic-ratelimit-unified-fallback") === "available";
162
169
  return {
163
170
  oauthProvider: "anthropic_claude_code",
164
171
  resetsAt: resetFromUnixSeconds(captured.headers.get("anthropic-ratelimit-unified-reset"), now),
165
- reason: claim
172
+ reason: fableLimit ? "Claude Code Fable usage limit reached." : claim
166
173
  ? `Claude Code ${claim.replaceAll("_", " ")} usage limit reached.`
167
174
  : modelLimit ? `Claude Code usage limit for ${model} reached.` : "Claude Code usage limit reached.",
168
175
  ...(modelLimit ? { model } : {}),
@@ -158,6 +158,7 @@ function usageBody(credential, now) {
158
158
  utilization: usage.utilization,
159
159
  resets_at: usage.resetsAt.toISOString(),
160
160
  windows: usage.windows.map((window) => ({
161
+ ...(window.modelFamily === undefined ? {} : { model_family: window.modelFamily }),
161
162
  minutes: window.minutes,
162
163
  utilization: window.utilization,
163
164
  resets_at: window.resetsAt.toISOString(),
@@ -25,7 +25,7 @@
25
25
  * limit) leaves the subscription serving its other models.
26
26
  */
27
27
  import type { Database } from "bun:sqlite";
28
- import type { SubscriptionUsage } from "../../providers/subscription_limits.js";
28
+ import { type SubscriptionUsage } from "../../providers/subscription_limits.js";
29
29
  import { type SecretBox } from "../secret_box.js";
30
30
  import type { OAuthTokens, SubscriptionProvider } from "./oauth.js";
31
31
  export declare const SWITCH_AT_UTILIZATION = 0.95;
@@ -1,4 +1,5 @@
1
1
  import { randomBytes, randomUUID } from "node:crypto";
2
+ import { subscriptionUsageFromWindows } from "../../providers/subscription_limits.js";
2
3
  import { openWithoutKey } from "../secret_box.js";
3
4
  // The share of a usage window past which conversations leave a subscription
4
5
  // at their next turn, before the provider starts refusing requests.
@@ -196,6 +197,13 @@ export class SubscriptionStore {
196
197
  }
197
198
  /** Record the usage a response reported for a subscription. */
198
199
  recordUsage(id, usage, now = new Date()) {
200
+ if (usage.windows.length > 0) {
201
+ // Responses may omit meters belonging to another model family. Only
202
+ // replace matching windows, including explicit resets, and age out the rest.
203
+ const previous = this.get(id)?.usage?.windows ?? [];
204
+ const windows = [...previous.filter((old) => !usage.windows.some((window) => window.minutes === old.minutes && window.modelFamily === old.modelFamily)), ...usage.windows];
205
+ usage = subscriptionUsageFromWindows(windows.map((window) => ({ ...window, used: window.utilization })), now) ?? usage;
206
+ }
199
207
  this.db.run(`UPDATE subscription_credentials SET usage_utilization = ?, usage_resets_at = ?, usage_observed_at = ?,
200
208
  usage_windows = ? WHERE id = ?`, [usage.utilization, usage.resetsAt.getTime(), now.getTime(), windowsJson(usage), id]);
201
209
  }
@@ -427,11 +435,7 @@ export function currentUsage(credential, now) {
427
435
  // Usage recorded before per-window reports has only the binding window.
428
436
  if (usage.windows.length === 0)
429
437
  return usage.resetsAt > now ? usage : null;
430
- const windows = usage.windows.filter((window) => window.resetsAt > now);
431
- if (windows.length === 0)
432
- return null;
433
- const binding = windows.reduce((a, b) => (b.utilization > a.utilization ? b : a));
434
- return { utilization: binding.utilization, resetsAt: binding.resetsAt, windows };
438
+ return subscriptionUsageFromWindows(usage.windows.map((window) => ({ ...window, used: window.utilization })), now);
435
439
  }
436
440
  function hasHeadroom(credential, now) {
437
441
  return (currentUsage(credential, now)?.utilization ?? 0) < SWITCH_AT_UTILIZATION;
@@ -454,9 +458,19 @@ function rotationFrom(all, anchor) {
454
458
  // Spend quota about to reset first; a subscription with no current usage
455
459
  // report (fresh, or its window reset) comes after, then rotation order.
456
460
  function soonestResetFirst(now, order) {
461
+ const sharedReset = (credential) => {
462
+ const usage = currentUsage(credential, now);
463
+ if (usage === null)
464
+ return Infinity;
465
+ if (usage.windows.length === 0)
466
+ return usage.resetsAt.getTime();
467
+ const binding = usage.windows.filter((window) => window.modelFamily === undefined)
468
+ .reduce((most, window) => most === null || window.utilization > most.utilization ? window : most, null);
469
+ return binding?.resetsAt.getTime() ?? Infinity;
470
+ };
457
471
  return (a, b) => {
458
- const resetA = currentUsage(a, now)?.resetsAt.getTime() ?? Infinity;
459
- const resetB = currentUsage(b, now)?.resetsAt.getTime() ?? Infinity;
472
+ const resetA = sharedReset(a);
473
+ const resetB = sharedReset(b);
460
474
  return resetA - resetB || order.get(a.id) - order.get(b.id);
461
475
  };
462
476
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.315",
3
+ "version": "1.0.317",
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": {
@@ -52,7 +52,7 @@
52
52
  },
53
53
  "dependencies": {
54
54
  "@aws-sdk/client-sts": "3.1063.0",
55
- "@mupt-ai/dari-router": "1.0.315",
55
+ "@mupt-ai/dari-router": "1.0.317",
56
56
  "@mupt-ai/pi-ai": "1.5.2-mupt.1"
57
57
  },
58
58
  "devDependencies": {
@@ -66,7 +66,7 @@ export type LinkPlan = {
66
66
  serves: string;
67
67
  unavailable_until: string | null;
68
68
  // Quota windows the plan last reported, shortest first; empty when unknown.
69
- usage: Array<{ window_minutes: number; utilization: number; resets_at: string }>;
69
+ usage: Array<{ window_minutes: number; utilization: number; resets_at: string; model_family?: "fable" }>;
70
70
  // Why the plan does or does not serve the app now, and when it will again.
71
71
  state: "ready" | "plan_limit";
72
72
  available_at: string | null;
@@ -787,6 +787,7 @@ async function grantBody(platform: GatewayPlatform, request: Request, accessToke
787
787
  serves: client === undefined ? "any_app" : `${client}_only`,
788
788
  unavailable_until: subscription.unavailableUntil,
789
789
  usage: subscription.usage.map((window) => ({
790
+ ...(window.modelFamily === undefined ? {} : { model_family: window.modelFamily }),
790
791
  window_minutes: window.minutes,
791
792
  utilization: window.utilization,
792
793
  resets_at: window.resetsAt,
@@ -817,7 +818,7 @@ function planState(subscription: LinkSubscription, now: number): {
817
818
  } {
818
819
  const planTimes = [
819
820
  ...(subscription.unavailableUntil !== null && Date.parse(subscription.unavailableUntil) > now ? [subscription.unavailableUntil] : []),
820
- ...subscription.usage.filter((window) => window.utilization >= 1 && Date.parse(window.resetsAt) > now).map((window) => window.resetsAt),
821
+ ...subscription.usage.filter((window) => window.modelFamily === undefined && window.utilization >= 1 && Date.parse(window.resetsAt) > now).map((window) => window.resetsAt),
821
822
  ];
822
823
  return planTimes.length > 0 ? { state: "plan_limit", available_at: latest(planTimes) } : { state: "ready", available_at: null };
823
824
  }
@@ -1593,7 +1594,7 @@ function planOption(authorize: AuthorizeRequest, subscription: LinkSubscription,
1593
1594
  const kind = subscription.provider as SubscriptionKind;
1594
1595
  const only = subscriptionClient(kind);
1595
1596
  const purpose = authorize.purposes[only === "claude_code" || only === "muse_code" ? only : "any_app"];
1596
- const binding = subscription.usage.reduce<LinkSubscription["usage"][number] | null>(
1597
+ const binding = subscription.usage.filter((window) => window.modelFamily === undefined).reduce<LinkSubscription["usage"][number] | null>(
1597
1598
  (most, window) => most === null || window.utilization > most.utilization ? window : most,
1598
1599
  null,
1599
1600
  );
@@ -178,6 +178,7 @@ function linkSubscription(credential: SubscriptionCredential): LinkSubscription
178
178
  ? credential.unavailableUntil.toISOString()
179
179
  : null,
180
180
  usage: (currentUsage(credential, now)?.windows ?? []).map((window) => ({
181
+ ...(window.modelFamily === undefined ? {} : { modelFamily: window.modelFamily }),
181
182
  minutes: window.minutes,
182
183
  utilization: window.utilization,
183
184
  resetsAt: window.resetsAt.toISOString(),
@@ -283,6 +283,7 @@ export type LinkApp = {
283
283
 
284
284
  /** One quota window of a plan: its length, share used (0 to 1), and reset. */
285
285
  export type LinkUsageWindow = {
286
+ modelFamily?: "fable";
286
287
  minutes: number;
287
288
  utilization: number;
288
289
  resetsAt: string;
@@ -21,6 +21,8 @@ export type SubscriptionUsageLimit = {
21
21
 
22
22
  /** One quota window of a plan: its length, share used (0 to 1), and reset. */
23
23
  export type SubscriptionUsageWindow = {
24
+ // Absent for shared plan quota; a family limit must not exhaust the plan.
25
+ modelFamily?: "fable";
24
26
  minutes: number;
25
27
  utilization: number;
26
28
  resetsAt: Date;
@@ -29,7 +31,8 @@ export type SubscriptionUsageWindow = {
29
31
  /**
30
32
  * How much of a subscription's quota is used, from a successful response.
31
33
  * `windows` lists every window with a future reset, shortest first;
32
- * `utilization` and `resetsAt` are the binding window's: the one closest to
34
+ * Model-family windows are separate meters and never bind the whole plan.
35
+ * `utilization` and `resetsAt` are the shared binding window's: the one closest to
33
36
  * its limit.
34
37
  */
35
38
  export type SubscriptionUsage = {
@@ -44,7 +47,7 @@ const ONE_WEEK = 7 * 24 * 60;
44
47
  // Claude Code's unified limiter reports each window on every response, the
45
48
  // same headers Claude Code itself reads: `-utilization` as a fraction of the
46
49
  // window and `-reset` in unix seconds.
47
- const CLAUDE_CODE_USAGE_WINDOWS = [["5h", FIVE_HOURS], ["7d", ONE_WEEK]] as const;
50
+ const CLAUDE_CODE_USAGE_WINDOWS = [["5h", FIVE_HOURS], ["7d", ONE_WEEK], ["7d_oi", ONE_WEEK]] as const;
48
51
 
49
52
  // The ChatGPT backend reports each Codex window on every response, the same
50
53
  // headers the Codex CLI reads: `-used-percent` out of 100, `-reset-at` in
@@ -53,20 +56,23 @@ export const CODEX_USAGE_WINDOWS = [["primary", FIVE_HOURS], ["secondary", ONE_W
53
56
 
54
57
  /** Usage from raw windows, dropping malformed or already-reset ones. */
55
58
  export function subscriptionUsageFromWindows(
56
- raw: Array<{ minutes: number; used: number; resetsAt: Date | null }>,
59
+ raw: Array<{ minutes: number; used: number; resetsAt: Date | null; modelFamily?: "fable" }>,
57
60
  now: Date,
58
61
  ): SubscriptionUsage | null {
59
62
  const windows = raw
60
63
  .filter((window) => Number.isFinite(window.used) && window.resetsAt !== null && window.resetsAt > now)
61
64
  .map((window) => ({
65
+ ...(window.modelFamily === undefined ? {} : { modelFamily: window.modelFamily }),
62
66
  minutes: window.minutes,
63
67
  utilization: Math.max(0, Math.min(1, window.used)),
64
68
  resetsAt: window.resetsAt as Date,
65
69
  }))
66
- .sort((a, b) => a.minutes - b.minutes);
70
+ .sort((a, b) => a.minutes - b.minutes || (a.modelFamily ?? "").localeCompare(b.modelFamily ?? ""));
67
71
  if (windows.length === 0) return null;
68
- const binding = windows.reduce((a, b) => (b.utilization > a.utilization ? b : a));
69
- return { utilization: binding.utilization, resetsAt: binding.resetsAt, windows };
72
+ const binding = windows.filter((window) => window.modelFamily === undefined)
73
+ .reduce<SubscriptionUsageWindow | null>((a, b) => a === null || b.utilization > a.utilization ? b : a, null);
74
+ // Family-only reports still carry useful meters, but no shared-plan usage.
75
+ return { utilization: binding?.utilization ?? 0, resetsAt: binding?.resetsAt ?? windows[0]!.resetsAt, windows };
70
76
  }
71
77
 
72
78
  /**
@@ -82,6 +88,7 @@ export function subscriptionUsageFromHeaders(
82
88
  const oauthProvider = subscriptionOAuthProviderFor(provider, keySource);
83
89
  const windows = oauthProvider === "anthropic_claude_code"
84
90
  ? CLAUDE_CODE_USAGE_WINDOWS.map(([window, minutes]) => ({
91
+ ...(window === "7d_oi" ? { modelFamily: "fable" as const } : {}),
85
92
  minutes,
86
93
  used: Number(headers.get(`anthropic-ratelimit-unified-${window}-utilization`) ?? NaN),
87
94
  resetsAt: unixSecondsDeadline(headers.get(`anthropic-ratelimit-unified-${window}-reset`), now),
@@ -210,7 +217,9 @@ export function detectSubscriptionUsageLimit(args: {
210
217
 
211
218
  // Claude Code plans also cap some model families on their own
212
219
  // (`seven_day_opus`, `seven_day_sonnet`). The representative claim names the
213
- // window that refused, and `-fallback: available` says another model can still
220
+ // window that refused. Fable uses `seven_day_overage_included` (the separate
221
+ // included Fable allowance), not the shared `seven_day` window.
222
+ // `-fallback: available` also says another model can still
214
223
  // serve; either way the rest of the plan is not exhausted.
215
224
  const ANTHROPIC_MODEL_CLAIM = /^(?:five_hour|seven_day)_(?:opus|sonnet|haiku|fable|mythos)(?:_|$)/;
216
225
 
@@ -228,12 +237,13 @@ function anthropicUsageLimit(
228
237
  return null;
229
238
  }
230
239
  const claim = captured.headers.get("anthropic-ratelimit-unified-representative-claim");
231
- const modelLimit = (claim !== null && ANTHROPIC_MODEL_CLAIM.test(claim))
240
+ const fableLimit = claim === "seven_day_overage_included";
241
+ const modelLimit = fableLimit || (claim !== null && ANTHROPIC_MODEL_CLAIM.test(claim))
232
242
  || captured.headers.get("anthropic-ratelimit-unified-fallback") === "available";
233
243
  return {
234
244
  oauthProvider: "anthropic_claude_code",
235
245
  resetsAt: resetFromUnixSeconds(captured.headers.get("anthropic-ratelimit-unified-reset"), now),
236
- reason: claim
246
+ reason: fableLimit ? "Claude Code Fable usage limit reached." : claim
237
247
  ? `Claude Code ${claim.replaceAll("_", " ")} usage limit reached.`
238
248
  : modelLimit ? `Claude Code usage limit for ${model} reached.` : "Claude Code usage limit reached.",
239
249
  ...(modelLimit ? { model } : {}),
@@ -181,6 +181,7 @@ function usageBody(credential: SubscriptionCredential, now: Date) {
181
181
  utilization: usage.utilization,
182
182
  resets_at: usage.resetsAt.toISOString(),
183
183
  windows: usage.windows.map((window) => ({
184
+ ...(window.modelFamily === undefined ? {} : { model_family: window.modelFamily }),
184
185
  minutes: window.minutes,
185
186
  utilization: window.utilization,
186
187
  resets_at: window.resetsAt.toISOString(),
@@ -27,7 +27,7 @@
27
27
  import type { Database } from "bun:sqlite";
28
28
  import { randomBytes, randomUUID } from "node:crypto";
29
29
 
30
- import type { SubscriptionUsage } from "../../providers/subscription_limits.js";
30
+ import { subscriptionUsageFromWindows, type SubscriptionUsage } from "../../providers/subscription_limits.js";
31
31
  import { type SecretBox, openWithoutKey } from "../secret_box.js";
32
32
  import type { OAuthTokens, SubscriptionProvider } from "./oauth.js";
33
33
 
@@ -326,6 +326,15 @@ export class SubscriptionStore {
326
326
 
327
327
  /** Record the usage a response reported for a subscription. */
328
328
  recordUsage(id: string, usage: SubscriptionUsage, now = new Date()): void {
329
+ if (usage.windows.length > 0) {
330
+ // Responses may omit meters belonging to another model family. Only
331
+ // replace matching windows, including explicit resets, and age out the rest.
332
+ const previous = this.get(id)?.usage?.windows ?? [];
333
+ const windows = [...previous.filter((old) => !usage.windows.some((window) =>
334
+ window.minutes === old.minutes && window.modelFamily === old.modelFamily,
335
+ )), ...usage.windows];
336
+ usage = subscriptionUsageFromWindows(windows.map((window) => ({ ...window, used: window.utilization })), now) ?? usage;
337
+ }
329
338
  this.db.run(
330
339
  `UPDATE subscription_credentials SET usage_utilization = ?, usage_resets_at = ?, usage_observed_at = ?,
331
340
  usage_windows = ? WHERE id = ?`,
@@ -608,10 +617,7 @@ export function currentUsage(credential: SubscriptionCredential, now: Date): Sub
608
617
  if (usage === null) return null;
609
618
  // Usage recorded before per-window reports has only the binding window.
610
619
  if (usage.windows.length === 0) return usage.resetsAt > now ? usage : null;
611
- const windows = usage.windows.filter((window) => window.resetsAt > now);
612
- if (windows.length === 0) return null;
613
- const binding = windows.reduce((a, b) => (b.utilization > a.utilization ? b : a));
614
- return { utilization: binding.utilization, resetsAt: binding.resetsAt, windows };
620
+ return subscriptionUsageFromWindows(usage.windows.map((window) => ({ ...window, used: window.utilization })), now);
615
621
  }
616
622
 
617
623
  function hasHeadroom(credential: SubscriptionCredential, now: Date): boolean {
@@ -638,9 +644,19 @@ function rotationFrom(all: SubscriptionCredential[], anchor: SubscriptionCredent
638
644
  // Spend quota about to reset first; a subscription with no current usage
639
645
  // report (fresh, or its window reset) comes after, then rotation order.
640
646
  function soonestResetFirst(now: Date, order: Map<string, number>) {
647
+ const sharedReset = (credential: SubscriptionCredential): number => {
648
+ const usage = currentUsage(credential, now);
649
+ if (usage === null) return Infinity;
650
+ if (usage.windows.length === 0) return usage.resetsAt.getTime();
651
+ const binding = usage.windows.filter((window) => window.modelFamily === undefined)
652
+ .reduce<SubscriptionUsage["windows"][number] | null>(
653
+ (most, window) => most === null || window.utilization > most.utilization ? window : most, null,
654
+ );
655
+ return binding?.resetsAt.getTime() ?? Infinity;
656
+ };
641
657
  return (a: SubscriptionCredential, b: SubscriptionCredential): number => {
642
- const resetA = currentUsage(a, now)?.resetsAt.getTime() ?? Infinity;
643
- const resetB = currentUsage(b, now)?.resetsAt.getTime() ?? Infinity;
658
+ const resetA = sharedReset(a);
659
+ const resetB = sharedReset(b);
644
660
  return resetA - resetB || order.get(a.id)! - order.get(b.id)!;
645
661
  };
646
662
  }
@@ -713,6 +729,6 @@ function parseModelHolds(value: string | null): SubscriptionModelHold[] {
713
729
  // Rows recorded before windows were stored have none.
714
730
  function parseWindows(value: string | null): SubscriptionUsage["windows"] {
715
731
  if (value === null) return [];
716
- return (JSON.parse(value) as Array<{ minutes: number; utilization: number; resetsAt: number }>)
732
+ return (JSON.parse(value) as Array<Omit<SubscriptionUsage["windows"][number], "resetsAt"> & { resetsAt: number }>)
717
733
  .map((window) => ({ ...window, resetsAt: new Date(window.resetsAt) }));
718
734
  }