@cartanova/qgrid-cli 2.13.1 → 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 (39) hide show
  1. package/bundle/dist/application/qgrid/qgrid.frame.js +6 -2
  2. package/bundle/dist/utils/providers/anthropic/anthropic-dispatcher.js +12 -13
  3. package/bundle/dist/utils/providers/anthropic/anthropic-quota.js +11 -7
  4. package/bundle/dist/utils/providers/common/model-cost.js +31 -7
  5. package/bundle/dist/utils/providers/grok/grok-constants.js +2 -2
  6. package/bundle/dist/utils/providers/grok/grok-dispatcher.js +15 -15
  7. package/bundle/dist/utils/providers/grok/grok-media-client.js +2 -2
  8. package/bundle/src/application/qgrid/qgrid.frame.test.ts +22 -8
  9. package/bundle/src/application/qgrid/qgrid.frame.ts +6 -1
  10. package/bundle/src/utils/providers/anthropic/anthropic-dispatcher.test.ts +31 -4
  11. package/bundle/src/utils/providers/anthropic/anthropic-dispatcher.ts +14 -14
  12. package/bundle/src/utils/providers/anthropic/anthropic-quota.test.ts +27 -3
  13. package/bundle/src/utils/providers/anthropic/anthropic-quota.ts +18 -8
  14. package/bundle/src/utils/providers/common/model-cost.test.ts +26 -4
  15. package/bundle/src/utils/providers/common/model-cost.ts +44 -11
  16. package/bundle/src/utils/providers/grok/grok-constants.ts +2 -2
  17. package/bundle/src/utils/providers/grok/grok-dispatcher.test.ts +23 -7
  18. package/bundle/src/utils/providers/grok/grok-dispatcher.ts +19 -23
  19. package/bundle/src/utils/providers/grok/grok-media-client.test.ts +6 -6
  20. package/bundle/src/utils/providers/grok/grok-types.test.ts +4 -4
  21. package/bundle/src/utils/providers/openai/openai-dispatcher.test.ts +2 -2
  22. package/bundle/web-dist/client/assets/{index-DplV-wqZ.js → index-jExDfi8j.js} +3 -3
  23. package/bundle/web-dist/client/assets/{logs-st46aRba.js → logs-ol_IGjcT.js} +1 -1
  24. package/bundle/web-dist/client/assets/{monit-BMXR2tY2.js → monit-CGTRk2U0.js} +1 -1
  25. package/bundle/web-dist/client/assets/{routes-BWPjgvhg.js → routes-D9l20OWa.js} +2 -2
  26. package/bundle/web-dist/client/assets/{settings-DTXZjDAw.js → settings-D2zIv0xR.js} +1 -1
  27. package/bundle/web-dist/client/assets/{show-CdWNFPyS.js → show-DefwCScC.js} +1 -1
  28. package/bundle/web-dist/client/assets/{tokens-eA34Gw5f.js → tokens-CbmIxMZ9.js} +1 -1
  29. package/bundle/web-dist/client/assets/{use-oauth-login-flow-CcUdLsa7.js → use-oauth-login-flow-CEufhZcR.js} +1 -1
  30. package/bundle/web-dist/client/assets/{use-update-token-mutation-D2r5K5Bz.js → use-update-token-mutation-E5ey27W6.js} +1 -1
  31. package/bundle/web-dist/client/index.html +1 -1
  32. package/bundle/web-dist/server/assets/{routes-CjWxvHAO.js → routes-CCdBJqP_.js} +11 -10
  33. package/bundle/web-dist/server/entry-server.generated.js +2 -2
  34. package/package.json +1 -1
  35. package/skills/qgrid/references/anthropic-claude-code-runtime.md +4 -3
  36. package/skills/qgrid/references/decision-rationale.md +4 -3
  37. package/skills/qgrid/references/grok-runtime.md +10 -1
  38. package/skills/qgrid/references/sonamu-api-web-flow.md +4 -0
  39. package/skills/qgrid/references/token-auth-quota-lifecycle.md +8 -4
@@ -270,13 +270,33 @@ const GROK_COSTS = new Map<string, ModelCosts>(
270
270
  }),
271
271
  );
272
272
 
273
- // Ticks per generated image at the default 1k resolution (the probe's quality 1k image cost exactly
274
- // this amount). Unlisted image models have no estimate.
275
- const GROK_IMAGE_PRICE_TICKS = new Map<string, number>(
276
- Object.entries({
277
- "grok-imagine-image-quality": 500_000_000,
278
- }),
279
- );
273
+ // Per-image ticks from https://docs.x.ai/developers/pricing (2026-10-25).
274
+ const GROK_IMAGE_PRICE_TICKS = new Map<
275
+ string,
276
+ { input: number; output: Readonly<Record<string, number>> }
277
+ >([
278
+ [
279
+ "grok-imagine-image",
280
+ {
281
+ input: 20_000_000,
282
+ output: { "1k": 200_000_000, "2k": 200_000_000 },
283
+ },
284
+ ],
285
+ [
286
+ "grok-imagine-image-2.0",
287
+ {
288
+ input: 100_000_000,
289
+ output: {
290
+ "1k:low": 400_000_000,
291
+ "1.5k:low": 500_000_000,
292
+ "2k:low": 600_000_000,
293
+ "1k:medium": 600_000_000,
294
+ "1.5k:medium": 700_000_000,
295
+ "2k:medium": 800_000_000,
296
+ },
297
+ },
298
+ ],
299
+ ]);
280
300
 
281
301
  export interface GrokMediaCost {
282
302
  costUsd: number;
@@ -286,19 +306,32 @@ export interface GrokMediaCost {
286
306
  }
287
307
 
288
308
  /**
289
- * Image cost: the reported ticks when present, otherwise the per-image catalog price times the
290
- * image count. Undefined when neither is known, so callers store an unknown cost, not a guess.
309
+ * Prefer reported ticks; otherwise price output quality/resolution and input images separately.
310
+ * Unknown models or price combinations have no estimate.
291
311
  */
292
312
  export function grokImageCost(
293
313
  model: string,
294
314
  imageCount: number,
295
315
  reportedTicks?: number,
316
+ options: { resolution?: string; quality?: string; inputImageCount?: number } = {},
296
317
  ): GrokMediaCost | undefined {
297
318
  if (reportedTicks !== undefined) return grokReportedCost(reportedTicks);
298
- const perImage = GROK_IMAGE_PRICE_TICKS.get(model.split("/").pop() ?? model);
319
+ const id = model.split("/").pop() ?? model;
320
+ const prices = GROK_IMAGE_PRICE_TICKS.get(id);
321
+
322
+ if (!prices) return undefined;
323
+ const inputImageCount = options.inputImageCount ?? 0;
324
+ const resolution = options.resolution ?? "1k";
325
+ const defaultQuality = inputImageCount > 0 ? "medium" : "low";
326
+
327
+ const quality = options.quality && options.quality !== "auto" ? options.quality : defaultQuality;
328
+
329
+ const priceKey = id === "grok-imagine-image-2.0" ? `${resolution}:${quality}` : resolution;
330
+
331
+ const perImage = Object.hasOwn(prices.output, priceKey) ? prices.output[priceKey] : undefined;
299
332
 
300
333
  if (perImage === undefined) return undefined;
301
- const ticks = perImage * imageCount;
334
+ const ticks = perImage * imageCount + prices.input * inputImageCount;
302
335
 
303
336
  return { costUsd: usdFromGrokTicks(ticks), costSource: "pricing_table", ticks };
304
337
  }
@@ -55,8 +55,8 @@ export const GROK_CLIENT_MODE = "headless";
55
55
  // U0 capture 2026-10-16 (GET /models default and /settings default_model)
56
56
  export const GROK_DEFAULT_MODEL = "grok-4.7";
57
57
 
58
- // grok-build 1.0.45 image_gen/mod.rs:33
59
- export const GROK_IMAGE_DEFAULT_MODEL = "grok-imagine-image-quality";
58
+ // https://docs.x.ai/developers/migration/imagine-image-quality-nov-2
59
+ export const GROK_IMAGE_DEFAULT_MODEL = "grok-imagine-image-2.0";
60
60
 
61
61
  // grok-build 1.0.45 video_gen/mod.rs:36-40
62
62
  export const GROK_VIDEO_DEFAULT_MODEL = "grok-imagine-video-1.5";
@@ -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,
@@ -92,7 +92,7 @@ describe("GrokMediaClient images", () => {
92
92
  // Key order matters for byte-level parity with grok-build.
93
93
  expect(JSON.stringify(sent?.body)).toBe(
94
94
  JSON.stringify({
95
- model: "grok-imagine-image-quality",
95
+ model: "grok-imagine-image-2.0",
96
96
  prompt: "red square",
97
97
  n: 1,
98
98
  aspect_ratio: "1:1",
@@ -106,20 +106,20 @@ describe("GrokMediaClient images", () => {
106
106
  it("maps SDK option names and keeps response_format b64_json", async () => {
107
107
  const { impl, calls } = fakeFetch(async () => json(imageResponse));
108
108
  await new GrokMediaClient({ fetch: impl }).generateImages(AUTH, {
109
- model: "grok-imagine-image-pro",
109
+ model: "grok-imagine-image-2.0",
110
110
  prompt: "p",
111
111
  n: 3,
112
112
  resolution: "2k",
113
- quality: "high",
113
+ quality: "medium",
114
114
  outputFormat: "png",
115
115
  });
116
116
  expect(calls[0]?.body).toEqual({
117
- model: "grok-imagine-image-pro",
117
+ model: "grok-imagine-image-2.0",
118
118
  prompt: "p",
119
119
  n: 3,
120
120
  resolution: "2k",
121
121
  response_format: "b64_json",
122
- quality: "high",
122
+ quality: "medium",
123
123
  output_format: "png",
124
124
  });
125
125
  });
@@ -255,7 +255,7 @@ describe("GrokMediaClient images", () => {
255
255
  ]);
256
256
  expect(calls[0]?.headers["content-type"]).toBe("application/json");
257
257
  expect(calls[0]?.body).toEqual({
258
- model: "grok-imagine-image-quality",
258
+ model: "grok-imagine-image-2.0",
259
259
  prompt: "make it blue",
260
260
  n: 1,
261
261
  resolution: "1k",
@@ -205,13 +205,13 @@ describe("api.x.ai schemas", () => {
205
205
  const catalog = GrokApiImageModelCatalog.parse({
206
206
  models: [
207
207
  {
208
- id: "grok-imagine-image-quality",
209
- image_price: 500000000,
210
- pricing: [{ quality: "quality", resolution: "1k", price_per_image: 500000000 }],
208
+ id: "grok-imagine-image-2.0",
209
+ image_price: 400000000,
210
+ pricing: [{ quality: "low", resolution: "1k", price_per_image: 400000000 }],
211
211
  },
212
212
  ],
213
213
  });
214
- expect(grokCatalogModels(catalog)[0]?.pricing?.[0]?.price_per_image).toBe(500000000);
214
+ expect(grokCatalogModels(catalog)[0]?.pricing?.[0]?.price_per_image).toBe(400000000);
215
215
  });
216
216
 
217
217
  it("parses image, video, STT and TTS shapes", () => {
@@ -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
  });