@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,184 @@
1
+ /**
2
+ * Heuristic composition of the current retained surface, independent of route
3
+ * image pricing and provider usage. The state keeps the surviving system
4
+ * prompts in surface order and one running surface total; every other node is
5
+ * priced only as a delta, so state size follows the system prompts, not the
6
+ * message count.
7
+ */
8
+
9
+ import { z } from 'zod'
10
+ import { canonicalHeader, deriveEventMessage, isSurfaceEvent, SessionSeq } from '@open33/harness-session'
11
+ import type { SurfaceEvent } from '@open33/harness-session'
12
+ import type { ProjectionDefinition } from '@open33/harness-session-projection'
13
+ // Type-only: the `compaction/*` SessionEventMap merges (shadow-price events).
14
+ import type {} from '@open33/harness-compaction'
15
+ import { estimateMessage, estimateToolsTokens } from './estimate.ts'
16
+ // Type-only: the client projection key and value declaration.
17
+ import type {} from './projection.ts'
18
+
19
+ const tokenCount = z.number().int().nonnegative()
20
+ const sessionSeq = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).transform(SessionSeq)
21
+
22
+ const breakdownSchema = z.object({
23
+ systemTokens: tokenCount,
24
+ toolsTokens: tokenCount,
25
+ messageTokens: tokenCount,
26
+ }).strict()
27
+
28
+ /** One surviving `system/message` node and its heuristic price. */
29
+ const systemNodeSchema = z.object({
30
+ seq: sessionSeq,
31
+ tokens: tokenCount,
32
+ }).strict()
33
+
34
+ /**
35
+ * Shadow price armed by the `compaction/summary` or `compaction/prune` event
36
+ * immediately before a replacement: the replaced range, its heuristic price,
37
+ * and the surviving system prompts inside it.
38
+ */
39
+ const claimSchema = z.object({
40
+ start: sessionSeq,
41
+ end: sessionSeq,
42
+ tokens: tokenCount,
43
+ systemSeqs: z.array(sessionSeq),
44
+ }).strict()
45
+
46
+ /** Plain-JSON checkpoint: surviving system prompts in surface order, the surface total, and an armed claim. */
47
+ const contextBreakdownStateSchema = z.object({
48
+ systems: z.array(systemNodeSchema),
49
+ surfaceTokens: tokenCount,
50
+ claim: claimSchema.optional(),
51
+ breakdown: breakdownSchema,
52
+ }).strict()
53
+ type ContextBreakdownState = z.infer<typeof contextBreakdownStateSchema>
54
+ type SystemNode = ContextBreakdownState['systems'][number]
55
+ type BreakdownClaim = z.infer<typeof claimSchema>
56
+
57
+ /** The system prompts and surface total after one surface event. */
58
+ interface SurfaceTotals {
59
+ readonly systems: SystemNode[]
60
+ readonly surfaceTokens: number
61
+ }
62
+
63
+ /**
64
+ * Place one surface event's priced node.
65
+ * @param state - state before the event, without its armed claim.
66
+ * @param claim - shadow price armed by the immediately preceding event, if any.
67
+ * @param event - the surface event.
68
+ * @param tokens - the event message's heuristic price.
69
+ * @returns the system prompts and surface total after the event.
70
+ * @throws when a metered replacement names another range than its claim, or
71
+ * puts a system message in place of a metered range.
72
+ */
73
+ function placeSurfaceEvent(
74
+ state: ContextBreakdownState,
75
+ claim: BreakdownClaim | undefined,
76
+ event: SurfaceEvent,
77
+ tokens: number,
78
+ ): SurfaceTotals {
79
+ const op = event.surfaceOp
80
+ const node: SystemNode = { seq: event.seq, tokens }
81
+ const isSystem = event.type === 'system/message'
82
+ if (op === 'append') {
83
+ return { systems: isSystem ? [...state.systems, node] : state.systems, surfaceTokens: state.surfaceTokens + tokens }
84
+ }
85
+ if (claim !== undefined) {
86
+ if (claim.start !== op.startSeq || claim.end !== op.endSeq) {
87
+ throw new Error(
88
+ `context breakdown: replace at seq ${event.seq} over range ${op.startSeq}-${op.endSeq} has no adjacent shadow price`
89
+ + ` (armed claim covers ${claim.start}-${claim.end})`,
90
+ )
91
+ }
92
+ if (isSystem) {
93
+ throw new Error(
94
+ `context breakdown: replace at seq ${event.seq} puts a system message in place of a metered range;`
95
+ + ' its order among the surviving system prompts is unknown',
96
+ )
97
+ }
98
+ const shadowed = new Set<number>(claim.systemSeqs)
99
+ return {
100
+ systems: state.systems.filter(system => !shadowed.has(system.seq)),
101
+ surfaceTokens: state.surfaceTokens + tokens - claim.tokens,
102
+ }
103
+ }
104
+ const index = op.startSeq === op.endSeq ? state.systems.findIndex(system => system.seq === op.startSeq) : -1
105
+ const replaced = state.systems[index]
106
+ if (replaced === undefined) {
107
+ // Bounded state cannot price an unmetered non-system range, so it folds at
108
+ // zero delta; current producers meter every such replacement.
109
+ return { systems: state.systems, surfaceTokens: state.surfaceTokens }
110
+ }
111
+ return {
112
+ systems: isSystem ? state.systems.with(index, node) : state.systems.toSpliced(index, 1),
113
+ surfaceTokens: state.surfaceTokens + tokens - replaced.tokens,
114
+ }
115
+ }
116
+
117
+ /** Publish totals, keeping the previous breakdown object when its figures are unchanged. */
118
+ function withTotals(state: ContextBreakdownState, totals: SurfaceTotals): ContextBreakdownState {
119
+ const surfaceTokens = Math.max(0, totals.surfaceTokens)
120
+ const systemTokens = totals.systems.findLast(system => system.tokens > 0)?.tokens ?? 0
121
+ const messageTokens = Math.max(0, surfaceTokens - systemTokens)
122
+ const breakdown = systemTokens === state.breakdown.systemTokens && messageTokens === state.breakdown.messageTokens
123
+ ? state.breakdown
124
+ : { systemTokens, toolsTokens: state.breakdown.toolsTokens, messageTokens }
125
+ return { ...state, systems: totals.systems, surfaceTokens, breakdown }
126
+ }
127
+
128
+ /** Drop an armed claim; the state is returned unchanged when none is armed. */
129
+ function withoutClaim(state: ContextBreakdownState): ContextBreakdownState {
130
+ if (state.claim === undefined) return state
131
+ const { claim: _expired, ...unclaimed } = state
132
+ return unclaimed
133
+ }
134
+
135
+ /**
136
+ * Context composition with the last nonempty surviving system in surface
137
+ * order classified as system tokens; all other visible prices are messages.
138
+ * Appends add their price; a replacement subtracts the shadow price of the
139
+ * adjacent `compaction/summary` or `compaction/prune` event, whose
140
+ * `shadowedSeqs` also name the system prompts it removes, and a system-prompt
141
+ * rewrite subtracts the retained price of the system node it replaces. Tools
142
+ * are priced from the latest request header. No route pricing applies.
143
+ */
144
+ export const contextBreakdownProjectionDefinition = {
145
+ key: 'contextBreakdown',
146
+ stateVersion: 6,
147
+ stateSchema: contextBreakdownStateSchema,
148
+ init: (): ContextBreakdownState => ({
149
+ systems: [],
150
+ surfaceTokens: 0,
151
+ breakdown: { systemTokens: 0, toolsTokens: 0, messageTokens: 0 },
152
+ }),
153
+ apply: (state, event) => {
154
+ if (event.type === 'compaction/summary' || event.type === 'compaction/prune') {
155
+ const shadowed = new Set<number>(event.data.shadowedSeqs)
156
+ return {
157
+ ...state,
158
+ claim: {
159
+ start: SessionSeq(event.data.shadowedRange.start),
160
+ end: SessionSeq(event.data.shadowedRange.end),
161
+ tokens: event.data.shadowedTokenCount,
162
+ systemSeqs: state.systems.filter(system => shadowed.has(system.seq)).map(system => system.seq),
163
+ },
164
+ }
165
+ }
166
+ // A claim prices only the event immediately after its metering event.
167
+ const unclaimed = withoutClaim(state)
168
+ if (event.type === 'request/header') {
169
+ const toolsTokens = estimateToolsTokens(canonicalHeader(event.data.header))
170
+ return toolsTokens === unclaimed.breakdown.toolsTokens
171
+ ? unclaimed
172
+ : { ...unclaimed, breakdown: { ...unclaimed.breakdown, toolsTokens } }
173
+ }
174
+ if (!isSurfaceEvent(event)) return unclaimed
175
+ const message = deriveEventMessage(event)
176
+ const tokens = message === null ? 0 : estimateMessage(message)
177
+ return withTotals(unclaimed, placeSurfaceEvent(unclaimed, state.claim, event, tokens))
178
+ },
179
+ wire: {
180
+ viewSchema: breakdownSchema,
181
+ view: state => state.breakdown,
182
+ summary: false,
183
+ },
184
+ } satisfies ProjectionDefinition<'contextBreakdown', ContextBreakdownState>
package/src/client.ts ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Client-namespace projection of token-meter's browser-safe contracts and folds.
3
+ *
4
+ * @module @open33/harness-token-meter/client
5
+ */
6
+
7
+ export type * from './projection.ts'
8
+ export { deriveTurnTokenUsage } from './turn-usage.ts'
9
+ export type { TurnTokenUsage, TurnTokenUsageRoute } from './turn-usage.ts'
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Fixed-density heuristic token pricing shared by the meter service and the
3
+ * pure context-breakdown projection, so both surfaces price identical content
4
+ * to identical numbers.
5
+ *
6
+ * @module @open33/harness-token-meter/estimate
7
+ */
8
+
9
+ import type { ContentBlock, Message } from '@open33/harness-llm'
10
+ import type { EpochHeader } from '@open33/harness-session'
11
+
12
+ /** Fixed text-density estimate used until exact tokenization is needed. */
13
+ const CHARS_PER_TOKEN = 4
14
+
15
+ /** Per-block structural overhead for JSON framing and type tags. */
16
+ const BLOCK_OVERHEAD = 4
17
+
18
+ /** Role-field framing overhead added to every priced message. */
19
+ export const ROLE_OVERHEAD = 4
20
+
21
+ /**
22
+ * Structural JSON price of one block outside the typed pricing arms: the
23
+ * fixed heuristic for merge-extended blocks and for image references, whose
24
+ * request price is route-owned rather than fixed. Image offload marks do not
25
+ * change this reference-only heuristic; route pricing owns their placeholders.
26
+ * @param block - block to price without mutation.
27
+ * @returns heuristic tokens for the block's JSON structure.
28
+ */
29
+ export function estimateStructuralBlock(block: ContentBlock): number {
30
+ if (block.type === 'image') {
31
+ const { offloaded: _offloaded, ...reference } = block
32
+ return BLOCK_OVERHEAD + Math.ceil(JSON.stringify(reference).length / CHARS_PER_TOKEN)
33
+ }
34
+ return BLOCK_OVERHEAD + Math.ceil(JSON.stringify(block).length / CHARS_PER_TOKEN)
35
+ }
36
+
37
+ /**
38
+ * Price content blocks recursively under the fixed density heuristic.
39
+ * @param blocks - content blocks to price without mutation.
40
+ * @returns heuristic tokens including per-block structural overhead.
41
+ */
42
+ export function estimateContent(blocks: readonly ContentBlock[]): number {
43
+ let tokens = 0
44
+ for (const block of blocks) {
45
+ switch (block.type) {
46
+ case 'text':
47
+ case 'reasoning':
48
+ tokens += Math.ceil(block.text.length / CHARS_PER_TOKEN) + BLOCK_OVERHEAD
49
+ break
50
+ case 'tool-call':
51
+ tokens += Math.ceil(block.name.length / CHARS_PER_TOKEN)
52
+ + Math.ceil(block.arguments.length / CHARS_PER_TOKEN)
53
+ + BLOCK_OVERHEAD
54
+ break
55
+ default:
56
+ // ContentBlockMap is merge-extensible; unknown blocks (and image
57
+ // references, whose request price is route-owned) retain a
58
+ // conservative structural JSON price under the fixed heuristic.
59
+ tokens += estimateStructuralBlock(block)
60
+ }
61
+ }
62
+ return tokens
63
+ }
64
+
65
+ /**
66
+ * Price the rendered system prompt: the `system/message` surface node's text.
67
+ * Adapters serialize the prompt as a plain string — a system-role message or
68
+ * the request's system field — not as a typed content block, so the price is
69
+ * text density plus role framing with no per-block overhead.
70
+ * @param message - system-role message to price without mutation.
71
+ * @returns heuristic system-prompt tokens; 0 for empty content ("no system prompt").
72
+ */
73
+ export function estimateSystemMessage(message: Message): number {
74
+ if (message.content.length === 0) return 0
75
+ let characters = 0
76
+ for (const block of message.content) {
77
+ characters += block.type === 'text' ? block.text.length : JSON.stringify(block).length
78
+ }
79
+ return Math.ceil(characters / CHARS_PER_TOKEN) + ROLE_OVERHEAD
80
+ }
81
+
82
+ /**
83
+ * Heuristically price one model-visible message.
84
+ * @param message - message to price without mutation.
85
+ * @returns content and role-framing tokens under the fixed heuristic; a
86
+ * system-role message prices as {@link estimateSystemMessage}.
87
+ */
88
+ export function estimateMessage(message: Message): number {
89
+ if (message.role === 'system') return estimateSystemMessage(message)
90
+ return estimateContent(message.content) + ROLE_OVERHEAD
91
+ }
92
+
93
+ /**
94
+ * Price the tool-schema part of a canonical request envelope — the envelope's
95
+ * only priced field, since the system prompt is a surface node.
96
+ * @param header - canonical envelope, or undefined before any request.
97
+ * @returns heuristic tool-schema tokens; 0 when absent or empty.
98
+ */
99
+ export function estimateToolsTokens(header: EpochHeader | undefined): number {
100
+ if (header?.tools === undefined || header.tools.length === 0) return 0
101
+ return Math.ceil(JSON.stringify(header.tools).length / CHARS_PER_TOKEN) + BLOCK_OVERHEAD
102
+ }
package/src/index.ts ADDED
@@ -0,0 +1,296 @@
1
+ /**
2
+ * Single replay-aware token-meter service for request and surface pressure.
3
+ *
4
+ * @module @open33/harness-token-meter
5
+ */
6
+
7
+ import { Context, Service } from '@open33/cordis'
8
+ import type {} from '@open33/harness-compaction-image-offload/projection'
9
+ import z from '@open33/schemastery'
10
+ import type { LlmImageRequestPricing, LlmRuntime, Message, TokenUsage } from '@open33/harness-llm'
11
+ import { deepFreeze } from '@open33/harness-util-values'
12
+ import type {
13
+ EpochHeader,
14
+ Session,
15
+ SessionEvent,
16
+ SessionSeq as SessionSeqType,
17
+ SessionLogOffset as SessionLogOffsetType,
18
+ } from '@open33/harness-session'
19
+ import {
20
+ canonicalHeader,
21
+ headerEquals,
22
+ isSurfaceEvent,
23
+ SessionLogOffset,
24
+ SessionSeq,
25
+ } from '@open33/harness-session'
26
+ import type { ProjectionHandle } from '@open33/harness-session-projection'
27
+ import type {
28
+ ContextPressureProjection,
29
+ TokenMeasurement,
30
+ TokenMeasurementBaseline,
31
+ TokenMeterConfig,
32
+ } from './types.ts'
33
+ import { contextBreakdownProjectionDefinition } from './breakdown-projection.ts'
34
+ import { contextPressureProjectionDefinition, tokenUsageProjectionDefinition } from './usage-projection.ts'
35
+ import type { ContextPressureState } from './usage-projection.ts'
36
+ import { estimateMessage, estimateToolsTokens } from './estimate.ts'
37
+ import { advanceMeasurement, measurementProjectionDefinition } from './measurement-projection.ts'
38
+ import type { MeasurementState } from './measurement-projection.ts'
39
+ import { commitSurfaceTokens, planSurfaceTokens } from './surface-fold.ts'
40
+ import type { MeterSurfaceNode } from './surface-fold.ts'
41
+ import { priceSurface } from './route-pricing.ts'
42
+
43
+ export type * from './types.ts'
44
+
45
+ /** Rebuildable positional prices, excluded from projection checkpoints. */
46
+ interface ReplayState {
47
+ consumedEvents: SessionLogOffsetType
48
+ surface: MeterSurfaceNode[]
49
+ header: { seq: SessionSeqType | null; value: EpochHeader } | undefined
50
+ anchorHeader: { seq: SessionSeqType | null; value: EpochHeader } | undefined
51
+ anchorNodes: readonly MeterSurfaceNode[]
52
+ /** Preserve synchronous construction-time reads before registration completes. */
53
+ pendingMeasurement: MeasurementState
54
+ }
55
+
56
+ /** Sum disjoint provider usage buckets without double-counting reasoning output. */
57
+ function usageTokens(usage: TokenUsage): number {
58
+ return usage.inputTokens
59
+ + (usage.cacheReadTokens ?? 0)
60
+ + (usage.cacheWriteTokens ?? 0)
61
+ + usage.outputTokens
62
+ }
63
+
64
+ /** Compare optional envelopes so a headerless estimate can track later surface deltas. */
65
+ function optionalHeaderEquals(
66
+ left: EpochHeader | undefined,
67
+ right: EpochHeader | undefined,
68
+ ): boolean {
69
+ if (left === undefined || right === undefined) return left === right
70
+ return headerEquals(left, right)
71
+ }
72
+
73
+ /** Reject stale or misspelled keys before defaults can hide them. */
74
+ function validateConfigKeys(config: TokenMeterConfig): void {
75
+ for (const key of Object.keys(config)) {
76
+ throw new Error(`TokenMeterConfig: unknown key "${key}" (no settings are supported)`)
77
+ }
78
+ }
79
+
80
+ declare module '@open33/cordis' {
81
+ interface Context {
82
+ tokenMeter: TokenMeter
83
+ }
84
+ }
85
+
86
+ /** Replay owner for one service-wide estimator and isolated per-session folds. */
87
+ export class TokenMeter extends Service {
88
+ // Schemastery preserves untrusted loader keys on an empty object schema;
89
+ // the public type excludes settings while validateConfigKeys rejects them.
90
+ static Config: z<TokenMeterConfig> = z.object({}) as unknown as z<TokenMeterConfig>
91
+
92
+ static inject = ['sessionProjections']
93
+
94
+ private readonly states = new WeakMap<Session, ReplayState>()
95
+ private measurementProjectionHandle: ProjectionHandle<MeasurementState> | undefined
96
+ private contextPressureProjectionHandle!: ProjectionHandle<ContextPressureState>
97
+
98
+ constructor(ctx: Context, config: TokenMeterConfig = {}) {
99
+ super(ctx, 'tokenMeter')
100
+ validateConfigKeys(config)
101
+ }
102
+
103
+ protected async [Service.init](): Promise<void> {
104
+ const ctx = this.ctx
105
+ this.measurementProjectionHandle = await ctx.sessionProjections.register(measurementProjectionDefinition)
106
+ await ctx.sessionProjections.register(tokenUsageProjectionDefinition)
107
+ this.contextPressureProjectionHandle = await ctx.sessionProjections.register(contextPressureProjectionDefinition)
108
+ await ctx.sessionProjections.register(contextBreakdownProjectionDefinition)
109
+
110
+ // Readers catch up independently, while eager observation bounds ordinary
111
+ // read latency without creating state for sessions no consumer has read.
112
+ ctx.on('session/event', (session) => {
113
+ if (this.states.has(session)) this._sync(session)
114
+ })
115
+ }
116
+
117
+ /**
118
+ * Read the latest logged provider prompt size and route capacity.
119
+ * @param session - Session whose committed usage and request capacity are read.
120
+ * @returns context pressure; fields remain absent until their source events are recorded.
121
+ */
122
+ contextPressure(session: Session): Pick<ContextPressureProjection, 'pressureTokens' | 'contextWindow'> {
123
+ const { pressureTokens, contextWindow } = this.contextPressureProjectionHandle.stateOf(session)
124
+ return {
125
+ ...pressureTokens === undefined ? {} : { pressureTokens },
126
+ ...contextWindow === undefined ? {} : { contextWindow },
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Measure current request pressure and surface through the durable tail.
132
+ *
133
+ * The effective envelope's routed provider/model selects the request-image
134
+ * pricing every node is priced under: a route whose adapter declares image
135
+ * pricing charges each retained image its visual tokens plus its
136
+ * model-visible text, while other routes keep the fixed heuristic. Provider
137
+ * usage is reused only when the latest successful call's canonical request
138
+ * envelope matches `requestHeader` and its total is no lower than that
139
+ * call's full route-priced anchor; otherwise the complete envelope and
140
+ * surface are repriced. The anchor includes all surface nodes immediately
141
+ * before the assistant message, including inputs admitted after step/start.
142
+ *
143
+ * `requestHeader` replaces the latest logged envelope for pressure and node
144
+ * pricing; the node set always describes the current session surface. Every
145
+ * call clones those positional nodes, so measurement is O(surface).
146
+ *
147
+ * @param session - session to replay through its current durable tail.
148
+ * @param requestHeader - optional effective request envelope replacing the latest logged header.
149
+ * @returns a detached deeply immutable pressure and surface measurement.
150
+ */
151
+ measure(session: Session, requestHeader?: EpochHeader): TokenMeasurement {
152
+ const { prices: state, measurement } = this._sync(session)
153
+ const header = requestHeader === undefined
154
+ ? this._cachedHeader(state, measurement.headerSeq)
155
+ : canonicalHeader(requestHeader)
156
+ const pricing = this._routeImagePricing(header)
157
+ const fileText = this._fileRequestText()
158
+ const surface = priceSurface(state.surface, pricing, fileText)
159
+ const anchor = measurement.anchor
160
+
161
+ let baseline: TokenMeasurementBaseline
162
+ let surfaceDeltaTokens: number
163
+ if (anchor !== null && optionalHeaderEquals(this._cachedHeader(state, anchor.headerSeq), header)) {
164
+ // Matching headers share one route, so the anchored snapshot reprices
165
+ // under the same pricing as the current surface and the signed delta
166
+ // compares like with like.
167
+ const anchorSurfaceTokens = priceSurface(state.anchorNodes, pricing, fileText).surfaceTokens
168
+ + anchor.assistantTokens
169
+ const estimatedAnchorTokens = estimateToolsTokens(header) + anchorSurfaceTokens
170
+ const usage = anchor.usage
171
+ // Signed heuristic deltas remain conservative only from an anchor
172
+ // that is at least as large as the matching full heuristic price.
173
+ baseline = usage !== null && usageTokens(usage) >= estimatedAnchorTokens
174
+ ? { kind: 'usage', tokens: usageTokens(usage), usage }
175
+ : { kind: 'estimated', tokens: estimatedAnchorTokens }
176
+ surfaceDeltaTokens = surface.surfaceTokens - anchorSurfaceTokens
177
+ } else if (header === undefined && surface.surfaceTokens === 0) {
178
+ baseline = { kind: 'none', tokens: 0 }
179
+ surfaceDeltaTokens = 0
180
+ } else {
181
+ baseline = {
182
+ kind: 'estimated',
183
+ tokens: estimateToolsTokens(header) + surface.surfaceTokens,
184
+ }
185
+ surfaceDeltaTokens = 0
186
+ }
187
+
188
+ return deepFreeze(structuredClone({
189
+ logRevision: state.consumedEvents,
190
+ baseline,
191
+ surfaceDeltaTokens,
192
+ totalTokens: Math.max(0, baseline.tokens + surfaceDeltaTokens),
193
+ surfaceTokens: surface.surfaceTokens,
194
+ nodes: surface.nodes,
195
+ }))
196
+ }
197
+
198
+ /** Resolve the routed model's image pricing, when the llm service and route declare one. */
199
+ private _routeImagePricing(header: EpochHeader | undefined): LlmImageRequestPricing | undefined {
200
+ const config = header?.config
201
+ if (config === undefined) return undefined
202
+ return this.ctx.get('llm')?.imageRequestPricing(config.provider, config.model)
203
+ }
204
+
205
+ /** Resolve request-time file projection when an LLM service is mounted. */
206
+ private _fileRequestText(): (
207
+ (ref: Parameters<LlmRuntime['fileRequestText']>[0]) => string
208
+ ) | undefined {
209
+ const llm = this.ctx.get('llm')
210
+ return llm === undefined ? undefined : ref => llm.fileRequestText(ref)
211
+ }
212
+
213
+ /**
214
+ * Heuristically price one model-visible message (instance face of the pure
215
+ * `estimateMessage` export from `estimate.ts`).
216
+ * @param message - message to price without mutation.
217
+ * @returns content and role-framing tokens under the fixed service heuristic.
218
+ */
219
+ estimateMessage(message: Message): number {
220
+ return estimateMessage(message)
221
+ }
222
+
223
+ /** Resolve one of the two header payloads retained by the rebuildable price cache. */
224
+ private _cachedHeader(state: ReplayState, seq: SessionSeqType | null): EpochHeader | undefined {
225
+ if (seq === null) return undefined
226
+ if (state.header?.seq === seq) return state.header.value
227
+ return state.anchorHeader?.value
228
+ }
229
+
230
+ /** Catch rebuildable prices up to the current durable tail. */
231
+ private _sync(session: Session, useProjection = true): { prices: ReplayState; measurement: MeasurementState } {
232
+ let state = this.states.get(session)
233
+ if (state === undefined) {
234
+ state = {
235
+ consumedEvents: SessionLogOffset(0),
236
+ surface: [],
237
+ header: undefined,
238
+ anchorHeader: undefined,
239
+ anchorNodes: [],
240
+ pendingMeasurement: measurementProjectionDefinition.init(),
241
+ }
242
+ this.states.set(session, state)
243
+ }
244
+ const projected = useProjection ? this.measurementProjectionHandle?.stateOf(session) : undefined
245
+ while (state.consumedEvents < session.seq) {
246
+ // Cold price caches may replay resident history.
247
+ // oxlint-disable-next-line typescript/no-non-null-assertion, typescript/no-deprecated
248
+ const event = session.eventAt(SessionSeq(state.consumedEvents))!
249
+ const next = projected !== undefined
250
+ ? undefined
251
+ : measurementProjectionDefinition.apply(state.pendingMeasurement, event)
252
+ const measurement = next ?? projected
253
+ if (measurement?.invalidSeq === event.seq) {
254
+ // Match the original assistant validation order before committing any prices.
255
+ if (event.type === 'assistant/message') planSurfaceTokens(state.surface, event)
256
+ advanceMeasurement(measurement, event)
257
+ }
258
+ this._foldEvent(state, event)
259
+ if (next !== undefined) state.pendingMeasurement = next
260
+ state.consumedEvents = SessionLogOffset(state.consumedEvents + 1)
261
+ }
262
+ if (projected !== undefined && (projected.headerSeq !== (state.header?.seq ?? null)
263
+ || (projected.anchor !== null && projected.anchor.headerSeq !== (state.anchorHeader?.seq ?? null)))) {
264
+ // A checkpoint reference must match the original journal. Discard the
265
+ // rebuildable cache and use the same calculation from the beginning.
266
+ this.states.delete(session)
267
+ return this._sync(session, false)
268
+ }
269
+ // An initialized registration supplies `projected`; earlier reads keep the same pure fold locally.
270
+ return { prices: state, measurement: projected ?? state.pendingMeasurement }
271
+ }
272
+
273
+ /** Update only discardable positional prices and the pre-assistant view. */
274
+ private _foldEvent(state: ReplayState, event: SessionEvent): void {
275
+ if (event.type === 'request/header') state.header = { seq: event.seq, value: canonicalHeader(event.data.header) }
276
+ if (event.type === 'image/offload') {
277
+ const offloaded = new Map(event.data.targets.map(target => [target.seq, new Set(target.imageIndexes)]))
278
+ state.surface = state.surface.map((node) => {
279
+ const indexes = offloaded.get(node.seq)
280
+ if (indexes === undefined) return node
281
+ return {
282
+ ...node,
283
+ images: node.images.map((image, index) => (indexes.has(index) ? { ...image, offloaded: true as const } : image)),
284
+ }
285
+ })
286
+ }
287
+ const plan = isSurfaceEvent(event) ? planSurfaceTokens(state.surface, event) : undefined
288
+ if (event.type === 'assistant/message') {
289
+ state.anchorNodes = [...state.surface]
290
+ state.anchorHeader = state.header
291
+ }
292
+ if (plan !== undefined) commitSurfaceTokens(state.surface, plan)
293
+ }
294
+ }
295
+
296
+ export default TokenMeter