@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,100 @@
1
+ /** Fixed-size recovery facts; positional attachment prices remain a rebuildable cache. */
2
+ import { z } from 'zod'
3
+ import { assembleAssistantStream } from '@open33/harness-llm'
4
+ import type { TokenUsage } from '@open33/harness-llm'
5
+ import { canonicalHeader, deriveEventMessage, SessionSeq } from '@open33/harness-session'
6
+ import type { SessionEvent } from '@open33/harness-session'
7
+ import type { ProjectionDefinition } from '@open33/harness-session-projection'
8
+ import { estimateContent, estimateMessage, ROLE_OVERHEAD } from './estimate.ts'
9
+
10
+ const seqSchema = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).transform(SessionSeq)
11
+ const countSchema = z.number()
12
+ const usageFields = z.looseObject({
13
+ inputTokens: countSchema,
14
+ outputTokens: countSchema,
15
+ totalTokens: countSchema.optional(),
16
+ cacheReadTokens: countSchema.optional(),
17
+ cacheWriteTokens: countSchema.optional(),
18
+ reasoningTokens: countSchema.optional(),
19
+ })
20
+ // Keep provider fields and optional-property presence exactly as recorded.
21
+ const usageSchema = z.custom<TokenUsage>(value => usageFields.safeParse(value).success)
22
+
23
+ const measurementStateSchema = z.object({
24
+ headerSeq: seqSchema.nullable(),
25
+ stepStart: z.object({ turn: z.number(), step: z.number() }).strict().nullable(),
26
+ anchor: z.object({
27
+ headerSeq: seqSchema.nullable(),
28
+ assistantTokens: countSchema,
29
+ usage: usageSchema.nullable(),
30
+ }).strict().nullable(),
31
+ invalidSeq: seqSchema.nullable(),
32
+ }).strict()
33
+
34
+ /** One header reference, one open step, and the latest successful call's usage facts. */
35
+ export type MeasurementState = z.infer<typeof measurementStateSchema>
36
+
37
+ /**
38
+ * Advance one measurement prefix without mutating its previous state.
39
+ * @param state - measurement facts before the candidate event.
40
+ * @param event - next committed journal event.
41
+ * @returns updated measurement facts.
42
+ * @throws the original measurement error for invalid boundaries or payloads.
43
+ */
44
+ export function advanceMeasurement(state: MeasurementState, event: SessionEvent): MeasurementState {
45
+ switch (event.type) {
46
+ case 'request/header':
47
+ canonicalHeader(event.data.header)
48
+ return { ...state, headerSeq: event.seq }
49
+ case 'step/start':
50
+ if (state.stepStart !== null) {
51
+ throw new Error(`token meter: step/start at seq ${event.seq} arrived before turn ${state.stepStart.turn}/step ${state.stepStart.step} ended`)
52
+ }
53
+ return { ...state, stepStart: { turn: event.data.turn, step: event.data.step } }
54
+ case 'step/end':
55
+ if (state.stepStart === null
56
+ || state.stepStart.turn !== event.data.turn
57
+ || state.stepStart.step !== event.data.step) {
58
+ throw new Error(`token meter: step/end at seq ${event.seq} has no matching step/start event`)
59
+ }
60
+ return { ...state, stepStart: null }
61
+ case 'assistant/message': {
62
+ if (state.stepStart === null
63
+ || state.stepStart.turn !== event.data.turn
64
+ || state.stepStart.step !== event.data.step) {
65
+ throw new Error(`token meter: assistant/message at seq ${event.seq} has no matching step/start event`)
66
+ }
67
+ let assistantTokens: number
68
+ let usage: TokenUsage | null = null
69
+ if (event.data.usage !== undefined && state.headerSeq !== null) {
70
+ const content = assembleAssistantStream(event.data.stream).blocks()
71
+ assistantTokens = content.length === 0 ? 0 : estimateContent(content) + ROLE_OVERHEAD
72
+ usage = event.data.usage
73
+ } else {
74
+ const message = deriveEventMessage(event)
75
+ assistantTokens = message === null ? 0 : estimateMessage(message)
76
+ }
77
+ return { ...state, anchor: { headerSeq: state.headerSeq, assistantTokens, usage } }
78
+ }
79
+ default:
80
+ return state
81
+ }
82
+ }
83
+
84
+ /** Host-only measurement facts, independent of session and surface length. */
85
+ export const measurementProjectionDefinition = {
86
+ key: 'tokenMeasurement',
87
+ stateVersion: 2,
88
+ stateSchema: measurementStateSchema,
89
+ init: (): MeasurementState => ({ headerSeq: null, stepStart: null, anchor: null, invalidSeq: null }),
90
+ apply: (state, event) => {
91
+ if (state.invalidSeq !== null) return state
92
+ try {
93
+ return advanceMeasurement(state, event)
94
+ } catch (_error) {
95
+ // Retain the first failed position. measure() repeats the calculation there
96
+ // to report its original error without blocking unrelated projection units.
97
+ return { ...state, invalidSeq: event.seq }
98
+ }
99
+ },
100
+ } satisfies ProjectionDefinition<'tokenMeasurement', MeasurementState>
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Pure client-safe token-projection vocabulary.
3
+ *
4
+ * @module @open33/harness-token-meter/projection
5
+ */
6
+
7
+ import type { SessionProjectionSummaryExcluded } from '@open33/harness-session-projection/types'
8
+
9
+ /**
10
+ * Durable cumulative provider usage for a complete session log.
11
+ *
12
+ * The four buckets are disjoint. In particular, reasoning tokens are already
13
+ * included in `outputTokens` and are not accumulated again.
14
+ */
15
+ export interface TokenUsageProjection {
16
+ uncachedInputTokens: number
17
+ outputTokens: number
18
+ cacheReadTokens: number
19
+ cacheWriteTokens: number
20
+ }
21
+
22
+ /**
23
+ * Approximate context occupancy for a status display.
24
+ *
25
+ * The fields, when present, are deliberately NOT one atomic request
26
+ * observation: each is a last-wins record of a different moment. Switching
27
+ * models can therefore pair a fresh capacity with the previous route's
28
+ * pressure until the next request reports usage. This is an intentional trade
29
+ * — the value is a user-facing reference, not a billing or gating input. See
30
+ * the token-meter README for the full rationale.
31
+ */
32
+ export interface ContextPressureProjection {
33
+ /**
34
+ * Provider-reported prompt size of the most recent request: uncached input
35
+ * plus cache reads and writes. Response output is excluded, so this does not
36
+ * grow as the current turn streams. Absent until a provider reports usage.
37
+ */
38
+ pressureTokens?: number
39
+ /**
40
+ * What the NEXT request's prompt would cost: {@link pressureTokens} plus the
41
+ * heuristic repricing of everything the surface gained or lost since that
42
+ * sample. Only the delta is estimated, so the figure stays anchored to the
43
+ * provider while still reacting the moment a compaction shadows a span —
44
+ * which `pressureTokens` alone cannot do, since compaction reports no usage
45
+ * of its own. Absent until a provider reports usage.
46
+ */
47
+ projectedTokens?: number
48
+ /** Newest recorded route capacity; absent when no adapter advertised one. */
49
+ contextWindow?: number
50
+ }
51
+
52
+ /**
53
+ * Heuristic composition of the next request's context: what the prompt is
54
+ * made of, not what it costs. All three figures use the meter's fixed
55
+ * density estimate, so they will not sum to the provider-anchored
56
+ * `projectedTokens`: the estimator systematically underprices CJK text and
57
+ * JSON schemas, which is exactly the error the anchoring in
58
+ * {@link ContextPressureProjection.projectedTokens} keeps out of the occupancy
59
+ * figure. Present these as approximations of composition, never as a total.
60
+ */
61
+ export interface ContextBreakdownProjection {
62
+ /** Heuristic tokens of the last nonempty surviving system prompt in surface order; 0 when none exists. */
63
+ systemTokens: number
64
+ /** Heuristic tokens of the newest request envelope's tool schemas; 0 before any request. */
65
+ toolsTokens: number
66
+ /** Heuristic tokens of every other visible surface node, including superseded system prompts. */
67
+ messageTokens: number
68
+ }
69
+
70
+ declare module '@open33/harness-session-projection/types' {
71
+ interface SessionProjectionMap {
72
+ /** Provider-reported usage accumulated across the complete durable log. */
73
+ tokenUsage: TokenUsageProjection
74
+ /** Newest request pressure paired with the newest known route capacity. */
75
+ contextPressure: SessionProjectionSummaryExcluded<ContextPressureProjection>
76
+ /** Heuristic system/tools/message composition of the next request. */
77
+ contextBreakdown: SessionProjectionSummaryExcluded<ContextBreakdownProjection>
78
+ }
79
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Request-projected surface pricing: replaces attachment-block heuristics with
3
+ * the image and file representations sent to the routed model.
4
+ *
5
+ * @module @open33/harness-token-meter/route-pricing
6
+ */
7
+
8
+ import type { ContentBlock, LlmImageRequestPricing } from '@open33/harness-llm'
9
+ import { estimateContent } from './estimate.ts'
10
+ import type { MeterSurfaceNode } from './surface-fold.ts'
11
+ import type { TokenSurfaceNode } from './types.ts'
12
+
13
+ type FileAttachmentRef = Extract<ContentBlock, { type: 'file' }>['attachment']
14
+
15
+ /** One surface priced for a request route: public nodes plus their total. */
16
+ export interface PricedSurface {
17
+ /** Positional nodes carrying both the route price and the fixed-heuristic price. */
18
+ readonly nodes: TokenSurfaceNode[]
19
+ /** Sum of the route prices across the surface. */
20
+ readonly surfaceTokens: number
21
+ }
22
+
23
+ /**
24
+ * Price one ordered surface under its model-request attachment projection.
25
+ * @param nodes - the fold's current or snapshotted surface, in model-visible order.
26
+ * @param pricing - the routed model's image pricing, or undefined to keep the fixed heuristic.
27
+ * @param fileText - exact file handle projection used by the mounted LLM service.
28
+ * @returns detached public nodes and their route-priced total.
29
+ * @throws when the pricing answers a different occurrence count than it was
30
+ * asked — misalignment would silently misprice nodes, so it must fail loud.
31
+ */
32
+ export function priceSurface(
33
+ nodes: readonly MeterSurfaceNode[],
34
+ pricing: LlmImageRequestPricing | undefined,
35
+ fileText?: (ref: FileAttachmentRef) => string,
36
+ ): PricedSurface {
37
+ const images = pricing === undefined ? [] : nodes.flatMap(node => node.images)
38
+ const hasFiles = fileText !== undefined && nodes.some(node => node.files.length > 0)
39
+ if ((pricing === undefined || images.length === 0) && !hasFiles) {
40
+ let surfaceTokens = 0
41
+ const publicNodes = nodes.map((node) => {
42
+ surfaceTokens += node.heuristicTokens
43
+ return { seq: node.seq, tokens: node.heuristicTokens, heuristicTokens: node.heuristicTokens }
44
+ })
45
+ return { nodes: publicNodes, surfaceTokens }
46
+ }
47
+ const prices = pricing === undefined ? [] : pricing.priceImages(images)
48
+ if (pricing !== undefined && prices.length !== images.length) {
49
+ throw new Error(
50
+ `token meter: route image pricing answered ${prices.length} prices for ${images.length} occurrences`,
51
+ )
52
+ }
53
+ let cursor = 0
54
+ let surfaceTokens = 0
55
+ const publicNodes = nodes.map((node) => {
56
+ let tokens = node.heuristicTokens
57
+ if (fileText !== undefined && node.files.length > 0) {
58
+ tokens -= node.fileStructuralTokens
59
+ for (const file of node.files) {
60
+ tokens += estimateContent([{ type: 'text', text: fileText(file) }])
61
+ }
62
+ }
63
+ if (pricing !== undefined && node.images.length > 0) {
64
+ tokens -= node.imageStructuralTokens
65
+ for (let occurrence = 0; occurrence < node.images.length; occurrence += 1) {
66
+ // oxlint-disable-next-line typescript/no-non-null-assertion -- length equality is asserted above
67
+ const price = prices[cursor]!
68
+ cursor += 1
69
+ tokens += price.visualTokens + estimateContent([{ type: 'text', text: price.text }])
70
+ }
71
+ }
72
+ surfaceTokens += tokens
73
+ return { seq: node.seq, tokens, heuristicTokens: node.heuristicTokens }
74
+ })
75
+ return { nodes: publicNodes, surfaceTokens }
76
+ }
@@ -0,0 +1,142 @@
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
+
17
+ import { deriveEventMessage } from '@open33/harness-session'
18
+ import type { SessionSeq, SurfaceEvent } from '@open33/harness-session'
19
+ import type { ContentBlock, ImageBlock, Message } from '@open33/harness-llm'
20
+ import { estimateMessage, estimateStructuralBlock } from './estimate.ts'
21
+
22
+ type FileAttachmentRef = Extract<ContentBlock, { type: 'file' }>['attachment']
23
+
24
+ /** One priced surface node with the image occurrences route pricing replaces. */
25
+ export interface MeterSurfaceNode {
26
+ /** Durable sequence number of the surface event. */
27
+ readonly seq: SessionSeq
28
+ /** Fixed-heuristic price of the node's exact message. */
29
+ readonly heuristicTokens: number
30
+ /** Structural JSON price replaced when the routed request projects images. */
31
+ readonly imageStructuralTokens: number
32
+ /** Structural JSON price replaced when request assembly projects files to text. */
33
+ readonly fileStructuralTokens: number
34
+ /** Durable image blocks in message order, `offloaded` marks included; empty for image-free nodes. */
35
+ readonly images: readonly ImageBlock[]
36
+ /** Durable file occurrences in message order; empty for file-free nodes. */
37
+ readonly files: readonly FileAttachmentRef[]
38
+ }
39
+
40
+ /** One validated surface transition that has not mutated the priced surface yet. */
41
+ export interface SurfaceTokenPlan<Node = MeterSurfaceNode> {
42
+ /** Heuristic price of the event's own message; 0 when it derives none. */
43
+ readonly tokens: number
44
+ /** Signed change in the surface total: `tokens` minus anything shadowed. */
45
+ readonly deltaTokens: number
46
+ /** The priced node the commit inserts for this event. */
47
+ readonly node: Node
48
+ /** Commit position: `append`, or the inclusive replaced index range. */
49
+ readonly target: 'append' | { readonly startIdx: number; readonly endIdx: number }
50
+ }
51
+
52
+ /** Collect projected attachment occurrences and their structural prices. */
53
+ function collectProjectedAttachments(
54
+ blocks: readonly ContentBlock[],
55
+ images: ImageBlock[],
56
+ files: FileAttachmentRef[],
57
+ ): { readonly imageTokens: number; readonly fileTokens: number } {
58
+ let imageTokens = 0
59
+ let fileTokens = 0
60
+ for (const block of blocks) {
61
+ if (block.type === 'image') {
62
+ images.push(block)
63
+ imageTokens += estimateStructuralBlock(block)
64
+ } else if (block.type === 'file') {
65
+ files.push(block.attachment)
66
+ fileTokens += estimateStructuralBlock(block)
67
+ }
68
+ }
69
+ return { imageTokens, fileTokens }
70
+ }
71
+
72
+ /** Build one priced node from a surface event's derived message. */
73
+ function analyzeNode(seq: SessionSeq, message: Message | null): MeterSurfaceNode {
74
+ if (message === null) {
75
+ return {
76
+ seq,
77
+ heuristicTokens: 0,
78
+ imageStructuralTokens: 0,
79
+ fileStructuralTokens: 0,
80
+ images: [],
81
+ files: [],
82
+ }
83
+ }
84
+ const heuristicTokens = estimateMessage(message)
85
+ const images: ImageBlock[] = []
86
+ const files: FileAttachmentRef[] = []
87
+ const structural = collectProjectedAttachments(message.content, images, files)
88
+ return {
89
+ seq,
90
+ heuristicTokens,
91
+ imageStructuralTokens: structural.imageTokens,
92
+ fileStructuralTokens: structural.fileTokens,
93
+ images,
94
+ files,
95
+ }
96
+ }
97
+
98
+ /**
99
+ * Validate and price one surface event without mutating the surface.
100
+ * @param nodes - the priced surface preceding this event, in model-visible order.
101
+ * @param event - the surface event to place.
102
+ * @returns the plan for {@link commitSurfaceTokens}.
103
+ * @throws when a replacement names a range absent from `nodes` — committed
104
+ * logs are surface-validated at append time, so an unresolvable range is log
105
+ * corruption and must fail loud rather than skip the event.
106
+ */
107
+ export function planSurfaceTokens(
108
+ nodes: readonly Pick<MeterSurfaceNode, 'seq' | 'heuristicTokens'>[],
109
+ event: SurfaceEvent,
110
+ ): SurfaceTokenPlan {
111
+ const node = analyzeNode(event.seq, deriveEventMessage(event))
112
+ const tokens = node.heuristicTokens
113
+ const op = event.surfaceOp
114
+ if (op === 'append') {
115
+ return { tokens, deltaTokens: tokens, node, target: 'append' }
116
+ }
117
+ const startIdx = nodes.findIndex(candidate => candidate.seq === op.startSeq)
118
+ const endIdx = nodes.findIndex(candidate => candidate.seq === op.endSeq)
119
+ if (startIdx === -1 || endIdx === -1 || startIdx > endIdx) {
120
+ throw new Error(
121
+ `token surface: replace at seq ${event.seq} has invalid current range ${op.startSeq}-${op.endSeq}`,
122
+ )
123
+ }
124
+ const removed = nodes
125
+ .slice(startIdx, endIdx + 1)
126
+ .reduce((total, candidate) => total + candidate.heuristicTokens, 0)
127
+ return { tokens, deltaTokens: tokens - removed, node, target: { startIdx, endIdx } }
128
+ }
129
+
130
+ /**
131
+ * Apply one validated plan to the priced surface in place; infallible, so it
132
+ * cannot leave a half-applied surface behind.
133
+ * @param nodes - the exact priced surface the plan was built against.
134
+ * @param plan - the transition returned by {@link planSurfaceTokens}.
135
+ */
136
+ export function commitSurfaceTokens<Node>(nodes: Node[], plan: SurfaceTokenPlan<Node>): void {
137
+ if (plan.target === 'append') {
138
+ nodes.push(plan.node)
139
+ return
140
+ }
141
+ nodes.splice(plan.target.startIdx, plan.target.endIdx - plan.target.startIdx + 1, plan.node)
142
+ }
@@ -0,0 +1,96 @@
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
+
18
+ import { deriveEventMessage, isSurfaceEvent, SessionSeq } from '@open33/harness-session'
19
+ import type { SessionEvent } from '@open33/harness-session'
20
+ // Type-only: the `compaction/*` SessionEventMap merges (shadow-price events).
21
+ import type {} from '@open33/harness-compaction'
22
+ import { estimateMessage } from './estimate.ts'
23
+
24
+ /**
25
+ * One armed shadow price: the heuristic tokens of the surface range the
26
+ * IMMEDIATELY following event replaces. Plain JSON — it is part of the
27
+ * persisted unit state while armed.
28
+ */
29
+ export interface ShadowPriceClaim {
30
+ /** Declared inclusive first surface-node seq of the priced range. */
31
+ start: SessionSeq
32
+ /** Declared inclusive last surface-node seq of the priced range. */
33
+ end: SessionSeq
34
+ /** Heuristic tokens of the priced range under the fixed estimator. */
35
+ tokens: number
36
+ }
37
+
38
+ /** One event's effect on a running surface-token total. */
39
+ export interface SurfaceTokensFold {
40
+ /** Signed change in the surface total; 0 for events off the surface. */
41
+ readonly deltaTokens: number
42
+ /** Claim to carry into the next event; undefined when none survives. */
43
+ readonly claim: ShadowPriceClaim | undefined
44
+ }
45
+
46
+ /**
47
+ * Fold one committed event onto a running surface-token total.
48
+ *
49
+ * A shadow-price event arms a claim; any other event expires it, and a
50
+ * surface `replace` consumes the claim naming its exact range — the
51
+ * producers append the metering event and the replacement synchronously
52
+ * adjacent, so a surviving claim always prices the very next event.
53
+ * A replace with no claim folds with zero delta because the bounded state
54
+ * cannot reconstruct the replaced range. An armed claim for another range
55
+ * still fails because the adjacent events contradict each other.
56
+ * @param claim - the claim armed by the immediately preceding event, if any.
57
+ * @param event - the next committed session event.
58
+ * @returns the signed token delta and the claim state after this event.
59
+ * @throws when a replacement arrives with an armed claim for a different
60
+ * range — the metering event was adjacent, so this is a live producer's
61
+ * shadow-price contract violation, not historical data, and must fail
62
+ * loud rather than let the total drift.
63
+ */
64
+ export function foldSurfaceProjection(
65
+ claim: ShadowPriceClaim | undefined,
66
+ event: SessionEvent,
67
+ ): SurfaceTokensFold {
68
+ if (event.type === 'compaction/summary' || event.type === 'compaction/prune') {
69
+ const { shadowedRange, shadowedTokenCount } = event.data
70
+ return {
71
+ deltaTokens: 0,
72
+ claim: {
73
+ start: SessionSeq(shadowedRange.start),
74
+ end: SessionSeq(shadowedRange.end),
75
+ tokens: shadowedTokenCount,
76
+ },
77
+ }
78
+ }
79
+ if (!isSurfaceEvent(event)) return { deltaTokens: 0, claim: undefined }
80
+ const message = deriveEventMessage(event)
81
+ const tokens = message === null ? 0 : estimateMessage(message)
82
+ const op = event.surfaceOp
83
+ if (op === 'append') return { deltaTokens: tokens, claim: undefined }
84
+ // Sessions recorded before the shadow-price protocol log replacements with
85
+ // no adjacent metering event; the bounded state cannot reconstruct the
86
+ // replaced range's price, so fold those neutrally — historical replay
87
+ // degrades to drift instead of failing.
88
+ if (claim === undefined) return { deltaTokens: 0, claim: undefined }
89
+ if (claim.start !== op.startSeq || claim.end !== op.endSeq) {
90
+ throw new Error(
91
+ `token surface: replace at seq ${event.seq} over range ${op.startSeq}-${op.endSeq} has no adjacent shadow price`
92
+ + ` (armed claim covers ${claim.start}-${claim.end})`,
93
+ )
94
+ }
95
+ return { deltaTokens: tokens - claim.tokens, claim: undefined }
96
+ }