opencode-quota-gui 1.3.1 → 1.3.2

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 (155) hide show
  1. package/README.md +16 -12
  2. package/dist/contracts/build-identity.js +1 -1
  3. package/dist/contracts/card-order.d.ts +2 -0
  4. package/dist/contracts/card-order.js +2 -2
  5. package/dist/contracts/card-visibility.d.ts +2 -1
  6. package/dist/contracts/card-visibility.js +2 -1
  7. package/dist/contracts/dashboard.d.ts +87 -5
  8. package/dist/contracts/dashboard.js +10 -0
  9. package/dist/contracts/dto-guards.d.ts +4 -0
  10. package/dist/contracts/dto-guards.js +29 -7
  11. package/dist/contracts/guards.js +3 -1
  12. package/dist/contracts/identity.d.ts +37 -5
  13. package/dist/contracts/identity.js +43 -0
  14. package/dist/contracts/provider-auto-resume.d.ts +9 -0
  15. package/dist/contracts/provider-auto-resume.js +24 -0
  16. package/dist/contracts/provider-failure.d.ts +22 -0
  17. package/dist/contracts/provider-failure.js +25 -1
  18. package/dist/contracts/row-order.d.ts +13 -0
  19. package/dist/contracts/row-order.js +34 -0
  20. package/dist/contracts/row-visibility.d.ts +53 -0
  21. package/dist/contracts/row-visibility.js +130 -0
  22. package/dist/data/modelsdev-pricing.min.json +1 -1
  23. package/dist/data/modelsdev-temporal.min.json +3 -634
  24. package/dist/gui/aggregation.d.ts +29 -1
  25. package/dist/gui/aggregation.js +157 -4
  26. package/dist/gui/analytics-bridge.d.ts +8 -9
  27. package/dist/gui/analytics-bridge.js +197 -54
  28. package/dist/gui/analytics-engine.d.ts +7 -15
  29. package/dist/gui/analytics-engine.js +246 -106
  30. package/dist/gui/analytics-model.d.ts +7 -0
  31. package/dist/gui/analytics-model.js +75 -9
  32. package/dist/gui/analytics-pricing-upkeep.d.ts +21 -0
  33. package/dist/gui/analytics-pricing-upkeep.js +23 -0
  34. package/dist/gui/analytics-protocol.d.ts +17 -7
  35. package/dist/gui/analytics-protocol.js +1 -0
  36. package/dist/gui/analytics-service.d.ts +10 -0
  37. package/dist/gui/analytics-service.js +30 -9
  38. package/dist/gui/analytics-state.d.ts +30 -5
  39. package/dist/gui/analytics-state.js +46 -7
  40. package/dist/gui/analytics-worker-runtime.d.ts +5 -0
  41. package/dist/gui/analytics-worker-runtime.js +9 -1
  42. package/dist/gui/analytics-worker.js +11 -0
  43. package/dist/gui/config.d.ts +2 -2
  44. package/dist/gui/config.js +46 -5
  45. package/dist/gui/identity.d.ts +6 -20
  46. package/dist/gui/identity.js +6 -54
  47. package/dist/gui/primary-quota-windows.js +55 -34
  48. package/dist/gui/provider-cards.d.ts +12 -8
  49. package/dist/gui/provider-cards.js +12 -53
  50. package/dist/gui/quota-notification-detector.d.ts +25 -2
  51. package/dist/gui/quota-notification-detector.js +60 -5
  52. package/dist/gui/quota-notification-observer.d.ts +1 -1
  53. package/dist/gui/quota-notification-observer.js +5 -1
  54. package/dist/gui/quota-observation.d.ts +4 -0
  55. package/dist/gui/quota-observation.js +18 -0
  56. package/dist/gui/rpc.js +3 -0
  57. package/dist/gui/server.js +6 -1
  58. package/dist/gui/snapshot-service.d.ts +3 -17
  59. package/dist/gui/snapshot-service.js +159 -9
  60. package/dist/gui/sources.js +84 -11
  61. package/dist/gui/temporal-status.d.ts +3 -2
  62. package/dist/gui/temporal-status.js +10 -6
  63. package/dist/gui-experimental.cjs +228 -228
  64. package/dist/lib/accounting-format.d.ts +8 -0
  65. package/dist/lib/accounting-format.js +12 -2
  66. package/dist/lib/anthropic-api-auth.d.ts +7 -0
  67. package/dist/lib/anthropic-api-auth.js +27 -0
  68. package/dist/lib/anthropic-api-rate-limits.d.ts +47 -0
  69. package/dist/lib/anthropic-api-rate-limits.js +92 -0
  70. package/dist/lib/anthropic-oauth-throttle.d.ts +76 -0
  71. package/dist/lib/anthropic-oauth-throttle.js +379 -0
  72. package/dist/lib/anthropic.d.ts +22 -4
  73. package/dist/lib/anthropic.js +498 -180
  74. package/dist/lib/cache-observer-ingestion.js +27 -0
  75. package/dist/lib/cache-observer.d.ts +3 -0
  76. package/dist/lib/cache-observer.js +9 -3
  77. package/dist/lib/cli-show.d.ts +5 -0
  78. package/dist/lib/cli-show.js +16 -5
  79. package/dist/lib/cli-status.js +3 -6
  80. package/dist/lib/config.d.ts +1 -1
  81. package/dist/lib/config.js +64 -2
  82. package/dist/lib/dashboard-visibility.d.ts +5 -0
  83. package/dist/lib/dashboard-visibility.js +11 -10
  84. package/dist/lib/display-sanitize.js +1 -0
  85. package/dist/lib/entries.d.ts +10 -1
  86. package/dist/lib/entries.js +4 -0
  87. package/dist/lib/grouped-entry-normalization.js +1 -1
  88. package/dist/lib/maintainer-announcements.js +2 -2
  89. package/dist/lib/modelsdev-pricing.d.ts +74 -2
  90. package/dist/lib/modelsdev-pricing.js +457 -63
  91. package/dist/lib/modelsdev-temporal.d.ts +6 -0
  92. package/dist/lib/modelsdev-temporal.js +16 -2
  93. package/dist/lib/opencode-config-providers.js +2 -2
  94. package/dist/lib/opencode-storage.d.ts +20 -0
  95. package/dist/lib/opencode-storage.js +89 -2
  96. package/dist/lib/opencode-version-core.d.ts +7 -0
  97. package/dist/lib/opencode-version-core.js +10 -0
  98. package/dist/lib/opencode-warming-refresh.d.ts +19 -0
  99. package/dist/lib/opencode-warming-refresh.js +95 -0
  100. package/dist/lib/provider-metadata.d.ts +11 -3
  101. package/dist/lib/provider-metadata.js +20 -2
  102. package/dist/lib/provider-registration.d.ts +342 -3
  103. package/dist/lib/provider-registration.js +409 -27
  104. package/dist/lib/quota-auto-resume.d.ts +74 -0
  105. package/dist/lib/quota-auto-resume.js +539 -0
  106. package/dist/lib/quota-command-format.js +22 -9
  107. package/dist/lib/quota-identity.d.ts +64 -0
  108. package/dist/lib/quota-identity.js +111 -0
  109. package/dist/lib/quota-providers.js +2 -2
  110. package/dist/lib/quota-render-data.js +2 -2
  111. package/dist/lib/quota-reset-notifications.js +11 -155
  112. package/dist/lib/quota-retry-wait.d.ts +106 -5
  113. package/dist/lib/quota-retry-wait.js +301 -34
  114. package/dist/lib/quota-runtime-context.js +1 -0
  115. package/dist/lib/quota-state-codec.d.ts +2 -0
  116. package/dist/lib/quota-state-codec.js +14 -1
  117. package/dist/lib/quota-state.d.ts +1 -1
  118. package/dist/lib/quota-state.js +60 -28
  119. package/dist/lib/quota-stats.d.ts +26 -0
  120. package/dist/lib/quota-stats.js +19 -1
  121. package/dist/lib/quota-surface-data.js +18 -3
  122. package/dist/lib/quota-telemetry.js +2 -2
  123. package/dist/lib/resolved-auth-identity.d.ts +19 -0
  124. package/dist/lib/resolved-auth-identity.js +44 -0
  125. package/dist/lib/state-file-lock.d.ts +26 -0
  126. package/dist/lib/state-file-lock.js +205 -0
  127. package/dist/lib/toast-format-grouped.js +7 -4
  128. package/dist/lib/tui-compact-format.js +29 -16
  129. package/dist/lib/types.d.ts +20 -0
  130. package/dist/lib/types.js +4 -1
  131. package/dist/plugin.js +67 -1
  132. package/dist/providers/alibaba-coding-plan.js +21 -3
  133. package/dist/providers/alibaba-token-plan.js +9 -5
  134. package/dist/providers/anthropic.d.ts +6 -2
  135. package/dist/providers/anthropic.js +123 -14
  136. package/dist/providers/chutes.js +2 -0
  137. package/dist/providers/claude-agent.js +24 -5
  138. package/dist/providers/copilot.js +5 -4
  139. package/dist/providers/glm-coding-plan-provider.js +30 -23
  140. package/dist/providers/ollama-cloud.js +10 -0
  141. package/dist/providers/openai.js +24 -23
  142. package/dist/providers/opencode-go.js +7 -6
  143. package/dist/providers/opencode-zen.js +1 -1
  144. package/dist/providers/result-helpers.d.ts +4 -2
  145. package/dist/providers/result-helpers.js +5 -1
  146. package/dist/providers/synthetic.js +4 -0
  147. package/dist/providers/xai.js +9 -8
  148. package/dist/rpc.d.ts +8 -0
  149. package/dist/rpc.js +15 -2
  150. package/dist/ui/assets/{index-BcueIm3Z.css → index-6_g1FHs-.css} +1 -1
  151. package/dist/ui/assets/index-sZnGUuML.js +10 -0
  152. package/dist/ui/assets/{popover-4bFSvRZ7.js → popover-C4ZLYe9E.js} +1 -1
  153. package/dist/ui/index.html +2 -2
  154. package/package.json +3 -3
  155. package/dist/ui/assets/index-C6qRSoh8.js +0 -10
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "crypto";
1
2
  import { readFileSync } from "fs";
2
3
  import { readFile } from "fs/promises";
3
4
  import { join } from "path";
@@ -5,6 +6,7 @@ import { writeJsonAtomic } from "./atomic-json.js";
5
6
  import { fetchWithTimeout } from "./http.js";
6
7
  import { getOpencodeRuntimeDirs } from "./opencode-runtime-paths.js";
7
8
  import { getGuiPrivateCacheDir } from "./private-state-paths.js";
9
+ import { acquireStateFileLock } from "./state-file-lock.js";
8
10
  const SOURCE_URL = "https://models.dev/api.json";
9
11
  const COST_KEYS = ["input", "output", "cache_read", "cache_write", "reasoning"];
10
12
  const RUNTIME_SNAPSHOT_FILENAME = "modelsdev-pricing.runtime.min.json";
@@ -12,7 +14,13 @@ const RUNTIME_REFRESH_STATE_FILENAME = "modelsdev-pricing.refresh-state.json";
12
14
  const DEFAULT_REFRESH_MIN_ATTEMPT_INTERVAL_MS = 6 * 60 * 60 * 1000;
13
15
  const DEFAULT_REFRESH_TIMEOUT_MS = 6_000;
14
16
  const MS_PER_DAY = 24 * 60 * 60 * 1000;
15
- export const DEFAULT_PRICING_SNAPSHOT_MAX_AGE_MS = 3 * 24 * 60 * 60 * 1000;
17
+ /** Approved automatic network budget across every refresh kind, rolling 24h. */
18
+ const MAX_AUTOMATIC_REQUESTS_PER_DAY = 10;
19
+ /** Cheap analytics-side gate: re-read refresh state/snapshot at most this often. */
20
+ const ANALYTICS_PRICING_CHECK_INTERVAL_MS = 15 * 60 * 1000;
21
+ /** Reservation is a tiny read+write; a busy lock must not block analytics. */
22
+ const DEFAULT_BUDGET_LOCK_TIMEOUT_MS = 250;
23
+ export const DEFAULT_PRICING_SNAPSHOT_MAX_AGE_MS = MS_PER_DAY;
16
24
  const EMPTY_SNAPSHOT = {
17
25
  _meta: {
18
26
  source: "none",
@@ -27,8 +35,9 @@ let SNAPSHOT_SOURCE = "bundled";
27
35
  let SNAPSHOT_SELECTION = "auto";
28
36
  let MODEL_INDEX = null;
29
37
  let REFRESH_IN_FLIGHT = null;
30
- let PROCESS_REFRESH_CHECKED = false;
31
38
  let CONFIGURED_PRICING_SNAPSHOT_MAX_AGE_MS = DEFAULT_PRICING_SNAPSHOT_MAX_AGE_MS;
39
+ let LAST_ANALYTICS_PRICING_CHECK_AT_MS = 0;
40
+ let LAST_ANALYTICS_UNPRICED_SIGNATURE = "";
32
41
  function asRecord(value) {
33
42
  return value && typeof value === "object" ? value : null;
34
43
  }
@@ -230,6 +239,14 @@ function applySnapshotSelection(params) {
230
239
  setSnapshot(selected.snapshot, selected.source);
231
240
  return selected;
232
241
  }
242
+ /**
243
+ * Adopt a runtime snapshot rewritten by another process (the plugin host, or
244
+ * this worker's own refresh). A fresh `_meta` object is what invalidates the
245
+ * analytics pricing fingerprint and its derived presentation caches.
246
+ */
247
+ export function reloadPricingSnapshotFromDisk(params) {
248
+ applySnapshotSelection(params);
249
+ }
233
250
  function ensureLoaded() {
234
251
  if (SNAPSHOT)
235
252
  return SNAPSHOT;
@@ -281,29 +298,77 @@ function normalizeRefreshState(raw) {
281
298
  "not_modified",
282
299
  "skipped_fresh",
283
300
  "skipped_throttled",
301
+ "skipped_budget",
284
302
  "failed",
285
303
  ]);
286
304
  if (allowed.has(obj.lastResult)) {
287
305
  out.lastResult = obj.lastResult;
288
306
  }
289
307
  }
308
+ if (Array.isArray(obj.attempts24h)) {
309
+ const attempts = [];
310
+ for (const rawAttempt of obj.attempts24h) {
311
+ const attempt = asRecord(rawAttempt);
312
+ const at = Number(attempt?.at);
313
+ if (!Number.isFinite(at) || at <= 0 || typeof attempt?.automatic !== "boolean")
314
+ continue;
315
+ const id = typeof attempt.id === "string" && attempt.id ? attempt.id : undefined;
316
+ attempts.push({
317
+ at: Math.trunc(at),
318
+ automatic: attempt.automatic,
319
+ ...(id === undefined ? {} : { id }),
320
+ });
321
+ }
322
+ if (attempts.length > 0)
323
+ out.attempts24h = attempts;
324
+ }
290
325
  if (typeof obj.lastError === "string" && obj.lastError)
291
326
  out.lastError = obj.lastError;
292
327
  if (typeof obj.etag === "string" && obj.etag)
293
328
  out.etag = obj.etag;
294
329
  if (typeof obj.lastModified === "string" && obj.lastModified)
295
330
  out.lastModified = obj.lastModified;
331
+ const unpricedChecked = normalizeRouteChecks(obj.unpricedChecked);
332
+ if (unpricedChecked)
333
+ out.unpricedChecked = unpricedChecked;
334
+ const unpricedBypassUsed = normalizeRouteChecks(obj.unpricedBypassUsed);
335
+ if (unpricedBypassUsed)
336
+ out.unpricedBypassUsed = unpricedBypassUsed;
296
337
  return out;
297
338
  }
298
- async function readRefreshState(path) {
339
+ function normalizeRouteChecks(raw) {
340
+ const obj = asRecord(raw);
341
+ if (typeof obj?.key !== "string" || !obj.key)
342
+ return undefined;
343
+ const routes = Array.isArray(obj.routes)
344
+ ? [
345
+ ...new Set(obj.routes.filter((route) => typeof route === "string" && route.length > 0)),
346
+ ]
347
+ : [];
348
+ return routes.length > 0 ? { key: obj.key, routes } : undefined;
349
+ }
350
+ function isEnoentError(error) {
351
+ return (typeof error === "object" && error !== null && error.code === "ENOENT");
352
+ }
353
+ /**
354
+ * Distinguish a fresh install (ENOENT) from a ledger that exists but cannot be
355
+ * trusted (malformed JSON, unsupported version, permission or I/O failure). The
356
+ * budget must fail closed for the latter instead of resetting reservations.
357
+ */
358
+ async function readRefreshStateDetailed(path) {
299
359
  try {
300
360
  const raw = await readFile(path, "utf-8");
301
- return normalizeRefreshState(JSON.parse(raw));
361
+ const state = normalizeRefreshState(JSON.parse(raw));
362
+ return state ? { kind: "ok", state } : { kind: "unreadable" };
302
363
  }
303
- catch {
304
- return null;
364
+ catch (error) {
365
+ return isEnoentError(error) ? { kind: "missing" } : { kind: "unreadable" };
305
366
  }
306
367
  }
368
+ async function readRefreshState(path) {
369
+ const result = await readRefreshStateDetailed(path);
370
+ return result.kind === "ok" ? result.state : null;
371
+ }
307
372
  export async function readPricingRefreshState(runtimeDirs) {
308
373
  return await readRefreshState(getRuntimePricingRefreshStatePath(runtimeDirs));
309
374
  }
@@ -313,6 +378,263 @@ function makeDefaultRefreshState(nowMs) {
313
378
  updatedAt: nowMs,
314
379
  };
315
380
  }
381
+ function pruneRefreshAttempts(attempts, nowMs) {
382
+ if (!attempts)
383
+ return [];
384
+ return attempts.filter((attempt) => attempt.at > nowMs - MS_PER_DAY);
385
+ }
386
+ function automaticAttemptsWithinDay(attempts, nowMs) {
387
+ return attempts.filter((attempt) => attempt.automatic && attempt.at > nowMs - MS_PER_DAY).length;
388
+ }
389
+ /** Stable identity of the catalog state a kicker attempt was based on. */
390
+ function refreshStateKey(state) {
391
+ return (state?.etag ?? state?.lastModified ?? `generatedAt:${getPricingSnapshotMeta().generatedAt}`);
392
+ }
393
+ function routeChecksForIdentity(checks, state) {
394
+ return checks && checks.key === refreshStateKey(state)
395
+ ? new Set(checks.routes)
396
+ : new Set();
397
+ }
398
+ function withRouteChecks(existing, key, routes) {
399
+ return {
400
+ key,
401
+ routes: existing && existing.key === key
402
+ ? [...new Set([...existing.routes, ...routes])]
403
+ : [...new Set(routes)],
404
+ };
405
+ }
406
+ /**
407
+ * Routes with no recorded unpriced check against the state's catalog identity.
408
+ * A route checked against an older identity counts again because the new
409
+ * catalog may price it.
410
+ */
411
+ function unpricedRoutesUntried(routeKeys, state) {
412
+ if (!routeKeys || routeKeys.length === 0)
413
+ return [];
414
+ const checked = routeChecksForIdentity(state?.unpricedChecked, state);
415
+ return routeKeys.filter((routeKey) => !checked.has(routeKey));
416
+ }
417
+ /**
418
+ * Untried routes that may still spend their one throttle bypass for the current
419
+ * catalog identity. A route whose bypass was already reserved at this identity
420
+ * waits for the ordinary minimum interval.
421
+ */
422
+ function unpricedRoutesBypassable(routeKeys, state) {
423
+ const untried = unpricedRoutesUntried(routeKeys, state);
424
+ if (untried.length === 0)
425
+ return [];
426
+ const used = routeChecksForIdentity(state?.unpricedBypassUsed, state);
427
+ return untried.filter((routeKey) => !used.has(routeKey));
428
+ }
429
+ function appendRefreshAttempt(state, nowMs, automatic) {
430
+ return {
431
+ ...state,
432
+ attempts24h: [
433
+ ...pruneRefreshAttempts(state.attempts24h, nowMs),
434
+ { at: nowMs, automatic, id: randomUUID() },
435
+ ],
436
+ };
437
+ }
438
+ function mergeRefreshAttempts(...lists) {
439
+ const byKey = new Map();
440
+ for (const attempts of lists) {
441
+ for (const attempt of attempts ?? []) {
442
+ byKey.set(attempt.id ?? `${attempt.at}\u0000${attempt.automatic}`, attempt);
443
+ }
444
+ }
445
+ return [...byKey.values()].sort((a, b) => a.at - b.at);
446
+ }
447
+ function mergeRouteChecks(winner, other, field) {
448
+ const a = winner[field];
449
+ const b = other?.[field];
450
+ if (!a || !b || a.key !== b.key)
451
+ return a ?? b;
452
+ return { key: a.key, routes: [...new Set([...a.routes, ...b.routes])] };
453
+ }
454
+ /**
455
+ * Reserve one automatic slot atomically in the refresh-state file. The
456
+ * read-check-append-write happens under a cross-process lock, so plugin hosts,
457
+ * workers, and separate OpenCode processes share one hard 10/24h budget. A lock
458
+ * that cannot be acquired promptly skips the attempt instead of blocking. An
459
+ * unreadable ledger fails closed for automatic attempts: it is never mistaken
460
+ * for a fresh install that resets the rolling budget.
461
+ */
462
+ async function reserveRefreshAttempt(params) {
463
+ let release;
464
+ try {
465
+ release = await acquireStateFileLock(params.statePath, { timeoutMs: params.lockTimeoutMs });
466
+ }
467
+ catch {
468
+ return { ok: false, reason: "busy", state: params.fallbackState };
469
+ }
470
+ try {
471
+ const read = await readRefreshStateDetailed(params.statePath);
472
+ if (read.kind === "unreadable" && !params.force) {
473
+ // A manual refresh may still proceed and repair the file on completion;
474
+ // an automatic one must not spend or reset the shared budget blind.
475
+ return { ok: false, reason: "state_unreadable", state: params.fallbackState };
476
+ }
477
+ const current = read.kind === "ok" ? read.state : makeDefaultRefreshState(params.nowMs);
478
+ const bypassableUnpricedRoutes = unpricedRoutesBypassable(params.unpricedRouteKeys, current);
479
+ if (!params.force &&
480
+ bypassableUnpricedRoutes.length === 0 &&
481
+ current.lastAttemptAt &&
482
+ params.nowMs - current.lastAttemptAt < params.minAttemptIntervalMs) {
483
+ return {
484
+ ok: false,
485
+ reason: "throttled",
486
+ state: {
487
+ ...current,
488
+ updatedAt: params.nowMs,
489
+ lastResult: "skipped_throttled",
490
+ },
491
+ };
492
+ }
493
+ const recentAttempts = pruneRefreshAttempts(current.attempts24h, params.nowMs);
494
+ if (!params.force &&
495
+ automaticAttemptsWithinDay(recentAttempts, params.nowMs) >= MAX_AUTOMATIC_REQUESTS_PER_DAY) {
496
+ return {
497
+ ok: false,
498
+ reason: "budget",
499
+ state: {
500
+ ...current,
501
+ updatedAt: params.nowMs,
502
+ lastResult: "skipped_budget",
503
+ attempts24h: recentAttempts,
504
+ },
505
+ };
506
+ }
507
+ const attemptState = appendRefreshAttempt(current, params.nowMs, params.automatic);
508
+ const reserved = {
509
+ ...attemptState,
510
+ version: 1,
511
+ updatedAt: params.nowMs,
512
+ lastAttemptAt: params.nowMs,
513
+ ...(!params.force && bypassableUnpricedRoutes.length > 0
514
+ ? {
515
+ unpricedBypassUsed: withRouteChecks(attemptState.unpricedBypassUsed, refreshStateKey(current), bypassableUnpricedRoutes),
516
+ }
517
+ : {}),
518
+ };
519
+ await writeJsonAtomic(params.statePath, reserved, { trailingNewline: true });
520
+ return { ok: true, state: reserved };
521
+ }
522
+ catch {
523
+ return { ok: false, reason: "busy", state: params.fallbackState };
524
+ }
525
+ finally {
526
+ await release();
527
+ }
528
+ }
529
+ /**
530
+ * Completion writes merge the latest reservations from other processes instead
531
+ * of overwriting them, so a slow request cannot erase a newer budget slot.
532
+ */
533
+ async function writeRefreshStateMerged(statePath, nextState, lockTimeoutMs) {
534
+ let release;
535
+ try {
536
+ release = await acquireStateFileLock(statePath, { timeoutMs: lockTimeoutMs });
537
+ }
538
+ catch {
539
+ // Never clobber a concurrent reservation; the attempt is already counted.
540
+ return;
541
+ }
542
+ try {
543
+ const current = await readRefreshState(statePath);
544
+ const attempts24h = mergeRefreshAttempts(current?.attempts24h, nextState.attempts24h);
545
+ const currentIsNewer = current !== null && current.updatedAt > nextState.updatedAt;
546
+ const winner = currentIsNewer ? current : nextState;
547
+ const other = currentIsNewer ? nextState : current;
548
+ const unpricedChecked = mergeRouteChecks(winner, other, "unpricedChecked");
549
+ const unpricedBypassUsed = mergeRouteChecks(winner, other, "unpricedBypassUsed");
550
+ const merged = {
551
+ ...winner,
552
+ attempts24h,
553
+ ...(unpricedChecked === undefined ? {} : { unpricedChecked }),
554
+ ...(unpricedBypassUsed === undefined ? {} : { unpricedBypassUsed }),
555
+ ...(currentIsNewer
556
+ ? {}
557
+ : {
558
+ updatedAt: Math.max(current?.updatedAt ?? 0, nextState.updatedAt),
559
+ ...(current?.lastAttemptAt !== undefined &&
560
+ (nextState.lastAttemptAt === undefined ||
561
+ current.lastAttemptAt > nextState.lastAttemptAt)
562
+ ? { lastAttemptAt: current.lastAttemptAt }
563
+ : {}),
564
+ }),
565
+ };
566
+ await writeJsonAtomic(statePath, merged, { trailingNewline: true });
567
+ }
568
+ finally {
569
+ await release();
570
+ }
571
+ }
572
+ function buildCompletionState(params) {
573
+ const state = {
574
+ ...params.attemptingState,
575
+ updatedAt: params.nowMs,
576
+ lastSuccessAt: params.nowMs,
577
+ lastResult: params.lastResult,
578
+ lastError: undefined,
579
+ etag: params.etag ?? params.attemptingState.etag,
580
+ lastModified: params.lastModified ?? params.attemptingState.lastModified,
581
+ };
582
+ const routeKeys = params.unpricedRouteKeys ?? [];
583
+ if (routeKeys.length > 0) {
584
+ state.unpricedChecked = withRouteChecks(state.unpricedChecked, refreshStateKey(state), routeKeys);
585
+ }
586
+ return state;
587
+ }
588
+ /** Persist a definitive catalog answer; a lost race must not fail the refresh. */
589
+ async function completeRefresh(params) {
590
+ const state = buildCompletionState(params);
591
+ try {
592
+ await writeRefreshStateMerged(params.statePath, state, params.lockTimeoutMs);
593
+ }
594
+ catch {
595
+ // best effort; the in-memory/runtime snapshot is already active
596
+ }
597
+ return { attempted: true, updated: true, state };
598
+ }
599
+ function pricingRouteKey(route) {
600
+ return `${route.providerID ?? ""}\u0000${route.modelID ?? ""}`;
601
+ }
602
+ /**
603
+ * True when the route already has explicit rates. Unknown routes are not
604
+ * priced, so they can justify one unpriced-triggered refresh attempt.
605
+ */
606
+ function pricingRouteIsPriced(route) {
607
+ const providerID = route.providerID?.trim();
608
+ const modelID = route.modelID?.trim();
609
+ if (!modelID)
610
+ return true;
611
+ const candidates = [];
612
+ const add = (provider, model) => {
613
+ if (!model)
614
+ return;
615
+ candidates.push([provider, model]);
616
+ };
617
+ add(providerID, modelID);
618
+ if (providerID && modelID.startsWith(`${providerID}/`)) {
619
+ add(providerID, modelID.slice(providerID.length + 1));
620
+ }
621
+ const slash = modelID.indexOf("/");
622
+ if (slash > 0)
623
+ add(modelID.slice(0, slash), modelID.slice(slash + 1));
624
+ add(inferProviderForModelId(modelID) ?? undefined, modelID);
625
+ return candidates.some(([provider, model]) => provider !== undefined && hasCost(provider, model));
626
+ }
627
+ function dedupePricingRoutes(routes) {
628
+ const byKey = new Map();
629
+ for (const route of routes) {
630
+ if (!route.modelID?.trim())
631
+ continue;
632
+ const key = pricingRouteKey(route);
633
+ if (!byKey.has(key))
634
+ byKey.set(key, route);
635
+ }
636
+ return [...byKey.values()];
637
+ }
316
638
  function pickRateBuckets(rawCost) {
317
639
  const obj = asRecord(rawCost);
318
640
  if (!obj)
@@ -573,15 +895,6 @@ export async function maybeRefreshPricingSnapshot(opts = {}) {
573
895
  },
574
896
  };
575
897
  }
576
- if (!force && PROCESS_REFRESH_CHECKED) {
577
- return {
578
- attempted: false,
579
- updated: false,
580
- reason: "already_checked_this_process",
581
- state: previousState,
582
- };
583
- }
584
- PROCESS_REFRESH_CHECKED = true;
585
898
  const health = getPricingSnapshotHealth({ nowMs, maxAgeMs });
586
899
  if (!force && !policy.enabled) {
587
900
  return {
@@ -595,7 +908,7 @@ export async function maybeRefreshPricingSnapshot(opts = {}) {
595
908
  },
596
909
  };
597
910
  }
598
- if (!force && !health.stale && !legacyRuntimePinnedByValidators) {
911
+ if (!force && !opts.refreshEvenIfFresh && !health.stale && !legacyRuntimePinnedByValidators) {
599
912
  return {
600
913
  attempted: false,
601
914
  updated: false,
@@ -607,7 +920,9 @@ export async function maybeRefreshPricingSnapshot(opts = {}) {
607
920
  },
608
921
  };
609
922
  }
923
+ const bypassableUnpricedRoutes = unpricedRoutesBypassable(opts.unpricedRouteKeys, previousState);
610
924
  if (!force &&
925
+ bypassableUnpricedRoutes.length === 0 &&
611
926
  previousState.lastAttemptAt &&
612
927
  nowMs - previousState.lastAttemptAt < minAttemptIntervalMs) {
613
928
  return {
@@ -621,12 +936,28 @@ export async function maybeRefreshPricingSnapshot(opts = {}) {
621
936
  },
622
937
  };
623
938
  }
624
- const attemptingState = {
625
- ...previousState,
626
- version: 1,
627
- updatedAt: nowMs,
628
- lastAttemptAt: nowMs,
629
- };
939
+ const lockTimeoutMs = opts.lockTimeoutMs ?? DEFAULT_BUDGET_LOCK_TIMEOUT_MS;
940
+ const reservation = await reserveRefreshAttempt({
941
+ statePath,
942
+ nowMs,
943
+ automatic: !force,
944
+ force,
945
+ minAttemptIntervalMs,
946
+ lockTimeoutMs,
947
+ fallbackState: previousState,
948
+ ...(opts.unpricedRouteKeys === undefined
949
+ ? {}
950
+ : { unpricedRouteKeys: opts.unpricedRouteKeys }),
951
+ });
952
+ if (!reservation.ok) {
953
+ return {
954
+ attempted: false,
955
+ updated: false,
956
+ reason: reservation.reason,
957
+ state: reservation.state,
958
+ };
959
+ }
960
+ const attemptingState = reservation.state;
630
961
  try {
631
962
  let fetchResult = await fetchModelsDevSnapshot({
632
963
  timeoutMs,
@@ -638,15 +969,32 @@ export async function maybeRefreshPricingSnapshot(opts = {}) {
638
969
  // An unconditional request must not answer 304. Retry once without
639
970
  // validators; a second 304 still cannot establish catalog presence, so
640
971
  // fail the refresh instead of persisting a fresh catalog-less snapshot.
972
+ // The retry is a real network request and reserves its own budget slot.
973
+ const retryReservation = await reserveRefreshAttempt({
974
+ statePath,
975
+ nowMs,
976
+ automatic: !force,
977
+ force,
978
+ minAttemptIntervalMs: 0,
979
+ lockTimeoutMs,
980
+ fallbackState: attemptingState,
981
+ });
982
+ if (!retryReservation.ok) {
983
+ throw new Error(retryReservation.reason === "budget"
984
+ ? "models.dev pricing refresh budget exhausted (10 automatic requests per 24h)"
985
+ : "models.dev pricing refresh budget reservation unavailable");
986
+ }
987
+ const retryState = retryReservation.state;
641
988
  const retry = await fetchModelsDevSnapshot({
642
989
  timeoutMs,
643
- state: attemptingState,
990
+ state: retryState,
644
991
  fetchFn: opts.fetchFn,
645
992
  conditional: false,
646
993
  });
647
994
  if (retry.kind === "not_modified") {
648
995
  throw new Error("models.dev returned not modified while an authoritative catalog refresh was required");
649
996
  }
997
+ attemptingState.attempts24h = retryState.attempts24h;
650
998
  fetchResult = retry;
651
999
  }
652
1000
  if (fetchResult.kind === "not_modified") {
@@ -672,26 +1020,16 @@ export async function maybeRefreshPricingSnapshot(opts = {}) {
672
1020
  bootstrapSnapshotOverride: opts.bootstrapSnapshotOverride,
673
1021
  selection,
674
1022
  });
675
- const nextState = {
676
- ...attemptingState,
677
- updatedAt: nowMs,
678
- lastSuccessAt: nowMs,
1023
+ return await completeRefresh({
1024
+ statePath,
1025
+ attemptingState,
1026
+ nowMs,
679
1027
  lastResult: "not_modified",
680
- lastError: undefined,
681
- etag: fetchResult.etag ?? attemptingState.etag,
682
- lastModified: fetchResult.lastModified ?? attemptingState.lastModified,
683
- };
684
- try {
685
- await writeJsonAtomic(statePath, nextState, { trailingNewline: true });
686
- }
687
- catch {
688
- // best effort; keep refreshed in-memory/runtime snapshot active
689
- }
690
- return {
691
- attempted: true,
692
- updated: true,
693
- state: nextState,
694
- };
1028
+ etag: fetchResult.etag,
1029
+ lastModified: fetchResult.lastModified,
1030
+ unpricedRouteKeys: opts.unpricedRouteKeys,
1031
+ lockTimeoutMs,
1032
+ });
695
1033
  }
696
1034
  const fetchedSnapshot = buildSnapshotFromApi(fetchResult.api, requestedProviderIDs, nowMs);
697
1035
  // An all-unpriced response is still authoritative when its catalog lists
@@ -732,26 +1070,16 @@ export async function maybeRefreshPricingSnapshot(opts = {}) {
732
1070
  bootstrapSnapshotOverride: opts.bootstrapSnapshotOverride,
733
1071
  selection,
734
1072
  });
735
- const nextState = {
736
- ...attemptingState,
737
- updatedAt: nowMs,
738
- lastSuccessAt: nowMs,
1073
+ return await completeRefresh({
1074
+ statePath,
1075
+ attemptingState,
1076
+ nowMs,
739
1077
  lastResult: "success",
740
- lastError: undefined,
741
- etag: fetchResult.etag ?? attemptingState.etag,
742
- lastModified: fetchResult.lastModified ?? attemptingState.lastModified,
743
- };
744
- try {
745
- await writeJsonAtomic(statePath, nextState, { trailingNewline: true });
746
- }
747
- catch {
748
- // best effort; snapshot has already been updated
749
- }
750
- return {
751
- attempted: true,
752
- updated: true,
753
- state: nextState,
754
- };
1078
+ etag: fetchResult.etag,
1079
+ lastModified: fetchResult.lastModified,
1080
+ unpricedRouteKeys: opts.unpricedRouteKeys,
1081
+ lockTimeoutMs,
1082
+ });
755
1083
  }
756
1084
  catch (error) {
757
1085
  const errorMessage = getErrorMessage(error);
@@ -763,7 +1091,7 @@ export async function maybeRefreshPricingSnapshot(opts = {}) {
763
1091
  lastError: errorMessage,
764
1092
  };
765
1093
  try {
766
- await writeJsonAtomic(statePath, nextState, { trailingNewline: true });
1094
+ await writeRefreshStateMerged(statePath, nextState, lockTimeoutMs);
767
1095
  }
768
1096
  catch {
769
1097
  // best effort; report original fetch/refresh error
@@ -780,6 +1108,71 @@ export async function maybeRefreshPricingSnapshot(opts = {}) {
780
1108
  });
781
1109
  return REFRESH_IN_FLIGHT;
782
1110
  }
1111
+ /**
1112
+ * Event-driven analytics pricing upkeep: adopt an externally refreshed runtime
1113
+ * snapshot, run the normal freshness refresh, and give one extra attempt when a
1114
+ * route used by Analytics is still unpriced or unknown. A route not yet checked
1115
+ * against the current catalog identity gets one throttle bypass per identity;
1116
+ * every attempt still obeys the rolling 24h automatic request budget, and a
1117
+ * bundled selection never refreshes. Cheap re-entry: unchanged unpriced routes
1118
+ * inside the check interval do no I/O.
1119
+ */
1120
+ export async function refreshAnalyticsPricing(opts) {
1121
+ const nowMs = opts?.nowMs ?? Date.now();
1122
+ const selection = opts?.snapshotSelection ?? SNAPSHOT_SELECTION;
1123
+ if (selection === "bundled")
1124
+ return undefined;
1125
+ const routes = dedupePricingRoutes(opts?.routes ?? []);
1126
+ const preliminarySignature = routes
1127
+ .filter((route) => !pricingRouteIsPriced(route))
1128
+ .map(pricingRouteKey)
1129
+ .sort()
1130
+ .join("\u0001");
1131
+ const currentlyStale = getPricingSnapshotHealth({
1132
+ nowMs,
1133
+ maxAgeMs: getPricingRefreshPolicy().maxAgeMs,
1134
+ }).stale;
1135
+ if (!currentlyStale &&
1136
+ nowMs - LAST_ANALYTICS_PRICING_CHECK_AT_MS < ANALYTICS_PRICING_CHECK_INTERVAL_MS &&
1137
+ preliminarySignature === LAST_ANALYTICS_UNPRICED_SIGNATURE) {
1138
+ return undefined;
1139
+ }
1140
+ reloadPricingSnapshotFromDisk({
1141
+ ...(opts?.runtimeDirs === undefined ? {} : { runtimeDirs: opts.runtimeDirs }),
1142
+ ...(opts?.bootstrapSnapshotOverride === undefined
1143
+ ? {}
1144
+ : { bootstrapSnapshotOverride: opts.bootstrapSnapshotOverride }),
1145
+ });
1146
+ const unpricedRoutes = routes.filter((route) => !pricingRouteIsPriced(route));
1147
+ const unpricedRouteKeys = unpricedRoutes.map(pricingRouteKey);
1148
+ const signature = [...unpricedRouteKeys].sort().join("\u0001");
1149
+ LAST_ANALYTICS_PRICING_CHECK_AT_MS = nowMs;
1150
+ LAST_ANALYTICS_UNPRICED_SIGNATURE = signature;
1151
+ const state = (await readRefreshState(getRuntimePricingRefreshStatePath(opts?.runtimeDirs))) ?? undefined;
1152
+ const health = getPricingSnapshotHealth({ nowMs, maxAgeMs: getPricingRefreshPolicy().maxAgeMs });
1153
+ if (!health.stale && unpricedRoutesUntried(unpricedRouteKeys, state).length === 0) {
1154
+ return undefined;
1155
+ }
1156
+ const result = await maybeRefreshPricingSnapshot({
1157
+ reason: unpricedRoutes.length > 0 ? "unpriced" : "status",
1158
+ refreshEvenIfFresh: unpricedRoutes.length > 0,
1159
+ unpricedRouteKeys,
1160
+ nowMs,
1161
+ snapshotSelection: selection,
1162
+ ...(opts?.runtimeDirs === undefined ? {} : { runtimeDirs: opts.runtimeDirs }),
1163
+ ...(opts?.fetchFn === undefined ? {} : { fetchFn: opts.fetchFn }),
1164
+ ...(opts?.bootstrapSnapshotOverride === undefined
1165
+ ? {}
1166
+ : { bootstrapSnapshotOverride: opts.bootstrapSnapshotOverride }),
1167
+ });
1168
+ reloadPricingSnapshotFromDisk({
1169
+ ...(opts?.runtimeDirs === undefined ? {} : { runtimeDirs: opts.runtimeDirs }),
1170
+ ...(opts?.bootstrapSnapshotOverride === undefined
1171
+ ? {}
1172
+ : { bootstrapSnapshotOverride: opts.bootstrapSnapshotOverride }),
1173
+ });
1174
+ return result;
1175
+ }
783
1176
  export function setPricingSnapshotSelection(selection) {
784
1177
  if (SNAPSHOT_SELECTION === selection)
785
1178
  return;
@@ -910,6 +1303,7 @@ export function __resetPricingSnapshotForTests() {
910
1303
  CONFIGURED_PRICING_SNAPSHOT_MAX_AGE_MS = DEFAULT_PRICING_SNAPSHOT_MAX_AGE_MS;
911
1304
  MODEL_INDEX = null;
912
1305
  REFRESH_IN_FLIGHT = null;
913
- PROCESS_REFRESH_CHECKED = false;
1306
+ LAST_ANALYTICS_PRICING_CHECK_AT_MS = 0;
1307
+ LAST_ANALYTICS_UNPRICED_SIGNATURE = "";
914
1308
  }
915
1309
  //# sourceMappingURL=modelsdev-pricing.js.map
@@ -49,6 +49,12 @@ export type TemporalMultiplier = {
49
49
  export type TemporalPolicyEntry = {
50
50
  status: "supported";
51
51
  source: string;
52
+ /**
53
+ * Unconditional source rates (`cost.text.*`). Absolute overrides replace
54
+ * these rates, so comparison must use them instead of a live/derived
55
+ * pricing snapshot. Absent for multiplier-only policies.
56
+ */
57
+ base?: TemporalRates;
52
58
  overrides: TemporalOverride[];
53
59
  multipliers: TemporalMultiplier[];
54
60
  } | {