@open33/harness-token-meter 0.0.0-stage → 0.1.0

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 (74) hide show
  1. package/LICENSE +22 -0
  2. package/README.i18n.yaml +64 -0
  3. package/README.md +162 -2
  4. package/README.zh.md +163 -0
  5. package/lib/index.js +981 -0
  6. package/lib/types/breakdown-projection.d.ts +128 -0
  7. package/lib/types/breakdown-projection.d.ts.map +1 -0
  8. package/lib/types/breakdown-projection.js +153 -0
  9. package/lib/types/breakdown-projection.js.map +1 -0
  10. package/lib/types/client.d.ts +9 -0
  11. package/lib/types/client.d.ts.map +1 -0
  12. package/lib/types/client.js +7 -0
  13. package/lib/types/client.js.map +1 -0
  14. package/lib/types/estimate.d.ts +50 -0
  15. package/lib/types/estimate.d.ts.map +1 -0
  16. package/lib/types/estimate.js +95 -0
  17. package/lib/types/estimate.js.map +1 -0
  18. package/lib/types/index.d.ts +73 -0
  19. package/lib/types/index.d.ts.map +1 -0
  20. package/lib/types/index.js +239 -0
  21. package/lib/types/index.js.map +1 -0
  22. package/lib/types/measurement-projection.d.ts +74 -0
  23. package/lib/types/measurement-projection.d.ts.map +1 -0
  24. package/lib/types/measurement-projection.js +94 -0
  25. package/lib/types/measurement-projection.js.map +1 -0
  26. package/lib/types/projection.d.ts +74 -0
  27. package/lib/types/projection.d.ts.map +1 -0
  28. package/lib/types/projection.js +7 -0
  29. package/lib/types/projection.js.map +1 -0
  30. package/lib/types/route-pricing.d.ts +31 -0
  31. package/lib/types/route-pricing.d.ts.map +1 -0
  32. package/lib/types/route-pricing.js +56 -0
  33. package/lib/types/route-pricing.js.map +1 -0
  34. package/lib/types/surface-fold.d.ts +68 -0
  35. package/lib/types/surface-fold.d.ts.map +1 -0
  36. package/lib/types/surface-fold.js +98 -0
  37. package/lib/types/surface-fold.js.map +1 -0
  38. package/lib/types/surface-projection.d.ts +58 -0
  39. package/lib/types/surface-projection.d.ts.map +1 -0
  40. package/lib/types/surface-projection.js +68 -0
  41. package/lib/types/surface-projection.js.map +1 -0
  42. package/lib/types/turn-usage.d.ts +33 -0
  43. package/lib/types/turn-usage.d.ts.map +1 -0
  44. package/lib/types/turn-usage.js +229 -0
  45. package/lib/types/turn-usage.js.map +1 -0
  46. package/lib/types/types.d.ts +56 -0
  47. package/lib/types/types.d.ts.map +1 -0
  48. package/lib/types/types.js +7 -0
  49. package/lib/types/types.js.map +1 -0
  50. package/lib/types/usage-projection.d.ts +196 -0
  51. package/lib/types/usage-projection.d.ts.map +1 -0
  52. package/lib/types/usage-projection.js +190 -0
  53. package/lib/types/usage-projection.js.map +1 -0
  54. package/locale/de.json +6 -0
  55. package/locale/en.json +5 -0
  56. package/locale/es.json +6 -0
  57. package/locale/fr.json +6 -0
  58. package/locale/ja.json +6 -0
  59. package/locale/pt.json +6 -0
  60. package/locale/ru.json +6 -0
  61. package/locale/zh.json +6 -0
  62. package/package.json +64 -3
  63. package/src/breakdown-projection.ts +184 -0
  64. package/src/client.ts +9 -0
  65. package/src/estimate.ts +102 -0
  66. package/src/index.ts +296 -0
  67. package/src/measurement-projection.ts +100 -0
  68. package/src/projection.ts +79 -0
  69. package/src/route-pricing.ts +76 -0
  70. package/src/surface-fold.ts +142 -0
  71. package/src/surface-projection.ts +96 -0
  72. package/src/turn-usage.ts +274 -0
  73. package/src/types.ts +54 -0
  74. package/src/usage-projection.ts +213 -0
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Positional pricing for measurement: each retained node keeps its identity,
3
+ * heuristic price, and the attachment details route pricing replaces. The
4
+ * occupancy and context-breakdown projections use the scalar shadow-price
5
+ * protocol instead.
6
+ *
7
+ * The fold is a plan/commit pair: {@link planSurfaceTokens} runs every
8
+ * fallible step read-only and {@link commitSurfaceTokens} mutates in place,
9
+ * so a throw leaves the caller's state untouched and the same malformed
10
+ * event fails identically on every retry.
11
+ * Nodes also carry durable attachment occurrences and their structural prices,
12
+ * so `measure()` can price the request representation sent to the model.
13
+ *
14
+ * @module @open33/harness-token-meter/surface-fold
15
+ */
16
+ import type { SessionSeq, SurfaceEvent } from '@open33/harness-session';
17
+ import type { ContentBlock, ImageBlock } from '@open33/harness-llm';
18
+ type FileAttachmentRef = Extract<ContentBlock, {
19
+ type: 'file';
20
+ }>['attachment'];
21
+ /** One priced surface node with the image occurrences route pricing replaces. */
22
+ export interface MeterSurfaceNode {
23
+ /** Durable sequence number of the surface event. */
24
+ readonly seq: SessionSeq;
25
+ /** Fixed-heuristic price of the node's exact message. */
26
+ readonly heuristicTokens: number;
27
+ /** Structural JSON price replaced when the routed request projects images. */
28
+ readonly imageStructuralTokens: number;
29
+ /** Structural JSON price replaced when request assembly projects files to text. */
30
+ readonly fileStructuralTokens: number;
31
+ /** Durable image blocks in message order, `offloaded` marks included; empty for image-free nodes. */
32
+ readonly images: readonly ImageBlock[];
33
+ /** Durable file occurrences in message order; empty for file-free nodes. */
34
+ readonly files: readonly FileAttachmentRef[];
35
+ }
36
+ /** One validated surface transition that has not mutated the priced surface yet. */
37
+ export interface SurfaceTokenPlan<Node = MeterSurfaceNode> {
38
+ /** Heuristic price of the event's own message; 0 when it derives none. */
39
+ readonly tokens: number;
40
+ /** Signed change in the surface total: `tokens` minus anything shadowed. */
41
+ readonly deltaTokens: number;
42
+ /** The priced node the commit inserts for this event. */
43
+ readonly node: Node;
44
+ /** Commit position: `append`, or the inclusive replaced index range. */
45
+ readonly target: 'append' | {
46
+ readonly startIdx: number;
47
+ readonly endIdx: number;
48
+ };
49
+ }
50
+ /**
51
+ * Validate and price one surface event without mutating the surface.
52
+ * @param nodes - the priced surface preceding this event, in model-visible order.
53
+ * @param event - the surface event to place.
54
+ * @returns the plan for {@link commitSurfaceTokens}.
55
+ * @throws when a replacement names a range absent from `nodes` — committed
56
+ * logs are surface-validated at append time, so an unresolvable range is log
57
+ * corruption and must fail loud rather than skip the event.
58
+ */
59
+ export declare function planSurfaceTokens(nodes: readonly Pick<MeterSurfaceNode, 'seq' | 'heuristicTokens'>[], event: SurfaceEvent): SurfaceTokenPlan;
60
+ /**
61
+ * Apply one validated plan to the priced surface in place; infallible, so it
62
+ * cannot leave a half-applied surface behind.
63
+ * @param nodes - the exact priced surface the plan was built against.
64
+ * @param plan - the transition returned by {@link planSurfaceTokens}.
65
+ */
66
+ export declare function commitSurfaceTokens<Node>(nodes: Node[], plan: SurfaceTokenPlan<Node>): void;
67
+ export {};
68
+ //# sourceMappingURL=surface-fold.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"surface-fold.d.ts","sourceRoot":"","sources":["../../src/surface-fold.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAA;AACvE,OAAO,KAAK,EAAE,YAAY,EAAE,UAAU,EAAW,MAAM,qBAAqB,CAAA;AAG5E,KAAK,iBAAiB,GAAG,OAAO,CAAC,YAAY,EAAE;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC,YAAY,CAAC,CAAA;AAE9E,iFAAiF;AACjF,MAAM,WAAW,gBAAgB;IAC/B,oDAAoD;IACpD,QAAQ,CAAC,GAAG,EAAE,UAAU,CAAA;IACxB,yDAAyD;IACzD,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAA;IAChC,8EAA8E;IAC9E,QAAQ,CAAC,qBAAqB,EAAE,MAAM,CAAA;IACtC,mFAAmF;IACnF,QAAQ,CAAC,oBAAoB,EAAE,MAAM,CAAA;IACrC,qGAAqG;IACrG,QAAQ,CAAC,MAAM,EAAE,SAAS,UAAU,EAAE,CAAA;IACtC,4EAA4E;IAC5E,QAAQ,CAAC,KAAK,EAAE,SAAS,iBAAiB,EAAE,CAAA;CAC7C;AAED,oFAAoF;AACpF,MAAM,WAAW,gBAAgB,CAAC,IAAI,GAAG,gBAAgB;IACvD,0EAA0E;IAC1E,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,4EAA4E;IAC5E,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAA;IAC5B,yDAAyD;IACzD,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAA;IACnB,wEAAwE;IACxE,QAAQ,CAAC,MAAM,EAAE,QAAQ,GAAG;QAAE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAA;CACnF;AAgDD;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAC/B,KAAK,EAAE,SAAS,IAAI,CAAC,gBAAgB,EAAE,KAAK,GAAG,iBAAiB,CAAC,EAAE,EACnE,KAAK,EAAE,YAAY,GAClB,gBAAgB,CAkBlB;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,gBAAgB,CAAC,IAAI,CAAC,GAAG,IAAI,CAM3F"}
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Positional pricing for measurement: each retained node keeps its identity,
3
+ * heuristic price, and the attachment details route pricing replaces. The
4
+ * occupancy and context-breakdown projections use the scalar shadow-price
5
+ * protocol instead.
6
+ *
7
+ * The fold is a plan/commit pair: {@link planSurfaceTokens} runs every
8
+ * fallible step read-only and {@link commitSurfaceTokens} mutates in place,
9
+ * so a throw leaves the caller's state untouched and the same malformed
10
+ * event fails identically on every retry.
11
+ * Nodes also carry durable attachment occurrences and their structural prices,
12
+ * so `measure()` can price the request representation sent to the model.
13
+ *
14
+ * @module @open33/harness-token-meter/surface-fold
15
+ */
16
+ import { deriveEventMessage } from '@open33/harness-session';
17
+ import { estimateMessage, estimateStructuralBlock } from "./estimate.js";
18
+ /** Collect projected attachment occurrences and their structural prices. */
19
+ function collectProjectedAttachments(blocks, images, files) {
20
+ let imageTokens = 0;
21
+ let fileTokens = 0;
22
+ for (const block of blocks) {
23
+ if (block.type === 'image') {
24
+ images.push(block);
25
+ imageTokens += estimateStructuralBlock(block);
26
+ }
27
+ else if (block.type === 'file') {
28
+ files.push(block.attachment);
29
+ fileTokens += estimateStructuralBlock(block);
30
+ }
31
+ }
32
+ return { imageTokens, fileTokens };
33
+ }
34
+ /** Build one priced node from a surface event's derived message. */
35
+ function analyzeNode(seq, message) {
36
+ if (message === null) {
37
+ return {
38
+ seq,
39
+ heuristicTokens: 0,
40
+ imageStructuralTokens: 0,
41
+ fileStructuralTokens: 0,
42
+ images: [],
43
+ files: [],
44
+ };
45
+ }
46
+ const heuristicTokens = estimateMessage(message);
47
+ const images = [];
48
+ const files = [];
49
+ const structural = collectProjectedAttachments(message.content, images, files);
50
+ return {
51
+ seq,
52
+ heuristicTokens,
53
+ imageStructuralTokens: structural.imageTokens,
54
+ fileStructuralTokens: structural.fileTokens,
55
+ images,
56
+ files,
57
+ };
58
+ }
59
+ /**
60
+ * Validate and price one surface event without mutating the surface.
61
+ * @param nodes - the priced surface preceding this event, in model-visible order.
62
+ * @param event - the surface event to place.
63
+ * @returns the plan for {@link commitSurfaceTokens}.
64
+ * @throws when a replacement names a range absent from `nodes` — committed
65
+ * logs are surface-validated at append time, so an unresolvable range is log
66
+ * corruption and must fail loud rather than skip the event.
67
+ */
68
+ export function planSurfaceTokens(nodes, event) {
69
+ const node = analyzeNode(event.seq, deriveEventMessage(event));
70
+ const tokens = node.heuristicTokens;
71
+ const op = event.surfaceOp;
72
+ if (op === 'append') {
73
+ return { tokens, deltaTokens: tokens, node, target: 'append' };
74
+ }
75
+ const startIdx = nodes.findIndex(candidate => candidate.seq === op.startSeq);
76
+ const endIdx = nodes.findIndex(candidate => candidate.seq === op.endSeq);
77
+ if (startIdx === -1 || endIdx === -1 || startIdx > endIdx) {
78
+ throw new Error(`token surface: replace at seq ${event.seq} has invalid current range ${op.startSeq}-${op.endSeq}`);
79
+ }
80
+ const removed = nodes
81
+ .slice(startIdx, endIdx + 1)
82
+ .reduce((total, candidate) => total + candidate.heuristicTokens, 0);
83
+ return { tokens, deltaTokens: tokens - removed, node, target: { startIdx, endIdx } };
84
+ }
85
+ /**
86
+ * Apply one validated plan to the priced surface in place; infallible, so it
87
+ * cannot leave a half-applied surface behind.
88
+ * @param nodes - the exact priced surface the plan was built against.
89
+ * @param plan - the transition returned by {@link planSurfaceTokens}.
90
+ */
91
+ export function commitSurfaceTokens(nodes, plan) {
92
+ if (plan.target === 'append') {
93
+ nodes.push(plan.node);
94
+ return;
95
+ }
96
+ nodes.splice(plan.target.startIdx, plan.target.endIdx - plan.target.startIdx + 1, plan.node);
97
+ }
98
+ //# sourceMappingURL=surface-fold.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"surface-fold.js","sourceRoot":"","sources":["../../src/surface-fold.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAA;AAG5D,OAAO,EAAE,eAAe,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAA;AAgCxE,4EAA4E;AAC5E,SAAS,2BAA2B,CAClC,MAA+B,EAC/B,MAAoB,EACpB,KAA0B;IAE1B,IAAI,WAAW,GAAG,CAAC,CAAA;IACnB,IAAI,UAAU,GAAG,CAAC,CAAA;IAClB,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QAC3B,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;YAC3B,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;YAClB,WAAW,IAAI,uBAAuB,CAAC,KAAK,CAAC,CAAA;QAC/C,CAAC;aAAM,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YACjC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAA;YAC5B,UAAU,IAAI,uBAAuB,CAAC,KAAK,CAAC,CAAA;QAC9C,CAAC;IACH,CAAC;IACD,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,CAAA;AACpC,CAAC;AAED,oEAAoE;AACpE,SAAS,W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EAAE,CAAC,SAAS,CAAC,GAAG,KAAK,EAAE,CAAC,MAAM,CAAC,CAAA;IACxE,IAAI,QAAQ,KAAK,CAAC,CAAC,IAAI,MAAM,KAAK,CAAC,CAAC,IAAI,QAAQ,GAAG,MAAM,EAAE,CAAC;QAC1D,MAAM,IAAI,KAAK,CACb,iCAAiC,KAAK,CAAC,GAAG,8BAA8B,EAAE,CAAC,QAAQ,IAAI,EAAE,CAAC,MAAM,EAAE,CACnG,CAAA;IACH,CAAC;IACD,MAAM,OAAO,GAAG,KAAK;SAClB,KAAK,CAAC,QAAQ,EAAE,MAAM,GAAG,CAAC,CAAC;SAC3B,MAAM,CAAC,CAAC,KAAK,EAAE,SAAS,EAAE,EAAE,CAAC,KAAK,GAAG,SAAS,CAAC,eAAe,EAAE,CAAC,CAAC,CAAA;IACrE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,CAAA;AACtF,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CAAO,KAAa,EAAE,IAA4B;IACnF,IAAI,IAAI,CAAC,MAAM,KAAK,QAAQ,EAAE,CAAC;QAC7B,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QACrB,OAAM;IACR,CAAC;IACD,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,QAAQ,GAAG,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,CAAA;AAC9F,CAAC"}
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The context-pressure projection's O(1) surface-token fold.
3
+ *
4
+ * Its checkpoint keeps scalar totals rather than the retained surface used
5
+ * by measurement. Replacements ride the compact
6
+ * seam's shadow-price protocol: the metering event immediately before a
7
+ * surface `replace` (`compaction/summary` or `compaction/prune`) states the
8
+ * heuristic price of the exact replaced range, so the fold keeps a running
9
+ * total plus at most one pending claim and never retains per-node prices.
10
+ * The counts are exact by construction: producers derive them from the same
11
+ * fixed estimator this module prices appends with. A replacement without an
12
+ * armed claim folds with zero delta because bounded state cannot reconstruct
13
+ * the replaced range; this preserves replay at the cost of possible drift.
14
+ *
15
+ * @module @open33/harness-token-meter/surface-projection
16
+ */
17
+ import { SessionSeq } from '@open33/harness-session';
18
+ import type { SessionEvent } from '@open33/harness-session';
19
+ /**
20
+ * One armed shadow price: the heuristic tokens of the surface range the
21
+ * IMMEDIATELY following event replaces. Plain JSON — it is part of the
22
+ * persisted unit state while armed.
23
+ */
24
+ export interface ShadowPriceClaim {
25
+ /** Declared inclusive first surface-node seq of the priced range. */
26
+ start: SessionSeq;
27
+ /** Declared inclusive last surface-node seq of the priced range. */
28
+ end: SessionSeq;
29
+ /** Heuristic tokens of the priced range under the fixed estimator. */
30
+ tokens: number;
31
+ }
32
+ /** One event's effect on a running surface-token total. */
33
+ export interface SurfaceTokensFold {
34
+ /** Signed change in the surface total; 0 for events off the surface. */
35
+ readonly deltaTokens: number;
36
+ /** Claim to carry into the next event; undefined when none survives. */
37
+ readonly claim: ShadowPriceClaim | undefined;
38
+ }
39
+ /**
40
+ * Fold one committed event onto a running surface-token total.
41
+ *
42
+ * A shadow-price event arms a claim; any other event expires it, and a
43
+ * surface `replace` consumes the claim naming its exact range — the
44
+ * producers append the metering event and the replacement synchronously
45
+ * adjacent, so a surviving claim always prices the very next event.
46
+ * A replace with no claim folds with zero delta because the bounded state
47
+ * cannot reconstruct the replaced range. An armed claim for another range
48
+ * still fails because the adjacent events contradict each other.
49
+ * @param claim - the claim armed by the immediately preceding event, if any.
50
+ * @param event - the next committed session event.
51
+ * @returns the signed token delta and the claim state after this event.
52
+ * @throws when a replacement arrives with an armed claim for a different
53
+ * range — the metering event was adjacent, so this is a live producer's
54
+ * shadow-price contract violation, not historical data, and must fail
55
+ * loud rather than let the total drift.
56
+ */
57
+ export declare function foldSurfaceProjection(claim: ShadowPriceClaim | undefined, event: SessionEvent): SurfaceTokensFold;
58
+ //# sourceMappingURL=surface-projection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"surface-projection.d.ts","sourceRoot":"","sources":["../../src/surface-projection.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAsC,UAAU,EAAE,MAAM,yBAAyB,CAAA;AACxF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAA;AAK3D;;;;GAIG;AACH,MAAM,WAAW,gBAAgB;IAC/B,qEAAqE;IACrE,KAAK,EAAE,UAAU,CAAA;IACjB,oEAAoE;IACpE,GAAG,EAAE,UAAU,CAAA;IACf,sEAAsE;IACtE,MAAM,EAAE,MAAM,CAAA;CACf;AAED,2DAA2D;AAC3D,MAAM,WAAW,iBAAiB;IAChC,wEAAwE;IACxE,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAA;IAC5B,wEAAwE;IACxE,QAAQ,CAAC,KAAK,EAAE,gBAAgB,GAAG,SAAS,CAAA;CAC7C;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,qBAAqB,CACnC,KAAK,EAAE,gBAAgB,GAAG,SAAS,EACnC,KAAK,EAAE,YAAY,GAClB,iBAAiB,CA6BnB"}
@@ -0,0 +1,68 @@
1
+ /**
2
+ * The context-pressure projection's O(1) surface-token fold.
3
+ *
4
+ * Its checkpoint keeps scalar totals rather than the retained surface used
5
+ * by measurement. Replacements ride the compact
6
+ * seam's shadow-price protocol: the metering event immediately before a
7
+ * surface `replace` (`compaction/summary` or `compaction/prune`) states the
8
+ * heuristic price of the exact replaced range, so the fold keeps a running
9
+ * total plus at most one pending claim and never retains per-node prices.
10
+ * The counts are exact by construction: producers derive them from the same
11
+ * fixed estimator this module prices appends with. A replacement without an
12
+ * armed claim folds with zero delta because bounded state cannot reconstruct
13
+ * the replaced range; this preserves replay at the cost of possible drift.
14
+ *
15
+ * @module @open33/harness-token-meter/surface-projection
16
+ */
17
+ import { deriveEventMessage, isSurfaceEvent, SessionSeq } from '@open33/harness-session';
18
+ import { estimateMessage } from "./estimate.js";
19
+ /**
20
+ * Fold one committed event onto a running surface-token total.
21
+ *
22
+ * A shadow-price event arms a claim; any other event expires it, and a
23
+ * surface `replace` consumes the claim naming its exact range — the
24
+ * producers append the metering event and the replacement synchronously
25
+ * adjacent, so a surviving claim always prices the very next event.
26
+ * A replace with no claim folds with zero delta because the bounded state
27
+ * cannot reconstruct the replaced range. An armed claim for another range
28
+ * still fails because the adjacent events contradict each other.
29
+ * @param claim - the claim armed by the immediately preceding event, if any.
30
+ * @param event - the next committed session event.
31
+ * @returns the signed token delta and the claim state after this event.
32
+ * @throws when a replacement arrives with an armed claim for a different
33
+ * range — the metering event was adjacent, so this is a live producer's
34
+ * shadow-price contract violation, not historical data, and must fail
35
+ * loud rather than let the total drift.
36
+ */
37
+ export function foldSurfaceProjection(claim, event) {
38
+ if (event.type === 'compaction/summary' || event.type === 'compaction/prune') {
39
+ const { shadowedRange, shadowedTokenCount } = event.data;
40
+ return {
41
+ deltaTokens: 0,
42
+ claim: {
43
+ start: SessionSeq(shadowedRange.start),
44
+ end: SessionSeq(shadowedRange.end),
45
+ tokens: shadowedTokenCount,
46
+ },
47
+ };
48
+ }
49
+ if (!isSurfaceEvent(event))
50
+ return { deltaTokens: 0, claim: undefined };
51
+ const message = deriveEventMessage(event);
52
+ const tokens = message === null ? 0 : estimateMessage(message);
53
+ const op = event.surfaceOp;
54
+ if (op === 'append')
55
+ return { deltaTokens: tokens, claim: undefined };
56
+ // Sessions recorded before the shadow-price protocol log replacements with
57
+ // no adjacent metering event; the bounded state cannot reconstruct the
58
+ // replaced range's price, so fold those neutrally — historical replay
59
+ // degrades to drift instead of failing.
60
+ if (claim === undefined)
61
+ return { deltaTokens: 0, claim: undefined };
62
+ if (claim.start !== op.startSeq || claim.end !== op.endSeq) {
63
+ throw new Error(`token surface: replace at seq ${event.seq} over range ${op.startSeq}-${op.endSeq} has no adjacent shadow price`
64
+ + ` (armed claim covers ${claim.start}-${claim.end})`);
65
+ }
66
+ return { deltaTokens: tokens - claim.tokens, claim: undefined };
67
+ }
68
+ //# sourceMappingURL=surface-projection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"surface-projection.js","sourceRoot":"","sources":["../../src/surface-projection.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,kBAAkB,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAA;AAIxF,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAA;AAwB/C;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,qBAAqB,CACnC,KAAmC,EACnC,KAAmB;IAEnB,IAAI,KAAK,CAAC,IAAI,KAAK,oBAAoB,IAAI,KAAK,CAAC,IAAI,KAAK,kBAAkB,EAAE,CAAC;QAC7E,MAAM,EAAE,aAAa,EAAE,kBAAkB,EAAE,GAAG,KAAK,CAAC,IAAI,CAAA;QACxD,OAAO;YACL,WAAW,EAAE,CAAC;YACd,KAAK,EAAE;gBACL,KAAK,EAAE,UAAU,CAAC,aAAa,CAAC,KAAK,CAAC;gBACtC,GAAG,EAAE,UAAU,CAAC,aAAa,CAAC,GAAG,CAAC;gBAClC,MAAM,EAAE,kBAAkB;aAC3B;SACF,CAAA;IACH,CAAC;IACD,IAAI,CAAC,cAAc,CAAC,KAAK,CAAC;QAAE,OAAO,EAAE,WAAW,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,CAAA;IACvE,MAAM,OAAO,GAAG,kBAAkB,CAAC,KAAK,CAAC,CAAA;IACzC,MAAM,MAAM,GAAG,OAAO,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,OAAO,CAAC,CAAA;IAC9D,MAAM,EAAE,GAAG,KAAK,CAAC,SAAS,CAAA;IAC1B,IAAI,EAAE,KAAK,QAAQ;QAAE,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,CAAA;IACrE,2EAA2E;IAC3E,uEAAuE;IACvE,sEAAsE;IACtE,wCAAwC;IACxC,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,EAAE,WAAW,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,CAAA;IACpE,IAAI,KAAK,CAAC,KAAK,KAAK,EAAE,CAAC,QAAQ,IAAI,KAAK,CAAC,GAAG,KAAK,EAAE,CAAC,MAAM,EAAE,CAAC;QAC3D,MAAM,IAAI,KAAK,CACb,iCAAiC,KAAK,CAAC,GAAG,eAAe,EAAE,CAAC,QAAQ,IAAI,EAAE,CAAC,MAAM,+BAA+B;cAC9G,wBAAwB,KAAK,CAAC,KAAK,IAAI,KAAK,CAAC,GAAG,GAAG,CACtD,CAAA;IACH,CAAC;IACD,OAAO,EAAE,WAAW,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,CAAA;AACjE,CAAC"}
@@ -0,0 +1,33 @@
1
+ import type { SessionEvent } from '@open33/harness-session/types';
2
+ /** One provider/model route that contributed a billed request attempt. */
3
+ export interface TurnTokenUsageRoute {
4
+ readonly provider: string;
5
+ readonly model: string;
6
+ }
7
+ /** Exact provider-reported token accounting for every attempt in one completed Turn. */
8
+ export interface TurnTokenUsage {
9
+ /** Sum of uncached prompt input across all attempts. */
10
+ readonly uncachedInputTokens: number;
11
+ readonly outputTokens: number;
12
+ /** Exact aggregate prompt plus output total across all attempts. */
13
+ readonly totalTokens: number;
14
+ /** Present only when every attempt reported the bucket. */
15
+ readonly cacheReadTokens?: number;
16
+ /** Present only when every attempt reported the bucket. */
17
+ readonly cacheWriteTokens?: number;
18
+ /** Output subset, present only when every attempt reported it. */
19
+ readonly reasoningTokens?: number;
20
+ /** Present only when every billed attempt has provider/model attribution. */
21
+ readonly routes?: readonly TurnTokenUsageRoute[];
22
+ }
23
+ /**
24
+ * Fold one complete Turn's durable attempt lifecycle into exact token accounting.
25
+ *
26
+ * No attempt is inferred from a usage sample. Any missing lifecycle boundary,
27
+ * incomplete attempt usage, unsafe count, or contradictory exact total makes
28
+ * the whole disclosure unavailable.
29
+ * @param events - Turn-local durable events from `turn/start` through `turn/end`.
30
+ * @returns exact aggregate usage, or undefined when it cannot be proven.
31
+ */
32
+ export declare function deriveTurnTokenUsage(events: readonly SessionEvent[]): TurnTokenUsage | undefined;
33
+ //# sourceMappingURL=turn-usage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"turn-usage.d.ts","sourceRoot":"","sources":["../../src/turn-usage.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAA;AAEjE,0EAA0E;AAC1E,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;IACzB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CACvB;AAED,wFAAwF;AACxF,MAAM,WAAW,cAAc;IAC7B,wDAAwD;IACxD,QAAQ,CAAC,mBAAmB,EAAE,MAAM,CAAA;IACpC,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAA;IAC7B,oEAAoE;IACpE,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAA;IAC5B,2DAA2D;IAC3D,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAA;IACjC,2DAA2D;IAC3D,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAA;IAClC,kEAAkE;IAClE,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAA;IACjC,6EAA6E;IAC7E,QAAQ,CAAC,MAAM,CAAC,EAAE,SAAS,mBAAmB,EAAE,CAAA;CACjD;AA8ID;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,SAAS,YAAY,EAAE,GAAG,cAAc,GAAG,SAAS,CAgGhG"}
@@ -0,0 +1,229 @@
1
+ import { lastAssistantStreamChunk } from '@open33/harness-llm/assistant-stream';
2
+ function isCount(value) {
3
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
4
+ }
5
+ function safeSum(values) {
6
+ let total = 0;
7
+ for (const value of values) {
8
+ total += value;
9
+ if (!Number.isSafeInteger(total))
10
+ return undefined;
11
+ }
12
+ return total;
13
+ }
14
+ function messageRoute(message) {
15
+ const { provider, model } = message.source;
16
+ return provider.length > 0 && model.length > 0 ? { provider, model } : undefined;
17
+ }
18
+ function streamUsage(stream) {
19
+ return lastAssistantStreamChunk(stream, 'usage')?.usage;
20
+ }
21
+ function normalizeUsage(usage, route) {
22
+ const { inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens, reasoningTokens, totalTokens, } = usage;
23
+ if (!isCount(inputTokens) || !isCount(outputTokens))
24
+ return undefined;
25
+ if (cacheReadTokens !== undefined && !isCount(cacheReadTokens))
26
+ return undefined;
27
+ if (cacheWriteTokens !== undefined && !isCount(cacheWriteTokens))
28
+ return undefined;
29
+ if (reasoningTokens !== undefined && (!isCount(reasoningTokens) || reasoningTokens > outputTokens)) {
30
+ return undefined;
31
+ }
32
+ const knownPrompt = safeSum([
33
+ inputTokens,
34
+ ...cacheReadTokens === undefined ? [] : [cacheReadTokens],
35
+ ...cacheWriteTokens === undefined ? [] : [cacheWriteTokens],
36
+ ]);
37
+ if (knownPrompt === undefined)
38
+ return undefined;
39
+ let exactTotal;
40
+ if (totalTokens !== undefined) {
41
+ if (!isCount(totalTokens))
42
+ return undefined;
43
+ const exactPrompt = totalTokens - outputTokens;
44
+ if (!isCount(exactPrompt) || exactPrompt < knownPrompt)
45
+ return undefined;
46
+ if (cacheReadTokens !== undefined && cacheWriteTokens !== undefined && exactPrompt !== knownPrompt) {
47
+ return undefined;
48
+ }
49
+ exactTotal = totalTokens;
50
+ }
51
+ else {
52
+ if (cacheReadTokens === undefined || cacheWriteTokens === undefined)
53
+ return undefined;
54
+ const derivedTotal = safeSum([knownPrompt, outputTokens]);
55
+ if (derivedTotal === undefined)
56
+ return undefined;
57
+ exactTotal = derivedTotal;
58
+ }
59
+ return {
60
+ inputTokens,
61
+ outputTokens,
62
+ totalTokens: exactTotal,
63
+ ...cacheReadTokens === undefined ? {} : { cacheReadTokens },
64
+ ...cacheWriteTokens === undefined ? {} : { cacheWriteTokens },
65
+ ...reasoningTokens === undefined ? {} : { reasoningTokens },
66
+ ...route === undefined ? {} : { route },
67
+ };
68
+ }
69
+ function aggregateAttempts(attempts) {
70
+ if (attempts.length === 0)
71
+ return undefined;
72
+ const inputTokens = safeSum(attempts.map(attempt => attempt.inputTokens));
73
+ const outputTokens = safeSum(attempts.map(attempt => attempt.outputTokens));
74
+ const totalTokens = safeSum(attempts.map(attempt => attempt.totalTokens));
75
+ if (inputTokens === undefined || outputTokens === undefined || totalTokens === undefined)
76
+ return undefined;
77
+ const cacheRead = attempts.map(attempt => attempt.cacheReadTokens);
78
+ const cacheWrite = attempts.map(attempt => attempt.cacheWriteTokens);
79
+ const reasoning = attempts.map(attempt => attempt.reasoningTokens);
80
+ const cacheReadTokens = cacheRead.every(isCount) ? safeSum(cacheRead) : undefined;
81
+ const cacheWriteTokens = cacheWrite.every(isCount) ? safeSum(cacheWrite) : undefined;
82
+ const reasoningTokens = reasoning.every(isCount) ? safeSum(reasoning) : undefined;
83
+ // A present cache bucket is bounded by exact prompt, and reasoning is bounded
84
+ // by output. Safe required aggregates therefore imply safe optional sums.
85
+ let routes;
86
+ const attributed = attempts.map(attempt => attempt.route);
87
+ if (attributed.every((route) => route !== undefined)) {
88
+ const unique = new Map();
89
+ for (const route of attributed)
90
+ unique.set(`${route.provider}\0${route.model}`, route);
91
+ routes = [...unique.values()];
92
+ }
93
+ return {
94
+ uncachedInputTokens: inputTokens,
95
+ outputTokens,
96
+ totalTokens,
97
+ ...cacheReadTokens === undefined ? {} : { cacheReadTokens },
98
+ ...cacheWriteTokens === undefined ? {} : { cacheWriteTokens },
99
+ ...reasoningTokens === undefined ? {} : { reasoningTokens },
100
+ ...routes === undefined ? {} : { routes },
101
+ };
102
+ }
103
+ function sameAttempt(state, turn, step) {
104
+ return state.turn === turn && state.step === step;
105
+ }
106
+ /**
107
+ * Fold one complete Turn's durable attempt lifecycle into exact token accounting.
108
+ *
109
+ * No attempt is inferred from a usage sample. Any missing lifecycle boundary,
110
+ * incomplete attempt usage, unsafe count, or contradictory exact total makes
111
+ * the whole disclosure unavailable.
112
+ * @param events - Turn-local durable events from `turn/start` through `turn/end`.
113
+ * @returns exact aggregate usage, or undefined when it cannot be proven.
114
+ */
115
+ export function deriveTurnTokenUsage(events) {
116
+ let state = { kind: 'idle' };
117
+ const attempts = [];
118
+ let turn;
119
+ let sawEnd = false;
120
+ let invalid = false;
121
+ const closeOpen = (route) => {
122
+ if (state.kind !== 'open' || state.sample === undefined)
123
+ return false;
124
+ const normalized = normalizeUsage(state.sample, route);
125
+ if (normalized === undefined)
126
+ return false;
127
+ attempts.push(normalized);
128
+ return true;
129
+ };
130
+ for (const event of events) {
131
+ if (invalid)
132
+ break;
133
+ if (event.type === 'turn/start') {
134
+ if (turn !== undefined || state.kind !== 'idle')
135
+ invalid = true;
136
+ else
137
+ turn = event.data.turn;
138
+ continue;
139
+ }
140
+ if (turn === undefined) {
141
+ invalid = true;
142
+ break;
143
+ }
144
+ if (event.type === 'turn/end') {
145
+ if (event.data.turn !== turn || state.kind !== 'idle' || sawEnd)
146
+ invalid = true;
147
+ else
148
+ sawEnd = true;
149
+ continue;
150
+ }
151
+ if (sawEnd) {
152
+ invalid = true;
153
+ break;
154
+ }
155
+ if (event.type === 'step/start') {
156
+ if (event.data.turn !== turn || state.kind !== 'idle')
157
+ invalid = true;
158
+ else
159
+ state = { kind: 'open', turn, step: event.data.step };
160
+ continue;
161
+ }
162
+ if (event.type === 'llm/retry-started') {
163
+ if (event.data.turn !== turn
164
+ || state.kind !== 'settled'
165
+ || state.by !== 'retry'
166
+ || !sameAttempt(state, event.data.turn, event.data.step))
167
+ invalid = true;
168
+ else
169
+ state = { kind: 'open', turn, step: event.data.step };
170
+ continue;
171
+ }
172
+ if (event.type === 'assistant/attempt') {
173
+ if (event.data.turn !== turn
174
+ || state.kind !== 'open'
175
+ || !sameAttempt(state, event.data.turn, event.data.step)) {
176
+ invalid = true;
177
+ continue;
178
+ }
179
+ const sample = streamUsage(event.data.stream) ?? state.sample;
180
+ state = { kind: 'open', turn, step: event.data.step, ...(sample === undefined ? {} : { sample }) };
181
+ if (!closeOpen())
182
+ invalid = true;
183
+ else
184
+ state = { kind: 'finishClosed', turn, step: event.data.step };
185
+ continue;
186
+ }
187
+ if (event.type === 'assistant/message') {
188
+ if (event.data.turn !== turn
189
+ || state.kind !== 'open'
190
+ || !sameAttempt(state, event.data.turn, event.data.step)) {
191
+ invalid = true;
192
+ continue;
193
+ }
194
+ const sample = event.data.usage ?? streamUsage(event.data.stream);
195
+ if (sample !== undefined)
196
+ state = { ...state, sample };
197
+ if (!closeOpen(messageRoute(event.data.message)))
198
+ invalid = true;
199
+ else
200
+ state = { kind: 'settled', turn, step: event.data.step, by: 'message' };
201
+ continue;
202
+ }
203
+ if (event.type === 'llm/retry') {
204
+ if (event.data.turn !== turn || state.kind === 'idle'
205
+ || !sameAttempt(state, event.data.turn, event.data.step)) {
206
+ invalid = true;
207
+ continue;
208
+ }
209
+ if (state.kind === 'settled' || (state.kind === 'open' && !closeOpen()))
210
+ invalid = true;
211
+ if (!invalid)
212
+ state = { kind: 'settled', turn, step: event.data.step, by: 'retry' };
213
+ continue;
214
+ }
215
+ if (event.type === 'step/end') {
216
+ if (event.data.turn !== turn || state.kind === 'idle'
217
+ || !sameAttempt(state, event.data.turn, event.data.step)) {
218
+ invalid = true;
219
+ continue;
220
+ }
221
+ if (state.kind === 'open' && !closeOpen())
222
+ invalid = true;
223
+ if (!invalid)
224
+ state = { kind: 'idle' };
225
+ }
226
+ }
227
+ return invalid || !sawEnd || state.kind !== 'idle' ? undefined : aggregateAttempts(attempts);
228
+ }
229
+ //# sourceMappingURL=turn-usage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"turn-usage.js","sourceRoot":"","sources":["../../src/turn-usage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,sCAAsC,CAAA;AA0D/E,SAAS,OAAO,CAAC,KAAc;IAC7B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,CAAA;AAC/E,CAAC;AAED,SAAS,OAAO,CAAC,MAAyB;IACxC,IAAI,KAAK,GAAG,CAAC,CAAA;IACb,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QAC3B,KAAK,IAAI,KAAK,CAAA;QACd,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC;YAAE,OAAO,SAAS,CAAA;IACpD,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC;AAED,SAAS,YAAY,CAAC,OAAyB;IAC7C,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,GAAG,OAAO,CAAC,MAAM,CAAA;IAC1C,OAAO,QAAQ,CAAC,MAAM,GAAG,CAAC,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,SAAS,CAAA;AAClF,CAAC;AAED,SAAS,WAAW,CAAC,MAA2D;IAC9E,OAAO,wBAAwB,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,KAAK,CAAA;AACzD,CAAC;AAED,SAAS,cAAc,CAAC,KAAiB,EAAE,KAA2B;IACpE,MAAM,EACJ,WAAW,EAAE,YAAY,EAAE,eAAe,EAAE,gBAAgB,EAAE,eAAe,EAAE,WAAW,GAC3F,GAAG,KAAK,CAAA;IACT,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAA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AE,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,CAAA;YACnF,SAAQ;QACV,CAAC;QACD,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;YAC9B,IAAI,KAAK,CAAC,IAAI,CAAC,IAAI,KAAK,IAAI,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM;mBAChD,CAAC,WAAW,CAAC,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;gBAC3D,OAAO,GAAG,IAAI,CAAA;gBACd,SAAQ;YACV,CAAC;YACD,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM,IAAI,CAAC,SAAS,EAAE;gBAAE,OAAO,GAAG,IAAI,CAAA;YACzD,IAAI,CAAC,OAAO;gBAAE,KAAK,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,CAAA;QACxC,CAAC;IACH,CAAC;IAED,OAAO,OAAO,IAAI,CAAC,MAAM,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,iBAAiB,CAAC,QAAQ,CAAC,CAAA;AAC9F,CAAC"}
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Public configuration and measurement vocabulary for replay token metering.
3
+ *
4
+ * @module @open33/harness-token-meter/types
5
+ */
6
+ import type { TokenUsage } from '@open33/harness-llm';
7
+ import type { SessionLogOffset, SessionSeq } from '@open33/harness-session/types';
8
+ export type { ContextBreakdownProjection, ContextPressureProjection, TokenUsageProjection } from './projection.ts';
9
+ /** Token-meter plugin configuration; the fixed estimator has no settings. */
10
+ export type TokenMeterConfig = Record<string, never>;
11
+ /** The baseline from which a signed surface delta produces current pressure. */
12
+ export type TokenMeasurementBaseline = {
13
+ readonly kind: 'none';
14
+ readonly tokens: 0;
15
+ } | {
16
+ readonly kind: 'estimated';
17
+ readonly tokens: number;
18
+ } | {
19
+ readonly kind: 'usage';
20
+ readonly tokens: number;
21
+ readonly usage: Readonly<TokenUsage>;
22
+ };
23
+ /** Detached immutable request-pressure and surface snapshot at one consumed log revision. */
24
+ export interface TokenMeasurement {
25
+ /** Number of durable events consumed; equal to the next unread event seq. */
26
+ readonly logRevision: SessionLogOffset;
27
+ /** Provider or heuristic anchor used for this measurement. */
28
+ readonly baseline: TokenMeasurementBaseline;
29
+ /** Signed repricing of current surface content relative to the baseline anchor. */
30
+ readonly surfaceDeltaTokens: number;
31
+ /** Non-negative current request-and-response pressure. */
32
+ readonly totalTokens: number;
33
+ /** Total route-priced request tokens across the current surface; equals the sum of the node prices. */
34
+ readonly surfaceTokens: number;
35
+ /** Current surface nodes in positional head-to-tail order. */
36
+ readonly nodes: readonly TokenSurfaceNode[];
37
+ }
38
+ /** One token-priced node in the current ordered session surface. */
39
+ export interface TokenSurfaceNode {
40
+ /** Durable sequence number of the surface event. */
41
+ readonly seq: SessionSeq;
42
+ /**
43
+ * Request-pressure tokens for the exact message projected by this node under
44
+ * the measured route: image occurrences carry the route's declared visual
45
+ * price when the routed adapter declares one, and the fixed heuristic
46
+ * otherwise. Trigger, retention, and range selection all read this price.
47
+ */
48
+ readonly tokens: number;
49
+ /**
50
+ * Fixed-heuristic tokens for the same message, independent of any route.
51
+ * The shadow-price protocol prices replacements with this value so the O(1)
52
+ * projection fold stays in agreement with its own appends.
53
+ */
54
+ readonly heuristicTokens: number;
55
+ }
56
+ //# sourceMappingURL=types.d.ts.map