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
@@ -25,6 +25,8 @@ export interface OwnedStep {
25
25
  pricedAny: boolean;
26
26
  unpricedTokens: number;
27
27
  unknownTokens: number;
28
+ recordedCostUsd: number;
29
+ recordedCostTokens: number;
28
30
  }
29
31
  export interface HomeAnalyticsRollup {
30
32
  usage: Usage;
@@ -41,6 +43,11 @@ export interface AnalyticsModel {
41
43
  groups(query: AnalyticsGroupQuery, nowMs: number): AnalyticsGroupSnapshot;
42
44
  earliestActivityMs(): number | undefined;
43
45
  ownedStepCount(): number;
46
+ /** Distinct analytics routes whose last pricing outcome had no cost. */
47
+ unpricedRoutes(): Array<{
48
+ providerID?: string;
49
+ modelID?: string;
50
+ }>;
44
51
  }
45
52
  /** Host calendar zone used for every bucket boundary in this model. */
46
53
  export interface AnalyticsModelOptions {
@@ -13,9 +13,9 @@ import { planRangeBuckets, rangeBucketUnit, rangeWindow, } from "../contracts/ra
13
13
  import { lookupCost, selectCostAtContext } from "../lib/modelsdev-pricing.js";
14
14
  import { getTemporalPolicy, resolveTemporalRates, TEMPORAL_RATE_KEYS, } from "../lib/modelsdev-temporal.js";
15
15
  import { rawAssistantRowFingerprint, rawAssistantRowHasTokenUsage, } from "../lib/opencode-storage.js";
16
- import { priceTokenBuckets, resolvePricingKey, } from "../lib/quota-stats.js";
16
+ import { priceTokenBucketsWithRecordedCost, resolvePricingKey, } from "../lib/quota-stats.js";
17
17
  import { selectForkOwners } from "../lib/usage-ownership.js";
18
- import { UNKNOWN_PROJECT_ID, UNTITLED_SESSION_TITLE } from "./aggregation.js";
18
+ import { recordedCostFields, UNKNOWN_PROJECT_ID, UNTITLED_SESSION_TITLE } from "./aggregation.js";
19
19
  const HOUR_MS = 3_600_000;
20
20
  const TEMPORAL_FACTOR_EPSILON = 1e-9;
21
21
  function createAccumulator() {
@@ -29,6 +29,8 @@ function createAccumulator() {
29
29
  pricedCount: 0,
30
30
  unpricedTokens: 0,
31
31
  unknownTokens: 0,
32
+ recordedCostUsd: 0,
33
+ recordedCostTokens: 0,
32
34
  };
33
35
  }
34
36
  function addStepToAccumulator(accumulator, step) {
@@ -42,6 +44,8 @@ function addStepToAccumulator(accumulator, step) {
42
44
  accumulator.pricedCount += 1;
43
45
  accumulator.unpricedTokens += step.unpricedTokens;
44
46
  accumulator.unknownTokens += step.unknownTokens;
47
+ accumulator.recordedCostUsd += step.recordedCostUsd;
48
+ accumulator.recordedCostTokens += step.recordedCostTokens;
45
49
  }
46
50
  function subtractStepFromAccumulator(accumulator, step) {
47
51
  accumulator.input -= step.tokens.input;
@@ -54,6 +58,8 @@ function subtractStepFromAccumulator(accumulator, step) {
54
58
  accumulator.pricedCount -= 1;
55
59
  accumulator.unpricedTokens -= step.unpricedTokens;
56
60
  accumulator.unknownTokens -= step.unknownTokens;
61
+ accumulator.recordedCostUsd -= step.recordedCostUsd;
62
+ accumulator.recordedCostTokens -= step.recordedCostTokens;
57
63
  }
58
64
  function mergeAccumulator(target, source) {
59
65
  target.input += source.input;
@@ -65,6 +71,8 @@ function mergeAccumulator(target, source) {
65
71
  target.pricedCount += source.pricedCount;
66
72
  target.unpricedTokens += source.unpricedTokens;
67
73
  target.unknownTokens += source.unknownTokens;
74
+ target.recordedCostUsd += source.recordedCostUsd;
75
+ target.recordedCostTokens += source.recordedCostTokens;
68
76
  }
69
77
  function finalize(accumulator) {
70
78
  const stack = {
@@ -80,6 +88,7 @@ function finalize(accumulator) {
80
88
  apiEquivalentCostUsd: accumulator.pricedCount > 0 ? accumulator.costUsd : null,
81
89
  unpricedTokens: accumulator.unpricedTokens,
82
90
  unknownTokens: accumulator.unknownTokens,
91
+ ...recordedCostFields(accumulator.recordedCostUsd, accumulator.recordedCostTokens),
83
92
  };
84
93
  }
85
94
  function createGroupNode() {
@@ -295,6 +304,7 @@ export function createAnalyticsModel(options = {}) {
295
304
  const timeZone = options.timeZone ?? "UTC";
296
305
  const pricingCache = new Map();
297
306
  const groups = new Map();
307
+ const unpricedRouteByKey = new Map();
298
308
  const ownedByFp = new Map();
299
309
  const ownedBySession = new Map();
300
310
  const hours = new Map();
@@ -315,7 +325,7 @@ export function createAnalyticsModel(options = {}) {
315
325
  row.tokens.reasoning +
316
326
  row.tokens.cacheRead +
317
327
  row.tokens.cacheWrite;
318
- const outcome = priceTokenBuckets({
328
+ const outcome = priceTokenBucketsWithRecordedCost({
319
329
  providerID: row.providerID,
320
330
  modelID: row.modelID,
321
331
  tokens: {
@@ -325,6 +335,7 @@ export function createAnalyticsModel(options = {}) {
325
335
  cache_read: row.tokens.cacheRead,
326
336
  cache_write: row.tokens.cacheWrite,
327
337
  },
338
+ recordedCostUsd: row.cost,
328
339
  // Historical temporal pricing follows the physical assistant completion
329
340
  // instant, not the enclosing range window or the worker's wall clock.
330
341
  atMs: row.completedAtMs,
@@ -336,15 +347,48 @@ export function createAnalyticsModel(options = {}) {
336
347
  pricedAny: true,
337
348
  unpricedTokens: outcome.unpricedTokens,
338
349
  unknownTokens: 0,
350
+ recordedCostUsd: 0,
351
+ recordedCostTokens: 0,
339
352
  };
340
353
  }
341
354
  if (outcome.status === "priced") {
342
- return { costUsd: outcome.costUsd, pricedAny: true, unpricedTokens: 0, unknownTokens: 0 };
355
+ return {
356
+ costUsd: outcome.costUsd,
357
+ pricedAny: true,
358
+ unpricedTokens: 0,
359
+ unknownTokens: 0,
360
+ recordedCostUsd: 0,
361
+ recordedCostTokens: 0,
362
+ };
363
+ }
364
+ if (outcome.status === "recorded_cost") {
365
+ return {
366
+ costUsd: outcome.costUsd,
367
+ pricedAny: true,
368
+ unpricedTokens: 0,
369
+ unknownTokens: 0,
370
+ recordedCostUsd: outcome.costUsd,
371
+ recordedCostTokens: outcome.recordedTokens,
372
+ };
343
373
  }
344
374
  if (outcome.status === "unpriced") {
345
- return { costUsd: 0, pricedAny: false, unpricedTokens: total, unknownTokens: 0 };
375
+ return {
376
+ costUsd: 0,
377
+ pricedAny: false,
378
+ unpricedTokens: total,
379
+ unknownTokens: 0,
380
+ recordedCostUsd: 0,
381
+ recordedCostTokens: 0,
382
+ };
346
383
  }
347
- return { costUsd: 0, pricedAny: false, unpricedTokens: 0, unknownTokens: total };
384
+ return {
385
+ costUsd: 0,
386
+ pricedAny: false,
387
+ unpricedTokens: 0,
388
+ unknownTokens: total,
389
+ recordedCostUsd: 0,
390
+ recordedCostTokens: 0,
391
+ };
348
392
  }
349
393
  /**
350
394
  * Relative movement of one effective monetary rate state against the route's
@@ -479,9 +523,12 @@ export function createAnalyticsModel(options = {}) {
479
523
  return undefined;
480
524
  const promptTokens = step.tokens.input + step.tokens.cacheRead + step.tokens.cacheWrite;
481
525
  const cost = lookupCost(key.provider, key.model);
482
- if (cost === null)
526
+ // Absolute overrides are meaningful only against the policy's own base.
527
+ // The live snapshot can be a derived price that matches neither side, so
528
+ // prefer the base captured with the temporal policy when present.
529
+ const base = policy.base ?? (cost ? selectCostAtContext(cost, promptTokens).rates : null);
530
+ if (base === null)
483
531
  return undefined;
484
- const base = selectCostAtContext(cost, promptTokens).rates;
485
532
  const resolved = resolveTemporalRates(key.provider, key.model, step.completedAtMs, base);
486
533
  if (resolved.status !== "resolved" || resolved.rates === null)
487
534
  return undefined;
@@ -586,6 +633,8 @@ export function createAnalyticsModel(options = {}) {
586
633
  pricedAny: occurrence.pricedAny,
587
634
  unpricedTokens: occurrence.unpricedTokens,
588
635
  unknownTokens: occurrence.unknownTokens,
636
+ recordedCostUsd: occurrence.recordedCostUsd,
637
+ recordedCostTokens: occurrence.recordedCostTokens,
589
638
  };
590
639
  if (occurrence.providerID !== undefined)
591
640
  step.providerID = occurrence.providerID;
@@ -606,7 +655,9 @@ export function createAnalyticsModel(options = {}) {
606
655
  step.costUsd === occurrence.costUsd &&
607
656
  step.pricedAny === occurrence.pricedAny &&
608
657
  step.unpricedTokens === occurrence.unpricedTokens &&
609
- step.unknownTokens === occurrence.unknownTokens);
658
+ step.unknownTokens === occurrence.unknownTokens &&
659
+ step.recordedCostUsd === occurrence.recordedCostUsd &&
660
+ step.recordedCostTokens === occurrence.recordedCostTokens);
610
661
  }
611
662
  /**
612
663
  * Reuse the canonical step object for an unchanged winner. The same object is
@@ -722,6 +773,19 @@ export function createAnalyticsModel(options = {}) {
722
773
  groups.set(fingerprint, occurrences);
723
774
  }
724
775
  const priced = priceRow(row);
776
+ if (row.modelID) {
777
+ const routeKey = `${row.providerID ?? ""}\u0000${row.modelID}`;
778
+ // A recorded-cost price still asks the kicker to prefer models.dev once
779
+ // it publishes a price for the route.
780
+ if (priced.pricedAny && priced.recordedCostTokens === 0) {
781
+ unpricedRouteByKey.delete(routeKey);
782
+ }
783
+ else {
784
+ unpricedRouteByKey.set(routeKey, row.providerID === undefined
785
+ ? { modelID: row.modelID }
786
+ : { providerID: row.providerID, modelID: row.modelID });
787
+ }
788
+ }
725
789
  const occurrence = {
726
790
  sessionID: row.sessionID,
727
791
  messageID: row.messageID,
@@ -1335,6 +1399,7 @@ export function createAnalyticsModel(options = {}) {
1335
1399
  groups.clear();
1336
1400
  ownedByFp.clear();
1337
1401
  ownedBySession.clear();
1402
+ unpricedRouteByKey.clear();
1338
1403
  hours.clear();
1339
1404
  latestStepBySession.clear();
1340
1405
  earliestStepBySession.clear();
@@ -1405,6 +1470,7 @@ export function createAnalyticsModel(options = {}) {
1405
1470
  count += steps.size;
1406
1471
  return count;
1407
1472
  },
1473
+ unpricedRoutes: () => [...unpricedRouteByKey.values()],
1408
1474
  };
1409
1475
  }
1410
1476
  //# sourceMappingURL=analytics-model.js.map
@@ -0,0 +1,21 @@
1
+ import { type PricingRefreshResult, type PricingRoute } from "../lib/modelsdev-pricing.js";
2
+ import type { AnalyticsUpkeepNotification } from "./analytics-protocol.js";
3
+ /**
4
+ * Worker-side tracking for pricing upkeep started after an analytics reply.
5
+ *
6
+ * A refresh can outlive the read queue (the fetch timeout alone is 6 s). The
7
+ * worker advertises start/end frames so the host bridge delays idle retirement
8
+ * until the refresh settles, while the analytics reply itself is never awaited
9
+ * on the refresh.
10
+ */
11
+ export interface AnalyticsPricingUpkeep {
12
+ begin(): void;
13
+ }
14
+ export declare function createAnalyticsPricingUpkeep(params: {
15
+ postMessage: (message: AnalyticsUpkeepNotification) => void;
16
+ routes: () => readonly PricingRoute[];
17
+ refresh?: (options: {
18
+ routes: readonly PricingRoute[];
19
+ }) => Promise<void | PricingRefreshResult | undefined>;
20
+ }): AnalyticsPricingUpkeep;
21
+ //# sourceMappingURL=analytics-pricing-upkeep.d.ts.map
@@ -0,0 +1,23 @@
1
+ import { refreshAnalyticsPricing, } from "../lib/modelsdev-pricing.js";
2
+ export function createAnalyticsPricingUpkeep(params) {
3
+ const refresh = params.refresh ?? refreshAnalyticsPricing;
4
+ let active = 0;
5
+ return {
6
+ begin() {
7
+ active += 1;
8
+ if (active === 1)
9
+ params.postMessage({ type: "analytics-upkeep", active: true });
10
+ // Deferred one microtask: `begin` is called before the caller posts its
11
+ // reply frame, so the refresh starts only after that frame is queued.
12
+ void Promise.resolve()
13
+ .then(() => refresh({ routes: params.routes() }))
14
+ .catch(() => { })
15
+ .finally(() => {
16
+ active -= 1;
17
+ if (active === 0)
18
+ params.postMessage({ type: "analytics-upkeep", active: false });
19
+ });
20
+ },
21
+ };
22
+ }
23
+ //# sourceMappingURL=analytics-pricing-upkeep.js.map
@@ -5,9 +5,11 @@
5
5
  * boundary. Raw storage rows, compact fingerprints, coverage windows, and the
6
6
  * analytics model stay inside the worker.
7
7
  */
8
- import type { AnalyticsGroupQuery, AnalyticsGroupSnapshot, HomeSnapshot, ProjectSnapshot, SessionSnapshot } from "../contracts/dashboard.js";
8
+ import type { AnalyticsGroupQuery, AnalyticsGroupSnapshot, AnalyticsRangeReader, HomeSnapshot, ProjectSnapshot, SessionSnapshot } from "../contracts/dashboard.js";
9
9
  import type { RangeKey } from "../contracts/ranges.js";
10
+ import type { PricingSnapshotConfig } from "../lib/types.js";
10
11
  export declare const ANALYTICS_WORKER_PROTOCOL_VERSION = 1;
12
+ export { ANALYTICS_DEFAULT_REQUEST_TIMEOUT_MS } from "../contracts/dashboard.js";
11
13
  export type AnalyticsErrorCode = "bad-request" | "project-not-found" | "session-not-found" | "unavailable" | "closed" | "timeout";
12
14
  /** A controlled analytics failure; messages are fixed and path-free. */
13
15
  export declare class AnalyticsReadError extends Error {
@@ -17,6 +19,8 @@ export declare class AnalyticsReadError extends Error {
17
19
  export interface AnalyticsInitOptions {
18
20
  snapshotPath?: string;
19
21
  refreshIntervalMs?: number;
22
+ /** Owner's pricing snapshot selection and freshness policy for the worker. */
23
+ pricingSnapshot?: PricingSnapshotConfig;
20
24
  }
21
25
  /** Cumulative timing for one fixed worker phase; contains no identifying data. */
22
26
  export interface AnalyticsPhaseTiming {
@@ -44,6 +48,7 @@ export type AnalyticsWorkerCommand = {
44
48
  } | {
45
49
  kind: "home";
46
50
  range: RangeKey;
51
+ exact?: boolean;
47
52
  } | {
48
53
  kind: "project";
49
54
  projectId: string;
@@ -84,17 +89,22 @@ export interface AnalyticsGenerationNotification {
84
89
  type: "analytics-generation";
85
90
  generation: number;
86
91
  }
92
+ /**
93
+ * Unsolicited worker -> host notification: priced-snapshot upkeep (a models.dev
94
+ * refresh and persistence) is running or has settled. The host keeps the worker
95
+ * alive while upkeep is active so a refresh started after the last read reply
96
+ * can finish instead of being cut off by idle retirement.
97
+ */
98
+ export interface AnalyticsUpkeepNotification {
99
+ type: "analytics-upkeep";
100
+ active: boolean;
101
+ }
87
102
  /**
88
103
  * Host-side transport seam. Production uses a Node/Bun worker bridge; tests
89
104
  * substitute a loopback transport over the same engine/protocol.
90
105
  */
91
- export interface AnalyticsTransport {
106
+ export interface AnalyticsTransport extends AnalyticsRangeReader {
92
107
  init(options: AnalyticsInitOptions): Promise<void>;
93
- home(range: RangeKey): Promise<HomeSnapshot>;
94
- project(projectId: string, range: RangeKey): Promise<ProjectSnapshot>;
95
- session(sessionId: string): Promise<SessionSnapshot>;
96
- groups(query: AnalyticsGroupQuery): Promise<AnalyticsGroupSnapshot>;
97
- refresh(): Promise<void>;
98
108
  /** Optional diagnostics seam; the real worker implements it. */
99
109
  stats?(): Promise<AnalyticsWorkerMemoryStats>;
100
110
  /** Optional GC seam; returns false when the runtime exposes no hook. */
@@ -1,4 +1,5 @@
1
1
  export const ANALYTICS_WORKER_PROTOCOL_VERSION = 1;
2
+ export { ANALYTICS_DEFAULT_REQUEST_TIMEOUT_MS } from "../contracts/dashboard.js";
2
3
  /** A controlled analytics failure; messages are fixed and path-free. */
3
4
  export class AnalyticsReadError extends Error {
4
5
  code;
@@ -8,11 +8,14 @@
8
8
  */
9
9
  import type { AnalyticsGroupQuery, AnalyticsGroupSnapshot, HomeSnapshot, ProjectSnapshot, SessionSnapshot } from "../contracts/dashboard.js";
10
10
  import { type RangeKey } from "../contracts/ranges.js";
11
+ import type { PricingSnapshotConfig } from "../lib/types.js";
11
12
  import { type AnalyticsTransport, type AnalyticsWorkerMemoryStats } from "./analytics-protocol.js";
12
13
  import { type GuiLogger } from "./log.js";
13
14
  export interface AnalyticsReadService {
14
15
  home(input: {
15
16
  range: RangeKey;
17
+ exact?: boolean;
18
+ background?: boolean;
16
19
  }): Promise<HomeSnapshot>;
17
20
  project(input: {
18
21
  projectId: string;
@@ -36,6 +39,8 @@ export interface AnalyticsReadService {
36
39
  export interface AnalyticsReadServiceOptions {
37
40
  snapshotPath?: string;
38
41
  refreshIntervalMs?: number;
42
+ /** Owner's pricing snapshot selection/freshness policy, applied in the worker. */
43
+ pricingSnapshot?: PricingSnapshotConfig;
39
44
  requestTimeoutMs?: number;
40
45
  logger?: GuiLogger;
41
46
  /** Optional Node worker heap ceiling; omit for runtime-managed default. */
@@ -44,6 +49,11 @@ export interface AnalyticsReadServiceOptions {
44
49
  maxTransportAttempts?: number;
45
50
  /** Base backoff for transport init recovery (default 250 ms). */
46
51
  transportRetryBaseMs?: number;
52
+ /**
53
+ * Keep a warm worker this long after its queue drains (default 5000 ms) so a
54
+ * quick tab switch does not re-load the persisted index. 0 retires at once.
55
+ */
56
+ idleRetireMs?: number;
47
57
  /** Test/embedding seam; production default builds the Node/Bun worker bridge. */
48
58
  createTransport?: () => AnalyticsTransport | Promise<AnalyticsTransport>;
49
59
  }
@@ -13,12 +13,18 @@ import { AnalyticsReadError, } from "./analytics-protocol.js";
13
13
  import { createGuiLogger } from "./log.js";
14
14
  const DEFAULT_MAX_TRANSPORT_ATTEMPTS = 5;
15
15
  const DEFAULT_TRANSPORT_RETRY_BASE_MS = 250;
16
+ const DEFAULT_IDLE_RETIRE_MS = 5_000;
16
17
  const MAX_TRANSPORT_RETRY_DELAY_MS = 5_000;
17
18
  function badRequest() {
18
19
  return new AnalyticsReadError("bad-request");
19
20
  }
20
21
  export function createAnalyticsReadService(options = {}) {
21
22
  const logger = options.logger ?? createGuiLogger();
23
+ const idleRetireMs = options.idleRetireMs !== undefined &&
24
+ Number.isFinite(options.idleRetireMs) &&
25
+ options.idleRetireMs >= 0
26
+ ? options.idleRetireMs
27
+ : DEFAULT_IDLE_RETIRE_MS;
22
28
  const createTransport = options.createTransport ??
23
29
  (() => createAnalyticsBridge({
24
30
  ...(options.requestTimeoutMs === undefined
@@ -27,6 +33,7 @@ export function createAnalyticsReadService(options = {}) {
27
33
  ...(options.workerHeapLimitMb === undefined
28
34
  ? {}
29
35
  : { workerHeapLimitMb: options.workerHeapLimitMb }),
36
+ idleRetireMs,
30
37
  logger,
31
38
  }));
32
39
  const maxTransportAttempts = options.maxTransportAttempts !== undefined &&
@@ -40,6 +47,7 @@ export function createAnalyticsReadService(options = {}) {
40
47
  ? options.transportRetryBaseMs
41
48
  : DEFAULT_TRANSPORT_RETRY_BASE_MS;
42
49
  let transportPromise;
50
+ let initPromise;
43
51
  let initialized = false;
44
52
  let failures = 0;
45
53
  let nextRetryAtMs = 0;
@@ -89,15 +97,28 @@ export function createAnalyticsReadService(options = {}) {
89
97
  const created = await transportPromise;
90
98
  if (initialized)
91
99
  return created;
92
- if (Date.now() < nextRetryAtMs)
93
- throw new AnalyticsReadError("unavailable");
94
- try {
95
- await created.init({
96
- ...(options.snapshotPath === undefined ? {} : { snapshotPath: options.snapshotPath }),
97
- ...(options.refreshIntervalMs === undefined
98
- ? {}
99
- : { refreshIntervalMs: options.refreshIntervalMs }),
100
+ // Simultaneous first callers share one init and one failure count.
101
+ if (!initPromise) {
102
+ if (Date.now() < nextRetryAtMs)
103
+ throw new AnalyticsReadError("unavailable");
104
+ initPromise = initTransport(created).finally(() => {
105
+ initPromise = undefined;
100
106
  });
107
+ }
108
+ return await initPromise;
109
+ }
110
+ async function initTransport(created) {
111
+ try {
112
+ const initOptions = {};
113
+ if (options.snapshotPath !== undefined)
114
+ initOptions.snapshotPath = options.snapshotPath;
115
+ if (options.refreshIntervalMs !== undefined) {
116
+ initOptions.refreshIntervalMs = options.refreshIntervalMs;
117
+ }
118
+ if (options.pricingSnapshot !== undefined) {
119
+ initOptions.pricingSnapshot = options.pricingSnapshot;
120
+ }
121
+ await created.init(initOptions);
101
122
  initialized = true;
102
123
  failures = 0;
103
124
  nextRetryAtMs = 0;
@@ -129,7 +150,7 @@ export function createAnalyticsReadService(options = {}) {
129
150
  return {
130
151
  async home(input) {
131
152
  validateRange(input.range);
132
- return (await ensureTransport()).home(input.range);
153
+ return (await ensureTransport()).home(input.range, input.exact, input.background);
133
154
  },
134
155
  async project(input) {
135
156
  validateRange(input.range);
@@ -1,16 +1,21 @@
1
1
  import type { HomeSnapshot, ProjectSnapshot, SessionSnapshot } from "../contracts/dashboard.js";
2
2
  import { type RangeKey } from "../contracts/ranges.js";
3
3
  import { type OpenCodeProjectInfo, type OpenCodeRawAssistantRow, type OpenCodeSessionInfo, type OpenCodeSourceIdentity } from "../lib/opencode-storage.js";
4
- export declare const ANALYTICS_SNAPSHOT_VERSION = 3;
4
+ /** 4: compact fingerprints carry unknown-vs-zero cache telemetry (v3 files rebuild). */
5
+ export declare const ANALYTICS_SNAPSHOT_VERSION = 4;
5
6
  export declare const ANALYTICS_SNAPSHOT_SCHEMA = "ocq-analytics-state";
6
7
  /**
7
8
  * Warm DTO aggregation semantics. This is separate from the compact candidate
8
9
  * version because the presentation cache is disposable: a sidecar written
9
10
  * under older semantics (for example before zero-token rows were excluded from
10
11
  * usage rollups, or before exact historical temporal pricing) must be rebuilt,
11
- * not served as if it were current.
12
+ * not served as if it were current. 5 adds recorded-cost fallback provenance to
13
+ * cost totals. 6 adds input-source markers to session steps; older payloads
14
+ * would render without them. 7 places markers by assistant creation time or
15
+ * explicit parent linkage, so 6 payloads can mark a step that was already
16
+ * running when the input arrived.
12
17
  */
13
- export declare const ANALYTICS_PRESENTATION_VERSION = 3;
18
+ export declare const ANALYTICS_PRESENTATION_VERSION = 7;
14
19
  export interface AnalyticsCoverage {
15
20
  /** Inclusive start; absent means the lifetime read reached the beginning. */
16
21
  sinceMs?: number;
@@ -28,7 +33,9 @@ export type CompactFingerprint = [
28
33
  reasoning: number,
29
34
  cacheRead: number,
30
35
  cacheWrite: number,
31
- cost: number | null
36
+ cost: number | null,
37
+ /** Bit 1: cache-read counter was not stored; bit 2: cache-write. 0 = both observed. */
38
+ cacheMissing: number
32
39
  ];
33
40
  /** One physical occurrence of a fingerprint contribution. */
34
41
  export interface Occurrence {
@@ -40,6 +47,8 @@ export interface Occurrence {
40
47
  updatedAtMs: number | null;
41
48
  /** In-memory only: never persisted, so detail-only agents stay transient. */
42
49
  agent?: string;
50
+ /** In-memory only, like `agent`: the recorded reasoning effort for session detail. */
51
+ variant?: string;
43
52
  }
44
53
  /**
45
54
  * In-memory newest session DTOs retained. The serialized sidecar can keep
@@ -101,12 +110,24 @@ export interface AnalyticsState {
101
110
  sourceCursorAtMs?: number;
102
111
  /** Wall time of the last completed full reconciliation (7-day repair). */
103
112
  lastFullRepairAtMs?: number;
113
+ /**
114
+ * Earliest completion time known to be in the future when the last global
115
+ * projection ran. Once wall time reaches it, the signature gate must not skip
116
+ * the read that can finally include the row.
117
+ */
118
+ futureCompletionAtMs?: number;
119
+ /**
120
+ * Cheap source-change signature observed before the read that produced this
121
+ * state. A later refresh with the same signature can skip revision discovery.
122
+ */
123
+ sourceSignature?: string;
104
124
  presentation?: AnalyticsPresentation;
105
125
  }
106
126
  export declare function rowKey(sessionID: string, messageID: string): string;
127
+ /** Contribution identity: the upstream fingerprint plus unknown-vs-zero cache telemetry. */
107
128
  export declare function fingerprintOf(row: OpenCodeRawAssistantRow): string;
108
129
  export declare function compactFingerprintOf(row: OpenCodeRawAssistantRow): CompactFingerprint;
109
- export declare function rowFromFingerprint(fingerprint: CompactFingerprint, occurrence: Pick<Occurrence, "sessionID" | "messageID" | "agent">): OpenCodeRawAssistantRow;
130
+ export declare function rowFromFingerprint(fingerprint: CompactFingerprint, occurrence: Pick<Occurrence, "sessionID" | "messageID" | "agent" | "variant">): OpenCodeRawAssistantRow;
110
131
  interface PersistedAnalyticsStateV3 {
111
132
  version: typeof ANALYTICS_SNAPSHOT_VERSION;
112
133
  schema: typeof ANALYTICS_SNAPSHOT_SCHEMA;
@@ -116,6 +137,10 @@ interface PersistedAnalyticsStateV3 {
116
137
  sourceCursorAtMs: number | null;
117
138
  /** Additive v3 field: absent/null in legacy files means "repair due". */
118
139
  lastFullRepairAtMs: number | null;
140
+ /** Additive v3 field: absent/null means a revision scan is required. */
141
+ sourceSignature: string | null;
142
+ /** Additive v3 field: earliest completion still in the future at projection time. */
143
+ futureCompletionAtMs: number | null;
119
144
  sourceIdentity: SourceIdentityTuple | null;
120
145
  extent: {
121
146
  sinceMs: number | null;
@@ -17,16 +17,21 @@ import { isRangeKey } from "../contracts/ranges.js";
17
17
  import { getOpencodeRuntimeDirs } from "../lib/opencode-runtime-paths.js";
18
18
  import { rawAssistantRowFingerprint, } from "../lib/opencode-storage.js";
19
19
  import { getAnalyticsPricingFingerprint } from "./analytics-pricing-revision.js";
20
- export const ANALYTICS_SNAPSHOT_VERSION = 3;
20
+ /** 4: compact fingerprints carry unknown-vs-zero cache telemetry (v3 files rebuild). */
21
+ export const ANALYTICS_SNAPSHOT_VERSION = 4;
21
22
  export const ANALYTICS_SNAPSHOT_SCHEMA = "ocq-analytics-state";
22
23
  /**
23
24
  * Warm DTO aggregation semantics. This is separate from the compact candidate
24
25
  * version because the presentation cache is disposable: a sidecar written
25
26
  * under older semantics (for example before zero-token rows were excluded from
26
27
  * usage rollups, or before exact historical temporal pricing) must be rebuilt,
27
- * not served as if it were current.
28
+ * not served as if it were current. 5 adds recorded-cost fallback provenance to
29
+ * cost totals. 6 adds input-source markers to session steps; older payloads
30
+ * would render without them. 7 places markers by assistant creation time or
31
+ * explicit parent linkage, so 6 payloads can mark a step that was already
32
+ * running when the input arrived.
28
33
  */
29
- export const ANALYTICS_PRESENTATION_VERSION = 3;
34
+ export const ANALYTICS_PRESENTATION_VERSION = 7;
30
35
  /**
31
36
  * In-memory newest session DTOs retained. The serialized sidecar can keep
32
37
  * fewer because its byte budget is a disk cap, not a heap bound.
@@ -35,8 +40,15 @@ export const ANALYTICS_PRESENTATION_SESSION_LIMIT = 8;
35
40
  export function rowKey(sessionID, messageID) {
36
41
  return `${sessionID}\u0000${messageID}`;
37
42
  }
43
+ function cacheMissingBits(row) {
44
+ return (row.cacheReadMissing ? 1 : 0) | (row.cacheWriteMissing ? 2 : 0);
45
+ }
46
+ /** Contribution identity: the upstream fingerprint plus unknown-vs-zero cache telemetry. */
38
47
  export function fingerprintOf(row) {
39
- return rawAssistantRowFingerprint(row);
48
+ const bits = cacheMissingBits(row);
49
+ return bits === 0
50
+ ? rawAssistantRowFingerprint(row)
51
+ : `${rawAssistantRowFingerprint(row)}|${bits}`;
40
52
  }
41
53
  export function compactFingerprintOf(row) {
42
54
  return [
@@ -50,6 +62,7 @@ export function compactFingerprintOf(row) {
50
62
  row.tokens.cacheRead,
51
63
  row.tokens.cacheWrite,
52
64
  row.cost ?? null,
65
+ cacheMissingBits(row),
53
66
  ];
54
67
  }
55
68
  export function rowFromFingerprint(fingerprint, occurrence) {
@@ -72,8 +85,14 @@ export function rowFromFingerprint(fingerprint, occurrence) {
72
85
  row.modelID = fingerprint[3];
73
86
  if (fingerprint[9] !== null)
74
87
  row.cost = fingerprint[9];
88
+ if (fingerprint[10] & 1)
89
+ row.cacheReadMissing = true;
90
+ if (fingerprint[10] & 2)
91
+ row.cacheWriteMissing = true;
75
92
  if (occurrence.agent !== undefined)
76
93
  row.agent = occurrence.agent;
94
+ if (occurrence.variant !== undefined)
95
+ row.variant = occurrence.variant;
77
96
  return row;
78
97
  }
79
98
  export function encodeAnalyticsState(state, savedAtMs) {
@@ -113,6 +132,8 @@ export function encodeAnalyticsState(state, savedAtMs) {
113
132
  frontierAtMs: state.frontierAtMs,
114
133
  sourceCursorAtMs: state.sourceCursorAtMs ?? null,
115
134
  lastFullRepairAtMs: state.lastFullRepairAtMs ?? null,
135
+ sourceSignature: state.sourceSignature ?? null,
136
+ futureCompletionAtMs: state.futureCompletionAtMs ?? null,
116
137
  sourceIdentity: state.sourceIdentity ? identityToTuple(state.sourceIdentity) : null,
117
138
  extent: state.extent === undefined
118
139
  ? null
@@ -166,7 +187,7 @@ function isStringArray(value) {
166
187
  return Array.isArray(value) && value.every((item) => typeof item === "string");
167
188
  }
168
189
  function isCompactFingerprint(value) {
169
- if (!Array.isArray(value) || value.length !== 10)
190
+ if (!Array.isArray(value) || value.length !== 11)
170
191
  return false;
171
192
  if (!isFiniteNumber(value[0]) || !isFiniteNumber(value[1]))
172
193
  return false;
@@ -176,7 +197,9 @@ function isCompactFingerprint(value) {
176
197
  if (!isFiniteNumber(value[index]))
177
198
  return false;
178
199
  }
179
- return value[9] === null || isFiniteNumber(value[9]);
200
+ if (value[9] !== null && !isFiniteNumber(value[9]))
201
+ return false;
202
+ return value[10] === 0 || value[10] === 1 || value[10] === 2 || value[10] === 3;
180
203
  }
181
204
  function isOccurrenceTuple(value, fingerprintCount) {
182
205
  if (!Array.isArray(value) || value.length !== 4)
@@ -290,6 +313,16 @@ export function decodeAnalyticsState(value) {
290
313
  if (repairValue !== undefined && repairValue !== null && !isFiniteNumber(repairValue)) {
291
314
  return undefined;
292
315
  }
316
+ const signatureValue = record.sourceSignature;
317
+ if (signatureValue !== undefined &&
318
+ signatureValue !== null &&
319
+ (!isStringOrNull(signatureValue) || signatureValue.length === 0 || signatureValue.length > 512)) {
320
+ return undefined;
321
+ }
322
+ const futureValue = record.futureCompletionAtMs;
323
+ if (futureValue !== undefined && futureValue !== null && !isFiniteNumber(futureValue)) {
324
+ return undefined;
325
+ }
293
326
  const identityValue = record.sourceIdentity;
294
327
  if (identityValue !== null &&
295
328
  identityValue !== undefined &&
@@ -383,7 +416,7 @@ export function decodeAnalyticsState(value) {
383
416
  });
384
417
  }
385
418
  const persistedPresentation = record.presentation;
386
- return {
419
+ const state = {
387
420
  sessions,
388
421
  projects,
389
422
  fingerprints,
@@ -408,6 +441,12 @@ export function decodeAnalyticsState(value) {
408
441
  }
409
442
  : {}),
410
443
  };
444
+ if (isStringOrNull(signatureValue) && signatureValue !== null) {
445
+ state.sourceSignature = signatureValue;
446
+ }
447
+ if (isFiniteNumber(futureValue))
448
+ state.futureCompletionAtMs = futureValue;
449
+ return state;
411
450
  }
412
451
  export function defaultAnalyticsSnapshotPath() {
413
452
  return join(getOpencodeRuntimeDirs().stateDir, "opencode-quota-gui", "analytics-v3.json");