@cartanova/qgrid-cli 2.14.0 → 2.14.1

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 (28) hide show
  1. package/bundle/dist/utils/providers/anthropic/anthropic-dispatcher.js +12 -13
  2. package/bundle/dist/utils/providers/anthropic/anthropic-quota.js +10 -6
  3. package/bundle/dist/utils/providers/grok/grok-dispatcher.js +15 -15
  4. package/bundle/src/utils/providers/anthropic/anthropic-dispatcher.test.ts +31 -4
  5. package/bundle/src/utils/providers/anthropic/anthropic-dispatcher.ts +14 -14
  6. package/bundle/src/utils/providers/anthropic/anthropic-quota.test.ts +12 -7
  7. package/bundle/src/utils/providers/anthropic/anthropic-quota.ts +17 -7
  8. package/bundle/src/utils/providers/grok/grok-dispatcher.test.ts +23 -7
  9. package/bundle/src/utils/providers/grok/grok-dispatcher.ts +19 -23
  10. package/bundle/src/utils/providers/openai/openai-dispatcher.test.ts +2 -2
  11. package/bundle/web-dist/client/assets/{index-Cj7ZXipM.js → index-jExDfi8j.js} +3 -3
  12. package/bundle/web-dist/client/assets/{logs-DSuoyKRh.js → logs-ol_IGjcT.js} +1 -1
  13. package/bundle/web-dist/client/assets/{monit-BwLPgwHG.js → monit-CGTRk2U0.js} +1 -1
  14. package/bundle/web-dist/client/assets/{routes-_R4-gxLV.js → routes-D9l20OWa.js} +2 -2
  15. package/bundle/web-dist/client/assets/{settings-ZBCgAZaZ.js → settings-D2zIv0xR.js} +1 -1
  16. package/bundle/web-dist/client/assets/{show-DFFBtBqe.js → show-DefwCScC.js} +1 -1
  17. package/bundle/web-dist/client/assets/{tokens-DYSfYz8A.js → tokens-CbmIxMZ9.js} +1 -1
  18. package/bundle/web-dist/client/assets/{use-oauth-login-flow-CN8nxeAR.js → use-oauth-login-flow-CEufhZcR.js} +1 -1
  19. package/bundle/web-dist/client/assets/{use-update-token-mutation-B-N8fFUm.js → use-update-token-mutation-E5ey27W6.js} +1 -1
  20. package/bundle/web-dist/client/index.html +1 -1
  21. package/bundle/web-dist/server/assets/{routes-CjWxvHAO.js → routes-CCdBJqP_.js} +11 -10
  22. package/bundle/web-dist/server/entry-server.generated.js +2 -2
  23. package/package.json +1 -1
  24. package/skills/qgrid/references/anthropic-claude-code-runtime.md +4 -3
  25. package/skills/qgrid/references/decision-rationale.md +4 -4
  26. package/skills/qgrid/references/grok-runtime.md +4 -1
  27. package/skills/qgrid/references/sonamu-api-web-flow.md +4 -0
  28. package/skills/qgrid/references/token-auth-quota-lifecycle.md +8 -5
@@ -12,6 +12,7 @@ const {
12
12
  runClaudeSessionMock,
13
13
  refreshTokenMock,
14
14
  readAnthropicQuotaUsageMock,
15
+ fetchUsageWithMetaMock,
15
16
  invalidateAnthropicQuotaUsageMock,
16
17
  loggerInfoMock,
17
18
  loggerWarnMock,
@@ -19,6 +20,7 @@ const {
19
20
  runClaudeSessionMock: vi.fn(),
20
21
  refreshTokenMock: vi.fn(),
21
22
  readAnthropicQuotaUsageMock: vi.fn(),
23
+ fetchUsageWithMetaMock: vi.fn(),
22
24
  invalidateAnthropicQuotaUsageMock: vi.fn(),
23
25
  loggerInfoMock: vi.fn(),
24
26
  loggerWarnMock: vi.fn(),
@@ -38,6 +40,11 @@ vi.mock("./anthropic-quota", () => ({
38
40
  invalidateAnthropicQuotaUsage: invalidateAnthropicQuotaUsageMock,
39
41
  }));
40
42
 
43
+ vi.mock("../../../application/qgrid/oauth", () => ({
44
+ fetchUsageWithMeta: fetchUsageWithMetaMock,
45
+ invalidateAnthropicQuotaUsage: invalidateAnthropicQuotaUsageMock,
46
+ }));
47
+
41
48
  vi.mock("../../../application/qgrid/qgrid.frame", () => ({
42
49
  QgridFrame: { refreshToken: refreshTokenMock },
43
50
  }));
@@ -80,7 +87,7 @@ function baseReq(overrides: Partial<GenerateRequest> = {}): GenerateRequest {
80
87
  }
81
88
 
82
89
  function quotaOk(utilizationPct: number, cacheAgeMs = 100): AnthropicQuotaUsageResult {
83
- return { kind: "ok", utilizationPct, cacheAgeMs };
90
+ return { kind: "ok", utilizationPct, weeklyUtilizationPct: null, cacheAgeMs };
84
91
  }
85
92
 
86
93
  function quotaFail(reason = "usage lookup failed"): AnthropicQuotaUsageResult {
@@ -115,6 +122,8 @@ describe("AnthropicDispatcher", () => {
115
122
  refreshTokenMock.mockReset();
116
123
  refreshTokenMock.mockResolvedValue("sk-ant-oat01-refreshed");
117
124
  readAnthropicQuotaUsageMock.mockReset();
125
+ readAnthropicQuotaUsageMock.mockResolvedValue(quotaOk(0));
126
+ fetchUsageWithMetaMock.mockReset();
118
127
  invalidateAnthropicQuotaUsageMock.mockReset();
119
128
  loggerInfoMock.mockReset();
120
129
  loggerWarnMock.mockReset();
@@ -266,7 +275,7 @@ describe("AnthropicDispatcher", () => {
266
275
 
267
276
  expect(names.filter((name) => name === "tok-A")).toHaveLength(3);
268
277
  expect(names.filter((name) => name === "tok-B")).toHaveLength(1);
269
- expect(readAnthropicQuotaUsageMock).not.toHaveBeenCalled();
278
+ expect(readAnthropicQuotaUsageMock).toHaveBeenCalledTimes(8);
270
279
  });
271
280
 
272
281
  it("preferredTokenId 가 있으면 가중 선택과 무관하게 그 토큰을 고른다", async () => {
@@ -331,7 +340,7 @@ describe("AnthropicDispatcher", () => {
331
340
  d.onTokenAdded(1, "tok-A", creds(), 80, 1);
332
341
  d.onTokenAdded(2, "tok-B", creds(), 80, 1);
333
342
  readAnthropicQuotaUsageMock
334
- .mockResolvedValueOnce(quotaOk(100))
343
+ .mockResolvedValueOnce({ ...quotaOk(10), weeklyUtilizationPct: 100 })
335
344
  .mockResolvedValueOnce(quotaOk(10));
336
345
 
337
346
  const result = await d.generate(baseReq({ model: "claude-fable-5" }));
@@ -356,6 +365,24 @@ describe("AnthropicDispatcher", () => {
356
365
  expect(names.filter((name) => name === "tok-B")).toHaveLength(3);
357
366
  });
358
367
 
368
+ it.each([80, null])("allows a keepalive target below weekly exhaustion (threshold=%s)", async (threshold) => {
369
+ const { readAnthropicQuotaUsage } = await vi.importActual<typeof import("./anthropic-quota")>("./anthropic-quota");
370
+ readAnthropicQuotaUsageMock.mockImplementation(readAnthropicQuotaUsage);
371
+ const usage = {
372
+ five_hour: { utilization: 0, resets_at: null },
373
+ seven_day: { utilization: 92, resets_at: null },
374
+ };
375
+ fetchUsageWithMetaMock.mockImplementation(async () => ({ data: usage, cachedAt: Date.now() }));
376
+ const d = new AnthropicDispatcher();
377
+ d.onTokenAdded(1, "anthropic/noa", creds(), threshold);
378
+ const req = baseReq({ model: "claude-haiku-5-5", preferredTokenId: 1 });
379
+
380
+ expect((await d.generate(req)).tokenName).toBe("anthropic/noa");
381
+ usage.seven_day.utilization = 100;
382
+ await expect(d.generate(req)).rejects.toBeInstanceOf(QuotaThresholdExceededError);
383
+ expect(runClaudeSessionMock).toHaveBeenCalledTimes(1);
384
+ });
385
+
359
386
  it("threshold 초과 토큰은 후보에서 제외하고 미설정 토큰을 선택한다", async () => {
360
387
  const d = new AnthropicDispatcher();
361
388
  d.onTokenAdded(1, "tok-A", creds(), 80, 1);
@@ -365,7 +392,7 @@ describe("AnthropicDispatcher", () => {
365
392
  const result = await d.generate(baseReq());
366
393
 
367
394
  expect(result.tokenName).toBe("tok-B");
368
- expect(readAnthropicQuotaUsageMock).toHaveBeenCalledTimes(1);
395
+ expect(readAnthropicQuotaUsageMock).toHaveBeenCalledTimes(2);
369
396
  expect(loggerInfoMock).toHaveBeenCalledWith(
370
397
  expect.stringContaining("over_threshold"),
371
398
  expect.objectContaining({
@@ -175,25 +175,18 @@ export class AnthropicDispatcher implements ProviderDispatcher {
175
175
  eligible: PooledToken[];
176
176
  overThresholdTokens: Array<{ tokenName: string; threshold: number }>;
177
177
  }> {
178
- const thresholded = rows.filter((token) => this.hasQuotaThreshold(token));
179
-
180
- if (thresholded.length === 0) return { eligible: rows, overThresholdTokens: [] };
181
-
182
- const eligibleIds = new Set(
183
- rows.flatMap((token) => (this.hasQuotaThreshold(token) ? [] : [token.id])),
184
- );
185
-
178
+ const eligibleIds = new Set<number>();
186
179
  const overThresholdTokens: Array<{ tokenName: string; threshold: number }> = [];
187
180
 
188
181
  const checks = await Promise.allSettled(
189
- thresholded.map(async (token) => ({
182
+ rows.map(async (token) => ({
190
183
  token,
191
184
  result: await readAnthropicQuotaUsage(token.credentials.accessToken, model),
192
185
  })),
193
186
  );
194
187
 
195
188
  checks.forEach((check, index) => {
196
- const token = check.status === "rejected" ? thresholded[index] : check.value.token;
189
+ const token = check.status === "rejected" ? rows[index] : check.value.token;
197
190
 
198
191
  if (!token) return;
199
192
 
@@ -216,17 +209,24 @@ export class AnthropicDispatcher implements ProviderDispatcher {
216
209
  return;
217
210
  }
218
211
 
219
- if (result.utilizationPct >= token.quotaThreshold) {
212
+ const weeklyExhausted =
213
+ result.weeklyUtilizationPct !== null && result.weeklyUtilizationPct >= 100;
214
+
215
+ const threshold = weeklyExhausted ? 100 : (token.quotaThreshold ?? null);
216
+ const utilization = weeklyExhausted ? result.weeklyUtilizationPct : result.utilizationPct;
217
+
218
+ if (threshold !== null && utilization !== null && utilization >= threshold) {
220
219
  logger.info("quota_threshold gate: over_threshold", {
221
220
  tokenId: token.id,
222
221
  tokenName: token.name,
223
222
  provider: "anthropic",
224
- threshold: token.quotaThreshold,
225
- cachedUtilization: result.utilizationPct,
223
+ threshold,
224
+ cachedUtilization: utilization,
225
+ window: weeklyExhausted ? "weekly" : "five_hour",
226
226
  cacheAge: result.cacheAgeMs,
227
227
  reason: "over_threshold",
228
228
  });
229
- overThresholdTokens.push({ tokenName: token.name, threshold: token.quotaThreshold });
229
+ overThresholdTokens.push({ tokenName: token.name, threshold });
230
230
 
231
231
  return;
232
232
  }
@@ -30,15 +30,16 @@ describe("readAnthropicQuotaUsage", () => {
30
30
  await expect(readAnthropicQuotaUsage("access-token")).resolves.toEqual({
31
31
  kind: "ok",
32
32
  utilizationPct: 17,
33
+ weeklyUtilizationPct: null,
33
34
  cacheAgeMs: 1_250,
34
35
  });
35
36
  });
36
37
 
37
38
  it.each([
38
- { fiveHour: 0, sevenDay: 100, expected: 100 },
39
- { fiveHour: 80, sevenDay: 20, expected: 80 },
40
- { fiveHour: null, sevenDay: 100, expected: 100 },
41
- ])("includes shared weekly usage in Opus eligibility: %j", async ({ fiveHour, sevenDay, expected }) => {
39
+ { fiveHour: 0, sevenDay: 92 },
40
+ { fiveHour: 80, sevenDay: 20 },
41
+ { fiveHour: null, sevenDay: 100 },
42
+ ])("keeps five-hour and weekly usage separate: %j", async ({ fiveHour, sevenDay }) => {
42
43
  fetchUsageWithMetaMock.mockResolvedValueOnce({
43
44
  data: {
44
45
  five_hour: { utilization: fiveHour, resets_at: null },
@@ -49,7 +50,8 @@ describe("readAnthropicQuotaUsage", () => {
49
50
 
50
51
  await expect(readAnthropicQuotaUsage("access-token", "claude-opus-5-5")).resolves.toMatchObject({
51
52
  kind: "ok",
52
- utilizationPct: expected,
53
+ utilizationPct: fiveHour,
54
+ weeklyUtilizationPct: sevenDay,
53
55
  });
54
56
  });
55
57
 
@@ -65,19 +67,22 @@ describe("readAnthropicQuotaUsage", () => {
65
67
 
66
68
  await expect(readAnthropicQuotaUsage("access-token", "claude-fable-5")).resolves.toMatchObject({
67
69
  kind: "ok",
68
- utilizationPct: 100,
70
+ utilizationPct: 10,
71
+ weeklyUtilizationPct: 100,
69
72
  });
70
73
  await expect(
71
74
  readAnthropicQuotaUsage("access-token", "claude-fable-5-1"),
72
75
  ).resolves.toMatchObject({
73
76
  kind: "ok",
74
- utilizationPct: 100,
77
+ utilizationPct: 10,
78
+ weeklyUtilizationPct: 100,
75
79
  });
76
80
  await expect(
77
81
  readAnthropicQuotaUsage("access-token", "claude-sonnet-4-6"),
78
82
  ).resolves.toMatchObject({
79
83
  kind: "ok",
80
84
  utilizationPct: 10,
85
+ weeklyUtilizationPct: null,
81
86
  });
82
87
  });
83
88
 
@@ -7,7 +7,12 @@ import { isFableFamilyModel } from "./anthropic-constants";
7
7
  export { invalidateAnthropicQuotaUsage };
8
8
 
9
9
  export type AnthropicQuotaUsageResult =
10
- | { kind: "ok"; utilizationPct: number; cacheAgeMs: number }
10
+ | {
11
+ kind: "ok";
12
+ utilizationPct: number | null;
13
+ weeklyUtilizationPct: number | null;
14
+ cacheAgeMs: number;
15
+ }
11
16
  | { kind: "lookup_failed"; reason: string };
12
17
 
13
18
  export async function readAnthropicQuotaUsage(
@@ -19,26 +24,31 @@ export async function readAnthropicQuotaUsage(
19
24
 
20
25
  if (data.error) return { kind: "lookup_failed", reason: data.error };
21
26
 
22
- const utilizations = [data.five_hour?.utilization, data.seven_day?.utilization];
27
+ const fiveHour = data.five_hour?.utilization ?? null;
28
+ const utilizationPct = fiveHour !== null && Number.isFinite(fiveHour) ? fiveHour : null;
29
+ const weeklyUsages = [data.seven_day?.utilization];
23
30
 
24
31
  // Fable 계열(5, 5.1)은 5시간 창과 별개로 usage credits 기반 7일 버킷도 소진될 수 있다.
25
32
  if (isFableFamilyModel(model)) {
26
- utilizations.push(data.seven_day_overage_included?.utilization);
33
+ weeklyUsages.push(data.seven_day_overage_included?.utilization);
27
34
  }
28
35
 
29
- const utilization = Math.max(
30
- ...utilizations.filter(
36
+ const weeklyUsage = Math.max(
37
+ ...weeklyUsages.filter(
31
38
  (value): value is number => value !== null && value !== undefined && Number.isFinite(value),
32
39
  ),
33
40
  );
34
41
 
35
- if (!Number.isFinite(utilization)) {
42
+ const weeklyUtilizationPct = Number.isFinite(weeklyUsage) ? weeklyUsage : null;
43
+
44
+ if (utilizationPct === null && weeklyUtilizationPct === null) {
36
45
  return { kind: "lookup_failed", reason: "quota utilization unavailable" };
37
46
  }
38
47
 
39
48
  return {
40
49
  kind: "ok",
41
- utilizationPct: utilization,
50
+ utilizationPct,
51
+ weeklyUtilizationPct,
42
52
  cacheAgeMs: Math.max(Date.now() - cachedAt, 0),
43
53
  };
44
54
  } catch (e) {
@@ -354,7 +354,7 @@ describe("GrokDispatcher selection", () => {
354
354
  const preferred = await h.dispatcher.selectToken("chat", { preferredTokenId: 2 });
355
355
  expect(preferred.token.id).toBe(2);
356
356
  preferred.release();
357
- h.billing.set(1, billingAt(90));
357
+ h.billing.set(1, billingAt(100));
358
358
  await expect(
359
359
  h.dispatcher.selectToken("chat", { preferredTokenId: 1, requirePreferredToken: true }),
360
360
  ).rejects.toBeInstanceOf(QuotaThresholdExceededError);
@@ -460,13 +460,29 @@ describe("GrokDispatcher selection", () => {
460
460
  expect(h.events.some((event) => event.startsWith("/billing"))).toBe(true);
461
461
  });
462
462
 
463
- it("blocks over-threshold tokens and reports QuotaThresholdExceededError", async () => {
463
+ it("ignores the configured threshold while weekly quota remains", async () => {
464
464
  const h = createHarness();
465
- h.add(1, 1, 50);
466
- h.billing.set(1, billingAt(75));
465
+ h.add(1, 1, 75);
466
+ h.billing.set(1, billingAt(92));
467
+ const reservation = await h.dispatcher.selectToken("chat");
468
+ expect(reservation.token.id).toBe(1);
469
+ reservation.release();
470
+ expect(h.dispatcher.getQuotaSnapshot()[0]).toMatchObject({ threshold: 100, blocked: false });
471
+ });
472
+
473
+ it.each([75, null])("blocks exhausted weekly quota with configured threshold %s", async (threshold) => {
474
+ const h = createHarness();
475
+ h.add(1, 1, threshold);
476
+ h.billing.set(1, billingAt(100));
467
477
  await expect(h.dispatcher.selectToken("chat")).rejects.toBeInstanceOf(
468
478
  QuotaThresholdExceededError,
469
479
  );
480
+ expect(h.dispatcher.getQuotaSnapshot()[0]).toMatchObject({ threshold: 100, blocked: true });
481
+ h.clock.now += 61_000;
482
+ h.billing.set(1, billingAt(92));
483
+ const reservation = await h.dispatcher.selectToken("chat");
484
+ expect(reservation.token.id).toBe(1);
485
+ reservation.release();
470
486
  });
471
487
  });
472
488
 
@@ -596,7 +612,7 @@ describe("GrokDispatcher chat", () => {
596
612
  expect(h.clock.now - startedAt).toBe(30_000);
597
613
  });
598
614
 
599
- it("blocks an exhausted token until a fresh billing read below threshold", async () => {
615
+ it("clears an exhaustion block after fresh billing falls below 100%", async () => {
600
616
  const h = createHarness();
601
617
  h.add(1, 5, 80);
602
618
  h.add(2, 1);
@@ -609,7 +625,7 @@ describe("GrokDispatcher chat", () => {
609
625
  await h.dispatcher.prefetch(token);
610
626
  expect(h.dispatcher.isEligible(token, "chat")).toBe(false);
611
627
  h.clock.now += 61_000;
612
- h.billing.set(1, billingAt(50));
628
+ h.billing.set(1, billingAt(92));
613
629
  await h.dispatcher.prefetch(token);
614
630
  expect(h.dispatcher.isEligible(token, "chat")).toBe(true);
615
631
  });
@@ -980,7 +996,7 @@ describe("GrokDispatcher media", () => {
980
996
  };
981
997
  const h = createHarness({ media, maxInflightPerToken: 1 });
982
998
  h.add(1, 1, 50);
983
- h.billing.set(1, billingAt(75));
999
+ h.billing.set(1, billingAt(100));
984
1000
  const token = h.dispatcher.tokens.get(1)!;
985
1001
  token.cooldowns.set("video", h.clock.now + 120_000);
986
1002
  token.inFlight = 1;
@@ -86,6 +86,7 @@ export const GROK_REFRESH_FAILED_COOLDOWN_MS = 5_000;
86
86
  export const GROK_MAX_STALE_AUTH_RETRIES = 1;
87
87
  const DEFAULT_REQUEST_TIMEOUT_MS = 600_000;
88
88
  const DEFAULT_IDLE_TIMEOUT_MS = 300_000;
89
+ const GROK_WEEKLY_QUOTA_LIMIT = 100;
89
90
 
90
91
  // ---------------------------------------------------------------------------
91
92
  // Errors
@@ -820,7 +821,7 @@ export class GrokDispatcher implements GrokProviderDispatcher, MediaDispatcher,
820
821
 
821
822
  if ((token.quotaBlocks.get(requestClass) ?? 0) > now) return "quota";
822
823
 
823
- if (token.quotaThreshold !== null && token.overThreshold) return "quota";
824
+ if (token.overThreshold) return "quota";
824
825
 
825
826
  if ((token.cooldowns.get(requestClass) ?? 0) > now) return "cooldown";
826
827
 
@@ -838,29 +839,19 @@ export class GrokDispatcher implements GrokProviderDispatcher, MediaDispatcher,
838
839
  * Refreshes the 60 s settings/subscription/billing caches. Lookup failures fail open, so an
839
840
  * expired bearer is refreshed first: a lookup with it would fail and open every gate. A failed
840
841
  * refresh therefore takes the token out of selection (`refresh_failed`) instead of failing open.
841
- * Billing is read only when a threshold or quota block gates the token, unless `includeBilling`.
842
+ * Weekly exhaustion is checked for every token, independently of its configured threshold.
842
843
  */
843
- async prefetch(
844
- token: GrokTokenState,
845
- signal?: AbortSignal,
846
- includeBilling = false,
847
- ): Promise<void> {
844
+ async prefetch(token: GrokTokenState, signal?: AbortSignal): Promise<void> {
848
845
  if (!token.credentials || token.invalidReason || token.reauthRequired) return;
849
846
  let now = this.now();
850
847
  const tasks: Promise<void>[] = [];
851
848
 
852
- const wantsBilling = () =>
853
- includeBilling ||
854
- token.quotaThreshold !== null ||
855
- [...token.quotaBlocks.values()].some((until) => until > now);
856
-
857
849
  const stale = (entry: Cached<unknown> | undefined) =>
858
850
  !entry ||
859
851
  entry.generation !== token.generation ||
860
852
  now - entry.fetchedAt >= GROK_LOOKUP_CACHE_TTL_MS;
861
853
 
862
- const billingDue = () =>
863
- wantsBilling() && stale(token.billing) && now >= token.billingNotBefore;
854
+ const billingDue = () => stale(token.billing) && now >= token.billingNotBefore;
864
855
 
865
856
  if (!stale(token.settings) && !stale(token.subscription) && !billingDue()) return;
866
857
 
@@ -903,7 +894,7 @@ export class GrokDispatcher implements GrokProviderDispatcher, MediaDispatcher,
903
894
  async refreshUsage(tokenId: number): Promise<void> {
904
895
  const token = this.tokens.get(tokenId);
905
896
 
906
- if (token) await this.prefetch(token, undefined, true);
897
+ if (token) await this.prefetch(token);
907
898
  }
908
899
 
909
900
  /** Transient refresh failure for `presented`; ignored when the token already holds newer ones. */
@@ -1036,18 +1027,18 @@ export class GrokDispatcher implements GrokProviderDispatcher, MediaDispatcher,
1036
1027
  return;
1037
1028
  }
1038
1029
 
1039
- const limit = token.quotaThreshold ?? 100;
1040
- const over = token.quotaThreshold !== null && result.utilizationPct >= token.quotaThreshold;
1030
+ const limit = GROK_WEEKLY_QUOTA_LIMIT;
1031
+ const over = result.utilizationPct >= limit;
1041
1032
 
1042
1033
  if (over && !token.overThreshold) {
1043
1034
  logger.info(
1044
- `quota_threshold gate: over_threshold ${token.name}[${token.id}] (${result.utilizationPct}% >= ${token.quotaThreshold}%)`,
1035
+ `quota_threshold gate: over_threshold ${token.name}[${token.id}] (${result.utilizationPct}% >= ${limit}%)`,
1045
1036
  );
1046
1037
  }
1047
1038
 
1048
1039
  if (!over && token.overThreshold) {
1049
1040
  logger.info(
1050
- `quota_threshold gate: recovered ${token.name}[${token.id}] (${result.utilizationPct}% < ${token.quotaThreshold}%)`,
1041
+ `quota_threshold gate: recovered ${token.name}[${token.id}] (${result.utilizationPct}% < ${limit}%)`,
1051
1042
  );
1052
1043
  }
1053
1044
 
@@ -1202,7 +1193,12 @@ export class GrokDispatcher implements GrokProviderDispatcher, MediaDispatcher,
1202
1193
  if (present.has("quota")) {
1203
1194
  const over = [...reasons].flatMap(([token, reason]) =>
1204
1195
  reason === "quota"
1205
- ? [{ name: token.name, threshold: token.overThreshold ? token.quotaThreshold : null }]
1196
+ ? [
1197
+ {
1198
+ name: token.name,
1199
+ threshold: token.overThreshold ? GROK_WEEKLY_QUOTA_LIMIT : null,
1200
+ },
1201
+ ]
1206
1202
  : [],
1207
1203
  );
1208
1204
 
@@ -1231,7 +1227,7 @@ export class GrokDispatcher implements GrokProviderDispatcher, MediaDispatcher,
1231
1227
  if (reason === "quota") {
1232
1228
  return new QuotaThresholdExceededError(
1233
1229
  quotaMessage([
1234
- { name: token.name, threshold: token.overThreshold ? token.quotaThreshold : null },
1230
+ { name: token.name, threshold: token.overThreshold ? GROK_WEEKLY_QUOTA_LIMIT : null },
1235
1231
  ]),
1236
1232
  );
1237
1233
  }
@@ -2097,7 +2093,7 @@ export class GrokDispatcher implements GrokProviderDispatcher, MediaDispatcher,
2097
2093
  fetchedAt: token.billing!.fetchedAt,
2098
2094
  }
2099
2095
  : null,
2100
- quotaThreshold: token.quotaThreshold,
2096
+ quotaThreshold: GROK_WEEKLY_QUOTA_LIMIT,
2101
2097
  overThreshold: token.overThreshold,
2102
2098
  onDemandExcluded: settings?.kind === "ok" && settings.onDemandEnabled === true,
2103
2099
  zdrVideoExcluded: token.zdr === true,
@@ -2141,7 +2137,7 @@ export class GrokDispatcher implements GrokProviderDispatcher, MediaDispatcher,
2141
2137
  return {
2142
2138
  name: token.name,
2143
2139
  usedPercent: fresh ? billing.utilizationPct : null,
2144
- threshold: token.quotaThreshold,
2140
+ threshold: GROK_WEEKLY_QUOTA_LIMIT,
2145
2141
  blocked:
2146
2142
  token.overThreshold || [...token.quotaBlocks.values()].some((until) => until > now),
2147
2143
  resetsAt: fresh ? billing.periodEndMs : null,
@@ -946,13 +946,13 @@ describe("OpenAIDispatcher direct runtime", () => {
946
946
  expect(started).not.toHaveBeenCalled();
947
947
  });
948
948
 
949
- it("routes past an over-threshold token instead of treating it as capacity", async () => {
949
+ it("applies the configured threshold to the OpenAI weekly primary window", async () => {
950
950
  const names: string[] = [];
951
951
  const d = new OpenAIDispatcher(config(), {
952
952
  clientFactory: () => ({ responses: () => events({ type: "completed", responseId: "r" }) }),
953
953
  fetch: async () =>
954
954
  new Response(
955
- JSON.stringify({ rate_limits: { primary_window: { used_percent: 90 } } }),
955
+ JSON.stringify({ rate_limits: { primary_window: { used_percent: 90, limit_window_seconds: 604_800 } } }),
956
956
  { status: 200, headers: { "content-type": "application/json" } },
957
957
  ),
958
958
  });