@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,274 @@
1
+ import { lastAssistantStreamChunk } from '@open33/harness-llm/assistant-stream'
2
+ import type { AssistantMessage, TokenUsage } from '@open33/harness-llm/types'
3
+ import type {} from '@open33/harness-llm-retry/types'
4
+ import type { SessionEvent } from '@open33/harness-session/types'
5
+
6
+ /** One provider/model route that contributed a billed request attempt. */
7
+ export interface TurnTokenUsageRoute {
8
+ readonly provider: string
9
+ readonly model: string
10
+ }
11
+
12
+ /** Exact provider-reported token accounting for every attempt in one completed Turn. */
13
+ export interface TurnTokenUsage {
14
+ /** Sum of uncached prompt input across all attempts. */
15
+ readonly uncachedInputTokens: number
16
+ readonly outputTokens: number
17
+ /** Exact aggregate prompt plus output total across all attempts. */
18
+ readonly totalTokens: number
19
+ /** Present only when every attempt reported the bucket. */
20
+ readonly cacheReadTokens?: number
21
+ /** Present only when every attempt reported the bucket. */
22
+ readonly cacheWriteTokens?: number
23
+ /** Output subset, present only when every attempt reported it. */
24
+ readonly reasoningTokens?: number
25
+ /** Present only when every billed attempt has provider/model attribution. */
26
+ readonly routes?: readonly TurnTokenUsageRoute[]
27
+ }
28
+
29
+ interface NormalizedAttempt {
30
+ readonly inputTokens: number
31
+ readonly outputTokens: number
32
+ readonly totalTokens: number
33
+ readonly cacheReadTokens?: number
34
+ readonly cacheWriteTokens?: number
35
+ readonly reasoningTokens?: number
36
+ readonly route?: TurnTokenUsageRoute
37
+ }
38
+
39
+ type AttemptState =
40
+ | { readonly kind: 'idle' }
41
+ | {
42
+ readonly kind: 'open'
43
+ readonly turn: number
44
+ readonly step: number
45
+ readonly sample?: TokenUsage
46
+ }
47
+ | {
48
+ readonly kind: 'finishClosed'
49
+ readonly turn: number
50
+ readonly step: number
51
+ }
52
+ | {
53
+ readonly kind: 'settled'
54
+ readonly turn: number
55
+ readonly step: number
56
+ readonly by: 'message' | 'retry'
57
+ }
58
+
59
+ function isCount(value: unknown): value is number {
60
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0
61
+ }
62
+
63
+ function safeSum(values: readonly number[]): number | undefined {
64
+ let total = 0
65
+ for (const value of values) {
66
+ total += value
67
+ if (!Number.isSafeInteger(total)) return undefined
68
+ }
69
+ return total
70
+ }
71
+
72
+ function messageRoute(message: AssistantMessage): TurnTokenUsageRoute | undefined {
73
+ const { provider, model } = message.source
74
+ return provider.length > 0 && model.length > 0 ? { provider, model } : undefined
75
+ }
76
+
77
+ function streamUsage(stream: SessionEvent<'assistant/message'>['data']['stream']): TokenUsage | undefined {
78
+ return lastAssistantStreamChunk(stream, 'usage')?.usage
79
+ }
80
+
81
+ function normalizeUsage(usage: TokenUsage, route?: TurnTokenUsageRoute): NormalizedAttempt | undefined {
82
+ const {
83
+ inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens, reasoningTokens, totalTokens,
84
+ } = usage
85
+ if (!isCount(inputTokens) || !isCount(outputTokens)) return undefined
86
+ if (cacheReadTokens !== undefined && !isCount(cacheReadTokens)) return undefined
87
+ if (cacheWriteTokens !== undefined && !isCount(cacheWriteTokens)) return undefined
88
+ if (reasoningTokens !== undefined && (!isCount(reasoningTokens) || reasoningTokens > outputTokens)) {
89
+ return undefined
90
+ }
91
+
92
+ const knownPrompt = safeSum([
93
+ inputTokens,
94
+ ...cacheReadTokens === undefined ? [] : [cacheReadTokens],
95
+ ...cacheWriteTokens === undefined ? [] : [cacheWriteTokens],
96
+ ])
97
+ if (knownPrompt === undefined) return undefined
98
+
99
+ let exactTotal: number
100
+ if (totalTokens !== undefined) {
101
+ if (!isCount(totalTokens)) return undefined
102
+ const exactPrompt = totalTokens - outputTokens
103
+ if (!isCount(exactPrompt) || exactPrompt < knownPrompt) return undefined
104
+ if (cacheReadTokens !== undefined && cacheWriteTokens !== undefined && exactPrompt !== knownPrompt) {
105
+ return undefined
106
+ }
107
+ exactTotal = totalTokens
108
+ } else {
109
+ if (cacheReadTokens === undefined || cacheWriteTokens === undefined) return undefined
110
+ const derivedTotal = safeSum([knownPrompt, outputTokens])
111
+ if (derivedTotal === undefined) return undefined
112
+ exactTotal = derivedTotal
113
+ }
114
+
115
+ return {
116
+ inputTokens,
117
+ outputTokens,
118
+ totalTokens: exactTotal,
119
+ ...cacheReadTokens === undefined ? {} : { cacheReadTokens },
120
+ ...cacheWriteTokens === undefined ? {} : { cacheWriteTokens },
121
+ ...reasoningTokens === undefined ? {} : { reasoningTokens },
122
+ ...route === undefined ? {} : { route },
123
+ }
124
+ }
125
+
126
+ function aggregateAttempts(attempts: readonly NormalizedAttempt[]): TurnTokenUsage | undefined {
127
+ if (attempts.length === 0) return undefined
128
+ const inputTokens = safeSum(attempts.map(attempt => attempt.inputTokens))
129
+ const outputTokens = safeSum(attempts.map(attempt => attempt.outputTokens))
130
+ const totalTokens = safeSum(attempts.map(attempt => attempt.totalTokens))
131
+ if (inputTokens === undefined || outputTokens === undefined || totalTokens === undefined) return undefined
132
+
133
+ const cacheRead = attempts.map(attempt => attempt.cacheReadTokens)
134
+ const cacheWrite = attempts.map(attempt => attempt.cacheWriteTokens)
135
+ const reasoning = attempts.map(attempt => attempt.reasoningTokens)
136
+ const cacheReadTokens = cacheRead.every(isCount) ? safeSum(cacheRead) : undefined
137
+ const cacheWriteTokens = cacheWrite.every(isCount) ? safeSum(cacheWrite) : undefined
138
+ const reasoningTokens = reasoning.every(isCount) ? safeSum(reasoning) : undefined
139
+ // A present cache bucket is bounded by exact prompt, and reasoning is bounded
140
+ // by output. Safe required aggregates therefore imply safe optional sums.
141
+
142
+ let routes: readonly TurnTokenUsageRoute[] | undefined
143
+ const attributed = attempts.map(attempt => attempt.route)
144
+ if (attributed.every((route): route is TurnTokenUsageRoute => route !== undefined)) {
145
+ const unique = new Map<string, TurnTokenUsageRoute>()
146
+ for (const route of attributed) unique.set(`${route.provider}\0${route.model}`, route)
147
+ routes = [...unique.values()]
148
+ }
149
+
150
+ return {
151
+ uncachedInputTokens: inputTokens,
152
+ outputTokens,
153
+ totalTokens,
154
+ ...cacheReadTokens === undefined ? {} : { cacheReadTokens },
155
+ ...cacheWriteTokens === undefined ? {} : { cacheWriteTokens },
156
+ ...reasoningTokens === undefined ? {} : { reasoningTokens },
157
+ ...routes === undefined ? {} : { routes },
158
+ }
159
+ }
160
+
161
+ function sameAttempt(
162
+ state: Exclude<AttemptState, { kind: 'idle' }>,
163
+ turn: number,
164
+ step: number,
165
+ ): boolean {
166
+ return state.turn === turn && state.step === step
167
+ }
168
+
169
+ /**
170
+ * Fold one complete Turn's durable attempt lifecycle into exact token accounting.
171
+ *
172
+ * No attempt is inferred from a usage sample. Any missing lifecycle boundary,
173
+ * incomplete attempt usage, unsafe count, or contradictory exact total makes
174
+ * the whole disclosure unavailable.
175
+ * @param events - Turn-local durable events from `turn/start` through `turn/end`.
176
+ * @returns exact aggregate usage, or undefined when it cannot be proven.
177
+ */
178
+ export function deriveTurnTokenUsage(events: readonly SessionEvent[]): TurnTokenUsage | undefined {
179
+ let state: AttemptState = { kind: 'idle' }
180
+ const attempts: NormalizedAttempt[] = []
181
+ let turn: number | undefined
182
+ let sawEnd = false
183
+ let invalid = false
184
+
185
+ const closeOpen = (route?: TurnTokenUsageRoute): boolean => {
186
+ if (state.kind !== 'open' || state.sample === undefined) return false
187
+ const normalized = normalizeUsage(state.sample, route)
188
+ if (normalized === undefined) return false
189
+ attempts.push(normalized)
190
+ return true
191
+ }
192
+
193
+ for (const event of events) {
194
+ if (invalid) break
195
+ if (event.type === 'turn/start') {
196
+ if (turn !== undefined || state.kind !== 'idle') invalid = true
197
+ else turn = event.data.turn
198
+ continue
199
+ }
200
+ if (turn === undefined) {
201
+ invalid = true
202
+ break
203
+ }
204
+ if (event.type === 'turn/end') {
205
+ if (event.data.turn !== turn || state.kind !== 'idle' || sawEnd) invalid = true
206
+ else sawEnd = true
207
+ continue
208
+ }
209
+ if (sawEnd) {
210
+ invalid = true
211
+ break
212
+ }
213
+ if (event.type === 'step/start') {
214
+ if (event.data.turn !== turn || state.kind !== 'idle') invalid = true
215
+ else state = { kind: 'open', turn, step: event.data.step }
216
+ continue
217
+ }
218
+ if (event.type === 'llm/retry-started') {
219
+ if (event.data.turn !== turn
220
+ || state.kind !== 'settled'
221
+ || state.by !== 'retry'
222
+ || !sameAttempt(state, event.data.turn, event.data.step)) invalid = true
223
+ else state = { kind: 'open', turn, step: event.data.step }
224
+ continue
225
+ }
226
+ if (event.type === 'assistant/attempt') {
227
+ if (event.data.turn !== turn
228
+ || state.kind !== 'open'
229
+ || !sameAttempt(state, event.data.turn, event.data.step)) {
230
+ invalid = true
231
+ continue
232
+ }
233
+ const sample: TokenUsage | undefined = streamUsage(event.data.stream) ?? state.sample
234
+ state = { kind: 'open', turn, step: event.data.step, ...(sample === undefined ? {} : { sample }) }
235
+ if (!closeOpen()) invalid = true
236
+ else state = { kind: 'finishClosed', turn, step: event.data.step }
237
+ continue
238
+ }
239
+ if (event.type === 'assistant/message') {
240
+ if (event.data.turn !== turn
241
+ || state.kind !== 'open'
242
+ || !sameAttempt(state, event.data.turn, event.data.step)) {
243
+ invalid = true
244
+ continue
245
+ }
246
+ const sample = event.data.usage ?? streamUsage(event.data.stream)
247
+ if (sample !== undefined) state = { ...state, sample }
248
+ if (!closeOpen(messageRoute(event.data.message))) invalid = true
249
+ else state = { kind: 'settled', turn, step: event.data.step, by: 'message' }
250
+ continue
251
+ }
252
+ if (event.type === 'llm/retry') {
253
+ if (event.data.turn !== turn || state.kind === 'idle'
254
+ || !sameAttempt(state, event.data.turn, event.data.step)) {
255
+ invalid = true
256
+ continue
257
+ }
258
+ if (state.kind === 'settled' || (state.kind === 'open' && !closeOpen())) invalid = true
259
+ if (!invalid) state = { kind: 'settled', turn, step: event.data.step, by: 'retry' }
260
+ continue
261
+ }
262
+ if (event.type === 'step/end') {
263
+ if (event.data.turn !== turn || state.kind === 'idle'
264
+ || !sameAttempt(state, event.data.turn, event.data.step)) {
265
+ invalid = true
266
+ continue
267
+ }
268
+ if (state.kind === 'open' && !closeOpen()) invalid = true
269
+ if (!invalid) state = { kind: 'idle' }
270
+ }
271
+ }
272
+
273
+ return invalid || !sawEnd || state.kind !== 'idle' ? undefined : aggregateAttempts(attempts)
274
+ }
package/src/types.ts ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Public configuration and measurement vocabulary for replay token metering.
3
+ *
4
+ * @module @open33/harness-token-meter/types
5
+ */
6
+
7
+ import type { TokenUsage } from '@open33/harness-llm'
8
+ import type { SessionLogOffset, SessionSeq } from '@open33/harness-session/types'
9
+
10
+ export type { ContextBreakdownProjection, ContextPressureProjection, TokenUsageProjection } from './projection.ts'
11
+
12
+ /** Token-meter plugin configuration; the fixed estimator has no settings. */
13
+ export type TokenMeterConfig = Record<string, never>
14
+
15
+ /** The baseline from which a signed surface delta produces current pressure. */
16
+ export type TokenMeasurementBaseline =
17
+ | { readonly kind: 'none'; readonly tokens: 0 }
18
+ | { readonly kind: 'estimated'; readonly tokens: number }
19
+ | { readonly kind: 'usage'; readonly tokens: number; readonly usage: Readonly<TokenUsage> }
20
+
21
+ /** Detached immutable request-pressure and surface snapshot at one consumed log revision. */
22
+ export interface TokenMeasurement {
23
+ /** Number of durable events consumed; equal to the next unread event seq. */
24
+ readonly logRevision: SessionLogOffset
25
+ /** Provider or heuristic anchor used for this measurement. */
26
+ readonly baseline: TokenMeasurementBaseline
27
+ /** Signed repricing of current surface content relative to the baseline anchor. */
28
+ readonly surfaceDeltaTokens: number
29
+ /** Non-negative current request-and-response pressure. */
30
+ readonly totalTokens: number
31
+ /** Total route-priced request tokens across the current surface; equals the sum of the node prices. */
32
+ readonly surfaceTokens: number
33
+ /** Current surface nodes in positional head-to-tail order. */
34
+ readonly nodes: readonly TokenSurfaceNode[]
35
+ }
36
+
37
+ /** One token-priced node in the current ordered session surface. */
38
+ export interface TokenSurfaceNode {
39
+ /** Durable sequence number of the surface event. */
40
+ readonly seq: SessionSeq
41
+ /**
42
+ * Request-pressure tokens for the exact message projected by this node under
43
+ * the measured route: image occurrences carry the route's declared visual
44
+ * price when the routed adapter declares one, and the fixed heuristic
45
+ * otherwise. Trigger, retention, and range selection all read this price.
46
+ */
47
+ readonly tokens: number
48
+ /**
49
+ * Fixed-heuristic tokens for the same message, independent of any route.
50
+ * The shadow-price protocol prices replacements with this value so the O(1)
51
+ * projection fold stays in agreement with its own appends.
52
+ */
53
+ readonly heuristicTokens: number
54
+ }
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Pure folds for durable provider-reported token usage and context occupancy.
3
+ */
4
+
5
+ import { z } from 'zod'
6
+ import { lastAssistantStreamChunk, type TokenUsage } from '@open33/harness-llm'
7
+ import type {} from '@open33/harness-llm-retry/types'
8
+ import { SessionSeq } from '@open33/harness-session'
9
+ import type { SessionEvent } from '@open33/harness-session'
10
+ import type { ProjectionDefinition } from '@open33/harness-session-projection'
11
+ import type { ContextPressureProjection, TokenUsageProjection } from './projection.ts'
12
+ import { foldSurfaceProjection } from './surface-projection.ts'
13
+
14
+ const zeroBuckets = (): TokenUsageProjection => ({
15
+ uncachedInputTokens: 0,
16
+ outputTokens: 0,
17
+ cacheReadTokens: 0,
18
+ cacheWriteTokens: 0,
19
+ })
20
+
21
+ const bucketsFrom = (usage: TokenUsage): TokenUsageProjection => ({
22
+ uncachedInputTokens: usage.inputTokens,
23
+ outputTokens: usage.outputTokens,
24
+ cacheReadTokens: usage.cacheReadTokens ?? 0,
25
+ cacheWriteTokens: usage.cacheWriteTokens ?? 0,
26
+ })
27
+
28
+ const bucketsEqual = (left: TokenUsageProjection, right: TokenUsageProjection): boolean =>
29
+ left.uncachedInputTokens === right.uncachedInputTokens
30
+ && left.outputTokens === right.outputTokens
31
+ && left.cacheReadTokens === right.cacheReadTokens
32
+ && left.cacheWriteTokens === right.cacheWriteTokens
33
+
34
+ const addReplacing = (
35
+ totals: TokenUsageProjection,
36
+ previous: TokenUsageProjection | undefined,
37
+ next: TokenUsageProjection,
38
+ ): TokenUsageProjection => ({
39
+ uncachedInputTokens: totals.uncachedInputTokens - (previous?.uncachedInputTokens ?? 0) + next.uncachedInputTokens,
40
+ outputTokens: totals.outputTokens - (previous?.outputTokens ?? 0) + next.outputTokens,
41
+ cacheReadTokens: totals.cacheReadTokens - (previous?.cacheReadTokens ?? 0) + next.cacheReadTokens,
42
+ cacheWriteTokens: totals.cacheWriteTokens - (previous?.cacheWriteTokens ?? 0) + next.cacheWriteTokens,
43
+ })
44
+
45
+ const projectionSchema = z.object({
46
+ uncachedInputTokens: z.number().int().nonnegative(),
47
+ outputTokens: z.number().int().nonnegative(),
48
+ cacheReadTokens: z.number().int().nonnegative(),
49
+ cacheWriteTokens: z.number().int().nonnegative(),
50
+ }).strict()
51
+
52
+ /**
53
+ * The token-usage unit's state schema — the one definition of the state
54
+ * shape; the state type is inferred from it.
55
+ */
56
+ const tokenUsageStateSchema = z.object({
57
+ totals: projectionSchema,
58
+ last: z.object({
59
+ turn: z.number().int().nonnegative(),
60
+ step: z.number().int().nonnegative(),
61
+ buckets: projectionSchema,
62
+ }).nullable(),
63
+ }).strict()
64
+
65
+ type TokenUsageState = z.infer<typeof tokenUsageStateSchema>
66
+
67
+ const pressureSchema: z.ZodType<ContextPressureProjection> = z.object({
68
+ pressureTokens: z.number().int().nonnegative().optional(),
69
+ projectedTokens: z.number().int().nonnegative().optional(),
70
+ contextWindow: z.number().int().positive().optional(),
71
+ }).strict().transform(({ pressureTokens, projectedTokens, contextWindow }) => ({
72
+ ...pressureTokens === undefined ? {} : { pressureTokens },
73
+ ...projectedTokens === undefined ? {} : { projectedTokens },
74
+ ...contextWindow === undefined ? {} : { contextWindow },
75
+ }))
76
+
77
+ /** Prompt-side pressure of one request: input plus cache traffic, no output. */
78
+ const pressureFrom = (usage: TokenUsage): number =>
79
+ usage.inputTokens + (usage.cacheReadTokens ?? 0) + (usage.cacheWriteTokens ?? 0)
80
+
81
+ /** The usage one durable Assistant settlement reports for its attempt, if any. */
82
+ function usageOf(event: SessionEvent): TokenUsage | undefined {
83
+ if (event.type === 'assistant/message' && event.data.usage !== undefined) return event.data.usage
84
+ if (event.type !== 'assistant/message' && event.type !== 'assistant/attempt') return undefined
85
+ return lastAssistantStreamChunk(event.data.stream, 'usage')?.usage
86
+ }
87
+
88
+ /** The context-pressure state schema and source of its inferred type. */
89
+ const contextPressureStateSchema = z.object({
90
+ contextWindow: z.number().int().positive().optional(),
91
+ pressureTokens: z.number().int().nonnegative().optional(),
92
+ surfaceTokens: z.number().int().nonnegative(),
93
+ sampledSurfaceTokens: z.number().int().nonnegative().optional(),
94
+ claim: z.object({
95
+ start: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).transform(SessionSeq),
96
+ end: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).transform(SessionSeq),
97
+ tokens: z.number().int().nonnegative(),
98
+ }).optional(),
99
+ }).strict()
100
+
101
+ /** Host fold state for provider pressure and surface adjustments. */
102
+ export type ContextPressureState = z.infer<typeof contextPressureStateSchema>
103
+
104
+ /**
105
+ * Token-meter's session projection unit.
106
+ *
107
+ * Each v2 Assistant settlement contributes the last usage sample embedded in
108
+ * its stream. `llm/retry-started` closes the replacement slot so the retried
109
+ * attempt adds to the total.
110
+ */
111
+ export const tokenUsageProjectionDefinition = {
112
+ key: 'tokenUsage',
113
+ stateVersion: 2,
114
+ stateSchema: tokenUsageStateSchema,
115
+ init: () => ({ totals: zeroBuckets(), last: null }),
116
+ apply: (state, event) => {
117
+ if (event.type === 'llm/retry-started') {
118
+ return state.last?.turn === event.data.turn && state.last.step === event.data.step
119
+ ? { ...state, last: null }
120
+ : state
121
+ }
122
+ if (event.type !== 'assistant/message' && event.type !== 'assistant/attempt') {
123
+ return state
124
+ }
125
+ const sample = usageOf(event)
126
+ if (sample === undefined) return state
127
+ const { turn, step } = event.data
128
+ const usage: TokenUsage = sample
129
+
130
+ const buckets = bucketsFrom(usage)
131
+ const previous = state.last !== null
132
+ && state.last.turn === turn
133
+ && state.last.step === step
134
+ ? state.last.buckets
135
+ : undefined
136
+ if (previous !== undefined && bucketsEqual(previous, buckets)) return state
137
+
138
+ return {
139
+ totals: addReplacing(state.totals, previous, buckets),
140
+ last: { turn, step, buckets },
141
+ }
142
+ },
143
+ wire: { viewSchema: projectionSchema, view: state => state.totals },
144
+ } satisfies ProjectionDefinition<'tokenUsage', TokenUsageState>
145
+
146
+ /**
147
+ * Token-meter's context-occupancy projection unit.
148
+ *
149
+ * Independent last-wins slots: the newest usage sample supplies the provider
150
+ * numerator, the newest `request/context` record the denominator. Both are
151
+ * whole values, so replay order alone decides the result and no cross-field
152
+ * consistency is claimed — the pair is explicitly not one atomic request
153
+ * observation (see {@link ContextPressureProjection}).
154
+ *
155
+ * `pressureTokens` is prompt-side only, so it holds still while a turn streams
156
+ * and steps forward once the next request reports its usage. Because nothing
157
+ * but a request reports usage, it also cannot see a compaction: the fold
158
+ * therefore carries a running surface total alongside it and publishes
159
+ * `projectedTokens` — the sample plus the surface's signed movement since it
160
+ * was taken — so occupancy answers for the next request rather than the last
161
+ * one. The total rides {@link foldSurfaceProjection}, so the state stays O(1)
162
+ * and a replacement shrinks it by its logged shadow price. A replacement
163
+ * without a claim preserves the previous total. A usage sample is stamped
164
+ * BEFORE the same event joins the surface, so an `assistant/message` anchors
165
+ * against the surface its own request saw.
166
+ */
167
+ export const contextPressureProjectionDefinition = {
168
+ key: 'contextPressure',
169
+ stateVersion: 5,
170
+ stateSchema: contextPressureStateSchema,
171
+ init: () => ({ surfaceTokens: 0 }),
172
+ apply: (state, event) => {
173
+ const fold = foldSurfaceProjection(state.claim, event)
174
+ let next = state
175
+ if (event.type === 'request/context') {
176
+ const contextWindow = event.data.contextWindow
177
+ if (contextWindow !== state.contextWindow) {
178
+ if (contextWindow !== undefined) {
179
+ next = { ...next, contextWindow }
180
+ } else {
181
+ const { contextWindow: _removed, ...withoutContextWindow } = next
182
+ next = withoutContextWindow
183
+ }
184
+ }
185
+ }
186
+ const usage = usageOf(event)
187
+ if (usage !== undefined) {
188
+ const pressureTokens = pressureFrom(usage)
189
+ if (pressureTokens !== next.pressureTokens || next.sampledSurfaceTokens !== next.surfaceTokens) {
190
+ next = { ...next, pressureTokens, sampledSurfaceTokens: next.surfaceTokens }
191
+ }
192
+ }
193
+ if (fold.deltaTokens !== 0) {
194
+ next = { ...next, surfaceTokens: next.surfaceTokens + fold.deltaTokens }
195
+ }
196
+ // A defined fold.claim is always freshly built, so presence decides claim
197
+ // bookkeeping: no claim before or after this event leaves `next` as is.
198
+ if (state.claim === undefined && fold.claim === undefined) return next
199
+ const { claim: _expired, ...withoutClaim } = next
200
+ return fold.claim === undefined ? withoutClaim : { ...withoutClaim, claim: fold.claim }
201
+ },
202
+ wire: {
203
+ viewSchema: pressureSchema,
204
+ view: ({ contextWindow, pressureTokens, surfaceTokens, sampledSurfaceTokens }) => ({
205
+ ...contextWindow === undefined ? {} : { contextWindow },
206
+ ...pressureTokens === undefined ? {} : { pressureTokens },
207
+ ...pressureTokens === undefined || sampledSurfaceTokens === undefined
208
+ ? {}
209
+ : { projectedTokens: Math.max(0, pressureTokens + surfaceTokens - sampledSurfaceTokens) },
210
+ }),
211
+ summary: false,
212
+ },
213
+ } satisfies ProjectionDefinition<'contextPressure', ContextPressureState>