@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
@@ -0,0 +1,313 @@
1
+ /**
2
+ * The stats HTTP route of the token-usage plugin: a webServer exact route
3
+ * serving the JSON summary at `/token-usage/stats` for the web settings page.
4
+ * The /api prefix is owned by the browser-transport connection plugin and its
5
+ * RPC method table is closed, so the plugin data channel is its own route.
6
+ *
7
+ * @module token-usage/stats-route
8
+ */
9
+ import { readPricingTable, readUsdExchangeRate, resolveRate } from "./pricing.js";
10
+ import { attachCosts, buildSummary, filterRecordsBySessions, filterSummary, requestSeriesOf, summarizeRecords } from "./stats.js";
11
+ import { readCachedRecords } from "./record-cache.js";
12
+ import { bucketSeries, pointsOfBuckets } from "./trend-bucket.js";
13
+ import { decodeChildGroups, decodeSessionScope, DIR_GUARD_PATH, FULL_SYNC_PATH, MIGRATION_PATH, STATS_PATH, UNPRICED_KEY } from "./wire.js";
14
+ /** The stats endpoint path, exported for tests and the client half. */
15
+ export { STATS_PATH } from "./wire.js";
16
+ /** The migration-progress endpoint path, exported for the client half. */
17
+ export { MIGRATION_PATH } from "./wire.js";
18
+ /** The directory-guard endpoint path, exported for the client half. */
19
+ export { DIR_GUARD_PATH } from "./wire.js";
20
+ /** The full-sync endpoint path, exported for the client half. */
21
+ export { FULL_SYNC_PATH } from "./wire.js";
22
+ /** A day query key must be exactly `YYYY-MM-DD`. */
23
+ const DAY_KEY = /^\d{4}-\d{2}-\d{2}$/u;
24
+ /** Read the filter query parameters off the request URL. */
25
+ function readFilters(req) {
26
+ const params = new URL(req.url ?? '/', 'http://localhost').searchParams;
27
+ const pick = (key) => {
28
+ const value = params.get(key);
29
+ return value === null || value === '' ? undefined : value;
30
+ };
31
+ const fields = pick('fields');
32
+ return {
33
+ from: pick('from'),
34
+ to: pick('to'),
35
+ model: pick('model'),
36
+ sessionIds: decodeSessionScope(params),
37
+ childGroups: decodeChildGroups(params),
38
+ fields: fields === 'chip' || fields === 'session' ? fields : 'full',
39
+ };
40
+ }
41
+ /** Whether every present day key is well-formed and ordered. */
42
+ function isValidRange(filter) {
43
+ if (filter.from !== undefined && !DAY_KEY.test(filter.from))
44
+ return false;
45
+ if (filter.to !== undefined && !DAY_KEY.test(filter.to))
46
+ return false;
47
+ if (filter.from !== undefined && filter.to !== undefined && filter.from > filter.to)
48
+ return false;
49
+ return true;
50
+ }
51
+ /**
52
+ * Whether a request may read the stats: same-origin browser fetches only.
53
+ * Browsers send `Sec-Fetch-Site` on cross-origin requests; a cross-site value
54
+ * (or a cross-site GET from a page on another origin) is refused. The header
55
+ * is absent for non-browser clients (curl, tests), which are allowed.
56
+ * @param req - the incoming request.
57
+ * @returns whether the request originates from the served page.
58
+ */
59
+ export function isSameOriginFetch(req) {
60
+ const site = req.headers['sec-fetch-site'];
61
+ if (site === undefined)
62
+ return true;
63
+ return site === 'same-origin' || site === 'none';
64
+ }
65
+ /**
66
+ * Build the migration-progress route the browser card polls while a move
67
+ * runs. Read-only by construction: it answers the shared status object and
68
+ * nothing else.
69
+ * @param status - reads the live migration state.
70
+ * @returns the exact GET route answering the progress JSON.
71
+ */
72
+ export function createMigrationRoute(status) {
73
+ return {
74
+ kind: 'exact',
75
+ path: MIGRATION_PATH,
76
+ handler: (req, res) => {
77
+ if (req.method !== 'GET') {
78
+ res.writeHead(405, { 'content-type': 'text/plain; charset=utf-8' });
79
+ res.end('method not allowed');
80
+ return;
81
+ }
82
+ if (!isSameOriginFetch(req)) {
83
+ res.writeHead(403, { 'content-type': 'text/plain; charset=utf-8' });
84
+ res.end('forbidden');
85
+ return;
86
+ }
87
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
88
+ res.end(JSON.stringify(status() ?? null));
89
+ },
90
+ };
91
+ }
92
+ /**
93
+ * Build the directory-guard route the browser card consults before saving a
94
+ * staged directory edit: the settings wire never delivers a refused write's
95
+ * reason, so the card asks here whether the save would be refused and shows
96
+ * the verdict's count itself. Read-only by construction: it answers the
97
+ * caller's judge verdict and writes nothing.
98
+ * @param judge - answers the verdict for one proposed stored path
99
+ * (`undefined` when the save would clear the override).
100
+ * @returns the exact GET route answering the verdict JSON.
101
+ */
102
+ export function createDirectoryGuardRoute(judge) {
103
+ return {
104
+ kind: 'exact',
105
+ path: DIR_GUARD_PATH,
106
+ handler: (req, res) => {
107
+ if (req.method !== 'GET') {
108
+ res.writeHead(405, { 'content-type': 'text/plain; charset=utf-8' });
109
+ res.end('method not allowed');
110
+ return;
111
+ }
112
+ if (!isSameOriginFetch(req)) {
113
+ res.writeHead(403, { 'content-type': 'text/plain; charset=utf-8' });
114
+ res.end('forbidden');
115
+ return;
116
+ }
117
+ const params = new URL(req.url ?? '/', 'http://localhost').searchParams;
118
+ const raw = params.get('path');
119
+ // A blank path is the clear-back-to-default gesture, not a stored ''.
120
+ const proposed = raw === null || raw === '' ? undefined : raw;
121
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
122
+ res.end(JSON.stringify(judge(proposed)));
123
+ },
124
+ };
125
+ }
126
+ /**
127
+ * Build the full-sync route backing the card's manual "scan again" button.
128
+ * The handler is small by design: it only owns the request/response shape
129
+ * (GET polls the live status, POST kicks off a run). The actual scan lives
130
+ * on the host half and updates the shared status object, which `status()`
131
+ * reads. The scan is fire-and-forget on POST so the request never blocks
132
+ * behind a long walk; the card polls until the status leaves `running`.
133
+ * @param status - reads the shared status (the same view the card renders).
134
+ * @param trigger - kicks off a new run when the host is idle.
135
+ * @returns the exact route serving both methods.
136
+ */
137
+ export function createFullSyncRoute(status, trigger) {
138
+ return {
139
+ kind: 'exact',
140
+ path: FULL_SYNC_PATH,
141
+ handler: (req, res) => {
142
+ if (!isSameOriginFetch(req)) {
143
+ res.writeHead(403, { 'content-type': 'text/plain; charset=utf-8' });
144
+ res.end('forbidden');
145
+ return;
146
+ }
147
+ if (req.method === 'GET') {
148
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
149
+ res.end(JSON.stringify(status()));
150
+ return;
151
+ }
152
+ if (req.method === 'POST') {
153
+ const result = trigger();
154
+ if (!result.started) {
155
+ res.writeHead(409, { 'content-type': 'application/json; charset=utf-8' });
156
+ res.end(JSON.stringify({ error: result.reason }));
157
+ return;
158
+ }
159
+ res.writeHead(202, { 'content-type': 'application/json; charset=utf-8' });
160
+ res.end(JSON.stringify({ status: 'running' }));
161
+ return;
162
+ }
163
+ res.writeHead(405, { 'content-type': 'text/plain; charset=utf-8' });
164
+ res.end('method not allowed');
165
+ },
166
+ };
167
+ }
168
+ /** Fold one child group into the slim row the usage tab's subagent table reads. */
169
+ function childBreakdown(records, filter, dataDir, resolve, pricing) {
170
+ const rows = {};
171
+ for (const group of filter.childGroups) {
172
+ const scoped = filterRecordsBySessions(records, group.sessionIds);
173
+ const summary = attachCosts(filterSummary({ dataDir, ...summarizeRecords(scoped, resolve) }, filter.from, filter.to, filter.model), pricing);
174
+ rows[group.id] = {
175
+ total: summary.total,
176
+ totalCost: summary.totalCost,
177
+ unpricedModels: summary.unpricedModels,
178
+ };
179
+ }
180
+ return rows;
181
+ }
182
+ /** Session-scoped wire shape: `full` keeps the CostedSummary; `session` /
183
+ * `chip` drop the unused pricing / rate / recent / hour layers, and
184
+ * `session` sends a pre-bucketed request series (≤ 60 points). */
185
+ function slimSessionPayload(input) {
186
+ const { summary, sessionIds, series, currency, usdExchangeRate, fields, children } = input;
187
+ const requestSeries = fields === 'session' ? pointsOfBuckets(bucketSeries(series)) : [...series];
188
+ const full = {
189
+ ...summary,
190
+ scope: 'session',
191
+ sessionIds,
192
+ requestSeries,
193
+ currency,
194
+ usdExchangeRate,
195
+ ...children !== undefined ? { children } : {},
196
+ };
197
+ if (fields === 'full')
198
+ return full;
199
+ const chip = {
200
+ scope: 'session',
201
+ sessionIds,
202
+ total: summary.total,
203
+ totalCost: summary.totalCost,
204
+ unpricedModels: summary.unpricedModels,
205
+ currency,
206
+ usdExchangeRate,
207
+ ...children !== undefined ? { children } : {},
208
+ };
209
+ if (fields === 'chip')
210
+ return chip;
211
+ return {
212
+ ...chip,
213
+ byModel: summary.byModel,
214
+ byDay: summary.byDay,
215
+ requestSeries,
216
+ };
217
+ }
218
+ /**
219
+ * Build the stats route over a data directory the caller may relocate live.
220
+ * @param dir - reads the directory currently in force (per request, so a
221
+ * settings-driven move starts answering from the new location at once).
222
+ * @param options - the currency thunk; defaults to CNY (the domestic default).
223
+ * @returns the exact GET route serving the JSON summary.
224
+ */
225
+ export function createStatsRoute(dir, options = {}) {
226
+ return {
227
+ kind: 'exact',
228
+ path: STATS_PATH,
229
+ handler: async (req, res) => {
230
+ if (req.method !== 'GET') {
231
+ res.writeHead(405, { 'content-type': 'text/plain; charset=utf-8' });
232
+ res.end('method not allowed');
233
+ return;
234
+ }
235
+ if (!isSameOriginFetch(req)) {
236
+ res.writeHead(403, { 'content-type': 'text/plain; charset=utf-8' });
237
+ res.end('forbidden');
238
+ return;
239
+ }
240
+ const filter = readFilters(req);
241
+ if (!isValidRange(filter)) {
242
+ res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' });
243
+ res.end('invalid filter');
244
+ return;
245
+ }
246
+ try {
247
+ const dataDir = dir();
248
+ // The pricing table is user-maintained and may change between
249
+ // requests; reading it per request keeps the page honest without
250
+ // any caching (the file is small and the route is not hot).
251
+ const pricing = await readPricingTable(dataDir);
252
+ // Per-record pricing: each record resolves through the rule chain at
253
+ // its own timestamp (tier approximated by its input-side tokens).
254
+ const resolve = record => {
255
+ const rules = pricing[record.model];
256
+ if (rules === undefined)
257
+ return UNPRICED_KEY;
258
+ const tokens = record.usage;
259
+ const context = tokens === undefined ? 0
260
+ : tokens.inputTokens + (tokens.cacheReadTokens ?? 0) + (tokens.cacheWriteTokens ?? 0);
261
+ return resolveRate(rules, record.time, context).key;
262
+ };
263
+ // Session-scoped reads fold filtered raw records: the rollup rows
264
+ // carry no session dimension. Frozen day files come from the
265
+ // process cache so chip polls and the usage tab do not re-parse
266
+ // history; today's file re-reads when its stamp changes.
267
+ const allRecords = filter.sessionIds.length > 0 || filter.childGroups.length > 0
268
+ ? await readCachedRecords(dataDir)
269
+ : undefined;
270
+ const scoped = filter.sessionIds.length > 0 && allRecords !== undefined
271
+ ? filterRecordsBySessions(allRecords, filter.sessionIds)
272
+ : undefined;
273
+ const summary = attachCosts(filterSummary(scoped !== undefined
274
+ ? { dataDir, ...summarizeRecords(scoped, resolve) }
275
+ : await buildSummary(dataDir, undefined, resolve), filter.from, filter.to, filter.model), pricing);
276
+ // Display-currency metadata: amounts stay RMB on the wire; the
277
+ // page converts (÷ usdExchangeRate) when the region pick says USD.
278
+ const currency = options.currency?.() ?? 'CNY';
279
+ const usdExchangeRate = await readUsdExchangeRate(dataDir);
280
+ const children = allRecords !== undefined && filter.childGroups.length > 0
281
+ ? childBreakdown(allRecords, filter, dataDir, resolve, pricing)
282
+ : undefined;
283
+ const payload = scoped !== undefined
284
+ ? slimSessionPayload({
285
+ summary,
286
+ sessionIds: filter.sessionIds,
287
+ series: requestSeriesOf(scoped, filter.from, filter.to, filter.model),
288
+ currency,
289
+ usdExchangeRate,
290
+ fields: filter.fields,
291
+ children,
292
+ })
293
+ : {
294
+ ...summary,
295
+ scope: 'whole',
296
+ currency,
297
+ usdExchangeRate,
298
+ };
299
+ res.writeHead(200, {
300
+ 'content-type': 'application/json; charset=utf-8',
301
+ // Stats change with every request; the browser must not cache them.
302
+ 'cache-control': 'no-store',
303
+ });
304
+ res.end(JSON.stringify(payload));
305
+ }
306
+ catch (error) {
307
+ res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' });
308
+ res.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }));
309
+ }
310
+ },
311
+ };
312
+ }
313
+ //# sourceMappingURL=stats-route.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stats-route.js","sourceRoot":"","sources":["../src/stats-route.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAKH,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;AACjF,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,uBAAuB,EAAE,aAAa,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAEjI,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAA;AACrD,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AACjE,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,cAAc,EAAE,cAAc,EAAE,cAAc,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,WAAW,CAAA;AAI3I,uEAAuE;AACvE,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAA;AAEtC,0EAA0E;AAC1E,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAA;AAE1C,uEAAuE;AACvE,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAA;AAE1C,iEAAiE;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAA;AAE1C,oDAAoD;AACpD,MAAM,OAAO,GAAG,sBAAsB,CAAA;AAiBtC,4DAA4D;AAC5D,SAAS,WAAW,CAAC,GAAoB;IACvC,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,GAAG,IAAI,GAAG,EAAE,kBAAkB,CAAC,CAAC,YAAY,CAAA;IAC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e;qBACO,CAAA;gBAC1B,GAAG,CAAC,SAAS,CAAC,GAAG,EAAE;oBACjB,cAAc,EAAE,iCAAiC;oBACjD,oEAAoE;oBACpE,eAAe,EAAE,UAAU;iBAC5B,CAAC,CAAA;gBACF,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAA;YAClC,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,GAAG,CAAC,SAAS,CAAC,GAAG,EAAE,EAAE,cAAc,EAAE,iCAAiC,EAAE,CAAC,CAAA;gBACzE,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAA;YAC5F,CAAC;QACH,CAAC;KACF,CAAA;AACH,CAAC"}
package/lib/stats.d.ts ADDED
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Stats computation of the token-usage plugin: read the day files and fold
3
+ * the records into totals, per-day rows, per-model rows, and a bounded recent
4
+ * window — keeping one row per (day, model, rate identity) so every record
5
+ * is billed at the rate its own timestamp resolved through (see
6
+ * pricing.resolveRate). Frozen (pre-today) day files are served from the
7
+ * on-disk rollup (see rollup.ts); only today's file is read on every call.
8
+ * Pure aggregation lives apart from the file walk so the web route and tests
9
+ * share one implementation.
10
+ *
11
+ * @module token-usage/stats
12
+ */
13
+ import type { UsageRecord } from './usage-record.ts';
14
+ import type { CostedSummary, PricingTable, RateKey, RequestPoint, TokenSummary, UsageTotals } from './wire.ts';
15
+ /** Bounded recent window length: only the newest records cross the wire. */
16
+ export declare const RECENT_LIMIT = 20;
17
+ /**
18
+ * Resolves the rate identity one record was billed at. The route builds this
19
+ * from the pricing table (pricing.resolveRate over the record's model, time,
20
+ * and input-side tokens); the neutral default leaves every record unpriced.
21
+ */
22
+ export type RateResolver = (record: UsageRecord) => RateKey;
23
+ /** Zeroed totals; requests counts rows, the token buckets sum reported usage. */
24
+ export declare function emptyTotals(): UsageTotals;
25
+ /**
26
+ * Fold records into the token summary shape, one rate row per (day, model,
27
+ * rate identity) the resolver assigns. The recent window keeps the last
28
+ * {@link RECENT_LIMIT} records in input order (day files are chronological)
29
+ * and then sorts them by time descending.
30
+ * @param records - parsed records in day-file order.
31
+ * @param resolve - the rate resolver; defaults to leaving every record unpriced.
32
+ * @returns totals, day rows, model rows, rate rows, and the recent window.
33
+ */
34
+ export declare function summarizeRecords(records: readonly UsageRecord[], resolve?: RateResolver): TokenSummary;
35
+ /**
36
+ * Keep only the records owned by one of the listed sessions. The rollup
37
+ * carries no session dimension (its rows are (day, model, rate) cells), so a
38
+ * session-scoped read cannot reuse it and must fold the filtered raw records
39
+ * instead — cheap in practice (the JSONL day files are a few hundred KB) and
40
+ * only triggered by per-session fetches (view switches), never the settings
41
+ * page's whole-log read.
42
+ * @param records - parsed records in day-file order.
43
+ * @param sessionIds - the sessions whose requests stay; [] yields no records.
44
+ * @returns the records owned by those sessions, in the original order.
45
+ */
46
+ export declare function filterRecordsBySessions(records: readonly UsageRecord[], sessionIds: readonly string[]): UsageRecord[];
47
+ /** Inclusive day-range bounds derived from optional day keys; the window
48
+ * covers `[from 00:00, to 23:59:59.999]` local time on the boundary days. */
49
+ export interface DayRangeFilter {
50
+ /** Inclusive lower bound, epoch ms; undefined when unconstrained. */
51
+ start?: number;
52
+ /** Inclusive upper bound (with the day's millisecond span folded in), epoch ms. */
53
+ end?: number;
54
+ /** Exact model id; undefined matches any model. */
55
+ model?: string;
56
+ }
57
+ /**
58
+ * Derive the half-open day-range bounds from optional `YYYY-MM-DD` keys. A
59
+ * missing key leaves that side unbounded; the upper bound inherits the day's
60
+ * full millisecond span (the day-key convention used everywhere else).
61
+ * @param from - first day key (`YYYY-MM-DD`), inclusive; '' ignores both ends.
62
+ * @param to - last day key (`YYYY-MM-DD`), inclusive.
63
+ * @param model - exact model id; undefined matches any model.
64
+ * @returns the bounds (every field may be undefined).
65
+ */
66
+ export declare function dayRangeFilter(from?: string, to?: string, model?: string): DayRangeFilter;
67
+ /**
68
+ * Combine a day-range filter with a session-id filter. The session ids are
69
+ * applied first (cheap, preroll), the day-range second (per-record); the
70
+ * model id, if any, is per-record too. Returns the records passing both.
71
+ * @param records - parsed records in chronological order.
72
+ * @param sessions - the session ids whose records stay; undefined skips that
73
+ * dimension.
74
+ * @param range - the day-range + model filter; undefined skips every dimension.
75
+ */
76
+ export declare function filterRecordsByRange(records: readonly UsageRecord[], sessions: readonly string[] | undefined, range?: DayRangeFilter): UsageRecord[];
77
+ /**
78
+ * The per-request token series of a record set, in time order — one point
79
+ * per request, so a 55-request session plots 55 points. The conversation
80
+ * view tab draws this at request granularity; the settings page's hourly
81
+ * aggregation is unchanged (this field is session-scope only).
82
+ * @param records - the scoped records (day-file order is chronological).
83
+ * @param from - optional inclusive day key; the series keeps those requests.
84
+ * @param to - optional inclusive day key.
85
+ * @param model - optional exact model id.
86
+ * @returns one point per kept request, in the original time order.
87
+ */
88
+ export declare function requestSeriesOf(records: readonly UsageRecord[], from?: string, to?: string, model?: string): RequestPoint[];
89
+ /**
90
+ * Merge two summaries into one: totals and model rows add up, day rows fold
91
+ * by day key (a same-day record set landing in a later file must join the
92
+ * earlier bucket, never replace it), rate rows fold by their (day, model,
93
+ * rate) key, and the recent window keeps the newest {@link RECENT_LIMIT}
94
+ * records across both sides. Order-independent and associative: merging
95
+ * partial summaries equals summarizing the concatenated records.
96
+ * @param left - one partial summary.
97
+ * @param right - the other partial summary.
98
+ * @returns the folded summary.
99
+ */
100
+ export declare function mergeSummaries(left: TokenSummary, right: TokenSummary): TokenSummary;
101
+ /**
102
+ * Re-aggregate a summary under an optional inclusive day range and model
103
+ * filter, drawing every dimension from the rate rows so no file is reread.
104
+ * The recent window filters on its record timestamps
105
+ * ([from 00:00, to 23:59:59.999] local). No filters returns the input as-is.
106
+ * @param summary - the unfiltered summary.
107
+ * @param from - first day key (`YYYY-MM-DD`), inclusive.
108
+ * @param to - last day key (`YYYY-MM-DD`), inclusive.
109
+ * @param model - exact model id.
110
+ * @returns the filtered summary.
111
+ */
112
+ export declare function filterSummary(summary: TokenSummary & {
113
+ dataDir: string;
114
+ }, from?: string, to?: string, model?: string): TokenSummary & {
115
+ dataDir: string;
116
+ };
117
+ /**
118
+ * Attach the cost layer to a token-only summary: each rate row is priced at
119
+ * the prices its rate identity resolves to under the current table, folded
120
+ * into per-model costs, the total, the unpriced model list, and the table
121
+ * itself. Purely additive — totals, day rows, and the recent window are
122
+ * returned untouched, so the token aggregation (and the rollup format)
123
+ * never carries currency, and an updated table re-prices history for free.
124
+ * @param summary - the aggregated summary (build or filtered).
125
+ * @param pricing - the active pricing table.
126
+ * @returns the same summary plus the cost fields.
127
+ */
128
+ export declare function attachCosts(summary: TokenSummary & {
129
+ dataDir: string;
130
+ }, pricing: PricingTable): CostedSummary;
131
+ /**
132
+ * Read every day file into records, in day-file order. An absent data
133
+ * directory (nothing written yet) yields an empty list. Uncached — the
134
+ * session-scoped route uses `readCachedRecords` so repeated chip /
135
+ * usage-tab polls do not re-parse frozen files.
136
+ * @param dir - the plugin's data directory.
137
+ * @returns parsed records, or [] when the directory does not exist.
138
+ */
139
+ export declare function readAllRecords(dir: string): Promise<UsageRecord[]>;
140
+ /**
141
+ * Build the full stats payload for one data directory: the rollup over every
142
+ * frozen day file (advanced lazily and rewritten atomically when unabsorbed
143
+ * frozen files appear) merged with a fresh read of today's file. Day files
144
+ * named at or after today but already absorbed by a later rollup `upto` are
145
+ * skipped, so a clock stepping back cannot count an absorbed file twice.
146
+ * A failed rollup write logs and does not block the response — the next read
147
+ * retries the absorption. The resolver prices each record as it is absorbed,
148
+ * so the rollup carries rate identities (never prices) and a table update
149
+ * re-prices history without rebuilding anything.
150
+ * @param dir - the plugin's data directory.
151
+ * @param now - clock source for the frozen/today boundary (test seam).
152
+ * @param resolve - the rate resolver (see {@link RateResolver}).
153
+ * @returns the summary served to the web settings page.
154
+ */
155
+ export declare function buildSummary(dir: string, now?: () => Date, resolve?: RateResolver): Promise<TokenSummary & {
156
+ dataDir: string;
157
+ }>;
158
+ //# sourceMappingURL=stats.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stats.d.ts","sourceRoot":"","sources":["../src/stats.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAIH,OAAO,KAAK,EAAe,WAAW,EAAE,MAAM,mBAAmB,CAAA;AAGjE,OAAO,KAAK,EAEV,aAAa,EACb,YAAY,EACZ,OAAO,EACP,YAAY,EACZ,YAAY,EAKZ,WAAW,EACZ,MAAM,WAAW,CAAA;AAGlB,4EAA4E;AAC5E,eAAO,MAAM,YAAY,KAAK,CAAA;AAE9B;;;;GAIG;AACH,MAAM,MAAM,YAAY,GAAG,CAAC,MAAM,EAAE,WAAW,KAAK,OAAO,CAAA;AAO3D,iFAAiF;AACjF,wBAAgB,WAAW,IAAI,WAAW,CAQzC;AAyFD;;;;;;;;GAQG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,SAAS,WAAW,EAAE,EAAE,OAAO,GAAE,YAAiC,GAAG,YAAY,CAkC1H;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,SAAS,WAAW,EAAE,EAC/B,UAAU,EAAE,SAAS,MAAM,EAAE,GAC5B,WAAW,EAAE,CAGf;AAED;6EAC6E;AAC7E,MAAM,WAAW,cAAc;IAC7B,qEAAqE;IACrE,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,mFAAmF;IACnF,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,mDAAmD;IACnD,KAAK,CAAC,EAAE,MAAM,CAAA;CACf;AAED;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,cAAc,CAMzF;A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