dsh-token-usage-ledger 0.0.0-stage → 0.0.37

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 (48) hide show
  1. package/CHANGELOG.md +1081 -0
  2. package/LICENSE +21 -0
  3. package/README.md +247 -2
  4. package/cordis.patch.yml +30 -0
  5. package/docs/token-usage-image01.png +0 -0
  6. package/docs/token-usage-image02.png +0 -0
  7. package/lib/client.js +4469 -0
  8. package/lib/host/aggregate.d.ts +132 -0
  9. package/lib/host/aggregate.js +840 -0
  10. package/lib/host/api.d.ts +118 -0
  11. package/lib/host/api.js +346 -0
  12. package/lib/host/backfill.d.ts +54 -0
  13. package/lib/host/backfill.js +265 -0
  14. package/lib/host/collector.d.ts +139 -0
  15. package/lib/host/collector.js +441 -0
  16. package/lib/host/ledger-io.d.ts +125 -0
  17. package/lib/host/ledger-io.js +211 -0
  18. package/lib/host/operation-error.d.ts +22 -0
  19. package/lib/host/operation-error.js +28 -0
  20. package/lib/host/paths.d.ts +35 -0
  21. package/lib/host/paths.js +63 -0
  22. package/lib/host/pricing-module.d.ts +112 -0
  23. package/lib/host/pricing-module.js +63 -0
  24. package/lib/host/pricing-modules/deepseek-2026-09-10.d.ts +31 -0
  25. package/lib/host/pricing-modules/deepseek-2026-09-10.js +67 -0
  26. package/lib/host/pricing-modules/index.d.ts +27 -0
  27. package/lib/host/pricing-modules/index.js +30 -0
  28. package/lib/host/pricing.d.ts +192 -0
  29. package/lib/host/pricing.js +287 -0
  30. package/lib/host/records.d.ts +47 -0
  31. package/lib/host/records.js +116 -0
  32. package/lib/host/runtime-marker.d.ts +67 -0
  33. package/lib/host/runtime-marker.js +71 -0
  34. package/lib/host/schema.d.ts +77 -0
  35. package/lib/host/schema.js +158 -0
  36. package/lib/host/store.d.ts +171 -0
  37. package/lib/host/store.js +337 -0
  38. package/lib/host/workspace-titles.d.ts +38 -0
  39. package/lib/host/workspace-titles.js +136 -0
  40. package/lib/host/zstd.d.ts +41 -0
  41. package/lib/host/zstd.js +134 -0
  42. package/lib/index.d.ts +82 -0
  43. package/lib/index.js +512 -0
  44. package/lib/shared/format.d.ts +415 -0
  45. package/lib/shared/format.js +714 -0
  46. package/lib/shared/protocol.d.ts +646 -0
  47. package/lib/shared/protocol.js +129 -0
  48. package/package.json +87 -4
@@ -0,0 +1,840 @@
1
+ /**
2
+ * Pure aggregation from ledger records to the dashboard's summary payload.
3
+ *
4
+ * Kept free of I/O and of the clock so it can be tested directly: the caller
5
+ * supplies `now`, the records, and the active filters.
6
+ *
7
+ * Two attribution rules matter and are applied consistently here:
8
+ *
9
+ * - A **workspace filter** selects whole records (a Turn belongs to exactly one
10
+ * workspace). It accepts either the merged display key (the project's basename,
11
+ * what the dashboard sends after the WSL→Windows path change) or the exact raw
12
+ * path (one physical checkout), so both views stay possible.
13
+ * - A **model filter** selects individual ATTEMPTS, because one Turn can be
14
+ * billed across several routes after a retry or a model switch. Summing only
15
+ * the matching attempts keeps a filtered figure exact instead of apportioning
16
+ * a whole-turn number.
17
+ *
18
+ * The workspace BREAKDOWN additionally merges by display label so a project whose
19
+ * root moved between platforms reads as one row, while each original path stays
20
+ * available under `paths`. The model breakdown ignores attempts that have neither
21
+ * a route nor any usage: they are administrative (an errored turn settled without
22
+ * an assistant/message), not a model's turn.
23
+ *
24
+ * @module dsh-token-usage-ledger/host/aggregate
25
+ */
26
+ import { SUMMARY_SCHEMA_VERSION } from '../shared/protocol.js';
27
+ /** Zeroed buckets; a fresh object every call so callers cannot alias one. */
28
+ export function zeroBuckets() {
29
+ return { uncachedInput: 0, cacheRead: 0, cacheWrite: 0, output: 0, reasoning: 0 };
30
+ }
31
+ /** Add one bucket set into another, in place. */
32
+ function addBuckets(target, add) {
33
+ target.uncachedInput += add.uncachedInput;
34
+ target.cacheRead += add.cacheRead;
35
+ target.cacheWrite += add.cacheWrite;
36
+ target.output += add.output;
37
+ target.reasoning += add.reasoning;
38
+ }
39
+ /** Scale-invariant route identity used as the model filter key. */
40
+ export function routeKeyOf(provider, model) {
41
+ if (model.length === 0)
42
+ return '';
43
+ return provider.length === 0 ? model : `${provider}/${model}`;
44
+ }
45
+ /** Windows drive path or UNC share. */
46
+ const WINDOWS_PATH = /^[A-Za-z]:[\\/]/u;
47
+ /**
48
+ * Label the path shape for the workspace breakdown.
49
+ *
50
+ * Only a display hint: a `unix` shape can be a native Linux path or a WSL path
51
+ * (the UI therefore says "Linux/WSL", not "WSL"). Keeping this out of the merge
52
+ * key means the merge never depends on a guess about the platform.
53
+ *
54
+ * @param workspace - original workspace root, possibly empty.
55
+ * @returns the display platform.
56
+ */
57
+ export function platformOfWorkspacePath(workspace) {
58
+ if (WINDOWS_PATH.test(workspace) || workspace.startsWith('\\\\'))
59
+ return 'windows';
60
+ if (workspace.startsWith('/'))
61
+ return 'unix';
62
+ return 'unknown';
63
+ }
64
+ /**
65
+ * Identity the workspace breakdown aggregates by.
66
+ *
67
+ * A current Workspace title, when one is available, is the user-facing project
68
+ * identity: it follows a Workspace rename while the directory path stays the
69
+ * same, so old and new labels never become two rows. Without a registry match
70
+ * the stored display label (basename) is used, preserving the pre-registry
71
+ * behavior. A project whose path changed (WSL → Windows) still merges when the
72
+ * current titles match. Records written without a label (hand-written lines,
73
+ * very old formats) fall back to their raw path so they are never merged with
74
+ * an unrelated group; a record with neither is the single unattributed group.
75
+ *
76
+ * @param record - record carrying a workspace and its stored display label.
77
+ * @param titleOf - current-title resolver, or undefined when unavailable.
78
+ * @returns a non-empty group key.
79
+ */
80
+ export function workspaceGroupKeyOf(record, titleOf) {
81
+ if (record.workspace.length > 0 && titleOf !== undefined) {
82
+ const title = titleOf(record.workspace);
83
+ if (title !== undefined && title.length > 0)
84
+ return title;
85
+ }
86
+ if (record.workspaceLabel.length > 0)
87
+ return record.workspaceLabel;
88
+ if (record.workspace.length > 0)
89
+ return record.workspace;
90
+ return '(未知工作区)';
91
+ }
92
+ /**
93
+ * Local calendar day of one instant, as `YYYY-MM-DD`.
94
+ *
95
+ * Days are the machine's local days — "每日消耗" means the user's day, not UTC's
96
+ * — and the Host is the only place a day key is ever produced, so the client
97
+ * never re-derives one and cannot disagree.
98
+ *
99
+ * @param epochMs - instant to label.
100
+ * @returns the local day key.
101
+ */
102
+ export function localDayKey(epochMs) {
103
+ const date = new Date(epochMs);
104
+ const year = date.getFullYear();
105
+ const month = `${date.getMonth() + 1}`.padStart(2, '0');
106
+ const day = `${date.getDate()}`.padStart(2, '0');
107
+ return `${year}-${month}-${day}`;
108
+ }
109
+ /**
110
+ * Whole days between two local day keys, rounded so a DST shift cannot turn a
111
+ * 20-day span into 19 or 21.
112
+ * @param from - earlier day key.
113
+ * @param to - later day key.
114
+ * @returns the signed day count.
115
+ */
116
+ function daysBetweenKeys(from, to) {
117
+ return Math.round((startOfLocalDay(to) - startOfLocalDay(from)) / 86_400_000);
118
+ }
119
+ /**
120
+ * Shift a local day key by whole days, honouring DST transitions.
121
+ * @param key - source `YYYY-MM-DD`.
122
+ * @param delta - days to add (may be negative).
123
+ * @returns the shifted key.
124
+ */
125
+ export function addLocalDays(key, delta) {
126
+ const parts = key.split('-');
127
+ const year = Number(parts[0]);
128
+ const month = Number(parts[1]);
129
+ const day = Number(parts[2]);
130
+ const date = new Date(year, month - 1, day);
131
+ date.setDate(date.getDate() + delta);
132
+ return localDayKey(date.getTime());
133
+ }
134
+ /**
135
+ * Report whether one attempt belongs in the model breakdown.
136
+ *
137
+ * An attempt can settle without a route AND without any billable usage on an
138
+ * errored turn: the collector closes attempt-style events with
139
+ * `provider: '' / model: ''`, and when the sample is all zeros the record still
140
+ * exists (the turn happened, the ledger keeps it, and it counts toward the turn
141
+ * total). Such an attempt is administrative, not a model's turn — feeding it to
142
+ * the breakdown produced the misleading `(未标注模型) / 6 turns / 0 tokens / ¥0`
143
+ * row. Attempts that DO carry usage are always kept, even without a model: that
144
+ * is real unattributed consumption and must stay visible (marked estimated).
145
+ *
146
+ * @param attempt - one billed attempt from the ledger.
147
+ * @returns true when it should create/count toward a model facet.
148
+ */
149
+ function isAttributableAttempt(attempt) {
150
+ if (attempt.model.length > 0)
151
+ return true;
152
+ if (attempt.total !== 0 || attempt.cost !== 0)
153
+ return true;
154
+ const { tokens } = attempt;
155
+ return (tokens.uncachedInput !== 0 ||
156
+ tokens.cacheRead !== 0 ||
157
+ tokens.cacheWrite !== 0 ||
158
+ tokens.output !== 0 ||
159
+ tokens.reasoning !== 0);
160
+ }
161
+ /**
162
+ * Collapse one record's attempts into per-route sums.
163
+ *
164
+ * A single Turn can bill the SAME route several times (a retried step, a
165
+ * multi-step agentic loop), so accumulating attempt-by-attempt would report one
166
+ * route as several turns — the "轮次" column would inflate as the loop gets
167
+ * longer. Grouping first keeps turns honest while tokens and money stay exact.
168
+ *
169
+ * Zero-usage unattributed attempts are excluded (see {@link isAttributableAttempt}):
170
+ * this is the ONLY aggregation path that can create a model row, so filtering
171
+ * here cleans both the filter facets and the breakdown table without touching
172
+ * the totals, the daily series, or the workspace breakdown.
173
+ *
174
+ * @param attempts - the record's attempts.
175
+ * @param match - optional extra predicate (active provider filter, …).
176
+ * @returns one entry per distinct attributable route, in first-seen order.
177
+ */
178
+ function groupAttemptsByRoute(attempts, match) {
179
+ const grouped = new Map();
180
+ for (const attempt of attempts) {
181
+ if (!isAttributableAttempt(attempt))
182
+ continue;
183
+ if (match !== undefined && !match(attempt))
184
+ continue;
185
+ const key = routeKeyOf(attempt.provider, attempt.model);
186
+ const entry = grouped.get(key) ?? {
187
+ label: attempt.model.length === 0 ? '(未标注模型)' : attempt.model,
188
+ provider: attempt.provider,
189
+ tokens: zeroBuckets(),
190
+ total: 0,
191
+ cost: 0,
192
+ estimated: false,
193
+ };
194
+ addBuckets(entry.tokens, attempt.tokens);
195
+ entry.total += attempt.total;
196
+ entry.cost += attempt.cost;
197
+ entry.estimated = entry.estimated || attempt.estimated;
198
+ grouped.set(key, entry);
199
+ }
200
+ return grouped;
201
+ }
202
+ /**
203
+ * Collapse one record's attempts into per-PROVIDER sums.
204
+ *
205
+ * Same grouping rule as the model breakdown (one turn per record×provider, so a
206
+ * multi-step loop cannot inflate the turn count). Unattributed attempts
207
+ * (`provider === ''`) are left out: the UI's "all providers" sentinel is the
208
+ * empty string too, so such an option could never be selected.
209
+ *
210
+ * @param attempts - the record's attempts.
211
+ * @returns one entry per distinct attributed provider, in first-seen order.
212
+ */
213
+ function groupAttemptsByProvider(attempts) {
214
+ const grouped = new Map();
215
+ for (const attempt of attempts) {
216
+ if (!isAttributableAttempt(attempt))
217
+ continue;
218
+ if (attempt.provider.length === 0)
219
+ continue;
220
+ const entry = grouped.get(attempt.provider) ?? {
221
+ label: attempt.provider,
222
+ provider: attempt.provider,
223
+ tokens: zeroBuckets(),
224
+ total: 0,
225
+ cost: 0,
226
+ estimated: false,
227
+ };
228
+ addBuckets(entry.tokens, attempt.tokens);
229
+ entry.total += attempt.total;
230
+ entry.cost += attempt.cost;
231
+ entry.estimated = entry.estimated || attempt.estimated;
232
+ grouped.set(attempt.provider, entry);
233
+ }
234
+ return grouped;
235
+ }
236
+ /** A fresh accumulator. */
237
+ function newAccumulator() {
238
+ return { turns: 0, tokens: zeroBuckets(), total: 0, cost: 0, estimated: false };
239
+ }
240
+ /** Human labels for the shipped/user agent presets, with raw-id fallback. */
241
+ const AGENT_PRESET_LABELS = {
242
+ standard: '标准模式',
243
+ minimal: '极简模式',
244
+ code: '代码模式',
245
+ cordis: '创造模式',
246
+ ptc: 'PTC 模式',
247
+ };
248
+ /**
249
+ * Human label for one agent-preset id.
250
+ * @param preset - raw `agentPreset` value.
251
+ * @returns the Chinese label when known, otherwise the raw id.
252
+ */
253
+ function agentPresetLabel(preset) {
254
+ return AGENT_PRESET_LABELS[preset] ?? preset;
255
+ }
256
+ /**
257
+ * Add one filtered turn to a dimension row.
258
+ *
259
+ * `tokens`/`cost` use the same filter-aware contribution as the cards, while the
260
+ * cache/output columns come from the matching attempts so a mixed-route turn
261
+ * keeps its per-attempt cache detail.
262
+ *
263
+ * @param map - dimension map.
264
+ * @param key - stable row key.
265
+ * @param label - display label.
266
+ * @param contribution - filter-aware record contribution.
267
+ * @param matched - attempts selected by the active model/provider filters.
268
+ */
269
+ function addDimensionUsage(map, key, label, contribution, matched) {
270
+ const entry = map.get(key) ?? { key, label, turns: 0, calls: 0, tokens: 0, cacheRead: 0, uncachedInput: 0, output: 0, cost: 0 };
271
+ entry.turns += 1;
272
+ entry.calls += matched.length;
273
+ entry.tokens += contribution.total;
274
+ entry.cost += contribution.cost;
275
+ for (const attempt of matched) {
276
+ entry.cacheRead += attempt.tokens.cacheRead;
277
+ entry.uncachedInput += attempt.tokens.uncachedInput;
278
+ entry.output += attempt.tokens.output;
279
+ }
280
+ map.set(key, entry);
281
+ }
282
+ /**
283
+ * Sorted median (averaging the two middle values for an even count).
284
+ * @param values - already sorted numbers.
285
+ * @returns the median, or 0 for an empty list.
286
+ */
287
+ function medianOfSorted(values) {
288
+ if (values.length === 0)
289
+ return 0;
290
+ const middle = Math.floor(values.length / 2);
291
+ if (values.length % 2 === 1)
292
+ return values[middle] ?? 0;
293
+ return ((values[middle - 1] ?? 0) + (values[middle] ?? 0)) / 2;
294
+ }
295
+ /**
296
+ * Increment a histogram bin without tripping `noUncheckedIndexedAccess`.
297
+ * @param bins - histogram counters.
298
+ * @param index - bin index.
299
+ */
300
+ function bumpBin(bins, index) {
301
+ bins[index] = (bins[index] ?? 0) + 1;
302
+ }
303
+ /**
304
+ * Nearest-rank percentile of an already sorted list.
305
+ * @param values - already sorted numbers.
306
+ * @param ratio - 0..1.
307
+ * @returns the percentile value, or 0 for an empty list.
308
+ */
309
+ function percentileOfSorted(values, ratio) {
310
+ if (values.length === 0)
311
+ return 0;
312
+ return values[Math.min(values.length - 1, Math.floor((values.length - 1) * ratio))] ?? 0;
313
+ }
314
+ /**
315
+ * Build the extra call/agent/outcome statistics.
316
+ *
317
+ * Every figure follows the same workspace/model/provider selection as
318
+ * `totals`; the dashboard's local date range does not narrow it. This keeps the
319
+ * Host stateless and avoids a second round trip when the user pages the charts.
320
+ *
321
+ * @param selected - filtered records with their filter-aware contributions.
322
+ * @param model - active model key, or null.
323
+ * @param provider - active provider id, or null.
324
+ * @param currency - summary currency (foreign-currency costs are excluded).
325
+ * @returns the analytics block.
326
+ */
327
+ function buildAnalytics(selected, model, provider, currency) {
328
+ const calls = [];
329
+ const tokensPerTurn = [];
330
+ const costPerTurn = [];
331
+ const durations = [];
332
+ const attemptBins = [0, 0, 0, 0, 0, 0];
333
+ const durationBins = [0, 0, 0, 0, 0, 0];
334
+ const agents = new Map();
335
+ const origins = new Map();
336
+ const reasons = new Map();
337
+ const windows = new Map();
338
+ const sessions = new Map();
339
+ const hours = Array.from({ length: 24 }, (_unused, hour) => ({
340
+ hour,
341
+ turns: 0,
342
+ calls: 0,
343
+ tokens: 0,
344
+ cost: 0,
345
+ }));
346
+ let callTotal = 0;
347
+ const windowLabel = {
348
+ peak: '高峰',
349
+ 'off-peak': '空闲',
350
+ unknown: '未知',
351
+ };
352
+ for (const key of ['peak', 'off-peak', 'unknown']) {
353
+ windows.set(key, { key, label: windowLabel[key], calls: 0, tokens: 0, cost: 0 });
354
+ }
355
+ for (const { record, contribution } of selected) {
356
+ const matched = model === null && provider === null
357
+ ? record.attempts
358
+ : record.attempts.filter((attempt) => (model === null || routeKeyOf(attempt.provider, attempt.model) === model) &&
359
+ (provider === null || attempt.provider === provider));
360
+ callTotal += matched.length;
361
+ calls.push(matched.length);
362
+ tokensPerTurn.push(contribution.total);
363
+ costPerTurn.push(contribution.cost);
364
+ const duration = record.endedAt - record.startedAt;
365
+ if (Number.isFinite(duration) && duration >= 0) {
366
+ durations.push(duration);
367
+ if (duration < 60_000)
368
+ bumpBin(durationBins, 0);
369
+ else if (duration < 5 * 60_000)
370
+ bumpBin(durationBins, 1);
371
+ else if (duration < 15 * 60_000)
372
+ bumpBin(durationBins, 2);
373
+ else if (duration < 30 * 60_000)
374
+ bumpBin(durationBins, 3);
375
+ else if (duration < 60 * 60_000)
376
+ bumpBin(durationBins, 4);
377
+ else
378
+ bumpBin(durationBins, 5);
379
+ }
380
+ if (matched.length === 1)
381
+ bumpBin(attemptBins, 0);
382
+ else if (matched.length <= 10)
383
+ bumpBin(attemptBins, 1);
384
+ else if (matched.length <= 20)
385
+ bumpBin(attemptBins, 2);
386
+ else if (matched.length <= 50)
387
+ bumpBin(attemptBins, 3);
388
+ else if (matched.length <= 100)
389
+ bumpBin(attemptBins, 4);
390
+ else
391
+ bumpBin(attemptBins, 5);
392
+ const startedHour = new Date(record.startedAt).getHours();
393
+ if (Number.isInteger(startedHour) && startedHour >= 0 && startedHour < 24) {
394
+ const row = hours[startedHour];
395
+ if (row !== undefined)
396
+ row.turns += 1;
397
+ }
398
+ const preset = record.agentPreset.trim();
399
+ addDimensionUsage(agents, preset.length > 0 ? preset : 'unknown', preset.length > 0 ? agentPresetLabel(preset) : '未标注', contribution, matched);
400
+ const origin = record.origin === 'subagent' ? 'subagent' : record.origin.trim() || 'main';
401
+ addDimensionUsage(origins, origin, origin === 'subagent' ? '子代理' : origin === 'main' ? '主会话' : origin, contribution, matched);
402
+ const reason = record.reason.trim() || 'unknown';
403
+ const reasonLabel = reason === 'completed' ? '完成' : reason === 'aborted' ? '中止' : reason === 'error' ? '错误' : reason;
404
+ addDimensionUsage(reasons, reason, reasonLabel, contribution, matched);
405
+ const priced = record.cost.currency === currency;
406
+ for (const attempt of matched) {
407
+ const row = windows.get(attempt.window);
408
+ if (row !== undefined) {
409
+ row.calls += 1;
410
+ row.tokens += attempt.total;
411
+ row.cost += priced ? attempt.cost : 0;
412
+ }
413
+ const hour = new Date(attempt.at).getHours();
414
+ if (Number.isInteger(hour) && hour >= 0 && hour < 24) {
415
+ const hourRow = hours[hour];
416
+ if (hourRow !== undefined) {
417
+ hourRow.calls += 1;
418
+ hourRow.tokens += attempt.total;
419
+ hourRow.cost += priced ? attempt.cost : 0;
420
+ }
421
+ }
422
+ }
423
+ const session = sessions.get(record.sessionId) ?? { turns: 0, tokens: 0, cost: 0 };
424
+ session.turns += 1;
425
+ session.tokens += contribution.total;
426
+ session.cost += contribution.cost;
427
+ sessions.set(record.sessionId, session);
428
+ }
429
+ const sortedCalls = [...calls].sort((a, b) => a - b);
430
+ const sortedTokens = [...tokensPerTurn].sort((a, b) => a - b);
431
+ const sortedCosts = [...costPerTurn].sort((a, b) => a - b);
432
+ const sortedDurations = [...durations].sort((a, b) => a - b);
433
+ const turns = selected.length;
434
+ const callStats = {
435
+ total: callTotal,
436
+ turns,
437
+ multiCallTurns: calls.filter((value) => value > 1).length,
438
+ medianPerTurn: medianOfSorted(sortedCalls),
439
+ p90PerTurn: percentileOfSorted(sortedCalls, 0.9),
440
+ maxPerTurn: sortedCalls.at(-1) ?? 0,
441
+ averagePerTurn: turns === 0 ? 0 : callTotal / turns,
442
+ tokensPerTurnMedian: medianOfSorted(sortedTokens),
443
+ costPerTurnMedian: medianOfSorted(sortedCosts),
444
+ };
445
+ const durationStats = {
446
+ median: medianOfSorted(sortedDurations),
447
+ p90: percentileOfSorted(sortedDurations, 0.9),
448
+ max: sortedDurations.at(-1) ?? 0,
449
+ average: durations.length === 0 ? 0 : durations.reduce((sum, value) => sum + value, 0) / durations.length,
450
+ samples: durations.length,
451
+ };
452
+ const sessionRows = [...sessions.values()];
453
+ const sessionTurns = sessionRows.map((row) => row.turns).sort((a, b) => a - b);
454
+ const sessionTokens = sessionRows.map((row) => row.tokens).sort((a, b) => a - b);
455
+ const sessionCosts = sessionRows.map((row) => row.cost).sort((a, b) => a - b);
456
+ const sessionStats = {
457
+ count: sessionRows.length,
458
+ averageTurns: sessionRows.length === 0
459
+ ? 0
460
+ : sessionRows.reduce((sum, row) => sum + row.turns, 0) / sessionRows.length,
461
+ medianTurns: medianOfSorted(sessionTurns),
462
+ medianTokens: medianOfSorted(sessionTokens),
463
+ medianCost: medianOfSorted(sessionCosts),
464
+ };
465
+ const byCostThenTokens = (left, right) => right.cost - left.cost || right.tokens - left.tokens;
466
+ const byTurns = (left, right) => right.turns - left.turns || right.tokens - left.tokens;
467
+ return {
468
+ calls: callStats,
469
+ durations: durationStats,
470
+ attemptBins: [
471
+ { label: '1 次', count: attemptBins[0] ?? 0 },
472
+ { label: '2–10 次', count: attemptBins[1] ?? 0 },
473
+ { label: '11–20 次', count: attemptBins[2] ?? 0 },
474
+ { label: '21–50 次', count: attemptBins[3] ?? 0 },
475
+ { label: '51–100 次', count: attemptBins[4] ?? 0 },
476
+ { label: '100+ 次', count: attemptBins[5] ?? 0 },
477
+ ],
478
+ durationBins: [
479
+ { label: '<1 分', count: durationBins[0] ?? 0 },
480
+ { label: '1–5 分', count: durationBins[1] ?? 0 },
481
+ { label: '5–15 分', count: durationBins[2] ?? 0 },
482
+ { label: '15–30 分', count: durationBins[3] ?? 0 },
483
+ { label: '30–60 分', count: durationBins[4] ?? 0 },
484
+ { label: '≥60 分', count: durationBins[5] ?? 0 },
485
+ ],
486
+ sessions: sessionStats,
487
+ agents: [...agents.values()].sort(byCostThenTokens),
488
+ origins: [...origins.values()].sort(byTurns),
489
+ reasons: [...reasons.values()].sort(byTurns),
490
+ windows: [...windows.values()].filter((row) => row.calls > 0),
491
+ hours,
492
+ };
493
+ }
494
+ /**
495
+ * Create an empty merged workspace group.
496
+ * @param label - display label (merge key).
497
+ * @returns the entry.
498
+ */
499
+ function newWorkspaceEntry(label) {
500
+ return { label, acc: newAccumulator(), paths: new Map() };
501
+ }
502
+ /**
503
+ * Add one record's contribution to a merged workspace group.
504
+ *
505
+ * The per-path accumulators receive the SAME contribution the group receives, so
506
+ * under a model filter the path numbers are the filtered slice, just like the row
507
+ * they belong to. Money has already been currency-filtered by the caller.
508
+ *
509
+ * @param entry - group to update.
510
+ * @param workspace - original workspace root of the record.
511
+ * @param contribution - the slice of the record this view includes.
512
+ */
513
+ function addWorkspaceContribution(entry, workspace, contribution) {
514
+ accumulate(entry.acc, contribution);
515
+ const path = entry.paths.get(workspace) ?? newAccumulator();
516
+ accumulate(path, contribution);
517
+ entry.paths.set(workspace, path);
518
+ }
519
+ /**
520
+ * Select the part of a record the active model filter covers.
521
+ *
522
+ * Money is admitted only when the record was priced in the currency being
523
+ * reported. Tokens are currency-independent and always count; a cost figure is
524
+ * not, so summing `USD` into a `CNY` total would silently produce a wrong
525
+ * amount of money — the one class of error a spend tracker must never make.
526
+ * Excluded records are counted in `HealthReport.currencyMismatches`.
527
+ *
528
+ * @param record - ledger record to slice.
529
+ * @param model - active model key, or `null` for all.
530
+ * @param provider - active provider id, or `null` for all.
531
+ * @param currency - currency the summary reports.
532
+ * @returns the contribution, or undefined when the filter excludes it.
533
+ */
534
+ function contributionOf(record, model, provider, currency) {
535
+ const priced = record.cost.currency === currency;
536
+ if (model === null && provider === null) {
537
+ return {
538
+ tokens: record.tokens,
539
+ total: record.total,
540
+ cost: priced ? record.cost.total : 0,
541
+ estimated: priced && record.cost.estimated,
542
+ estimatedReason: priced ? record.cost.estimatedReason : undefined,
543
+ };
544
+ }
545
+ const tokens = zeroBuckets();
546
+ let total = 0;
547
+ let cost = 0;
548
+ let estimated = false;
549
+ let matched = false;
550
+ for (const attempt of record.attempts) {
551
+ if (model !== null && routeKeyOf(attempt.provider, attempt.model) !== model)
552
+ continue;
553
+ if (provider !== null && attempt.provider !== provider)
554
+ continue;
555
+ matched = true;
556
+ addBuckets(tokens, attempt.tokens);
557
+ total += attempt.total;
558
+ cost += priced ? attempt.cost : 0;
559
+ estimated = estimated || (priced && attempt.estimated);
560
+ }
561
+ return matched ? { tokens, total, cost, estimated } : undefined;
562
+ }
563
+ /** Fold one contribution into an accumulator. */
564
+ function accumulate(accumulator, contribution) {
565
+ accumulator.turns += 1;
566
+ addBuckets(accumulator.tokens, contribution.tokens);
567
+ accumulator.total += contribution.total;
568
+ accumulator.cost += contribution.cost;
569
+ // Agreement only: a day that mixes "model not in the price table" with
570
+ // "predates the earliest row" must not be labelled with either one. The first
571
+ // contribution seeds the value, later ones may only confirm it.
572
+ if (accumulator.estimated) {
573
+ if (accumulator.estimatedReason !== contribution.estimatedReason) {
574
+ delete accumulator.estimatedReason;
575
+ }
576
+ }
577
+ else if (contribution.estimatedReason !== undefined) {
578
+ accumulator.estimatedReason = contribution.estimatedReason;
579
+ }
580
+ accumulator.estimated = accumulator.estimated || contribution.estimated;
581
+ }
582
+ /** Project an accumulator into the wire `Totals` shape. */
583
+ function toTotals(accumulator) {
584
+ return {
585
+ turns: accumulator.turns,
586
+ tokens: accumulator.tokens,
587
+ total: accumulator.total,
588
+ cost: accumulator.cost,
589
+ estimated: accumulator.estimated,
590
+ };
591
+ }
592
+ /**
593
+ * Apply the workspace, model, and provider filters to the ledger.
594
+ * @param records - all accepted records.
595
+ * @param workspace - workspace key, or `null` for all.
596
+ * @param model - model key (provider/model), or `null` for all.
597
+ * @param provider - provider id, or `null` for all.
598
+ * @param currency - currency the summary reports.
599
+ * @param titleOf - current-workspace-title resolver, when available.
600
+ * @returns the selected records with their contributions.
601
+ */
602
+ function select(records, workspace, model, provider, currency, titleOf) {
603
+ const selected = [];
604
+ for (const record of records) {
605
+ // Match the merged display key (what the current UI sends) OR the raw path
606
+ // (what an older client or a hand-written query may send). Both stay exact:
607
+ // the label selects every path of that project, the raw path only one.
608
+ if (workspace !== null &&
609
+ record.workspace !== workspace &&
610
+ workspaceGroupKeyOf(record, titleOf) !== workspace) {
611
+ continue;
612
+ }
613
+ const contribution = contributionOf(record, model, provider, currency);
614
+ if (contribution === undefined)
615
+ continue;
616
+ selected.push({ record, contribution });
617
+ }
618
+ return selected;
619
+ }
620
+ /**
621
+ * Build the dashboard payload.
622
+ * @param input - records, filters, clock, and reporting context.
623
+ * @returns the serializable summary.
624
+ */
625
+ export function buildSummary(input) {
626
+ const { records, workspace, model, days, now } = input;
627
+ const providerFilter = input.provider ?? null;
628
+ // --- facets and all-time totals always describe the FULL ledger, so the
629
+ // filter controls never shrink to the point of being unusable.
630
+ const allTime = newAccumulator();
631
+ const workspaceAcc = new Map();
632
+ const modelAcc = new Map();
633
+ const providerAcc = new Map();
634
+ const daysWithUsage = new Set();
635
+ let currencyMismatches = 0;
636
+ for (const record of records) {
637
+ daysWithUsage.add(localDayKey(record.ts));
638
+ const priced = record.cost.currency === input.currency;
639
+ if (!priced)
640
+ currencyMismatches += 1;
641
+ const contribution = {
642
+ tokens: record.tokens,
643
+ total: record.total,
644
+ cost: priced ? record.cost.total : 0,
645
+ estimated: priced && record.cost.estimated,
646
+ estimatedReason: priced ? record.cost.estimatedReason : undefined,
647
+ };
648
+ accumulate(allTime, contribution);
649
+ const workspaceKey = workspaceGroupKeyOf(record, input.workspaceTitleOf);
650
+ const workspaceEntry = workspaceAcc.get(workspaceKey) ?? newWorkspaceEntry(workspaceKey);
651
+ addWorkspaceContribution(workspaceEntry, record.workspace, contribution);
652
+ workspaceAcc.set(workspaceKey, workspaceEntry);
653
+ for (const [key, perRoute] of groupAttemptsByRoute(record.attempts)) {
654
+ const entry = modelAcc.get(key) ?? { label: perRoute.label, provider: perRoute.provider, acc: newAccumulator() };
655
+ accumulate(entry.acc, {
656
+ tokens: perRoute.tokens,
657
+ total: perRoute.total,
658
+ cost: priced ? perRoute.cost : 0,
659
+ estimated: priced && perRoute.estimated,
660
+ });
661
+ modelAcc.set(key, entry);
662
+ }
663
+ for (const [key, perProvider] of groupAttemptsByProvider(record.attempts)) {
664
+ const entry = providerAcc.get(key) ?? { label: perProvider.label, acc: newAccumulator() };
665
+ accumulate(entry.acc, {
666
+ tokens: perProvider.tokens,
667
+ total: perProvider.total,
668
+ cost: priced ? perProvider.cost : 0,
669
+ estimated: priced && perProvider.estimated,
670
+ });
671
+ providerAcc.set(key, entry);
672
+ }
673
+ }
674
+ // --- the filtered view
675
+ const selected = select(records, workspace, model, providerFilter, input.currency, input.workspaceTitleOf);
676
+ const filtered = newAccumulator();
677
+ const byWorkspace = new Map();
678
+ const byModel = new Map();
679
+ const perDay = new Map();
680
+ const windowStart = addLocalDays(localDayKey(now), -(Math.max(1, days) - 1));
681
+ const windowStartMs = startOfLocalDay(windowStart);
682
+ for (const { record, contribution } of selected) {
683
+ accumulate(filtered, contribution);
684
+ const workspaceKey = workspaceGroupKeyOf(record, input.workspaceTitleOf);
685
+ const workspaceEntry = byWorkspace.get(workspaceKey) ?? newWorkspaceEntry(workspaceKey);
686
+ addWorkspaceContribution(workspaceEntry, record.workspace, contribution);
687
+ byWorkspace.set(workspaceKey, workspaceEntry);
688
+ // The breakdown mirrors the filter semantics: group only the attempts the
689
+ // active model/provider filters select. (A model filter must still show one
690
+ // route; a provider filter may span several models.)
691
+ const priced = record.cost.currency === input.currency;
692
+ const matchAttempt = (attempt) => (model === null || routeKeyOf(attempt.provider, attempt.model) === model) &&
693
+ (providerFilter === null || attempt.provider === providerFilter);
694
+ for (const [key, perRoute] of groupAttemptsByRoute(record.attempts, matchAttempt)) {
695
+ const entry = byModel.get(key) ?? { label: perRoute.label, provider: perRoute.provider, acc: newAccumulator() };
696
+ accumulate(entry.acc, {
697
+ tokens: perRoute.tokens,
698
+ total: perRoute.total,
699
+ cost: priced ? perRoute.cost : 0,
700
+ estimated: priced && perRoute.estimated,
701
+ });
702
+ byModel.set(key, entry);
703
+ }
704
+ if (record.ts >= windowStartMs) {
705
+ const key = localDayKey(record.ts);
706
+ const entry = perDay.get(key) ?? newAccumulator();
707
+ accumulate(entry, contribution);
708
+ perDay.set(key, entry);
709
+ }
710
+ }
711
+ // --- daily series: every day in the window, gaps filled, so the chart's
712
+ // x-axis is a real time axis rather than a list of days that had traffic.
713
+ //
714
+ // The window ends at the NEWEST RECORDED day, not at today: a record whose
715
+ // clock is ahead of ours (a clock going backwards, a hand-written line, a
716
+ // synthetic fixture) is counted by `totals` like any other, and a series that
717
+ // stopped at today would leave the charts silently disagreeing with the cards
718
+ // about usage that exists. It never SHORTENS the window either, so the usual
719
+ // case is unchanged.
720
+ const today = localDayKey(now);
721
+ const newestRecorded = [...perDay.keys()].sort().at(-1) ?? '';
722
+ const dailyDays = newestRecorded > today ? daysBetweenKeys(windowStart, newestRecorded) + 1 : Math.max(1, days);
723
+ const daily = [];
724
+ for (let offset = 0; offset < dailyDays; offset += 1) {
725
+ const key = addLocalDays(windowStart, offset);
726
+ const entry = perDay.get(key) ?? newAccumulator();
727
+ daily.push({
728
+ date: key,
729
+ turns: entry.turns,
730
+ tokens: entry.tokens,
731
+ total: entry.total,
732
+ cost: entry.cost,
733
+ estimated: entry.estimated,
734
+ ...(entry.estimatedReason === undefined ? {} : { estimatedReason: entry.estimatedReason }),
735
+ });
736
+ }
737
+ const sortedDays = [...daysWithUsage].sort();
738
+ const firstDay = sortedDays.at(0) ?? '';
739
+ const lastDay = sortedDays.at(-1) ?? '';
740
+ return {
741
+ schemaVersion: SUMMARY_SCHEMA_VERSION,
742
+ generatedAt: now,
743
+ pluginVersion: input.pluginVersion,
744
+ currency: input.currency,
745
+ pricing: input.pricing,
746
+ filters: { workspace, model, provider: providerFilter, days: Math.max(1, days) },
747
+ totals: toTotals(filtered),
748
+ allTime: toTotals(allTime),
749
+ facets: {
750
+ workspaces: toWorkspaceFacets(workspaceAcc),
751
+ models: toFacets(modelAcc),
752
+ providers: toFacets(providerAcc),
753
+ activeDays: daysWithUsage.size,
754
+ firstDay,
755
+ lastDay,
756
+ records: records.length,
757
+ },
758
+ daily,
759
+ byModel: toFacets(byModel),
760
+ byWorkspace: toWorkspaceFacets(byWorkspace),
761
+ analytics: buildAnalytics(selected, model, providerFilter, input.currency),
762
+ // Recomputed here rather than taken from the caller: which records were
763
+ // priced in another currency is an aggregation fact, and the count must
764
+ // describe the ledger the totals were actually drawn from.
765
+ health: { ...input.health, currencyMismatches },
766
+ };
767
+ }
768
+ /**
769
+ * Project an accumulator map into sorted facets.
770
+ * @param source - keyed accumulators.
771
+ * @returns facets, highest token count first.
772
+ */
773
+ function toFacets(source) {
774
+ const facets = [];
775
+ for (const [key, entry] of source) {
776
+ facets.push({
777
+ key,
778
+ label: entry.label.length > 0 ? entry.label : key,
779
+ turns: entry.acc.turns,
780
+ tokens: entry.acc.total,
781
+ cost: entry.acc.cost,
782
+ ...(entry.provider === undefined ? {} : { provider: entry.provider }),
783
+ });
784
+ }
785
+ return facets.sort((a, b) => b.tokens - a.tokens);
786
+ }
787
+ /**
788
+ * Project merged workspace groups into sorted facets with per-path detail.
789
+ *
790
+ * Sorting is by merged tokens (the table's default order) and the path list is
791
+ * sorted by raw path so a given ledger always renders the same order.
792
+ *
793
+ * @param source - keyed workspace groups.
794
+ * @returns workspace facets, highest token count first.
795
+ */
796
+ function toWorkspaceFacets(source) {
797
+ const facets = [];
798
+ for (const [key, entry] of source) {
799
+ const paths = [...entry.paths.entries()]
800
+ .map(([workspace, acc]) => ({
801
+ workspace,
802
+ platform: platformOfWorkspacePath(workspace),
803
+ turns: acc.turns,
804
+ tokens: acc.total,
805
+ cost: acc.cost,
806
+ }))
807
+ .sort((a, b) => (a.workspace < b.workspace ? -1 : a.workspace > b.workspace ? 1 : 0));
808
+ facets.push({
809
+ key,
810
+ label: entry.label.length > 0 ? entry.label : key,
811
+ turns: entry.acc.turns,
812
+ tokens: entry.acc.total,
813
+ cost: entry.acc.cost,
814
+ paths,
815
+ mergedCount: paths.length,
816
+ });
817
+ }
818
+ return facets.sort((a, b) => b.tokens - a.tokens);
819
+ }
820
+ /**
821
+ * Local start-of-day epoch milliseconds for a day key.
822
+ * @param key - `YYYY-MM-DD`.
823
+ * @returns the instant local midnight began.
824
+ */
825
+ export function startOfLocalDay(key) {
826
+ const parts = key.split('-');
827
+ return new Date(Number(parts[0]), Number(parts[1]) - 1, Number(parts[2])).getTime();
828
+ }
829
+ /**
830
+ * Total priced amount across one attempt list.
831
+ * @param attempts - attempts of one record.
832
+ * @returns the summed amount.
833
+ */
834
+ export function sumAttemptCost(attempts) {
835
+ let total = 0;
836
+ for (const attempt of attempts)
837
+ total += attempt.cost;
838
+ return total;
839
+ }
840
+ //# sourceMappingURL=aggregate.js.map