@laoyuehanni/dsh-token-usage 0.4.13 → 0.4.15

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 (106) hide show
  1. package/README.md +17 -9
  2. package/README.zh.md +17 -9
  3. package/lib/aux-request.d.ts +4 -0
  4. package/lib/aux-request.d.ts.map +1 -1
  5. package/lib/aux-request.js +1 -0
  6. package/lib/aux-request.js.map +1 -1
  7. package/lib/client/CostPill.d.ts +3 -4
  8. package/lib/client/CostPill.d.ts.map +1 -1
  9. package/lib/client/CostPill.js +5 -7
  10. package/lib/client/CostPill.js.map +1 -1
  11. package/lib/client/DashboardCards.d.ts +18 -10
  12. package/lib/client/DashboardCards.d.ts.map +1 -1
  13. package/lib/client/DashboardCards.js +14 -8
  14. package/lib/client/DashboardCards.js.map +1 -1
  15. package/lib/client/RequestPool.d.ts.map +1 -1
  16. package/lib/client/RequestPool.js +42 -18
  17. package/lib/client/RequestPool.js.map +1 -1
  18. package/lib/client/TokenUsageSection.d.ts.map +1 -1
  19. package/lib/client/TokenUsageSection.js +25 -14
  20. package/lib/client/TokenUsageSection.js.map +1 -1
  21. package/lib/client/UsageRows.d.ts +19 -11
  22. package/lib/client/UsageRows.d.ts.map +1 -1
  23. package/lib/client/UsageRows.js +59 -16
  24. package/lib/client/UsageRows.js.map +1 -1
  25. package/lib/client/cost-inflate-motion.d.ts +0 -4
  26. package/lib/client/cost-inflate-motion.d.ts.map +1 -1
  27. package/lib/client/cost-inflate-motion.js +0 -19
  28. package/lib/client/cost-inflate-motion.js.map +1 -1
  29. package/lib/client/cost-inflate.d.ts +4 -6
  30. package/lib/client/cost-inflate.d.ts.map +1 -1
  31. package/lib/client/cost-inflate.js +3 -5
  32. package/lib/client/cost-inflate.js.map +1 -1
  33. package/lib/client/format.d.ts +5 -0
  34. package/lib/client/format.d.ts.map +1 -1
  35. package/lib/client/format.js +5 -0
  36. package/lib/client/format.js.map +1 -1
  37. package/lib/client/locales.d.ts +10 -0
  38. package/lib/client/locales.d.ts.map +1 -1
  39. package/lib/client/locales.js +20 -0
  40. package/lib/client/locales.js.map +1 -1
  41. package/lib/client/use-cost-inflate.d.ts +5 -15
  42. package/lib/client/use-cost-inflate.d.ts.map +1 -1
  43. package/lib/client/use-cost-inflate.js +11 -51
  44. package/lib/client/use-cost-inflate.js.map +1 -1
  45. package/lib/client.js +288 -225
  46. package/lib/client.js.map +1 -1
  47. package/lib/compaction-attribution.d.ts +72 -0
  48. package/lib/compaction-attribution.d.ts.map +1 -0
  49. package/lib/compaction-attribution.js +82 -0
  50. package/lib/compaction-attribution.js.map +1 -0
  51. package/lib/field-completion.d.ts +46 -0
  52. package/lib/field-completion.d.ts.map +1 -0
  53. package/lib/field-completion.js +71 -0
  54. package/lib/field-completion.js.map +1 -0
  55. package/lib/index.d.ts.map +1 -1
  56. package/lib/index.js +145 -15
  57. package/lib/index.js.map +1 -1
  58. package/lib/migrate.d.ts +2 -1
  59. package/lib/migrate.d.ts.map +1 -1
  60. package/lib/migrate.js +13 -1
  61. package/lib/migrate.js.map +1 -1
  62. package/lib/provider-label.d.ts +20 -0
  63. package/lib/provider-label.d.ts.map +1 -0
  64. package/lib/provider-label.js +21 -0
  65. package/lib/provider-label.js.map +1 -0
  66. package/lib/provider-names.d.ts +60 -0
  67. package/lib/provider-names.d.ts.map +1 -0
  68. package/lib/provider-names.js +156 -0
  69. package/lib/provider-names.js.map +1 -0
  70. package/lib/rollup.d.ts +10 -4
  71. package/lib/rollup.d.ts.map +1 -1
  72. package/lib/rollup.js +21 -4
  73. package/lib/rollup.js.map +1 -1
  74. package/lib/session-request-details.d.ts.map +1 -1
  75. package/lib/session-request-details.js +2 -0
  76. package/lib/session-request-details.js.map +1 -1
  77. package/lib/stats-route.d.ts +4 -0
  78. package/lib/stats-route.d.ts.map +1 -1
  79. package/lib/stats-route.js +14 -1
  80. package/lib/stats-route.js.map +1 -1
  81. package/lib/stats.d.ts.map +1 -1
  82. package/lib/stats.js +86 -19
  83. package/lib/stats.js.map +1 -1
  84. package/lib/sync-state.d.ts +43 -0
  85. package/lib/sync-state.d.ts.map +1 -1
  86. package/lib/sync-state.js +106 -0
  87. package/lib/sync-state.js.map +1 -1
  88. package/lib/sync.d.ts.map +1 -1
  89. package/lib/sync.js +26 -5
  90. package/lib/sync.js.map +1 -1
  91. package/lib/usage-log.d.ts +31 -0
  92. package/lib/usage-log.d.ts.map +1 -1
  93. package/lib/usage-log.js +172 -8
  94. package/lib/usage-log.js.map +1 -1
  95. package/lib/usage-record.d.ts +33 -8
  96. package/lib/usage-record.d.ts.map +1 -1
  97. package/lib/usage-record.js +79 -12
  98. package/lib/usage-record.js.map +1 -1
  99. package/lib/wire.d.ts +53 -1
  100. package/lib/wire.d.ts.map +1 -1
  101. package/lib/wire.js.map +1 -1
  102. package/package.json +1 -1
  103. package/lib/client/CostDeltaFlyLabel.d.ts +0 -8
  104. package/lib/client/CostDeltaFlyLabel.d.ts.map +0 -1
  105. package/lib/client/CostDeltaFlyLabel.js +0 -24
  106. package/lib/client/CostDeltaFlyLabel.js.map +0 -1
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Compaction attribution (shared window): the model behind the rewrite
3
+ * annotation the request pool attaches to plain-request rows. Each session
4
+ * keeps a window of the
5
+ * compaction events that landed since its last PLAIN request — when a plain
6
+ * request row is projected and the window is non-empty, the row carries the
7
+ * window as its attribution and the window resets.
8
+ *
9
+ * Why attribution, not a cache verdict: the host's compaction rewrites the
10
+ * context prefix (tool-result pruning shadows messages, an LLM summary
11
+ * replaces history), so the prefix cache of the FIRST request after the
12
+ * rewrite may miss through no fault of the provider. The miss severity is a
13
+ * function of the earliest rewritten position, so「affected」 never implies
14
+ *「cache lost」 — the annotation explains, `assessRequestCache` stays
15
+ * untouched.
16
+ *
17
+ * Clustering: a prune batch lands as prune events interleaved with the
18
+ * step's straggling `tool/result` appends (verified on real session logs:
19
+ * seq 97–107 = prune / tool/result alternating at one step boundary), so
20
+ * EVERY prune inside one window folds into ONE cluster item (count = event
21
+ * count, tokens = the shadowed sum) no matter what non-compaction events
22
+ * interleave. A summary is its own item and separates the clusters around
23
+ * it (prune → summary → prune reads as two rewrites with the summary's
24
+ * replacement in between). Consuming the window for a plain request ends
25
+ * the cluster by definition.
26
+ *
27
+ * The window is pure in-memory state over the session event stream, so the
28
+ * live recorder and the history rescan drive the SAME implementation — the
29
+ * annotation can never diverge between the two paths.
30
+ *
31
+ * @module token-usage/compaction-attribution
32
+ */
33
+ import type { SessionEvent } from '@deepseek-ai/dsh-session';
34
+ /** Which host compaction operation rewrote the prefix. */
35
+ export type CompactionSourceKind = 'prune' | 'summary';
36
+ /** One attribution entry a request row may carry: the source kind plus the
37
+ * magnitude facts the tooltip needs. */
38
+ export interface CompactionAttributionItem {
39
+ /** `prune` — a run of `compaction/prune` events folded into one cluster;
40
+ * `summary` — one `compaction/summary` (its summarize call bills as its
41
+ * own compaction row; this entry only explains the prefix rewrite). */
42
+ kind: CompactionSourceKind;
43
+ /** Prune cluster: the number of folded prune events. Summary: always 1. */
44
+ count: number;
45
+ /** Shadow tokens: the cluster's summed / the summary's own
46
+ * `shadowedTokenCount` — the heuristic price of the shadowed content,
47
+ * NOT a claim about the exact context-size reduction. */
48
+ shadowedTokenCount: number;
49
+ }
50
+ /**
51
+ * The per-session attribution window: compaction events since the last plain
52
+ * request. Feed every session event through {@link observe} in stream order;
53
+ * call {@link consumeForRequest} when a plain-request row is projected — a
54
+ * non-empty window is returned (and reset) as that row's attribution.
55
+ */
56
+ export declare class CompactionAttributionWindow {
57
+ private items;
58
+ /** Fold one session event into the window. Only `compaction/prune` and
59
+ * `compaction/summary` contribute items; every other event type is
60
+ * cluster-transparent (straggling tool results and step/turn boundaries
61
+ * interleave a prune batch without splitting it — a cluster ends only at
62
+ * a summary or at the window's consumption). */
63
+ observe(event: SessionEvent): void;
64
+ /** Take the window for a plain-request row: the accumulated attribution
65
+ * when any, and the window resets either way (the request consumed it).
66
+ * Only plain request rows consume — a compaction row is the rewrite's own
67
+ * billing row, and a failure row has no cache figures to explain; the
68
+ * window then survives until the next plain request, whose prefix the
69
+ * rewrite still precedes. */
70
+ consumeForRequest(): CompactionAttributionItem[] | undefined;
71
+ }
72
+ //# sourceMappingURL=compaction-attribution.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compaction-attribution.d.ts","sourceRoot":"","sources":["../src/compaction-attribution.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAA;AAK5D,0DAA0D;AAC1D,MAAM,MAAM,oBAAoB,GAAG,OAAO,GAAG,SAAS,CAAA;AAEtD;wCACwC;AACxC,MAAM,WAAW,yBAAyB;IACxC;;2EAEuE;IACvE,IAAI,EAAE,oBAAoB,CAAA;IAC1B,2EAA2E;IAC3E,KAAK,EAAE,MAAM,CAAA;IACb;;6DAEyD;IACzD,kBAAkB,EAAE,MAAM,CAAA;CAC3B;AAQD;;;;;GAKG;AACH,qBAAa,2BAA2B;IACtC,OAAO,CAAC,KAAK,CAAkC;IAE/C;;;;oDAIgD;IAChD,OAAO,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI;IAiBlC;;;;;iCAK6B;IAC7B,iBAAiB,IAAI,yBAAyB,EAAE,GAAG,SAAS;CAM7D"}
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Compaction attribution (shared window): the model behind the rewrite
3
+ * annotation the request pool attaches to plain-request rows. Each session
4
+ * keeps a window of the
5
+ * compaction events that landed since its last PLAIN request — when a plain
6
+ * request row is projected and the window is non-empty, the row carries the
7
+ * window as its attribution and the window resets.
8
+ *
9
+ * Why attribution, not a cache verdict: the host's compaction rewrites the
10
+ * context prefix (tool-result pruning shadows messages, an LLM summary
11
+ * replaces history), so the prefix cache of the FIRST request after the
12
+ * rewrite may miss through no fault of the provider. The miss severity is a
13
+ * function of the earliest rewritten position, so「affected」 never implies
14
+ *「cache lost」 — the annotation explains, `assessRequestCache` stays
15
+ * untouched.
16
+ *
17
+ * Clustering: a prune batch lands as prune events interleaved with the
18
+ * step's straggling `tool/result` appends (verified on real session logs:
19
+ * seq 97–107 = prune / tool/result alternating at one step boundary), so
20
+ * EVERY prune inside one window folds into ONE cluster item (count = event
21
+ * count, tokens = the shadowed sum) no matter what non-compaction events
22
+ * interleave. A summary is its own item and separates the clusters around
23
+ * it (prune → summary → prune reads as two rewrites with the summary's
24
+ * replacement in between). Consuming the window for a plain request ends
25
+ * the cluster by definition.
26
+ *
27
+ * The window is pure in-memory state over the session event stream, so the
28
+ * live recorder and the history rescan drive the SAME implementation — the
29
+ * annotation can never diverge between the two paths.
30
+ *
31
+ * @module token-usage/compaction-attribution
32
+ */
33
+ /** Defensive read of one shadowed figure: a non-finite or negative value
34
+ * reads as 0 (the event count is still a fact; its magnitude is not). */
35
+ function shadowTokensOf(value) {
36
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0;
37
+ }
38
+ /**
39
+ * The per-session attribution window: compaction events since the last plain
40
+ * request. Feed every session event through {@link observe} in stream order;
41
+ * call {@link consumeForRequest} when a plain-request row is projected — a
42
+ * non-empty window is returned (and reset) as that row's attribution.
43
+ */
44
+ export class CompactionAttributionWindow {
45
+ items = [];
46
+ /** Fold one session event into the window. Only `compaction/prune` and
47
+ * `compaction/summary` contribute items; every other event type is
48
+ * cluster-transparent (straggling tool results and step/turn boundaries
49
+ * interleave a prune batch without splitting it — a cluster ends only at
50
+ * a summary or at the window's consumption). */
51
+ observe(event) {
52
+ if (event.type === 'compaction/prune') {
53
+ const last = this.items[this.items.length - 1];
54
+ const tokens = shadowTokensOf(event.data.shadowedTokenCount);
55
+ if (last !== undefined && last.kind === 'prune') {
56
+ last.count += 1;
57
+ last.shadowedTokenCount += tokens;
58
+ }
59
+ else {
60
+ this.items.push({ kind: 'prune', count: 1, shadowedTokenCount: tokens });
61
+ }
62
+ return;
63
+ }
64
+ if (event.type === 'compaction/summary') {
65
+ this.items.push({ kind: 'summary', count: 1, shadowedTokenCount: shadowTokensOf(event.data.shadowedTokenCount) });
66
+ }
67
+ }
68
+ /** Take the window for a plain-request row: the accumulated attribution
69
+ * when any, and the window resets either way (the request consumed it).
70
+ * Only plain request rows consume — a compaction row is the rewrite's own
71
+ * billing row, and a failure row has no cache figures to explain; the
72
+ * window then survives until the next plain request, whose prefix the
73
+ * rewrite still precedes. */
74
+ consumeForRequest() {
75
+ if (this.items.length === 0)
76
+ return undefined;
77
+ const out = this.items;
78
+ this.items = [];
79
+ return out;
80
+ }
81
+ }
82
+ //# sourceMappingURL=compaction-attribution.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compaction-attribution.js","sourceRoot":"","sources":["../src/compaction-attribution.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAyBH;yEACyE;AACzE,SAAS,cAAc,CAAC,KAAc;IACpC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA;AACtF,CAAC;AAED;;;;;GAKG;AACH,MAAM,OAAO,2BAA2B;IAC9B,KAAK,GAAgC,EAAE,CAAA;IAE/C;;;;oDAIgD;IAChD,OAAO,CAAC,KAAmB;QACzB,IAAI,KAAK,CAAC,IAAI,KAAK,kBAAkB,EAAE,CAAC;YACtC,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAA;YAC9C,MAAM,MAAM,GAAG,cAAc,CAAC,KAAK,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAA;YAC5D,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;gBAChD,IAAI,CAAC,KAAK,IAAI,CAAC,CAAA;gBACf,IAAI,CAAC,kBAAkB,IAAI,MAAM,CAAA;YACnC,CAAC;iBAAM,CAAC;gBACN,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,EAAE,kBAAkB,EAAE,MAAM,EAAE,CAAC,CAAA;YAC1E,CAAC;YACD,OAAM;QACR,CAAC;QACD,IAAI,KAAK,CAAC,IAAI,KAAK,oBAAoB,EAAE,CAAC;YACxC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC,EAAE,kBAAkB,EAAE,cAAc,CAAC,KAAK,CAAC,IAAI,CAAC,kBAAkB,CAAC,EAAE,CAAC,CAAA;QACnH,CAAC;IACH,CAAC;IAED;;;;;iCAK6B;IAC7B,iBAAiB;QACf,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,SAAS,CAAA;QAC7C,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAA;QACtB,IAAI,CAAC,KAAK,GAAG,EAAE,CAAA;QACf,OAAO,GAAG,CAAA;IACZ,CAAC;CACF"}
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Field completion of the token-usage plugin: a registry of one-shot
3
+ * "fill this absent field from the session log" passes. Live projection
4
+ * and history sync already share {@link recordOfEvent}; a row written
5
+ * before a field existed is never updated by that path (`requestId`
6
+ * dedupe skips it). Each completer says which rows still lack its field
7
+ * and how one session's events prove the value. The log walks every
8
+ * pending completer in a single read of each session.
9
+ *
10
+ * Timing backfill stays outside this registry. It shipped first, with its
11
+ * own marker, and moving it would rewrite day files without filling
12
+ * anything new.
13
+ *
14
+ * @module token-usage/field-completion
15
+ */
16
+ import type { SessionEvent } from '@deepseek-ai/dsh-session';
17
+ import { type UsageRecord } from './usage-record.ts';
18
+ /**
19
+ * One optional field that can be proved from a session log after the row
20
+ * was written. `prove` walks the session once and returns request id →
21
+ * proof. `fill` applies that proof only when the field is still absent.
22
+ */
23
+ export interface FieldCompleter {
24
+ /** Stable id stored in `state.json` `completedFields`. */
25
+ readonly id: string;
26
+ /** Whether this row still lacks the field. Auxiliary rows and rows with
27
+ * no session are never candidates: the session log cannot prove them. */
28
+ needs(record: UsageRecord): boolean;
29
+ /** Proofs this session's events can offer, keyed by request id. */
30
+ prove(sessionId: string, events: readonly SessionEvent[]): ReadonlyMap<string, unknown>;
31
+ /** Write the proof onto the row when the field is still absent.
32
+ * @returns whether the row changed. */
33
+ fill(record: UsageRecord, proof: unknown): boolean;
34
+ }
35
+ /**
36
+ * Route key of a usage row. The first completer on this registry.
37
+ * Ordinary requests match `message.id` to `source.provider`. Compaction
38
+ * and `llm/retry` match their own event's route. A `turn/end` error has
39
+ * no route of its own; it takes the last `request/context` or
40
+ * `assistant/message` route at or before that seq, and stays blank when
41
+ * that walk proves nothing.
42
+ */
43
+ export declare const PROVIDER_FIELD: FieldCompleter;
44
+ /** Completers the startup pass runs. Append a field here; do not add another backfill function. */
45
+ export declare const FIELD_COMPLETERS: readonly FieldCompleter[];
46
+ //# sourceMappingURL=field-completion.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"field-completion.d.ts","sourceRoot":"","sources":["../src/field-completion.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAA;AAG5D,OAAO,EAAmB,KAAK,WAAW,EAAE,MAAM,mBAAmB,CAAA;AAErE;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC7B,0DAA0D;IAC1D,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;IACnB;6EACyE;IACzE,KAAK,CAAC,MAAM,EAAE,WAAW,GAAG,OAAO,CAAA;IACnC,mEAAmE;IACnE,KAAK,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,YAAY,EAAE,GAAG,WAAW,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IACvF;2CACuC;IACvC,IAAI,CAAC,MAAM,EAAE,WAAW,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAAA;CACnD;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,cAAc,EAAE,cAgC5B,CAAA;AAED,mGAAmG;AACnG,eAAO,MAAM,gBAAgB,EAAE,SAAS,cAAc,EAAqB,CAAA"}
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Field completion of the token-usage plugin: a registry of one-shot
3
+ * "fill this absent field from the session log" passes. Live projection
4
+ * and history sync already share {@link recordOfEvent}; a row written
5
+ * before a field existed is never updated by that path (`requestId`
6
+ * dedupe skips it). Each completer says which rows still lack its field
7
+ * and how one session's events prove the value. The log walks every
8
+ * pending completer in a single read of each session.
9
+ *
10
+ * Timing backfill stays outside this registry. It shipped first, with its
11
+ * own marker, and moving it would rewrite day files without filling
12
+ * anything new.
13
+ *
14
+ * @module token-usage/field-completion
15
+ */
16
+ import { providerOfEvent } from "./usage-record.js";
17
+ /**
18
+ * Route key of a usage row. The first completer on this registry.
19
+ * Ordinary requests match `message.id` to `source.provider`. Compaction
20
+ * and `llm/retry` match their own event's route. A `turn/end` error has
21
+ * no route of its own; it takes the last `request/context` or
22
+ * `assistant/message` route at or before that seq, and stays blank when
23
+ * that walk proves nothing.
24
+ */
25
+ export const PROVIDER_FIELD = {
26
+ id: 'provider',
27
+ needs(record) {
28
+ if (record.kind === 'aux')
29
+ return false;
30
+ if (record.sessionId === '')
31
+ return false;
32
+ return record.provider === undefined || record.provider === '';
33
+ },
34
+ prove(sessionId, events) {
35
+ const proofs = new Map();
36
+ let lastProvider = '';
37
+ for (const event of events) {
38
+ const revealed = providerOfEvent(event);
39
+ if (revealed !== undefined)
40
+ lastProvider = revealed;
41
+ if (event.type === 'assistant/message') {
42
+ const provider = event.data.message.source.provider;
43
+ if (provider !== '')
44
+ proofs.set(event.data.message.id, provider);
45
+ }
46
+ else if (event.type === 'compaction/summary') {
47
+ if (event.data.provider !== '')
48
+ proofs.set(`compaction:${sessionId}:${String(event.seq)}`, event.data.provider);
49
+ }
50
+ else if (event.type === 'llm/retry') {
51
+ if (event.data.provider !== '')
52
+ proofs.set(`failure:${sessionId}:${String(event.seq)}`, event.data.provider);
53
+ }
54
+ else if (event.type === 'turn/end' && event.data.reason.kind === 'error' && lastProvider !== '') {
55
+ proofs.set(`failure:${sessionId}:${String(event.seq)}`, lastProvider);
56
+ }
57
+ }
58
+ return proofs;
59
+ },
60
+ fill(record, proof) {
61
+ if (typeof proof !== 'string' || proof === '')
62
+ return false;
63
+ if (record.provider !== undefined && record.provider !== '')
64
+ return false;
65
+ record.provider = proof;
66
+ return true;
67
+ },
68
+ };
69
+ /** Completers the startup pass runs. Append a field here; do not add another backfill function. */
70
+ export const FIELD_COMPLETERS = [PROVIDER_FIELD];
71
+ //# sourceMappingURL=field-completion.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"field-completion.js","sourceRoot":"","sources":["../src/field-completion.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAKH,OAAO,EAAE,eAAe,EAAoB,MAAM,mBAAmB,CAAA;AAoBrE;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,cAAc,GAAmB;IAC5C,EAAE,EAAE,UAAU;IACd,KAAK,CAAC,MAAM;QACV,IAAI,MAAM,CAAC,IAAI,KAAK,KAAK;YAAE,OAAO,KAAK,CAAA;QACvC,IAAI,MAAM,CAAC,SAAS,KAAK,EAAE;YAAE,OAAO,KAAK,CAAA;QACzC,OAAO,MAAM,CAAC,QAAQ,KAAK,SAAS,IAAI,MAAM,CAAC,QAAQ,KAAK,EAAE,CAAA;IAChE,CAAC;IACD,KAAK,CAAC,SAAS,EAAE,MAAM;QACrB,MAAM,MAAM,GAAG,IAAI,GAAG,EAAkB,CAAA;QACxC,IAAI,YAAY,GAAG,EAAE,CAAA;QACrB,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;YAC3B,MAAM,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CAAC,GAAG,CAaxB,CAAA;AAEF,4EAA4E;AAC5E,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAyDnD;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,UAAU,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAOrE;AAED,eAAO,MAAM,IAAI,gBAAgB,CAAA;AACjC,eAAO,MAAM,MAAM,UAAqC,CAAA;AAmBxD,0FAA0F;AAC1F,eAAO,MAAM,cAAc,gBAAgB,CAAA;AAE3C;;;;;;;GAOG;AACH,MAAM,WAAW,aAAa;IAC5B,qEAAqE;IACrE,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,+FAA+F;IAC/F,aAAa,CAAC,EAAE,UAAU,GAAG,UAAU,CAAA;CACxC;AAaD,oDAAoD;AACpD,MAAM,WAAW,YAAY;IAC3B,sEAAsE;IACtE,UAAU,EAAE,MAAM,GAAG,SAAS,CAAA;IAC9B,mEAAmE;IACnE,mBAAmB,EAAE,MAAM,CAAA;CAC5B;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,wBAAwB,CAAC,SAAS,EAAE,SAAS,CAAC,SAAS;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,EAAE,CAAC,EAAE,GAAG,MAAM,CAcpG;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,EAAE,KAAK,EAAE,YAAY,GAAG,kBAAkB,CAIpG;AAED,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,GAAE,MAAW,QAs2BtD"}
package/lib/index.js CHANGED
@@ -23,15 +23,18 @@ import { credentialRef } from '@deepseek-ai/dsh-credentials';
23
23
  import z from '@deepseek-ai/schemastery';
24
24
  import { UsageLog } from "./usage-log.js";
25
25
  import { SessionMetaStore } from "./session-meta.js";
26
+ import { ProviderNameStore } from "./provider-names.js";
27
+ import { FIELD_COMPLETERS } from "./field-completion.js";
26
28
  import { cleanSource, copyData } from "./migrate.js";
27
29
  import { resolvePricingUrl, syncCloudPricing } from "./pricing.js";
28
30
  import { PricingAssociationService } from "./pricing-association-service.js";
29
31
  import { createPricingAssociationsRoute } from "./pricing-associations-route.js";
30
32
  import { withPricingDirectoryMigration } from "./pricing-associations.js";
31
- import { extractFirstTokenTimeFromStream, modelOfEvent, recordOfEvent, responseModelOfReplay } from "./usage-record.js";
33
+ import { extractFirstTokenTimeFromStream, modelOfEvent, providerOfEvent, recordOfEvent, responseModelOfReplay } from "./usage-record.js";
32
34
  import { RequestObserver } from "./request-observe.js";
35
+ import { CompactionAttributionWindow } from "./compaction-attribution.js";
33
36
  import { classifyAuxRequest, recordFromAuxRequest } from "./aux-request.js";
34
- import { markTimingSynced, readSyncState } from "./sync-state.js";
37
+ import { markFieldCompletionOutcome, markTimingSynced, pendingCompleterIds, readSyncState } from "./sync-state.js";
35
38
  import { autoSyncIfNeeded, syncHistory, titleOfEvent } from "./sync.js";
36
39
  import { clearRecordCache, warmRecordCache } from "./record-cache.js";
37
40
  import { invalidateSummary } from "./stats.js";
@@ -248,6 +251,43 @@ export function apply(ctx, config = {}) {
248
251
  // below read them per event and per request, so a settings-driven move
249
252
  // swaps the running directory without re-registering anything.
250
253
  let current;
254
+ /** Last provider directory this process could read. A bypass callback
255
+ * often runs after the llm context has gone inactive, and touching the
256
+ * service then throws; the refresh below keeps this snapshot instead. */
257
+ let namedProviders = [];
258
+ /** Replaced while the llm service is attached. Never throws. */
259
+ let refreshNamedProviders = () => { };
260
+ /** When the provider directory was last read. Every recorded row asks for
261
+ * the display names, so the host directory is consulted at most once per
262
+ * interval instead of once per request. */
263
+ let namedProvidersAt = 0;
264
+ const PROVIDER_REFRESH_MS = 1_000;
265
+ /** Snapshot display names. With `only`, just the route keys a new row named.
266
+ * `force` reads the directory right away — the startup and the llm attach
267
+ * path use it so a rename lands on disk without waiting for a request. */
268
+ const rememberProviderNames = (only, force = false) => {
269
+ const store = current?.names;
270
+ if (store === undefined)
271
+ return;
272
+ const now = Date.now();
273
+ if (force || now - namedProvidersAt >= PROVIDER_REFRESH_MS) {
274
+ namedProvidersAt = now;
275
+ refreshNamedProviders();
276
+ }
277
+ const patch = {};
278
+ for (const entry of namedProviders) {
279
+ if (typeof entry.displayName !== 'string' || entry.displayName === '')
280
+ continue;
281
+ if (only !== undefined && !only.includes(entry.provider))
282
+ continue;
283
+ patch[entry.provider] = entry.displayName;
284
+ }
285
+ if (Object.keys(patch).length === 0)
286
+ return;
287
+ void store.upsert(patch).catch((error) => {
288
+ logger.warn('[token-usage] provider name upsert failed:', error);
289
+ });
290
+ };
251
291
  // Serialized relocations: a move runs to settlement before the next begins,
252
292
  // so two quick edits cannot interleave two migrations of the same files.
253
293
  let relocating = Promise.resolve();
@@ -269,6 +309,14 @@ export function apply(ctx, config = {}) {
269
309
  */
270
310
  const currentDir = () => current?.dir ?? resolveDataDir(sectionSource().path);
271
311
  const associations = new PricingAssociationService(currentDir, logger);
312
+ /**
313
+ * The startup chain: the first-run history sync and the marker writes
314
+ * that follow it. A relocation waits for it — the chain writes the sync
315
+ * markers into the directory it started in, and a marker written after
316
+ * the copy would leave the source with a file the target never received.
317
+ * The source would then keep a stale copy and never be emptied.
318
+ */
319
+ let startup = Promise.resolve();
272
320
  /**
273
321
  * Move the running data directory as a two-phase commit: refuse while any
274
322
  * session is live (their events append to the source mid-copy), copy every
@@ -296,6 +344,13 @@ export function apply(ctx, config = {}) {
296
344
  // The metadata index writes on its own queue; drain it too, so the
297
345
  // sessions.json that migrates is final.
298
346
  await previous.meta.flush();
347
+ await previous.names.flush();
348
+ // The startup chain writes the sync markers into the directory it
349
+ // started in. It must finish before the copy: a marker written
350
+ // afterwards lands in the source only, and the size check would then
351
+ // refuse to delete it — the source directory would keep a stale
352
+ // marker and never be emptied.
353
+ await startup;
299
354
  migration = { phase: 'copying', done: 0, total: 0 };
300
355
  const report = (progress) => {
301
356
  migration = { ...progress };
@@ -310,7 +365,7 @@ export function apply(ctx, config = {}) {
310
365
  const log = new UsageLog(nextDir, logger);
311
366
  await log.scan();
312
367
  const moved = await log.refileByEventDay();
313
- current = { dir: nextDir, log, meta: new SessionMetaStore(nextDir, logger) };
368
+ current = { dir: nextDir, log, meta: new SessionMetaStore(nextDir, logger), names: new ProviderNameStore(nextDir, logger) };
314
369
  associations.directoryChanged();
315
370
  clearRecordCache(previous.dir);
316
371
  if (moved > 0)
@@ -511,6 +566,14 @@ export function apply(ctx, config = {}) {
511
566
  // the one authoritative source (the built-in fallback in
512
567
  // credentials.ts covers hosts without the llm service).
513
568
  llmCtx.effect(() => {
569
+ refreshNamedProviders = () => {
570
+ try {
571
+ namedProviders = llmCtx.llm.listConfigurableProviders();
572
+ }
573
+ catch {
574
+ // Inactive context: the last snapshot still names the routes.
575
+ }
576
+ };
514
577
  quotaDirectory = (provider) => {
515
578
  const entry = llmCtx.llm.listConfigurableProviders().find(item => item.provider === provider);
516
579
  return entry === undefined ? undefined : {
@@ -519,7 +582,14 @@ export function apply(ctx, config = {}) {
519
582
  displayName: entry.displayName,
520
583
  };
521
584
  };
522
- return () => { quotaDirectory = undefined; };
585
+ // The llm service is attached: read the directory right away, so the
586
+ // names land on disk without waiting for the next recorded row.
587
+ rememberProviderNames(undefined, true);
588
+ return () => {
589
+ quotaDirectory = undefined;
590
+ refreshNamedProviders = () => { };
591
+ namedProviders = [];
592
+ };
523
593
  }, 'token-usage: quota provider directory');
524
594
  });
525
595
  ctx.inject(['settings'], (settingsCtx) => {
@@ -687,7 +757,7 @@ export function apply(ctx, config = {}) {
687
757
  requestId,
688
758
  });
689
759
  }
690
- void target.log.record(recordFromAuxRequest({
760
+ const row = recordFromAuxRequest({
691
761
  auxKind,
692
762
  requestId,
693
763
  time: startedAt,
@@ -695,7 +765,11 @@ export function apply(ctx, config = {}) {
695
765
  ...(sessionId !== undefined ? { sessionId } : {}),
696
766
  ...(responseModel !== undefined ? { responseModel } : {}),
697
767
  ...(usage !== undefined ? { usage } : {}),
698
- }));
768
+ ...(options.provider !== undefined && options.provider !== '' ? { provider: options.provider } : {}),
769
+ });
770
+ if (row.provider !== undefined)
771
+ rememberProviderNames([row.provider]);
772
+ void target.log.record(row);
699
773
  }
700
774
  }
701
775
  }
@@ -752,7 +826,8 @@ export function apply(ctx, config = {}) {
752
826
  const dir = resolved;
753
827
  const log = new UsageLog(dir, logger);
754
828
  const meta = new SessionMetaStore(dir, logger);
755
- current = { dir, log, meta };
829
+ current = { dir, log, meta, names: new ProviderNameStore(dir, logger) };
830
+ rememberProviderNames(undefined, true);
756
831
  associations.directoryChanged();
757
832
  void warmRecordCache(dir, undefined, logger);
758
833
  // Last-known route model per session: failure rows need a model to
@@ -760,6 +835,20 @@ export function apply(ctx, config = {}) {
760
835
  // events the sync walk does (request/context route changes, then
761
836
  // assistant/message confirmations). Bounded by the session count.
762
837
  const lastModel = new Map();
838
+ const lastProvider = new Map();
839
+ // Per-session compaction attribution windows (the shared implementation
840
+ // the history rescan also drives): compaction events since the session's
841
+ // last plain request, attached to the next plain-request row. Bounded by
842
+ // the session count, same as the route maps above.
843
+ const attributionWindows = new Map();
844
+ const attributionWindowOf = (sessionId) => {
845
+ let window = attributionWindows.get(sessionId);
846
+ if (window === undefined) {
847
+ window = new CompactionAttributionWindow();
848
+ attributionWindows.set(sessionId, window);
849
+ }
850
+ return window;
851
+ };
763
852
  const activeSteps = new Map();
764
853
  // Header facts are immutable, so one upsert per session is enough even
765
854
  // though events keep arriving; the index store dedupes the write anyway.
@@ -823,9 +912,25 @@ export function apply(ctx, config = {}) {
823
912
  const revealed = modelOfEvent(event);
824
913
  if (revealed !== undefined)
825
914
  lastModel.set(session.id, revealed);
826
- const record = recordOfEvent(event, session.id, lastModel.get(session.id) ?? '', recordCompaction, timing);
915
+ const revealedProvider = providerOfEvent(event);
916
+ if (revealedProvider !== undefined)
917
+ lastProvider.set(session.id, revealedProvider);
918
+ const attributionWindow = attributionWindowOf(session.id);
919
+ attributionWindow.observe(event);
920
+ const record = recordOfEvent(event, session.id, lastModel.get(session.id) ?? '', recordCompaction, timing, lastProvider.get(session.id) ?? '');
827
921
  if (record === null)
828
922
  return;
923
+ // The attribution lands only on plain-request rows: the compaction
924
+ // row is the rewrite's own billing row, a failure row has no cache
925
+ // figures to explain, and the window then survives to the next plain
926
+ // request, whose prefix the rewrite still precedes.
927
+ if (record.kind === undefined || record.kind === 'request') {
928
+ const attribution = attributionWindow.consumeForRequest();
929
+ if (attribution !== undefined)
930
+ record.compactionAttribution = attribution;
931
+ }
932
+ if (record.provider !== undefined)
933
+ rememberProviderNames([record.provider]);
829
934
  // Fire-and-forget: the log serializes appends and reports its own failures.
830
935
  void current?.log.record(requestObserver.decorateRecord(record));
831
936
  });
@@ -833,7 +938,7 @@ export function apply(ctx, config = {}) {
833
938
  // one-shot backfill. Both share the log's append queue, so a live write
834
939
  // cannot interleave with the rewrite. History sync then lands each new
835
940
  // row on the event's own day.
836
- void log.refileByEventDay()
941
+ startup = log.refileByEventDay()
837
942
  .then((moved) => {
838
943
  if (moved > 0) {
839
944
  logger.info(`[token-usage] refiled ${String(moved)} rows onto event-day files`);
@@ -845,6 +950,12 @@ export function apply(ctx, config = {}) {
845
950
  } }, dir);
846
951
  })
847
952
  .then(async (result) => {
953
+ // The directory may have moved while the first-run sync ran: the
954
+ // markers below belong to the directory now in force. Writing them
955
+ // into the directory that just moved would leave a stray marker —
956
+ // and, mid-write, its temp file — behind in the source.
957
+ const liveDir = current?.dir ?? dir;
958
+ const liveLog = current?.log ?? log;
848
959
  if (result !== null) {
849
960
  logger.info(`[token-usage] first-run sync: ${result.added} added, ${result.skipped} skipped, ${String(result.removed)} removed, ${String(result.failedSessions)} failed sessions`);
850
961
  // Appended rows (compactions backfilled by an upgrade, or requests
@@ -853,18 +964,34 @@ export function apply(ctx, config = {}) {
853
964
  // the new contents — including writes into frozen day files the
854
965
  // rollup may already have absorbed.
855
966
  if (result.added > 0 || result.removed > 0)
856
- invalidateDerivedState(dir);
967
+ invalidateDerivedState(liveDir);
857
968
  }
858
- const state = await readSyncState(dir, logger);
969
+ const state = await readSyncState(liveDir, logger);
859
970
  if (state !== null && state.timingSyncedAt === undefined && ctx.sessionPersistence !== undefined) {
860
- const patched = await log.backfillTiming(ctx.sessionPersistence);
971
+ const patched = await liveLog.backfillTiming(ctx.sessionPersistence);
861
972
  if (patched > 0) {
862
973
  logger.info(`[token-usage] backfilled timing figures for ${String(patched)} historical records`);
863
- invalidateDerivedState(dir);
974
+ invalidateDerivedState(liveDir);
975
+ }
976
+ await markTimingSynced(liveDir);
977
+ }
978
+ const pending = pendingCompleterIds(await readSyncState(liveDir, logger), FIELD_COMPLETERS.map(completer => completer.id));
979
+ if (pending.length > 0 && ctx.sessionPersistence !== undefined) {
980
+ const completion = await liveLog.completeFields(ctx.sessionPersistence, FIELD_COMPLETERS.filter(completer => pending.includes(completer.id)));
981
+ if (completion.patched > 0) {
982
+ logger.info(`[token-usage] completed fields on ${String(completion.patched)} historical records`);
983
+ invalidateDerivedState(liveDir);
984
+ }
985
+ const settled = await markFieldCompletionOutcome(liveDir, {
986
+ cleanIds: completion.cleanIds,
987
+ retriedIds: completion.retriedIds,
988
+ });
989
+ const abandoned = settled.filter(id => completion.retriedIds.includes(id));
990
+ if (abandoned.length > 0) {
991
+ logger.warn(`[token-usage] field completion gave up on unreadable sessions for: ${abandoned.join(', ')}`);
864
992
  }
865
- await markTimingSynced(dir);
866
993
  }
867
- return warmRecordCache(dir, undefined, logger);
994
+ return warmRecordCache(liveDir, undefined, logger);
868
995
  })
869
996
  .catch((error) => {
870
997
  logger.error('[token-usage] first-run sync failed:', error);
@@ -881,6 +1008,9 @@ export function apply(ctx, config = {}) {
881
1008
  // re-prices the page's currency on the next fetch without a restart.
882
1009
  webCtx.effect(() => webCtx.webServer.register(createStatsRoute(currentDir, {
883
1010
  currency: () => currencyOfRegion(effectiveInput().pricingRegion),
1011
+ // The provider dimension's display names: the running directory's
1012
+ // registry, read per request so a relocation serves the moved file.
1013
+ providerNames: () => current?.names.read() ?? Promise.resolve({}),
884
1014
  logger,
885
1015
  live: () => ({
886
1016
  snapshot: (sessionIds) => {