@laoyuehanni/dsh-token-usage 0.3.7

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 (215) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +178 -0
  3. package/README.zh.md +182 -0
  4. package/cordis.patch.yml +7 -0
  5. package/lib/client/CostDeltaFlyLabel.d.ts +8 -0
  6. package/lib/client/CostDeltaFlyLabel.d.ts.map +1 -0
  7. package/lib/client/CostDeltaFlyLabel.js +24 -0
  8. package/lib/client/CostDeltaFlyLabel.js.map +1 -0
  9. package/lib/client/HitRateText.d.ts +21 -0
  10. package/lib/client/HitRateText.d.ts.map +1 -0
  11. package/lib/client/HitRateText.js +16 -0
  12. package/lib/client/HitRateText.js.map +1 -0
  13. package/lib/client/QuotaButton.d.ts +70 -0
  14. package/lib/client/QuotaButton.d.ts.map +1 -0
  15. package/lib/client/QuotaButton.js +346 -0
  16. package/lib/client/QuotaButton.js.map +1 -0
  17. package/lib/client/SessionStatsChip.d.ts +47 -0
  18. package/lib/client/SessionStatsChip.d.ts.map +1 -0
  19. package/lib/client/SessionStatsChip.js +141 -0
  20. package/lib/client/SessionStatsChip.js.map +1 -0
  21. package/lib/client/StatCard.d.ts +26 -0
  22. package/lib/client/StatCard.d.ts.map +1 -0
  23. package/lib/client/StatCard.js +10 -0
  24. package/lib/client/StatCard.js.map +1 -0
  25. package/lib/client/TokenUsageCard.d.ts +41 -0
  26. package/lib/client/TokenUsageCard.d.ts.map +1 -0
  27. package/lib/client/TokenUsageCard.js +164 -0
  28. package/lib/client/TokenUsageCard.js.map +1 -0
  29. package/lib/client/TokenUsageSection.d.ts +32 -0
  30. package/lib/client/TokenUsageSection.d.ts.map +1 -0
  31. package/lib/client/TokenUsageSection.js +266 -0
  32. package/lib/client/TokenUsageSection.js.map +1 -0
  33. package/lib/client/TrendChart.d.ts +53 -0
  34. package/lib/client/TrendChart.d.ts.map +1 -0
  35. package/lib/client/TrendChart.js +141 -0
  36. package/lib/client/TrendChart.js.map +1 -0
  37. package/lib/client/UsageView.d.ts +42 -0
  38. package/lib/client/UsageView.d.ts.map +1 -0
  39. package/lib/client/UsageView.js +158 -0
  40. package/lib/client/UsageView.js.map +1 -0
  41. package/lib/client/async-resource.d.ts +54 -0
  42. package/lib/client/async-resource.d.ts.map +1 -0
  43. package/lib/client/async-resource.js +90 -0
  44. package/lib/client/async-resource.js.map +1 -0
  45. package/lib/client/card-form.d.ts +171 -0
  46. package/lib/client/card-form.d.ts.map +1 -0
  47. package/lib/client/card-form.js +300 -0
  48. package/lib/client/card-form.js.map +1 -0
  49. package/lib/client/cost-inflate-motion.d.ts +17 -0
  50. package/lib/client/cost-inflate-motion.d.ts.map +1 -0
  51. package/lib/client/cost-inflate-motion.js +61 -0
  52. package/lib/client/cost-inflate-motion.js.map +1 -0
  53. package/lib/client/cost-inflate.d.ts +28 -0
  54. package/lib/client/cost-inflate.d.ts.map +1 -0
  55. package/lib/client/cost-inflate.js +49 -0
  56. package/lib/client/cost-inflate.js.map +1 -0
  57. package/lib/client/day.d.ts +49 -0
  58. package/lib/client/day.d.ts.map +1 -0
  59. package/lib/client/day.js +84 -0
  60. package/lib/client/day.js.map +1 -0
  61. package/lib/client/format.d.ts +120 -0
  62. package/lib/client/format.d.ts.map +1 -0
  63. package/lib/client/format.js +163 -0
  64. package/lib/client/format.js.map +1 -0
  65. package/lib/client/index.d.ts +26 -0
  66. package/lib/client/index.d.ts.map +1 -0
  67. package/lib/client/index.js +131 -0
  68. package/lib/client/index.js.map +1 -0
  69. package/lib/client/locales.d.ts +131 -0
  70. package/lib/client/locales.d.ts.map +1 -0
  71. package/lib/client/locales.js +230 -0
  72. package/lib/client/locales.js.map +1 -0
  73. package/lib/client/quota-format.d.ts +69 -0
  74. package/lib/client/quota-format.d.ts.map +1 -0
  75. package/lib/client/quota-format.js +147 -0
  76. package/lib/client/quota-format.js.map +1 -0
  77. package/lib/client/session-stats.d.ts +105 -0
  78. package/lib/client/session-stats.d.ts.map +1 -0
  79. package/lib/client/session-stats.js +142 -0
  80. package/lib/client/session-stats.js.map +1 -0
  81. package/lib/client/trend-chart/axis.d.ts +21 -0
  82. package/lib/client/trend-chart/axis.d.ts.map +1 -0
  83. package/lib/client/trend-chart/axis.js +33 -0
  84. package/lib/client/trend-chart/axis.js.map +1 -0
  85. package/lib/client/trend-chart/bucket.d.ts +24 -0
  86. package/lib/client/trend-chart/bucket.d.ts.map +1 -0
  87. package/lib/client/trend-chart/bucket.js +28 -0
  88. package/lib/client/trend-chart/bucket.js.map +1 -0
  89. package/lib/client/trend-chart/index.d.ts +12 -0
  90. package/lib/client/trend-chart/index.d.ts.map +1 -0
  91. package/lib/client/trend-chart/index.js +9 -0
  92. package/lib/client/trend-chart/index.js.map +1 -0
  93. package/lib/client/trend-chart/points.d.ts +46 -0
  94. package/lib/client/trend-chart/points.d.ts.map +1 -0
  95. package/lib/client/trend-chart/points.js +82 -0
  96. package/lib/client/trend-chart/points.js.map +1 -0
  97. package/lib/client/trend-chart/scale.d.ts +47 -0
  98. package/lib/client/trend-chart/scale.d.ts.map +1 -0
  99. package/lib/client/trend-chart/scale.js +75 -0
  100. package/lib/client/trend-chart/scale.js.map +1 -0
  101. package/lib/client/use-color-scheme.d.ts +18 -0
  102. package/lib/client/use-color-scheme.d.ts.map +1 -0
  103. package/lib/client/use-color-scheme.js +37 -0
  104. package/lib/client/use-color-scheme.js.map +1 -0
  105. package/lib/client/use-cost-inflate.d.ts +33 -0
  106. package/lib/client/use-cost-inflate.d.ts.map +1 -0
  107. package/lib/client/use-cost-inflate.js +108 -0
  108. package/lib/client/use-cost-inflate.js.map +1 -0
  109. package/lib/client.js +3892 -0
  110. package/lib/client.js.map +1 -0
  111. package/lib/index.d.ts +132 -0
  112. package/lib/index.d.ts.map +1 -0
  113. package/lib/index.js +599 -0
  114. package/lib/index.js.map +1 -0
  115. package/lib/migrate.d.ts +60 -0
  116. package/lib/migrate.d.ts.map +1 -0
  117. package/lib/migrate.js +126 -0
  118. package/lib/migrate.js.map +1 -0
  119. package/lib/pricing.d.ts +212 -0
  120. package/lib/pricing.d.ts.map +1 -0
  121. package/lib/pricing.js +492 -0
  122. package/lib/pricing.js.map +1 -0
  123. package/lib/quota/adapters/deepseek-balance.d.ts +18 -0
  124. package/lib/quota/adapters/deepseek-balance.d.ts.map +1 -0
  125. package/lib/quota/adapters/deepseek-balance.js +76 -0
  126. package/lib/quota/adapters/deepseek-balance.js.map +1 -0
  127. package/lib/quota/adapters/kimi.d.ts +26 -0
  128. package/lib/quota/adapters/kimi.d.ts.map +1 -0
  129. package/lib/quota/adapters/kimi.js +91 -0
  130. package/lib/quota/adapters/kimi.js.map +1 -0
  131. package/lib/quota/adapters/minimax.d.ts +24 -0
  132. package/lib/quota/adapters/minimax.d.ts.map +1 -0
  133. package/lib/quota/adapters/minimax.js +136 -0
  134. package/lib/quota/adapters/minimax.js.map +1 -0
  135. package/lib/quota/adapters/opencode-go.d.ts +25 -0
  136. package/lib/quota/adapters/opencode-go.d.ts.map +1 -0
  137. package/lib/quota/adapters/opencode-go.js +105 -0
  138. package/lib/quota/adapters/opencode-go.js.map +1 -0
  139. package/lib/quota/adapters/openrouter.d.ts +15 -0
  140. package/lib/quota/adapters/openrouter.d.ts.map +1 -0
  141. package/lib/quota/adapters/openrouter.js +54 -0
  142. package/lib/quota/adapters/openrouter.js.map +1 -0
  143. package/lib/quota/adapters/zhipu.d.ts +38 -0
  144. package/lib/quota/adapters/zhipu.d.ts.map +1 -0
  145. package/lib/quota/adapters/zhipu.js +246 -0
  146. package/lib/quota/adapters/zhipu.js.map +1 -0
  147. package/lib/quota/credentials.d.ts +79 -0
  148. package/lib/quota/credentials.d.ts.map +1 -0
  149. package/lib/quota/credentials.js +130 -0
  150. package/lib/quota/credentials.js.map +1 -0
  151. package/lib/quota/http.d.ts +49 -0
  152. package/lib/quota/http.d.ts.map +1 -0
  153. package/lib/quota/http.js +114 -0
  154. package/lib/quota/http.js.map +1 -0
  155. package/lib/quota/provider-tracking.d.ts +45 -0
  156. package/lib/quota/provider-tracking.d.ts.map +1 -0
  157. package/lib/quota/provider-tracking.js +52 -0
  158. package/lib/quota/provider-tracking.js.map +1 -0
  159. package/lib/quota/quota-route.d.ts +22 -0
  160. package/lib/quota/quota-route.d.ts.map +1 -0
  161. package/lib/quota/quota-route.js +57 -0
  162. package/lib/quota/quota-route.js.map +1 -0
  163. package/lib/quota/quota-service.d.ts +54 -0
  164. package/lib/quota/quota-service.d.ts.map +1 -0
  165. package/lib/quota/quota-service.js +171 -0
  166. package/lib/quota/quota-service.js.map +1 -0
  167. package/lib/quota/registry.d.ts +24 -0
  168. package/lib/quota/registry.d.ts.map +1 -0
  169. package/lib/quota/registry.js +38 -0
  170. package/lib/quota/registry.js.map +1 -0
  171. package/lib/quota/types.d.ts +79 -0
  172. package/lib/quota/types.d.ts.map +1 -0
  173. package/lib/quota/types.js +24 -0
  174. package/lib/quota/types.js.map +1 -0
  175. package/lib/record-cache.d.ts +38 -0
  176. package/lib/record-cache.d.ts.map +1 -0
  177. package/lib/record-cache.js +143 -0
  178. package/lib/record-cache.js.map +1 -0
  179. package/lib/rollup.d.ts +52 -0
  180. package/lib/rollup.d.ts.map +1 -0
  181. package/lib/rollup.js +117 -0
  182. package/lib/rollup.js.map +1 -0
  183. package/lib/stats-route.d.ts +88 -0
  184. package/lib/stats-route.d.ts.map +1 -0
  185. package/lib/stats-route.js +313 -0
  186. package/lib/stats-route.js.map +1 -0
  187. package/lib/stats.d.ts +158 -0
  188. package/lib/stats.d.ts.map +1 -0
  189. package/lib/stats.js +426 -0
  190. package/lib/stats.js.map +1 -0
  191. package/lib/sync-state.d.ts +27 -0
  192. package/lib/sync-state.d.ts.map +1 -0
  193. package/lib/sync-state.js +56 -0
  194. package/lib/sync-state.js.map +1 -0
  195. package/lib/sync.d.ts +74 -0
  196. package/lib/sync.d.ts.map +1 -0
  197. package/lib/sync.js +64 -0
  198. package/lib/sync.js.map +1 -0
  199. package/lib/trend-bucket.d.ts +48 -0
  200. package/lib/trend-bucket.d.ts.map +1 -0
  201. package/lib/trend-bucket.js +87 -0
  202. package/lib/trend-bucket.js.map +1 -0
  203. package/lib/usage-log.d.ts +64 -0
  204. package/lib/usage-log.d.ts.map +1 -0
  205. package/lib/usage-log.js +144 -0
  206. package/lib/usage-log.js.map +1 -0
  207. package/lib/usage-record.d.ts +59 -0
  208. package/lib/usage-record.d.ts.map +1 -0
  209. package/lib/usage-record.js +115 -0
  210. package/lib/usage-record.js.map +1 -0
  211. package/lib/wire.d.ts +452 -0
  212. package/lib/wire.d.ts.map +1 -0
  213. package/lib/wire.js +144 -0
  214. package/lib/wire.js.map +1 -0
  215. package/package.json +100 -0
package/lib/sync.js ADDED
@@ -0,0 +1,64 @@
1
+ /**
2
+ * History sync: replay every persisted session log and append the request
3
+ * rows the log does not already hold, deduped by request id. The sync runs
4
+ * automatically ONCE, on the first startup after installation (gated by the
5
+ * initialized marker).
6
+ *
7
+ * @module token-usage/sync
8
+ */
9
+ import { isInitialized, markInitialized } from "./sync-state.js";
10
+ import { recordFromEvent } from "./usage-record.js";
11
+ /**
12
+ * Append every missing request row. The log's dedupe set is rebuilt from the
13
+ * data files first, so a second run is a no-op and rows recorded live in a
14
+ * previous process are not duplicated.
15
+ * @param deps - persistence and the shared log.
16
+ * @param onTick - optional progress callback; fires once before the first
17
+ * session (with `processed: 0` and the final `total`), then once per session
18
+ * as it finishes. The card passes this to drive its progress bar; the
19
+ * one-shot startup sync omits it.
20
+ * @param signal - cancellation; an aborted run throws `AbortError`.
21
+ */
22
+ export async function syncHistory(deps, onTick, signal) {
23
+ await deps.log.scan();
24
+ const sessions = await deps.persistence.list(signal);
25
+ let added = 0;
26
+ let skipped = 0;
27
+ const total = sessions.length;
28
+ let processed = 0;
29
+ onTick?.({ processed, total, added, skipped });
30
+ for (const session of sessions) {
31
+ signal?.throwIfAborted();
32
+ const inspection = await deps.persistence.inspect(session.id, signal);
33
+ for (const event of inspection.events) {
34
+ signal?.throwIfAborted();
35
+ if (event.type !== 'assistant/message')
36
+ continue;
37
+ const record = recordFromEvent(event, session.id);
38
+ if (await deps.log.record(record))
39
+ added += 1;
40
+ else
41
+ skipped += 1;
42
+ }
43
+ processed += 1;
44
+ onTick?.({ processed, total, added, skipped });
45
+ }
46
+ return { added, skipped };
47
+ }
48
+ /**
49
+ * Run the one-shot automatic sync when the initialized marker is absent, then
50
+ * persist the marker. A crash between the sync and the marker write leaves
51
+ * the marker absent, so the next startup re-runs the sync — a no-op thanks to
52
+ * dedupe.
53
+ * @param deps - persistence and the shared log.
54
+ * @param dir - the data directory holding the marker.
55
+ * @returns the sync outcome, or null when the marker was already present.
56
+ */
57
+ export async function autoSyncIfNeeded(deps, dir) {
58
+ if (await isInitialized(dir))
59
+ return null;
60
+ const result = await syncHistory(deps);
61
+ await markInitialized(dir);
62
+ return result;
63
+ }
64
+ //# sourceMappingURL=sync.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sync.js","sourceRoot":"","sources":["../src/sync.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AAChE,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AA4CnD;;;;;;;;;;GAUG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,IAAc,EACd,MAAyC,EACzC,MAAoB;IAEpB,MAAM,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,CAAA;IACrB,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;IACpD,IAAI,KAAK,GAAG,CAAC,CAAA;IACb,IAAI,OAAO,GAAG,CAAC,CAAA;IACf,MAAM,KAAK,GAAG,QAAQ,CAAC,MAAM,CAAA;IAC7B,IAAI,SAAS,GAAG,CAAC,CAAA;IACjB,MAAM,EAAE,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAA;IAC9C,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAC/B,MAAM,EAAE,cAAc,EAAE,CAAA;QACxB,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,EAAE,MAAM,CAAC,CAAA;QACrE,KAAK,MAAM,KAAK,IAAI,UAAU,CAAC,MAAM,EAAE,CAAC;YACtC,MAAM,EAAE,cAAc,EAAE,CAAA;YACxB,IAAI,KAAK,CAAC,IAAI,KAAK,mBAAmB;gBAAE,SAAQ;YAChD,MAAM,MAAM,GAAG,eAAe,CAAC,KAAK,EAAE,OAAO,CAAC,EAAE,CAAC,CAAA;YACjD,IAAI,MAAM,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC;gBAAE,KAAK,IAAI,CAAC,CAAA;;gBACxC,OAAO,IAAI,CAAC,CAAA;QACnB,CAAC;QACD,SAAS,IAAI,CAAC,CAAA;QACd,MAAM,EAAE,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAA;IAChD,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,CAAA;AAC3B,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAAC,IAAc,EAAE,GAAW;IAChE,IAAI,MAAM,aAAa,CAAC,GAAG,CAAC;QAAE,OAAO,IAAI,CAAA;IACzC,MAAM,MAAM,GAAG,MAAM,WAAW,CAAC,IAAI,CAAC,CAAA;IACtC,MAAM,eAAe,CAAC,GAAG,CAAC,CAAA;IAC1B,OAAO,MAAM,CAAA;AACf,CAAC"}
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Request-series time bucketing shared by the host stats route (wire
3
+ * downsample) and the conversation-view chart. Pure functions, no React,
4
+ * no I/O — the client bundle can inline this module.
5
+ *
6
+ * @module token-usage/trend-bucket
7
+ */
8
+ import type { RequestPoint } from './wire.ts';
9
+ /** One time bucket of the request-mode trend: requests folded by time span. */
10
+ export interface TrendBucket {
11
+ /** Bucket start, wall time. */
12
+ start: number;
13
+ /** Bucket end (exclusive). */
14
+ end: number;
15
+ /** Summed token totals of the requests inside the bucket. */
16
+ tokens: number;
17
+ /** Requests folded into the bucket. */
18
+ count: number;
19
+ }
20
+ /** Render / wire cap: the request trend never draws more points than this. */
21
+ export declare const MAX_BUCKETS = 60;
22
+ /** The bucket width for one span: the finest step whose count fits the cap. */
23
+ export declare function bucketWidth(spanMs: number): number;
24
+ /**
25
+ * Fold a request series into uniformly sized time buckets spanning the
26
+ * series' own first-to-last window. The axis starts at the series' first
27
+ * record, ends at its latest, and the middle is evenly divided — the chart
28
+ * shows the trend over TIME, not one point per request. Buckets align to
29
+ * the window's first record, not to wall-clock round hours.
30
+ *
31
+ * Implementation note: the buckets are tracked in a `Map` keyed by their
32
+ * 0-based index, not in a sparse array. A multi-month session could
33
+ * otherwise blow past V8's sparse-array bounds (the indices approach
34
+ * `spanMs / 5_000` which is unbounded); the Map collapses absent keys
35
+ * cleanly.
36
+ *
37
+ * @param requests - the per-request series, time-ascending.
38
+ * @returns the buckets in time order (empty for an empty series; only
39
+ * buckets holding at least one request are emitted).
40
+ */
41
+ export declare function bucketSeries(requests: readonly RequestPoint[]): TrendBucket[];
42
+ /**
43
+ * Project buckets back onto the wire {@link RequestPoint} shape: `time` is
44
+ * the bucket start, `end` / `count` mark a pre-bucketed point so the chart
45
+ * can plot it without folding again.
46
+ */
47
+ export declare function pointsOfBuckets(buckets: readonly TrendBucket[]): RequestPoint[];
48
+ //# sourceMappingURL=trend-bucket.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trend-bucket.d.ts","sourceRoot":"","sources":["../src/trend-bucket.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,WAAW,CAAA;AAE7C,+EAA+E;AAC/E,MAAM,WAAW,WAAW;IAC1B,+BAA+B;IAC/B,KAAK,EAAE,MAAM,CAAA;IACb,8BAA8B;IAC9B,GAAG,EAAE,MAAM,CAAA;IACX,6DAA6D;IAC7D,MAAM,EAAE,MAAM,CAAA;IACd,uCAAuC;IACvC,KAAK,EAAE,MAAM,CAAA;CACd;AAaD,8EAA8E;AAC9E,eAAO,MAAM,WAAW,KAAK,CAAA;AAE7B,+EAA+E;AAC/E,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAOlD;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,YAAY,CAAC,QAAQ,EAAE,SAAS,YAAY,EAAE,GAAG,WAAW,EAAE,CAwB7E;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,SAAS,WAAW,EAAE,GAAG,YAAY,EAAE,CAO/E"}
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Request-series time bucketing shared by the host stats route (wire
3
+ * downsample) and the conversation-view chart. Pure functions, no React,
4
+ * no I/O — the client bundle can inline this module.
5
+ *
6
+ * @module token-usage/trend-bucket
7
+ */
8
+ /**
9
+ * Bucket widths tried from fine to coarse (ms); the first whose bucket count
10
+ * stays at or under {@link MAX_BUCKETS} wins, so a short session gets
11
+ * fine-grained 5-second buckets and a multi-day session one per several
12
+ * hours — always within the render cap.
13
+ */
14
+ const BUCKET_STEPS_MS = [
15
+ 5_000, 15_000, 60_000, 300_000, 900_000,
16
+ 3_600_000, 10_800_000, 21_600_000, 43_200_000, 86_400_000,
17
+ ];
18
+ /** Render / wire cap: the request trend never draws more points than this. */
19
+ export const MAX_BUCKETS = 60;
20
+ /** The bucket width for one span: the finest step whose count fits the cap. */
21
+ export function bucketWidth(spanMs) {
22
+ for (const step of BUCKET_STEPS_MS) {
23
+ if (Math.ceil(spanMs / step) <= MAX_BUCKETS)
24
+ return step;
25
+ }
26
+ // Beyond the coarsest step (multi-month sessions): keep the cap by
27
+ // aligning a custom width up to the next whole hour.
28
+ return Math.ceil(spanMs / MAX_BUCKETS / 3_600_000) * 3_600_000;
29
+ }
30
+ /**
31
+ * Fold a request series into uniformly sized time buckets spanning the
32
+ * series' own first-to-last window. The axis starts at the series' first
33
+ * record, ends at its latest, and the middle is evenly divided — the chart
34
+ * shows the trend over TIME, not one point per request. Buckets align to
35
+ * the window's first record, not to wall-clock round hours.
36
+ *
37
+ * Implementation note: the buckets are tracked in a `Map` keyed by their
38
+ * 0-based index, not in a sparse array. A multi-month session could
39
+ * otherwise blow past V8's sparse-array bounds (the indices approach
40
+ * `spanMs / 5_000` which is unbounded); the Map collapses absent keys
41
+ * cleanly.
42
+ *
43
+ * @param requests - the per-request series, time-ascending.
44
+ * @returns the buckets in time order (empty for an empty series; only
45
+ * buckets holding at least one request are emitted).
46
+ */
47
+ export function bucketSeries(requests) {
48
+ if (requests.length === 0)
49
+ return [];
50
+ const first = requests[0].time;
51
+ const last = requests[requests.length - 1].time;
52
+ const width = bucketWidth(Math.max(last - first, 1));
53
+ const buckets = new Map();
54
+ for (const request of requests) {
55
+ const index = Math.floor((request.time - first) / width);
56
+ const existing = buckets.get(index);
57
+ if (existing === undefined) {
58
+ buckets.set(index, {
59
+ start: first + index * width,
60
+ end: first + (index + 1) * width,
61
+ tokens: request.tokens,
62
+ count: 1,
63
+ });
64
+ }
65
+ else {
66
+ existing.tokens += request.tokens;
67
+ existing.count += 1;
68
+ }
69
+ }
70
+ return [...buckets.entries()]
71
+ .sort(([left], [right]) => left - right)
72
+ .map(([, bucket]) => bucket);
73
+ }
74
+ /**
75
+ * Project buckets back onto the wire {@link RequestPoint} shape: `time` is
76
+ * the bucket start, `end` / `count` mark a pre-bucketed point so the chart
77
+ * can plot it without folding again.
78
+ */
79
+ export function pointsOfBuckets(buckets) {
80
+ return buckets.map(bucket => ({
81
+ time: bucket.start,
82
+ end: bucket.end,
83
+ tokens: bucket.tokens,
84
+ count: bucket.count,
85
+ }));
86
+ }
87
+ //# sourceMappingURL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-wide request-id dedupe set that
4
+ * both the live hook and the manual sync share.
5
+ *
6
+ * @module token-usage/usage-log
7
+ */
8
+ import { type UsageRecord } from './usage-record.ts';
9
+ declare const DAY_FILE: RegExp;
10
+ /** Test for this store's per-day file names; the migration shares the naming contract. */
11
+ export { DAY_FILE };
12
+ /** Day-file name for a local-time date, e.g. `usage-2026-01-15.jsonl`. */
13
+ export declare function dayFileName(date: Date): string;
14
+ /**
15
+ * Append-only per-day JSONL log with request-id dedupe.
16
+ *
17
+ * Ordering: every append runs on one promise chain, so concurrent callers
18
+ * land in call order. Dedupe: a request id is claimed synchronously before
19
+ * its append is queued; a failed append releases the claim, so the row can
20
+ * be retried later.
21
+ */
22
+ export declare class UsageLog {
23
+ private readonly dir;
24
+ private readonly now;
25
+ private readonly seen;
26
+ private queue;
27
+ private ready;
28
+ /**
29
+ * @param dir - absolute data directory (created lazily on first write).
30
+ * @param now - clock source for day-file selection (test seam).
31
+ */
32
+ constructor(dir: string, now?: () => Date);
33
+ /** Whether a request id is already known to this log. */
34
+ has(requestId: string): boolean;
35
+ /**
36
+ * Settle every queued append. The chain never rejects (each task absorbs
37
+ * its own failure), so this is the quiescence point a data-directory
38
+ * migration waits on before reading the files.
39
+ * @returns settlement after the last queued append.
40
+ */
41
+ flush(): Promise<void>;
42
+ /**
43
+ * Rebuild the dedupe set from every existing day file. Malformed lines are
44
+ * skipped with a console diagnostic; unreadable files are skipped the same
45
+ * way, so a corrupt log never blocks the sync.
46
+ */
47
+ scan(): Promise<void>;
48
+ /**
49
+ * Persist one record unless its request id was already written.
50
+ * @returns true when the row was appended, false when deduped.
51
+ */
52
+ record(record: UsageRecord): Promise<boolean>;
53
+ /** The directory is created once and remembered; an external deletion
54
+ * forces a rebuild on the next append (see {@link appendOnce}). */
55
+ private ensureDir;
56
+ /**
57
+ * Append one row, self-healing once when the directory vanished after the
58
+ * cached creation: the data location may be removed underneath a running
59
+ * process (a migration that stayed behind, a user cleanup), and failing
60
+ * every append forever after would silently drop the whole session's rows.
61
+ */
62
+ private appendOnce;
63
+ }
64
+ //# sourceMappingURL=usage-log.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usage-log.d.ts","sourceRoot":"","sources":["../src/usage-log.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAIH,OAAO,EAAgC,KAAK,WAAW,EAAE,MAAM,mBAAmB,CAAA;AAElF,QAAA,MAAM,QAAQ,QAAsC,CAAA;AAEpD,0FAA0F;AAC1F,OAAO,EAAE,QAAQ,EAAE,CAAA;AAEnB,0EAA0E;AAC1E,wBAAgB,WAAW,CAAC,IAAI,EAAE,IAAI,GAAG,MAAM,CAK9C;AAMD;;;;;;;GAOG;AACH,qBAAa,QAAQ;IAUjB,OAAO,CAAC,QAAQ,CAAC,GAAG;IACpB,OAAO,CAAC,QAAQ,CAAC,GAAG;IAVtB,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAoB;IACzC,OAAO,CAAC,KAAK,CAAmC;IAChD,OAAO,CAAC,KAAK,CAA2B;IAExC;;;OAGG;gBAEgB,GAAG,EAAE,MAAM,EACX,GAAG,GAAE,MAAM,IAAuB;IAGrD,yDAAyD;IACzD,GAAG,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO;IAI/B;;;;;OAKG;IACH,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAItB;;;;OAIG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IA4B3B;;;OAGG;IACH,MAAM,CAAC,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC;IAoB7C;uEACmE;YACrD,SAAS;IAKvB;;;;;OAKG;YACW,UAAU;CAWzB"}
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Durable JSONL store of the token-usage plugin: per-local-day files, a
3
+ * serialized append queue, and the process-wide request-id dedupe set that
4
+ * both the live hook and the manual sync share.
5
+ *
6
+ * @module token-usage/usage-log
7
+ */
8
+ import { appendFile, mkdir, readdir, readFile } from 'node:fs/promises';
9
+ import { join } from 'node:path';
10
+ import { parseRecord, serializeRecord } from "./usage-record.js";
11
+ const DAY_FILE = /^usage-\d{4}-\d{2}-\d{2}\.jsonl$/u;
12
+ /** Test for this store's per-day file names; the migration shares the naming contract. */
13
+ export { DAY_FILE };
14
+ /** Day-file name for a local-time date, e.g. `usage-2026-01-15.jsonl`. */
15
+ export function dayFileName(date) {
16
+ const year = date.getFullYear();
17
+ const month = String(date.getMonth() + 1).padStart(2, '0');
18
+ const day = String(date.getDate()).padStart(2, '0');
19
+ return `usage-${year}-${month}-${day}.jsonl`;
20
+ }
21
+ function dayFilePath(dir, date) {
22
+ return join(dir, dayFileName(date));
23
+ }
24
+ /**
25
+ * Append-only per-day JSONL log with request-id dedupe.
26
+ *
27
+ * Ordering: every append runs on one promise chain, so concurrent callers
28
+ * land in call order. Dedupe: a request id is claimed synchronously before
29
+ * its append is queued; a failed append releases the claim, so the row can
30
+ * be retried later.
31
+ */
32
+ export class UsageLog {
33
+ dir;
34
+ now;
35
+ seen = new Set();
36
+ queue = Promise.resolve();
37
+ ready;
38
+ /**
39
+ * @param dir - absolute data directory (created lazily on first write).
40
+ * @param now - clock source for day-file selection (test seam).
41
+ */
42
+ constructor(dir, now = () => new Date()) {
43
+ this.dir = dir;
44
+ this.now = now;
45
+ }
46
+ /** Whether a request id is already known to this log. */
47
+ has(requestId) {
48
+ return this.seen.has(requestId);
49
+ }
50
+ /**
51
+ * Settle every queued append. The chain never rejects (each task absorbs
52
+ * its own failure), so this is the quiescence point a data-directory
53
+ * migration waits on before reading the files.
54
+ * @returns settlement after the last queued append.
55
+ */
56
+ flush() {
57
+ return this.queue;
58
+ }
59
+ /**
60
+ * Rebuild the dedupe set from every existing day file. Malformed lines are
61
+ * skipped with a console diagnostic; unreadable files are skipped the same
62
+ * way, so a corrupt log never blocks the sync.
63
+ */
64
+ async scan() {
65
+ this.ready ??= mkdir(this.dir, { recursive: true }).then(() => undefined);
66
+ await this.ready;
67
+ let names;
68
+ try {
69
+ names = await readdir(this.dir);
70
+ }
71
+ catch (error) {
72
+ console.error(`[token-usage] cannot list data dir ${this.dir}:`, error);
73
+ return;
74
+ }
75
+ for (const name of names) {
76
+ if (!DAY_FILE.test(name))
77
+ continue;
78
+ const text = await readFile(join(this.dir, name), 'utf8').catch((error) => {
79
+ console.error(`[token-usage] cannot read ${name}:`, error);
80
+ return '';
81
+ });
82
+ for (const line of text.split('\n')) {
83
+ if (line === '')
84
+ continue;
85
+ const record = parseRecord(line);
86
+ if (record === null) {
87
+ console.error(`[token-usage] skipping malformed line in ${name}: ${line.slice(0, 120)}`);
88
+ continue;
89
+ }
90
+ this.seen.add(record.requestId);
91
+ }
92
+ }
93
+ }
94
+ /**
95
+ * Persist one record unless its request id was already written.
96
+ * @returns true when the row was appended, false when deduped.
97
+ */
98
+ record(record) {
99
+ if (this.seen.has(record.requestId))
100
+ return Promise.resolve(false);
101
+ // Claim before queueing: a concurrent call with the same id dedupes here.
102
+ this.seen.add(record.requestId);
103
+ const task = this.queue.then(async () => {
104
+ await this.ensureDir();
105
+ await this.appendOnce(record);
106
+ });
107
+ // A failed append must not poison the chain for later rows.
108
+ this.queue = task.catch(() => { });
109
+ return task
110
+ .then(() => true)
111
+ .catch((error) => {
112
+ // Release the claim so a later sync can retry this row.
113
+ this.seen.delete(record.requestId);
114
+ console.error('[token-usage] append failed:', error);
115
+ return false;
116
+ });
117
+ }
118
+ /** The directory is created once and remembered; an external deletion
119
+ * forces a rebuild on the next append (see {@link appendOnce}). */
120
+ async ensureDir() {
121
+ this.ready ??= mkdir(this.dir, { recursive: true }).then(() => undefined);
122
+ await this.ready;
123
+ }
124
+ /**
125
+ * Append one row, self-healing once when the directory vanished after the
126
+ * cached creation: the data location may be removed underneath a running
127
+ * process (a migration that stayed behind, a user cleanup), and failing
128
+ * every append forever after would silently drop the whole session's rows.
129
+ */
130
+ async appendOnce(record) {
131
+ const path = dayFilePath(this.dir, this.now());
132
+ try {
133
+ await appendFile(path, `${serializeRecord(record)}\n`, { flag: 'a' });
134
+ }
135
+ catch (error) {
136
+ if (error.code !== 'ENOENT')
137
+ throw error;
138
+ this.ready = undefined;
139
+ await this.ensureDir();
140
+ await appendFile(path, `${serializeRecord(record)}\n`, { flag: 'a' });
141
+ }
142
+ }
143
+ }
144
+ //# sourceMappingURL=usage-log.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usage-log.js","sourceRoot":"","sources":["../src/usage-log.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AACvE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EAAE,WAAW,EAAE,eAAe,EAAoB,MAAM,mBAAmB,CAAA;AAElF,MAAM,QAAQ,GAAG,mCAAmC,CAAA;AAEpD,0FAA0F;AAC1F,OAAO,EAAE,QAAQ,EAAE,CAAA;AAEnB,0EAA0E;AAC1E,MAAM,UAAU,WAAW,CAAC,IAAU;IACpC,MAAM,IAAI,GAAG,IAAI,CAAC,WAAW,EAAE,CAAA;IAC/B,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAA;IAC1D,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAA;IACnD,OAAO,SAAS,IAAI,IAAI,KAAK,IAAI,GAAG,QAAQ,CAAA;AAC9C,CAAC;AAED,SAAS,WAAW,CAAC,GAAW,EAAE,IAAU;IAC1C,OAAO,IAAI,CAAC,GAAG,EAAE,WAAW,CAAC,IAAI,CAAC,CAAC,CAAA;AACrC,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,OAAO,QAAQ;IAUA;IACA;IAVF,IAAI,GAAG,IAAI,GAAG,E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I,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,CAAA;YAClC,OAAO,CAAC,KAAK,CAAC,8BAA8B,EAAE,KAAK,CAAC,CAAA;YACpD,OAAO,KAAK,CAAA;QACd,CAAC,CAAC,CAAA;IACN,CAAC;IAED;uEACmE;IAC3D,KAAK,CAAC,SAAS;QACrB,IAAI,CAAC,KAAK,KAAK,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAA;QACzE,MAAM,IAAI,CAAC,KAAK,CAAA;IAClB,CAAC;IAED;;;;;OAKG;IACK,KAAK,CAAC,UAAU,CAAC,MAAmB;QAC1C,MAAM,IAAI,GAAG,WAAW,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC,CAAA;QAC9C,IAAI,CAAC;YACH,MAAM,UAAU,CAAC,IAAI,EAAE,GAAG,eAAe,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,CAAA;QACvE,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAK,KAA+B,CAAC,IAAI,KAAK,QAAQ;gBAAE,MAAM,KAAK,CAAA;YACnE,IAAI,CAAC,KAAK,GAAG,SAAS,CAAA;YACtB,MAAM,IAAI,CAAC,SAAS,EAAE,CAAA;YACtB,MAAM,UAAU,CAAC,IAAI,EAAE,GAAG,eAAe,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,CAAA;QACvE,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Pure record vocabulary of the token-usage plugin: the JSONL row type, its
3
+ * projection from a session event, and lenient line parsing for the dedupe
4
+ * scan. No I/O and no runtime imports, so every consumer shares one wire
5
+ * format. Rows stay minimal: request id, model, the four base token buckets,
6
+ * time, and session id — absent optional buckets are omitted, never null.
7
+ *
8
+ * @module token-usage/usage-record
9
+ */
10
+ import type { TokenUsage } from '@deepseek-ai/dsh-llm';
11
+ import type { SessionEvent } from '@deepseek-ai/dsh-session';
12
+ /** Provider-reported token buckets; absent optional buckets are omitted. */
13
+ export interface UsageFields {
14
+ /** Uncached input tokens (billed input = this + cacheRead + cacheWrite). */
15
+ inputTokens: number;
16
+ /** Output tokens. */
17
+ outputTokens: number;
18
+ /** Cache-hit input tokens; omitted when the provider reported none. */
19
+ cacheReadTokens?: number;
20
+ /** Cache-write input tokens; omitted when the provider reported none. */
21
+ cacheWriteTokens?: number;
22
+ }
23
+ /** One JSONL row: one successful model request. */
24
+ export interface UsageRecord {
25
+ /** Stable request identity: the assistant message id (dedupe key). */
26
+ requestId: string;
27
+ /** Session-event wall time, epoch milliseconds. */
28
+ time: number;
29
+ /** Owning session id. */
30
+ sessionId: string;
31
+ /** Provider model id that produced the message. */
32
+ model: string;
33
+ /** Token buckets; omitted when the provider reported no usage at all. */
34
+ usage?: UsageFields;
35
+ }
36
+ /**
37
+ * Project the event's optional provider usage into the four base buckets.
38
+ * A missing record or an invalid required bucket renders the whole usage
39
+ * absent: the row still records the request, but its numbers are not trusted.
40
+ */
41
+ export declare function projectUsage(usage: TokenUsage | undefined): UsageFields | undefined;
42
+ /** Build the log row for one assistant/message session event. */
43
+ export declare function recordFromEvent(event: SessionEvent<'assistant/message'>, sessionId: string): UsageRecord;
44
+ /** One JSONL line without the trailing newline. */
45
+ export declare function serializeRecord(record: UsageRecord): string;
46
+ /**
47
+ * Coerce an unknown value into a record, normalizing extra fields and null
48
+ * buckets to omission, so rows written by older field sets still dedupe
49
+ * (their request id is absorbed) without being rewritten.
50
+ * @returns the record, or null when the value is not a valid row.
51
+ */
52
+ export declare function coerceRecord(value: unknown): UsageRecord | null;
53
+ /**
54
+ * Parse one JSONL line back into a record. Extra fields are ignored and null
55
+ * buckets are normalized to omission (see {@link coerceRecord}).
56
+ * @returns the record, or null when the line is not a valid row.
57
+ */
58
+ export declare function parseRecord(line: string): UsageRecord | null;
59
+ //# sourceMappingURL=usage-record.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usage-record.d.ts","sourceRoot":"","sources":["../src/usage-record.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAA;AACtD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAA;AAE5D,4EAA4E;AAC5E,MAAM,WAAW,WAAW;IAC1B,4EAA4E;IAC5E,WAAW,EAAE,MAAM,CAAA;IACnB,qBAAqB;IACrB,YAAY,EAAE,MAAM,CAAA;IACpB,uEAAuE;IACvE,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,yEAAyE;IACzE,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAC1B;AAED,mDAAmD;AACnD,MAAM,WAAW,WAAW;IAC1B,sEAAsE;IACtE,SAAS,EAAE,MAAM,CAAA;IACjB,mDAAmD;IACnD,IAAI,EAAE,MAAM,CAAA;IACZ,yBAAyB;IACzB,SAAS,EAAE,MAAM,CAAA;IACjB,mDAAmD;IACnD,KAAK,EAAE,MAAM,CAAA;IACb,yEAAyE;IACzE,KAAK,CAAC,EAAE,WAAW,CAAA;CACpB;AAMD;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,UAAU,GAAG,SAAS,GAAG,WAAW,GAAG,SAAS,CASnF;AAED,iEAAiE;AACjE,wBAAgB,eAAe,CAC7B,KAAK,EAAE,YAAY,CAAC,mBAAmB,CAAC,EACxC,SAAS,EAAE,MAAM,GAChB,WAAW,CASb;AAED,mDAAmD;AACnD,wBAAgB,eAAe,CAAC,MAAM,EAAE,WAAW,GAAG,MAAM,CAE3D;AAsBD;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,WAAW,GAAG,IAAI,CA2B/D;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,IAAI,CAS5D"}
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Pure record vocabulary of the token-usage plugin: the JSONL row type, its
3
+ * projection from a session event, and lenient line parsing for the dedupe
4
+ * scan. No I/O and no runtime imports, so every consumer shares one wire
5
+ * format. Rows stay minimal: request id, model, the four base token buckets,
6
+ * time, and session id — absent optional buckets are omitted, never null.
7
+ *
8
+ * @module token-usage/usage-record
9
+ */
10
+ function isCount(value) {
11
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0;
12
+ }
13
+ /**
14
+ * Project the event's optional provider usage into the four base buckets.
15
+ * A missing record or an invalid required bucket renders the whole usage
16
+ * absent: the row still records the request, but its numbers are not trusted.
17
+ */
18
+ export function projectUsage(usage) {
19
+ if (usage === undefined)
20
+ return undefined;
21
+ if (!isCount(usage.inputTokens) || !isCount(usage.outputTokens))
22
+ return undefined;
23
+ return {
24
+ inputTokens: usage.inputTokens,
25
+ outputTokens: usage.outputTokens,
26
+ ...(isCount(usage.cacheReadTokens) ? { cacheReadTokens: usage.cacheReadTokens } : {}),
27
+ ...(isCount(usage.cacheWriteTokens) ? { cacheWriteTokens: usage.cacheWriteTokens } : {}),
28
+ };
29
+ }
30
+ /** Build the log row for one assistant/message session event. */
31
+ export function recordFromEvent(event, sessionId) {
32
+ const usage = projectUsage(event.data.usage);
33
+ return {
34
+ requestId: event.data.message.id,
35
+ time: event.time,
36
+ sessionId,
37
+ model: event.data.message.source.model,
38
+ ...(usage !== undefined ? { usage } : {}),
39
+ };
40
+ }
41
+ /** One JSONL line without the trailing newline. */
42
+ export function serializeRecord(record) {
43
+ return JSON.stringify(record);
44
+ }
45
+ function normalizeCount(value) {
46
+ return isCount(value) ? value : undefined;
47
+ }
48
+ function isUsageFields(value) {
49
+ if (typeof value !== 'object' || value === null)
50
+ return false;
51
+ const fields = value;
52
+ return isCount(fields.inputTokens) && isCount(fields.outputTokens);
53
+ }
54
+ function isRecord(value) {
55
+ if (typeof value !== 'object' || value === null)
56
+ return false;
57
+ const record = value;
58
+ return typeof record.requestId === 'string'
59
+ && isCount(record.time)
60
+ && typeof record.sessionId === 'string'
61
+ && typeof record.model === 'string'
62
+ && (record.usage === undefined || record.usage === null || isUsageFields(record.usage));
63
+ }
64
+ /**
65
+ * Coerce an unknown value into a record, normalizing extra fields and null
66
+ * buckets to omission, so rows written by older field sets still dedupe
67
+ * (their request id is absorbed) without being rewritten.
68
+ * @returns the record, or null when the value is not a valid row.
69
+ */
70
+ export function coerceRecord(value) {
71
+ if (!isRecord(value))
72
+ return null;
73
+ // The guard already validated the structure; this cast only enables field access.
74
+ const record = value;
75
+ if (record.usage === undefined || record.usage === null) {
76
+ return {
77
+ requestId: record.requestId,
78
+ time: record.time,
79
+ sessionId: record.sessionId,
80
+ model: record.model,
81
+ };
82
+ }
83
+ const fields = record.usage;
84
+ const cacheRead = normalizeCount(fields.cacheReadTokens);
85
+ const cacheWrite = normalizeCount(fields.cacheWriteTokens);
86
+ return {
87
+ requestId: record.requestId,
88
+ time: record.time,
89
+ sessionId: record.sessionId,
90
+ model: record.model,
91
+ usage: {
92
+ inputTokens: fields.inputTokens,
93
+ outputTokens: fields.outputTokens,
94
+ ...(cacheRead !== undefined ? { cacheReadTokens: cacheRead } : {}),
95
+ ...(cacheWrite !== undefined ? { cacheWriteTokens: cacheWrite } : {}),
96
+ },
97
+ };
98
+ }
99
+ /**
100
+ * Parse one JSONL line back into a record. Extra fields are ignored and null
101
+ * buckets are normalized to omission (see {@link coerceRecord}).
102
+ * @returns the record, or null when the line is not a valid row.
103
+ */
104
+ export function parseRecord(line) {
105
+ let value;
106
+ try {
107
+ value = JSON.parse(line);
108
+ }
109
+ catch {
110
+ // JSON.parse throws SyntaxError on malformed lines; the caller skips the line.
111
+ return null;
112
+ }
113
+ return coerceRecord(value);
114
+ }
115
+ //# sourceMappingURL=usage-record.js.map
@@ -0,0 +1 @@
1
+ {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