@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.
- package/LICENSE +22 -0
- package/README.i18n.yaml +64 -0
- package/README.md +162 -2
- package/README.zh.md +163 -0
- package/lib/index.js +981 -0
- package/lib/types/breakdown-projection.d.ts +128 -0
- package/lib/types/breakdown-projection.d.ts.map +1 -0
- package/lib/types/breakdown-projection.js +153 -0
- package/lib/types/breakdown-projection.js.map +1 -0
- package/lib/types/client.d.ts +9 -0
- package/lib/types/client.d.ts.map +1 -0
- package/lib/types/client.js +7 -0
- package/lib/types/client.js.map +1 -0
- package/lib/types/estimate.d.ts +50 -0
- package/lib/types/estimate.d.ts.map +1 -0
- package/lib/types/estimate.js +95 -0
- package/lib/types/estimate.js.map +1 -0
- package/lib/types/index.d.ts +73 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js +239 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/measurement-projection.d.ts +74 -0
- package/lib/types/measurement-projection.d.ts.map +1 -0
- package/lib/types/measurement-projection.js +94 -0
- package/lib/types/measurement-projection.js.map +1 -0
- package/lib/types/projection.d.ts +74 -0
- package/lib/types/projection.d.ts.map +1 -0
- package/lib/types/projection.js +7 -0
- package/lib/types/projection.js.map +1 -0
- package/lib/types/route-pricing.d.ts +31 -0
- package/lib/types/route-pricing.d.ts.map +1 -0
- package/lib/types/route-pricing.js +56 -0
- package/lib/types/route-pricing.js.map +1 -0
- package/lib/types/surface-fold.d.ts +68 -0
- package/lib/types/surface-fold.d.ts.map +1 -0
- package/lib/types/surface-fold.js +98 -0
- package/lib/types/surface-fold.js.map +1 -0
- package/lib/types/surface-projection.d.ts +58 -0
- package/lib/types/surface-projection.d.ts.map +1 -0
- package/lib/types/surface-projection.js +68 -0
- package/lib/types/surface-projection.js.map +1 -0
- package/lib/types/turn-usage.d.ts +33 -0
- package/lib/types/turn-usage.d.ts.map +1 -0
- package/lib/types/turn-usage.js +229 -0
- package/lib/types/turn-usage.js.map +1 -0
- package/lib/types/types.d.ts +56 -0
- package/lib/types/types.d.ts.map +1 -0
- package/lib/types/types.js +7 -0
- package/lib/types/types.js.map +1 -0
- package/lib/types/usage-projection.d.ts +196 -0
- package/lib/types/usage-projection.d.ts.map +1 -0
- package/lib/types/usage-projection.js +190 -0
- package/lib/types/usage-projection.js.map +1 -0
- package/locale/de.json +6 -0
- package/locale/en.json +5 -0
- package/locale/es.json +6 -0
- package/locale/fr.json +6 -0
- package/locale/ja.json +6 -0
- package/locale/pt.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +64 -3
- package/src/breakdown-projection.ts +184 -0
- package/src/client.ts +9 -0
- package/src/estimate.ts +102 -0
- package/src/index.ts +296 -0
- package/src/measurement-projection.ts +100 -0
- package/src/projection.ts +79 -0
- package/src/route-pricing.ts +76 -0
- package/src/surface-fold.ts +142 -0
- package/src/surface-projection.ts +96 -0
- package/src/turn-usage.ts +274 -0
- package/src/types.ts +54 -0
- package/src/usage-projection.ts +213 -0
package/lib/index.js
ADDED
|
@@ -0,0 +1,981 @@
|
|
|
1
|
+
import { Service } from "@open33/cordis";
|
|
2
|
+
import z from "@open33/schemastery";
|
|
3
|
+
import { deepFreeze } from "@open33/harness-util-values";
|
|
4
|
+
import { SessionLogOffset, SessionSeq, canonicalHeader, deriveEventMessage, headerEquals, isSurfaceEvent } from "@open33/harness-session";
|
|
5
|
+
import { z as z$1 } from "zod";
|
|
6
|
+
import { assembleAssistantStream, lastAssistantStreamChunk } from "@open33/harness-llm";
|
|
7
|
+
//#region lib/types/estimate.js
|
|
8
|
+
/**
|
|
9
|
+
* Fixed-density heuristic token pricing shared by the meter service and the
|
|
10
|
+
* pure context-breakdown projection, so both surfaces price identical content
|
|
11
|
+
* to identical numbers.
|
|
12
|
+
*
|
|
13
|
+
* @module @open33/harness-token-meter/estimate
|
|
14
|
+
*/
|
|
15
|
+
/** Fixed text-density estimate used until exact tokenization is needed. */
|
|
16
|
+
const CHARS_PER_TOKEN = 4;
|
|
17
|
+
/** Per-block structural overhead for JSON framing and type tags. */
|
|
18
|
+
const BLOCK_OVERHEAD = 4;
|
|
19
|
+
/**
|
|
20
|
+
* Structural JSON price of one block outside the typed pricing arms: the
|
|
21
|
+
* fixed heuristic for merge-extended blocks and for image references, whose
|
|
22
|
+
* request price is route-owned rather than fixed. Image offload marks do not
|
|
23
|
+
* change this reference-only heuristic; route pricing owns their placeholders.
|
|
24
|
+
* @param block - block to price without mutation.
|
|
25
|
+
* @returns heuristic tokens for the block's JSON structure.
|
|
26
|
+
*/
|
|
27
|
+
function estimateStructuralBlock(block) {
|
|
28
|
+
if (block.type === "image") {
|
|
29
|
+
const { offloaded: _offloaded, ...reference } = block;
|
|
30
|
+
return BLOCK_OVERHEAD + Math.ceil(JSON.stringify(reference).length / CHARS_PER_TOKEN);
|
|
31
|
+
}
|
|
32
|
+
return BLOCK_OVERHEAD + Math.ceil(JSON.stringify(block).length / CHARS_PER_TOKEN);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Price content blocks recursively under the fixed density heuristic.
|
|
36
|
+
* @param blocks - content blocks to price without mutation.
|
|
37
|
+
* @returns heuristic tokens including per-block structural overhead.
|
|
38
|
+
*/
|
|
39
|
+
function estimateContent(blocks) {
|
|
40
|
+
let tokens = 0;
|
|
41
|
+
for (const block of blocks) switch (block.type) {
|
|
42
|
+
case "text":
|
|
43
|
+
case "reasoning":
|
|
44
|
+
tokens += Math.ceil(block.text.length / CHARS_PER_TOKEN) + BLOCK_OVERHEAD;
|
|
45
|
+
break;
|
|
46
|
+
case "tool-call":
|
|
47
|
+
tokens += Math.ceil(block.name.length / CHARS_PER_TOKEN) + Math.ceil(block.arguments.length / CHARS_PER_TOKEN) + BLOCK_OVERHEAD;
|
|
48
|
+
break;
|
|
49
|
+
default: tokens += estimateStructuralBlock(block);
|
|
50
|
+
}
|
|
51
|
+
return tokens;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Price the rendered system prompt: the `system/message` surface node's text.
|
|
55
|
+
* Adapters serialize the prompt as a plain string — a system-role message or
|
|
56
|
+
* the request's system field — not as a typed content block, so the price is
|
|
57
|
+
* text density plus role framing with no per-block overhead.
|
|
58
|
+
* @param message - system-role message to price without mutation.
|
|
59
|
+
* @returns heuristic system-prompt tokens; 0 for empty content ("no system prompt").
|
|
60
|
+
*/
|
|
61
|
+
function estimateSystemMessage(message) {
|
|
62
|
+
if (message.content.length === 0) return 0;
|
|
63
|
+
let characters = 0;
|
|
64
|
+
for (const block of message.content) characters += block.type === "text" ? block.text.length : JSON.stringify(block).length;
|
|
65
|
+
return Math.ceil(characters / CHARS_PER_TOKEN) + 4;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Heuristically price one model-visible message.
|
|
69
|
+
* @param message - message to price without mutation.
|
|
70
|
+
* @returns content and role-framing tokens under the fixed heuristic; a
|
|
71
|
+
* system-role message prices as {@link estimateSystemMessage}.
|
|
72
|
+
*/
|
|
73
|
+
function estimateMessage(message) {
|
|
74
|
+
if (message.role === "system") return estimateSystemMessage(message);
|
|
75
|
+
return estimateContent(message.content) + 4;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Price the tool-schema part of a canonical request envelope — the envelope's
|
|
79
|
+
* only priced field, since the system prompt is a surface node.
|
|
80
|
+
* @param header - canonical envelope, or undefined before any request.
|
|
81
|
+
* @returns heuristic tool-schema tokens; 0 when absent or empty.
|
|
82
|
+
*/
|
|
83
|
+
function estimateToolsTokens(header) {
|
|
84
|
+
if (header?.tools === void 0 || header.tools.length === 0) return 0;
|
|
85
|
+
return Math.ceil(JSON.stringify(header.tools).length / CHARS_PER_TOKEN) + BLOCK_OVERHEAD;
|
|
86
|
+
}
|
|
87
|
+
//#endregion
|
|
88
|
+
//#region lib/types/breakdown-projection.js
|
|
89
|
+
/**
|
|
90
|
+
* Heuristic composition of the current retained surface, independent of route
|
|
91
|
+
* image pricing and provider usage. The state keeps the surviving system
|
|
92
|
+
* prompts in surface order and one running surface total; every other node is
|
|
93
|
+
* priced only as a delta, so state size follows the system prompts, not the
|
|
94
|
+
* message count.
|
|
95
|
+
*/
|
|
96
|
+
const tokenCount = z$1.number().int().nonnegative();
|
|
97
|
+
const sessionSeq = z$1.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).transform(SessionSeq);
|
|
98
|
+
const breakdownSchema = z$1.object({
|
|
99
|
+
systemTokens: tokenCount,
|
|
100
|
+
toolsTokens: tokenCount,
|
|
101
|
+
messageTokens: tokenCount
|
|
102
|
+
}).strict();
|
|
103
|
+
/** One surviving `system/message` node and its heuristic price. */
|
|
104
|
+
const systemNodeSchema = z$1.object({
|
|
105
|
+
seq: sessionSeq,
|
|
106
|
+
tokens: tokenCount
|
|
107
|
+
}).strict();
|
|
108
|
+
/**
|
|
109
|
+
* Shadow price armed by the `compaction/summary` or `compaction/prune` event
|
|
110
|
+
* immediately before a replacement: the replaced range, its heuristic price,
|
|
111
|
+
* and the surviving system prompts inside it.
|
|
112
|
+
*/
|
|
113
|
+
const claimSchema = z$1.object({
|
|
114
|
+
start: sessionSeq,
|
|
115
|
+
end: sessionSeq,
|
|
116
|
+
tokens: tokenCount,
|
|
117
|
+
systemSeqs: z$1.array(sessionSeq)
|
|
118
|
+
}).strict();
|
|
119
|
+
/** Plain-JSON checkpoint: surviving system prompts in surface order, the surface total, and an armed claim. */
|
|
120
|
+
const contextBreakdownStateSchema = z$1.object({
|
|
121
|
+
systems: z$1.array(systemNodeSchema),
|
|
122
|
+
surfaceTokens: tokenCount,
|
|
123
|
+
claim: claimSchema.optional(),
|
|
124
|
+
breakdown: breakdownSchema
|
|
125
|
+
}).strict();
|
|
126
|
+
/**
|
|
127
|
+
* Place one surface event's priced node.
|
|
128
|
+
* @param state - state before the event, without its armed claim.
|
|
129
|
+
* @param claim - shadow price armed by the immediately preceding event, if any.
|
|
130
|
+
* @param event - the surface event.
|
|
131
|
+
* @param tokens - the event message's heuristic price.
|
|
132
|
+
* @returns the system prompts and surface total after the event.
|
|
133
|
+
* @throws when a metered replacement names another range than its claim, or
|
|
134
|
+
* puts a system message in place of a metered range.
|
|
135
|
+
*/
|
|
136
|
+
function placeSurfaceEvent(state, claim, event, tokens) {
|
|
137
|
+
const op = event.surfaceOp;
|
|
138
|
+
const node = {
|
|
139
|
+
seq: event.seq,
|
|
140
|
+
tokens
|
|
141
|
+
};
|
|
142
|
+
const isSystem = event.type === "system/message";
|
|
143
|
+
if (op === "append") return {
|
|
144
|
+
systems: isSystem ? [...state.systems, node] : state.systems,
|
|
145
|
+
surfaceTokens: state.surfaceTokens + tokens
|
|
146
|
+
};
|
|
147
|
+
if (claim !== void 0) {
|
|
148
|
+
if (claim.start !== op.startSeq || claim.end !== op.endSeq) throw new Error(`context breakdown: replace at seq ${event.seq} over range ${op.startSeq}-${op.endSeq} has no adjacent shadow price (armed claim covers ${claim.start}-${claim.end})`);
|
|
149
|
+
if (isSystem) throw new Error(`context breakdown: replace at seq ${event.seq} puts a system message in place of a metered range; its order among the surviving system prompts is unknown`);
|
|
150
|
+
const shadowed = new Set(claim.systemSeqs);
|
|
151
|
+
return {
|
|
152
|
+
systems: state.systems.filter((system) => !shadowed.has(system.seq)),
|
|
153
|
+
surfaceTokens: state.surfaceTokens + tokens - claim.tokens
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
const index = op.startSeq === op.endSeq ? state.systems.findIndex((system) => system.seq === op.startSeq) : -1;
|
|
157
|
+
const replaced = state.systems[index];
|
|
158
|
+
if (replaced === void 0) return {
|
|
159
|
+
systems: state.systems,
|
|
160
|
+
surfaceTokens: state.surfaceTokens
|
|
161
|
+
};
|
|
162
|
+
return {
|
|
163
|
+
systems: isSystem ? state.systems.with(index, node) : state.systems.toSpliced(index, 1),
|
|
164
|
+
surfaceTokens: state.surfaceTokens + tokens - replaced.tokens
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
/** Publish totals, keeping the previous breakdown object when its figures are unchanged. */
|
|
168
|
+
function withTotals(state, totals) {
|
|
169
|
+
const surfaceTokens = Math.max(0, totals.surfaceTokens);
|
|
170
|
+
const systemTokens = totals.systems.findLast((system) => system.tokens > 0)?.tokens ?? 0;
|
|
171
|
+
const messageTokens = Math.max(0, surfaceTokens - systemTokens);
|
|
172
|
+
const breakdown = systemTokens === state.breakdown.systemTokens && messageTokens === state.breakdown.messageTokens ? state.breakdown : {
|
|
173
|
+
systemTokens,
|
|
174
|
+
toolsTokens: state.breakdown.toolsTokens,
|
|
175
|
+
messageTokens
|
|
176
|
+
};
|
|
177
|
+
return {
|
|
178
|
+
...state,
|
|
179
|
+
systems: totals.systems,
|
|
180
|
+
surfaceTokens,
|
|
181
|
+
breakdown
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
/** Drop an armed claim; the state is returned unchanged when none is armed. */
|
|
185
|
+
function withoutClaim(state) {
|
|
186
|
+
if (state.claim === void 0) return state;
|
|
187
|
+
const { claim: _expired, ...unclaimed } = state;
|
|
188
|
+
return unclaimed;
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Context composition with the last nonempty surviving system in surface
|
|
192
|
+
* order classified as system tokens; all other visible prices are messages.
|
|
193
|
+
* Appends add their price; a replacement subtracts the shadow price of the
|
|
194
|
+
* adjacent `compaction/summary` or `compaction/prune` event, whose
|
|
195
|
+
* `shadowedSeqs` also name the system prompts it removes, and a system-prompt
|
|
196
|
+
* rewrite subtracts the retained price of the system node it replaces. Tools
|
|
197
|
+
* are priced from the latest request header. No route pricing applies.
|
|
198
|
+
*/
|
|
199
|
+
const contextBreakdownProjectionDefinition = {
|
|
200
|
+
key: "contextBreakdown",
|
|
201
|
+
stateVersion: 6,
|
|
202
|
+
stateSchema: contextBreakdownStateSchema,
|
|
203
|
+
init: () => ({
|
|
204
|
+
systems: [],
|
|
205
|
+
surfaceTokens: 0,
|
|
206
|
+
breakdown: {
|
|
207
|
+
systemTokens: 0,
|
|
208
|
+
toolsTokens: 0,
|
|
209
|
+
messageTokens: 0
|
|
210
|
+
}
|
|
211
|
+
}),
|
|
212
|
+
apply: (state, event) => {
|
|
213
|
+
if (event.type === "compaction/summary" || event.type === "compaction/prune") {
|
|
214
|
+
const shadowed = new Set(event.data.shadowedSeqs);
|
|
215
|
+
return {
|
|
216
|
+
...state,
|
|
217
|
+
claim: {
|
|
218
|
+
start: SessionSeq(event.data.shadowedRange.start),
|
|
219
|
+
end: SessionSeq(event.data.shadowedRange.end),
|
|
220
|
+
tokens: event.data.shadowedTokenCount,
|
|
221
|
+
systemSeqs: state.systems.filter((system) => shadowed.has(system.seq)).map((system) => system.seq)
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
const unclaimed = withoutClaim(state);
|
|
226
|
+
if (event.type === "request/header") {
|
|
227
|
+
const toolsTokens = estimateToolsTokens(canonicalHeader(event.data.header));
|
|
228
|
+
return toolsTokens === unclaimed.breakdown.toolsTokens ? unclaimed : {
|
|
229
|
+
...unclaimed,
|
|
230
|
+
breakdown: {
|
|
231
|
+
...unclaimed.breakdown,
|
|
232
|
+
toolsTokens
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
if (!isSurfaceEvent(event)) return unclaimed;
|
|
237
|
+
const message = deriveEventMessage(event);
|
|
238
|
+
const tokens = message === null ? 0 : estimateMessage(message);
|
|
239
|
+
return withTotals(unclaimed, placeSurfaceEvent(unclaimed, state.claim, event, tokens));
|
|
240
|
+
},
|
|
241
|
+
wire: {
|
|
242
|
+
viewSchema: breakdownSchema,
|
|
243
|
+
view: (state) => state.breakdown,
|
|
244
|
+
summary: false
|
|
245
|
+
}
|
|
246
|
+
};
|
|
247
|
+
//#endregion
|
|
248
|
+
//#region lib/types/surface-projection.js
|
|
249
|
+
/**
|
|
250
|
+
* The context-pressure projection's O(1) surface-token fold.
|
|
251
|
+
*
|
|
252
|
+
* Its checkpoint keeps scalar totals rather than the retained surface used
|
|
253
|
+
* by measurement. Replacements ride the compact
|
|
254
|
+
* seam's shadow-price protocol: the metering event immediately before a
|
|
255
|
+
* surface `replace` (`compaction/summary` or `compaction/prune`) states the
|
|
256
|
+
* heuristic price of the exact replaced range, so the fold keeps a running
|
|
257
|
+
* total plus at most one pending claim and never retains per-node prices.
|
|
258
|
+
* The counts are exact by construction: producers derive them from the same
|
|
259
|
+
* fixed estimator this module prices appends with. A replacement without an
|
|
260
|
+
* armed claim folds with zero delta because bounded state cannot reconstruct
|
|
261
|
+
* the replaced range; this preserves replay at the cost of possible drift.
|
|
262
|
+
*
|
|
263
|
+
* @module @open33/harness-token-meter/surface-projection
|
|
264
|
+
*/
|
|
265
|
+
/**
|
|
266
|
+
* Fold one committed event onto a running surface-token total.
|
|
267
|
+
*
|
|
268
|
+
* A shadow-price event arms a claim; any other event expires it, and a
|
|
269
|
+
* surface `replace` consumes the claim naming its exact range — the
|
|
270
|
+
* producers append the metering event and the replacement synchronously
|
|
271
|
+
* adjacent, so a surviving claim always prices the very next event.
|
|
272
|
+
* A replace with no claim folds with zero delta because the bounded state
|
|
273
|
+
* cannot reconstruct the replaced range. An armed claim for another range
|
|
274
|
+
* still fails because the adjacent events contradict each other.
|
|
275
|
+
* @param claim - the claim armed by the immediately preceding event, if any.
|
|
276
|
+
* @param event - the next committed session event.
|
|
277
|
+
* @returns the signed token delta and the claim state after this event.
|
|
278
|
+
* @throws when a replacement arrives with an armed claim for a different
|
|
279
|
+
* range — the metering event was adjacent, so this is a live producer's
|
|
280
|
+
* shadow-price contract violation, not historical data, and must fail
|
|
281
|
+
* loud rather than let the total drift.
|
|
282
|
+
*/
|
|
283
|
+
function foldSurfaceProjection(claim, event) {
|
|
284
|
+
if (event.type === "compaction/summary" || event.type === "compaction/prune") {
|
|
285
|
+
const { shadowedRange, shadowedTokenCount } = event.data;
|
|
286
|
+
return {
|
|
287
|
+
deltaTokens: 0,
|
|
288
|
+
claim: {
|
|
289
|
+
start: SessionSeq(shadowedRange.start),
|
|
290
|
+
end: SessionSeq(shadowedRange.end),
|
|
291
|
+
tokens: shadowedTokenCount
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
if (!isSurfaceEvent(event)) return {
|
|
296
|
+
deltaTokens: 0,
|
|
297
|
+
claim: void 0
|
|
298
|
+
};
|
|
299
|
+
const message = deriveEventMessage(event);
|
|
300
|
+
const tokens = message === null ? 0 : estimateMessage(message);
|
|
301
|
+
const op = event.surfaceOp;
|
|
302
|
+
if (op === "append") return {
|
|
303
|
+
deltaTokens: tokens,
|
|
304
|
+
claim: void 0
|
|
305
|
+
};
|
|
306
|
+
if (claim === void 0) return {
|
|
307
|
+
deltaTokens: 0,
|
|
308
|
+
claim: void 0
|
|
309
|
+
};
|
|
310
|
+
if (claim.start !== op.startSeq || claim.end !== op.endSeq) throw new Error(`token surface: replace at seq ${event.seq} over range ${op.startSeq}-${op.endSeq} has no adjacent shadow price (armed claim covers ${claim.start}-${claim.end})`);
|
|
311
|
+
return {
|
|
312
|
+
deltaTokens: tokens - claim.tokens,
|
|
313
|
+
claim: void 0
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
//#endregion
|
|
317
|
+
//#region lib/types/usage-projection.js
|
|
318
|
+
/**
|
|
319
|
+
* Pure folds for durable provider-reported token usage and context occupancy.
|
|
320
|
+
*/
|
|
321
|
+
const zeroBuckets = () => ({
|
|
322
|
+
uncachedInputTokens: 0,
|
|
323
|
+
outputTokens: 0,
|
|
324
|
+
cacheReadTokens: 0,
|
|
325
|
+
cacheWriteTokens: 0
|
|
326
|
+
});
|
|
327
|
+
const bucketsFrom = (usage) => ({
|
|
328
|
+
uncachedInputTokens: usage.inputTokens,
|
|
329
|
+
outputTokens: usage.outputTokens,
|
|
330
|
+
cacheReadTokens: usage.cacheReadTokens ?? 0,
|
|
331
|
+
cacheWriteTokens: usage.cacheWriteTokens ?? 0
|
|
332
|
+
});
|
|
333
|
+
const bucketsEqual = (left, right) => left.uncachedInputTokens === right.uncachedInputTokens && left.outputTokens === right.outputTokens && left.cacheReadTokens === right.cacheReadTokens && left.cacheWriteTokens === right.cacheWriteTokens;
|
|
334
|
+
const addReplacing = (totals, previous, next) => ({
|
|
335
|
+
uncachedInputTokens: totals.uncachedInputTokens - (previous?.uncachedInputTokens ?? 0) + next.uncachedInputTokens,
|
|
336
|
+
outputTokens: totals.outputTokens - (previous?.outputTokens ?? 0) + next.outputTokens,
|
|
337
|
+
cacheReadTokens: totals.cacheReadTokens - (previous?.cacheReadTokens ?? 0) + next.cacheReadTokens,
|
|
338
|
+
cacheWriteTokens: totals.cacheWriteTokens - (previous?.cacheWriteTokens ?? 0) + next.cacheWriteTokens
|
|
339
|
+
});
|
|
340
|
+
const projectionSchema = z$1.object({
|
|
341
|
+
uncachedInputTokens: z$1.number().int().nonnegative(),
|
|
342
|
+
outputTokens: z$1.number().int().nonnegative(),
|
|
343
|
+
cacheReadTokens: z$1.number().int().nonnegative(),
|
|
344
|
+
cacheWriteTokens: z$1.number().int().nonnegative()
|
|
345
|
+
}).strict();
|
|
346
|
+
/**
|
|
347
|
+
* The token-usage unit's state schema — the one definition of the state
|
|
348
|
+
* shape; the state type is inferred from it.
|
|
349
|
+
*/
|
|
350
|
+
const tokenUsageStateSchema = z$1.object({
|
|
351
|
+
totals: projectionSchema,
|
|
352
|
+
last: z$1.object({
|
|
353
|
+
turn: z$1.number().int().nonnegative(),
|
|
354
|
+
step: z$1.number().int().nonnegative(),
|
|
355
|
+
buckets: projectionSchema
|
|
356
|
+
}).nullable()
|
|
357
|
+
}).strict();
|
|
358
|
+
const pressureSchema = z$1.object({
|
|
359
|
+
pressureTokens: z$1.number().int().nonnegative().optional(),
|
|
360
|
+
projectedTokens: z$1.number().int().nonnegative().optional(),
|
|
361
|
+
contextWindow: z$1.number().int().positive().optional()
|
|
362
|
+
}).strict().transform(({ pressureTokens, projectedTokens, contextWindow }) => ({
|
|
363
|
+
...pressureTokens === void 0 ? {} : { pressureTokens },
|
|
364
|
+
...projectedTokens === void 0 ? {} : { projectedTokens },
|
|
365
|
+
...contextWindow === void 0 ? {} : { contextWindow }
|
|
366
|
+
}));
|
|
367
|
+
/** Prompt-side pressure of one request: input plus cache traffic, no output. */
|
|
368
|
+
const pressureFrom = (usage) => usage.inputTokens + (usage.cacheReadTokens ?? 0) + (usage.cacheWriteTokens ?? 0);
|
|
369
|
+
/** The usage one durable Assistant settlement reports for its attempt, if any. */
|
|
370
|
+
function usageOf(event) {
|
|
371
|
+
if (event.type === "assistant/message" && event.data.usage !== void 0) return event.data.usage;
|
|
372
|
+
if (event.type !== "assistant/message" && event.type !== "assistant/attempt") return void 0;
|
|
373
|
+
return lastAssistantStreamChunk(event.data.stream, "usage")?.usage;
|
|
374
|
+
}
|
|
375
|
+
/** The context-pressure state schema and source of its inferred type. */
|
|
376
|
+
const contextPressureStateSchema = z$1.object({
|
|
377
|
+
contextWindow: z$1.number().int().positive().optional(),
|
|
378
|
+
pressureTokens: z$1.number().int().nonnegative().optional(),
|
|
379
|
+
surfaceTokens: z$1.number().int().nonnegative(),
|
|
380
|
+
sampledSurfaceTokens: z$1.number().int().nonnegative().optional(),
|
|
381
|
+
claim: z$1.object({
|
|
382
|
+
start: z$1.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).transform(SessionSeq),
|
|
383
|
+
end: z$1.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).transform(SessionSeq),
|
|
384
|
+
tokens: z$1.number().int().nonnegative()
|
|
385
|
+
}).optional()
|
|
386
|
+
}).strict();
|
|
387
|
+
/**
|
|
388
|
+
* Token-meter's session projection unit.
|
|
389
|
+
*
|
|
390
|
+
* Each v2 Assistant settlement contributes the last usage sample embedded in
|
|
391
|
+
* its stream. `llm/retry-started` closes the replacement slot so the retried
|
|
392
|
+
* attempt adds to the total.
|
|
393
|
+
*/
|
|
394
|
+
const tokenUsageProjectionDefinition = {
|
|
395
|
+
key: "tokenUsage",
|
|
396
|
+
stateVersion: 2,
|
|
397
|
+
stateSchema: tokenUsageStateSchema,
|
|
398
|
+
init: () => ({
|
|
399
|
+
totals: zeroBuckets(),
|
|
400
|
+
last: null
|
|
401
|
+
}),
|
|
402
|
+
apply: (state, event) => {
|
|
403
|
+
if (event.type === "llm/retry-started") return state.last?.turn === event.data.turn && state.last.step === event.data.step ? {
|
|
404
|
+
...state,
|
|
405
|
+
last: null
|
|
406
|
+
} : state;
|
|
407
|
+
if (event.type !== "assistant/message" && event.type !== "assistant/attempt") return state;
|
|
408
|
+
const sample = usageOf(event);
|
|
409
|
+
if (sample === void 0) return state;
|
|
410
|
+
const { turn, step } = event.data;
|
|
411
|
+
const buckets = bucketsFrom(sample);
|
|
412
|
+
const previous = state.last !== null && state.last.turn === turn && state.last.step === step ? state.last.buckets : void 0;
|
|
413
|
+
if (previous !== void 0 && bucketsEqual(previous, buckets)) return state;
|
|
414
|
+
return {
|
|
415
|
+
totals: addReplacing(state.totals, previous, buckets),
|
|
416
|
+
last: {
|
|
417
|
+
turn,
|
|
418
|
+
step,
|
|
419
|
+
buckets
|
|
420
|
+
}
|
|
421
|
+
};
|
|
422
|
+
},
|
|
423
|
+
wire: {
|
|
424
|
+
viewSchema: projectionSchema,
|
|
425
|
+
view: (state) => state.totals
|
|
426
|
+
}
|
|
427
|
+
};
|
|
428
|
+
/**
|
|
429
|
+
* Token-meter's context-occupancy projection unit.
|
|
430
|
+
*
|
|
431
|
+
* Independent last-wins slots: the newest usage sample supplies the provider
|
|
432
|
+
* numerator, the newest `request/context` record the denominator. Both are
|
|
433
|
+
* whole values, so replay order alone decides the result and no cross-field
|
|
434
|
+
* consistency is claimed — the pair is explicitly not one atomic request
|
|
435
|
+
* observation (see {@link ContextPressureProjection}).
|
|
436
|
+
*
|
|
437
|
+
* `pressureTokens` is prompt-side only, so it holds still while a turn streams
|
|
438
|
+
* and steps forward once the next request reports its usage. Because nothing
|
|
439
|
+
* but a request reports usage, it also cannot see a compaction: the fold
|
|
440
|
+
* therefore carries a running surface total alongside it and publishes
|
|
441
|
+
* `projectedTokens` — the sample plus the surface's signed movement since it
|
|
442
|
+
* was taken — so occupancy answers for the next request rather than the last
|
|
443
|
+
* one. The total rides {@link foldSurfaceProjection}, so the state stays O(1)
|
|
444
|
+
* and a replacement shrinks it by its logged shadow price. A replacement
|
|
445
|
+
* without a claim preserves the previous total. A usage sample is stamped
|
|
446
|
+
* BEFORE the same event joins the surface, so an `assistant/message` anchors
|
|
447
|
+
* against the surface its own request saw.
|
|
448
|
+
*/
|
|
449
|
+
const contextPressureProjectionDefinition = {
|
|
450
|
+
key: "contextPressure",
|
|
451
|
+
stateVersion: 5,
|
|
452
|
+
stateSchema: contextPressureStateSchema,
|
|
453
|
+
init: () => ({ surfaceTokens: 0 }),
|
|
454
|
+
apply: (state, event) => {
|
|
455
|
+
const fold = foldSurfaceProjection(state.claim, event);
|
|
456
|
+
let next = state;
|
|
457
|
+
if (event.type === "request/context") {
|
|
458
|
+
const contextWindow = event.data.contextWindow;
|
|
459
|
+
if (contextWindow !== state.contextWindow) if (contextWindow !== void 0) next = {
|
|
460
|
+
...next,
|
|
461
|
+
contextWindow
|
|
462
|
+
};
|
|
463
|
+
else {
|
|
464
|
+
const { contextWindow: _removed, ...withoutContextWindow } = next;
|
|
465
|
+
next = withoutContextWindow;
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
const usage = usageOf(event);
|
|
469
|
+
if (usage !== void 0) {
|
|
470
|
+
const pressureTokens = pressureFrom(usage);
|
|
471
|
+
if (pressureTokens !== next.pressureTokens || next.sampledSurfaceTokens !== next.surfaceTokens) next = {
|
|
472
|
+
...next,
|
|
473
|
+
pressureTokens,
|
|
474
|
+
sampledSurfaceTokens: next.surfaceTokens
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
if (fold.deltaTokens !== 0) next = {
|
|
478
|
+
...next,
|
|
479
|
+
surfaceTokens: next.surfaceTokens + fold.deltaTokens
|
|
480
|
+
};
|
|
481
|
+
if (state.claim === void 0 && fold.claim === void 0) return next;
|
|
482
|
+
const { claim: _expired, ...withoutClaim } = next;
|
|
483
|
+
return fold.claim === void 0 ? withoutClaim : {
|
|
484
|
+
...withoutClaim,
|
|
485
|
+
claim: fold.claim
|
|
486
|
+
};
|
|
487
|
+
},
|
|
488
|
+
wire: {
|
|
489
|
+
viewSchema: pressureSchema,
|
|
490
|
+
view: ({ contextWindow, pressureTokens, surfaceTokens, sampledSurfaceTokens }) => ({
|
|
491
|
+
...contextWindow === void 0 ? {} : { contextWindow },
|
|
492
|
+
...pressureTokens === void 0 ? {} : { pressureTokens },
|
|
493
|
+
...pressureTokens === void 0 || sampledSurfaceTokens === void 0 ? {} : { projectedTokens: Math.max(0, pressureTokens + surfaceTokens - sampledSurfaceTokens) }
|
|
494
|
+
}),
|
|
495
|
+
summary: false
|
|
496
|
+
}
|
|
497
|
+
};
|
|
498
|
+
//#endregion
|
|
499
|
+
//#region lib/types/measurement-projection.js
|
|
500
|
+
/** Fixed-size recovery facts; positional attachment prices remain a rebuildable cache. */
|
|
501
|
+
const seqSchema = z$1.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).transform(SessionSeq);
|
|
502
|
+
const countSchema = z$1.number();
|
|
503
|
+
const usageFields = z$1.looseObject({
|
|
504
|
+
inputTokens: countSchema,
|
|
505
|
+
outputTokens: countSchema,
|
|
506
|
+
totalTokens: countSchema.optional(),
|
|
507
|
+
cacheReadTokens: countSchema.optional(),
|
|
508
|
+
cacheWriteTokens: countSchema.optional(),
|
|
509
|
+
reasoningTokens: countSchema.optional()
|
|
510
|
+
});
|
|
511
|
+
const usageSchema = z$1.custom((value) => usageFields.safeParse(value).success);
|
|
512
|
+
const measurementStateSchema = z$1.object({
|
|
513
|
+
headerSeq: seqSchema.nullable(),
|
|
514
|
+
stepStart: z$1.object({
|
|
515
|
+
turn: z$1.number(),
|
|
516
|
+
step: z$1.number()
|
|
517
|
+
}).strict().nullable(),
|
|
518
|
+
anchor: z$1.object({
|
|
519
|
+
headerSeq: seqSchema.nullable(),
|
|
520
|
+
assistantTokens: countSchema,
|
|
521
|
+
usage: usageSchema.nullable()
|
|
522
|
+
}).strict().nullable(),
|
|
523
|
+
invalidSeq: seqSchema.nullable()
|
|
524
|
+
}).strict();
|
|
525
|
+
/**
|
|
526
|
+
* Advance one measurement prefix without mutating its previous state.
|
|
527
|
+
* @param state - measurement facts before the candidate event.
|
|
528
|
+
* @param event - next committed journal event.
|
|
529
|
+
* @returns updated measurement facts.
|
|
530
|
+
* @throws the original measurement error for invalid boundaries or payloads.
|
|
531
|
+
*/
|
|
532
|
+
function advanceMeasurement(state, event) {
|
|
533
|
+
switch (event.type) {
|
|
534
|
+
case "request/header":
|
|
535
|
+
canonicalHeader(event.data.header);
|
|
536
|
+
return {
|
|
537
|
+
...state,
|
|
538
|
+
headerSeq: event.seq
|
|
539
|
+
};
|
|
540
|
+
case "step/start":
|
|
541
|
+
if (state.stepStart !== null) throw new Error(`token meter: step/start at seq ${event.seq} arrived before turn ${state.stepStart.turn}/step ${state.stepStart.step} ended`);
|
|
542
|
+
return {
|
|
543
|
+
...state,
|
|
544
|
+
stepStart: {
|
|
545
|
+
turn: event.data.turn,
|
|
546
|
+
step: event.data.step
|
|
547
|
+
}
|
|
548
|
+
};
|
|
549
|
+
case "step/end":
|
|
550
|
+
if (state.stepStart === null || state.stepStart.turn !== event.data.turn || state.stepStart.step !== event.data.step) throw new Error(`token meter: step/end at seq ${event.seq} has no matching step/start event`);
|
|
551
|
+
return {
|
|
552
|
+
...state,
|
|
553
|
+
stepStart: null
|
|
554
|
+
};
|
|
555
|
+
case "assistant/message": {
|
|
556
|
+
if (state.stepStart === null || state.stepStart.turn !== event.data.turn || state.stepStart.step !== event.data.step) throw new Error(`token meter: assistant/message at seq ${event.seq} has no matching step/start event`);
|
|
557
|
+
let assistantTokens;
|
|
558
|
+
let usage = null;
|
|
559
|
+
if (event.data.usage !== void 0 && state.headerSeq !== null) {
|
|
560
|
+
const content = assembleAssistantStream(event.data.stream).blocks();
|
|
561
|
+
assistantTokens = content.length === 0 ? 0 : estimateContent(content) + 4;
|
|
562
|
+
usage = event.data.usage;
|
|
563
|
+
} else {
|
|
564
|
+
const message = deriveEventMessage(event);
|
|
565
|
+
assistantTokens = message === null ? 0 : estimateMessage(message);
|
|
566
|
+
}
|
|
567
|
+
return {
|
|
568
|
+
...state,
|
|
569
|
+
anchor: {
|
|
570
|
+
headerSeq: state.headerSeq,
|
|
571
|
+
assistantTokens,
|
|
572
|
+
usage
|
|
573
|
+
}
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
default: return state;
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
/** Host-only measurement facts, independent of session and surface length. */
|
|
580
|
+
const measurementProjectionDefinition = {
|
|
581
|
+
key: "tokenMeasurement",
|
|
582
|
+
stateVersion: 2,
|
|
583
|
+
stateSchema: measurementStateSchema,
|
|
584
|
+
init: () => ({
|
|
585
|
+
headerSeq: null,
|
|
586
|
+
stepStart: null,
|
|
587
|
+
anchor: null,
|
|
588
|
+
invalidSeq: null
|
|
589
|
+
}),
|
|
590
|
+
apply: (state, event) => {
|
|
591
|
+
if (state.invalidSeq !== null) return state;
|
|
592
|
+
try {
|
|
593
|
+
return advanceMeasurement(state, event);
|
|
594
|
+
} catch (_error) {
|
|
595
|
+
return {
|
|
596
|
+
...state,
|
|
597
|
+
invalidSeq: event.seq
|
|
598
|
+
};
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
};
|
|
602
|
+
//#endregion
|
|
603
|
+
//#region lib/types/surface-fold.js
|
|
604
|
+
/**
|
|
605
|
+
* Positional pricing for measurement: each retained node keeps its identity,
|
|
606
|
+
* heuristic price, and the attachment details route pricing replaces. The
|
|
607
|
+
* occupancy and context-breakdown projections use the scalar shadow-price
|
|
608
|
+
* protocol instead.
|
|
609
|
+
*
|
|
610
|
+
* The fold is a plan/commit pair: {@link planSurfaceTokens} runs every
|
|
611
|
+
* fallible step read-only and {@link commitSurfaceTokens} mutates in place,
|
|
612
|
+
* so a throw leaves the caller's state untouched and the same malformed
|
|
613
|
+
* event fails identically on every retry.
|
|
614
|
+
* Nodes also carry durable attachment occurrences and their structural prices,
|
|
615
|
+
* so `measure()` can price the request representation sent to the model.
|
|
616
|
+
*
|
|
617
|
+
* @module @open33/harness-token-meter/surface-fold
|
|
618
|
+
*/
|
|
619
|
+
/** Collect projected attachment occurrences and their structural prices. */
|
|
620
|
+
function collectProjectedAttachments(blocks, images, files) {
|
|
621
|
+
let imageTokens = 0;
|
|
622
|
+
let fileTokens = 0;
|
|
623
|
+
for (const block of blocks) if (block.type === "image") {
|
|
624
|
+
images.push(block);
|
|
625
|
+
imageTokens += estimateStructuralBlock(block);
|
|
626
|
+
} else if (block.type === "file") {
|
|
627
|
+
files.push(block.attachment);
|
|
628
|
+
fileTokens += estimateStructuralBlock(block);
|
|
629
|
+
}
|
|
630
|
+
return {
|
|
631
|
+
imageTokens,
|
|
632
|
+
fileTokens
|
|
633
|
+
};
|
|
634
|
+
}
|
|
635
|
+
/** Build one priced node from a surface event's derived message. */
|
|
636
|
+
function analyzeNode(seq, message) {
|
|
637
|
+
if (message === null) return {
|
|
638
|
+
seq,
|
|
639
|
+
heuristicTokens: 0,
|
|
640
|
+
imageStructuralTokens: 0,
|
|
641
|
+
fileStructuralTokens: 0,
|
|
642
|
+
images: [],
|
|
643
|
+
files: []
|
|
644
|
+
};
|
|
645
|
+
const heuristicTokens = estimateMessage(message);
|
|
646
|
+
const images = [];
|
|
647
|
+
const files = [];
|
|
648
|
+
const structural = collectProjectedAttachments(message.content, images, files);
|
|
649
|
+
return {
|
|
650
|
+
seq,
|
|
651
|
+
heuristicTokens,
|
|
652
|
+
imageStructuralTokens: structural.imageTokens,
|
|
653
|
+
fileStructuralTokens: structural.fileTokens,
|
|
654
|
+
images,
|
|
655
|
+
files
|
|
656
|
+
};
|
|
657
|
+
}
|
|
658
|
+
/**
|
|
659
|
+
* Validate and price one surface event without mutating the surface.
|
|
660
|
+
* @param nodes - the priced surface preceding this event, in model-visible order.
|
|
661
|
+
* @param event - the surface event to place.
|
|
662
|
+
* @returns the plan for {@link commitSurfaceTokens}.
|
|
663
|
+
* @throws when a replacement names a range absent from `nodes` — committed
|
|
664
|
+
* logs are surface-validated at append time, so an unresolvable range is log
|
|
665
|
+
* corruption and must fail loud rather than skip the event.
|
|
666
|
+
*/
|
|
667
|
+
function planSurfaceTokens(nodes, event) {
|
|
668
|
+
const node = analyzeNode(event.seq, deriveEventMessage(event));
|
|
669
|
+
const tokens = node.heuristicTokens;
|
|
670
|
+
const op = event.surfaceOp;
|
|
671
|
+
if (op === "append") return {
|
|
672
|
+
tokens,
|
|
673
|
+
deltaTokens: tokens,
|
|
674
|
+
node,
|
|
675
|
+
target: "append"
|
|
676
|
+
};
|
|
677
|
+
const startIdx = nodes.findIndex((candidate) => candidate.seq === op.startSeq);
|
|
678
|
+
const endIdx = nodes.findIndex((candidate) => candidate.seq === op.endSeq);
|
|
679
|
+
if (startIdx === -1 || endIdx === -1 || startIdx > endIdx) throw new Error(`token surface: replace at seq ${event.seq} has invalid current range ${op.startSeq}-${op.endSeq}`);
|
|
680
|
+
return {
|
|
681
|
+
tokens,
|
|
682
|
+
deltaTokens: tokens - nodes.slice(startIdx, endIdx + 1).reduce((total, candidate) => total + candidate.heuristicTokens, 0),
|
|
683
|
+
node,
|
|
684
|
+
target: {
|
|
685
|
+
startIdx,
|
|
686
|
+
endIdx
|
|
687
|
+
}
|
|
688
|
+
};
|
|
689
|
+
}
|
|
690
|
+
/**
|
|
691
|
+
* Apply one validated plan to the priced surface in place; infallible, so it
|
|
692
|
+
* cannot leave a half-applied surface behind.
|
|
693
|
+
* @param nodes - the exact priced surface the plan was built against.
|
|
694
|
+
* @param plan - the transition returned by {@link planSurfaceTokens}.
|
|
695
|
+
*/
|
|
696
|
+
function commitSurfaceTokens(nodes, plan) {
|
|
697
|
+
if (plan.target === "append") {
|
|
698
|
+
nodes.push(plan.node);
|
|
699
|
+
return;
|
|
700
|
+
}
|
|
701
|
+
nodes.splice(plan.target.startIdx, plan.target.endIdx - plan.target.startIdx + 1, plan.node);
|
|
702
|
+
}
|
|
703
|
+
//#endregion
|
|
704
|
+
//#region lib/types/route-pricing.js
|
|
705
|
+
/**
|
|
706
|
+
* Request-projected surface pricing: replaces attachment-block heuristics with
|
|
707
|
+
* the image and file representations sent to the routed model.
|
|
708
|
+
*
|
|
709
|
+
* @module @open33/harness-token-meter/route-pricing
|
|
710
|
+
*/
|
|
711
|
+
/**
|
|
712
|
+
* Price one ordered surface under its model-request attachment projection.
|
|
713
|
+
* @param nodes - the fold's current or snapshotted surface, in model-visible order.
|
|
714
|
+
* @param pricing - the routed model's image pricing, or undefined to keep the fixed heuristic.
|
|
715
|
+
* @param fileText - exact file handle projection used by the mounted LLM service.
|
|
716
|
+
* @returns detached public nodes and their route-priced total.
|
|
717
|
+
* @throws when the pricing answers a different occurrence count than it was
|
|
718
|
+
* asked — misalignment would silently misprice nodes, so it must fail loud.
|
|
719
|
+
*/
|
|
720
|
+
function priceSurface(nodes, pricing, fileText) {
|
|
721
|
+
const images = pricing === void 0 ? [] : nodes.flatMap((node) => node.images);
|
|
722
|
+
const hasFiles = fileText !== void 0 && nodes.some((node) => node.files.length > 0);
|
|
723
|
+
if ((pricing === void 0 || images.length === 0) && !hasFiles) {
|
|
724
|
+
let surfaceTokens = 0;
|
|
725
|
+
return {
|
|
726
|
+
nodes: nodes.map((node) => {
|
|
727
|
+
surfaceTokens += node.heuristicTokens;
|
|
728
|
+
return {
|
|
729
|
+
seq: node.seq,
|
|
730
|
+
tokens: node.heuristicTokens,
|
|
731
|
+
heuristicTokens: node.heuristicTokens
|
|
732
|
+
};
|
|
733
|
+
}),
|
|
734
|
+
surfaceTokens
|
|
735
|
+
};
|
|
736
|
+
}
|
|
737
|
+
const prices = pricing === void 0 ? [] : pricing.priceImages(images);
|
|
738
|
+
if (pricing !== void 0 && prices.length !== images.length) throw new Error(`token meter: route image pricing answered ${prices.length} prices for ${images.length} occurrences`);
|
|
739
|
+
let cursor = 0;
|
|
740
|
+
let surfaceTokens = 0;
|
|
741
|
+
return {
|
|
742
|
+
nodes: nodes.map((node) => {
|
|
743
|
+
let tokens = node.heuristicTokens;
|
|
744
|
+
if (fileText !== void 0 && node.files.length > 0) {
|
|
745
|
+
tokens -= node.fileStructuralTokens;
|
|
746
|
+
for (const file of node.files) tokens += estimateContent([{
|
|
747
|
+
type: "text",
|
|
748
|
+
text: fileText(file)
|
|
749
|
+
}]);
|
|
750
|
+
}
|
|
751
|
+
if (pricing !== void 0 && node.images.length > 0) {
|
|
752
|
+
tokens -= node.imageStructuralTokens;
|
|
753
|
+
for (let occurrence = 0; occurrence < node.images.length; occurrence += 1) {
|
|
754
|
+
const price = prices[cursor];
|
|
755
|
+
cursor += 1;
|
|
756
|
+
tokens += price.visualTokens + estimateContent([{
|
|
757
|
+
type: "text",
|
|
758
|
+
text: price.text
|
|
759
|
+
}]);
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
surfaceTokens += tokens;
|
|
763
|
+
return {
|
|
764
|
+
seq: node.seq,
|
|
765
|
+
tokens,
|
|
766
|
+
heuristicTokens: node.heuristicTokens
|
|
767
|
+
};
|
|
768
|
+
}),
|
|
769
|
+
surfaceTokens
|
|
770
|
+
};
|
|
771
|
+
}
|
|
772
|
+
//#endregion
|
|
773
|
+
//#region lib/types/index.js
|
|
774
|
+
/**
|
|
775
|
+
* Single replay-aware token-meter service for request and surface pressure.
|
|
776
|
+
*
|
|
777
|
+
* @module @open33/harness-token-meter
|
|
778
|
+
*/
|
|
779
|
+
/** Sum disjoint provider usage buckets without double-counting reasoning output. */
|
|
780
|
+
function usageTokens(usage) {
|
|
781
|
+
return usage.inputTokens + (usage.cacheReadTokens ?? 0) + (usage.cacheWriteTokens ?? 0) + usage.outputTokens;
|
|
782
|
+
}
|
|
783
|
+
/** Compare optional envelopes so a headerless estimate can track later surface deltas. */
|
|
784
|
+
function optionalHeaderEquals(left, right) {
|
|
785
|
+
if (left === void 0 || right === void 0) return left === right;
|
|
786
|
+
return headerEquals(left, right);
|
|
787
|
+
}
|
|
788
|
+
/** Reject stale or misspelled keys before defaults can hide them. */
|
|
789
|
+
function validateConfigKeys(config) {
|
|
790
|
+
for (const key of Object.keys(config)) throw new Error(`TokenMeterConfig: unknown key "${key}" (no settings are supported)`);
|
|
791
|
+
}
|
|
792
|
+
/** Replay owner for one service-wide estimator and isolated per-session folds. */
|
|
793
|
+
var TokenMeter = class extends Service {
|
|
794
|
+
static Config = z.object({});
|
|
795
|
+
static inject = ["sessionProjections"];
|
|
796
|
+
states = /* @__PURE__ */ new WeakMap();
|
|
797
|
+
measurementProjectionHandle;
|
|
798
|
+
contextPressureProjectionHandle;
|
|
799
|
+
constructor(ctx, config = {}) {
|
|
800
|
+
super(ctx, "tokenMeter");
|
|
801
|
+
validateConfigKeys(config);
|
|
802
|
+
}
|
|
803
|
+
async [Service.init]() {
|
|
804
|
+
const ctx = this.ctx;
|
|
805
|
+
this.measurementProjectionHandle = await ctx.sessionProjections.register(measurementProjectionDefinition);
|
|
806
|
+
await ctx.sessionProjections.register(tokenUsageProjectionDefinition);
|
|
807
|
+
this.contextPressureProjectionHandle = await ctx.sessionProjections.register(contextPressureProjectionDefinition);
|
|
808
|
+
await ctx.sessionProjections.register(contextBreakdownProjectionDefinition);
|
|
809
|
+
ctx.on("session/event", (session) => {
|
|
810
|
+
if (this.states.has(session)) this._sync(session);
|
|
811
|
+
});
|
|
812
|
+
}
|
|
813
|
+
/**
|
|
814
|
+
* Read the latest logged provider prompt size and route capacity.
|
|
815
|
+
* @param session - Session whose committed usage and request capacity are read.
|
|
816
|
+
* @returns context pressure; fields remain absent until their source events are recorded.
|
|
817
|
+
*/
|
|
818
|
+
contextPressure(session) {
|
|
819
|
+
const { pressureTokens, contextWindow } = this.contextPressureProjectionHandle.stateOf(session);
|
|
820
|
+
return {
|
|
821
|
+
...pressureTokens === void 0 ? {} : { pressureTokens },
|
|
822
|
+
...contextWindow === void 0 ? {} : { contextWindow }
|
|
823
|
+
};
|
|
824
|
+
}
|
|
825
|
+
/**
|
|
826
|
+
* Measure current request pressure and surface through the durable tail.
|
|
827
|
+
*
|
|
828
|
+
* The effective envelope's routed provider/model selects the request-image
|
|
829
|
+
* pricing every node is priced under: a route whose adapter declares image
|
|
830
|
+
* pricing charges each retained image its visual tokens plus its
|
|
831
|
+
* model-visible text, while other routes keep the fixed heuristic. Provider
|
|
832
|
+
* usage is reused only when the latest successful call's canonical request
|
|
833
|
+
* envelope matches `requestHeader` and its total is no lower than that
|
|
834
|
+
* call's full route-priced anchor; otherwise the complete envelope and
|
|
835
|
+
* surface are repriced. The anchor includes all surface nodes immediately
|
|
836
|
+
* before the assistant message, including inputs admitted after step/start.
|
|
837
|
+
*
|
|
838
|
+
* `requestHeader` replaces the latest logged envelope for pressure and node
|
|
839
|
+
* pricing; the node set always describes the current session surface. Every
|
|
840
|
+
* call clones those positional nodes, so measurement is O(surface).
|
|
841
|
+
*
|
|
842
|
+
* @param session - session to replay through its current durable tail.
|
|
843
|
+
* @param requestHeader - optional effective request envelope replacing the latest logged header.
|
|
844
|
+
* @returns a detached deeply immutable pressure and surface measurement.
|
|
845
|
+
*/
|
|
846
|
+
measure(session, requestHeader) {
|
|
847
|
+
const { prices: state, measurement } = this._sync(session);
|
|
848
|
+
const header = requestHeader === void 0 ? this._cachedHeader(state, measurement.headerSeq) : canonicalHeader(requestHeader);
|
|
849
|
+
const pricing = this._routeImagePricing(header);
|
|
850
|
+
const fileText = this._fileRequestText();
|
|
851
|
+
const surface = priceSurface(state.surface, pricing, fileText);
|
|
852
|
+
const anchor = measurement.anchor;
|
|
853
|
+
let baseline;
|
|
854
|
+
let surfaceDeltaTokens;
|
|
855
|
+
if (anchor !== null && optionalHeaderEquals(this._cachedHeader(state, anchor.headerSeq), header)) {
|
|
856
|
+
const anchorSurfaceTokens = priceSurface(state.anchorNodes, pricing, fileText).surfaceTokens + anchor.assistantTokens;
|
|
857
|
+
const estimatedAnchorTokens = estimateToolsTokens(header) + anchorSurfaceTokens;
|
|
858
|
+
const usage = anchor.usage;
|
|
859
|
+
baseline = usage !== null && usageTokens(usage) >= estimatedAnchorTokens ? {
|
|
860
|
+
kind: "usage",
|
|
861
|
+
tokens: usageTokens(usage),
|
|
862
|
+
usage
|
|
863
|
+
} : {
|
|
864
|
+
kind: "estimated",
|
|
865
|
+
tokens: estimatedAnchorTokens
|
|
866
|
+
};
|
|
867
|
+
surfaceDeltaTokens = surface.surfaceTokens - anchorSurfaceTokens;
|
|
868
|
+
} else if (header === void 0 && surface.surfaceTokens === 0) {
|
|
869
|
+
baseline = {
|
|
870
|
+
kind: "none",
|
|
871
|
+
tokens: 0
|
|
872
|
+
};
|
|
873
|
+
surfaceDeltaTokens = 0;
|
|
874
|
+
} else {
|
|
875
|
+
baseline = {
|
|
876
|
+
kind: "estimated",
|
|
877
|
+
tokens: estimateToolsTokens(header) + surface.surfaceTokens
|
|
878
|
+
};
|
|
879
|
+
surfaceDeltaTokens = 0;
|
|
880
|
+
}
|
|
881
|
+
return deepFreeze(structuredClone({
|
|
882
|
+
logRevision: state.consumedEvents,
|
|
883
|
+
baseline,
|
|
884
|
+
surfaceDeltaTokens,
|
|
885
|
+
totalTokens: Math.max(0, baseline.tokens + surfaceDeltaTokens),
|
|
886
|
+
surfaceTokens: surface.surfaceTokens,
|
|
887
|
+
nodes: surface.nodes
|
|
888
|
+
}));
|
|
889
|
+
}
|
|
890
|
+
/** Resolve the routed model's image pricing, when the llm service and route declare one. */
|
|
891
|
+
_routeImagePricing(header) {
|
|
892
|
+
const config = header?.config;
|
|
893
|
+
if (config === void 0) return void 0;
|
|
894
|
+
return this.ctx.get("llm")?.imageRequestPricing(config.provider, config.model);
|
|
895
|
+
}
|
|
896
|
+
/** Resolve request-time file projection when an LLM service is mounted. */
|
|
897
|
+
_fileRequestText() {
|
|
898
|
+
const llm = this.ctx.get("llm");
|
|
899
|
+
return llm === void 0 ? void 0 : (ref) => llm.fileRequestText(ref);
|
|
900
|
+
}
|
|
901
|
+
/**
|
|
902
|
+
* Heuristically price one model-visible message (instance face of the pure
|
|
903
|
+
* `estimateMessage` export from `estimate.ts`).
|
|
904
|
+
* @param message - message to price without mutation.
|
|
905
|
+
* @returns content and role-framing tokens under the fixed service heuristic.
|
|
906
|
+
*/
|
|
907
|
+
estimateMessage(message) {
|
|
908
|
+
return estimateMessage(message);
|
|
909
|
+
}
|
|
910
|
+
/** Resolve one of the two header payloads retained by the rebuildable price cache. */
|
|
911
|
+
_cachedHeader(state, seq) {
|
|
912
|
+
if (seq === null) return void 0;
|
|
913
|
+
if (state.header?.seq === seq) return state.header.value;
|
|
914
|
+
return state.anchorHeader?.value;
|
|
915
|
+
}
|
|
916
|
+
/** Catch rebuildable prices up to the current durable tail. */
|
|
917
|
+
_sync(session, useProjection = true) {
|
|
918
|
+
let state = this.states.get(session);
|
|
919
|
+
if (state === void 0) {
|
|
920
|
+
state = {
|
|
921
|
+
consumedEvents: SessionLogOffset(0),
|
|
922
|
+
surface: [],
|
|
923
|
+
header: void 0,
|
|
924
|
+
anchorHeader: void 0,
|
|
925
|
+
anchorNodes: [],
|
|
926
|
+
pendingMeasurement: measurementProjectionDefinition.init()
|
|
927
|
+
};
|
|
928
|
+
this.states.set(session, state);
|
|
929
|
+
}
|
|
930
|
+
const projected = useProjection ? this.measurementProjectionHandle?.stateOf(session) : void 0;
|
|
931
|
+
while (state.consumedEvents < session.seq) {
|
|
932
|
+
const event = session.eventAt(SessionSeq(state.consumedEvents));
|
|
933
|
+
const next = projected !== void 0 ? void 0 : measurementProjectionDefinition.apply(state.pendingMeasurement, event);
|
|
934
|
+
const measurement = next ?? projected;
|
|
935
|
+
if (measurement?.invalidSeq === event.seq) {
|
|
936
|
+
if (event.type === "assistant/message") planSurfaceTokens(state.surface, event);
|
|
937
|
+
advanceMeasurement(measurement, event);
|
|
938
|
+
}
|
|
939
|
+
this._foldEvent(state, event);
|
|
940
|
+
if (next !== void 0) state.pendingMeasurement = next;
|
|
941
|
+
state.consumedEvents = SessionLogOffset(state.consumedEvents + 1);
|
|
942
|
+
}
|
|
943
|
+
if (projected !== void 0 && (projected.headerSeq !== (state.header?.seq ?? null) || projected.anchor !== null && projected.anchor.headerSeq !== (state.anchorHeader?.seq ?? null))) {
|
|
944
|
+
this.states.delete(session);
|
|
945
|
+
return this._sync(session, false);
|
|
946
|
+
}
|
|
947
|
+
return {
|
|
948
|
+
prices: state,
|
|
949
|
+
measurement: projected ?? state.pendingMeasurement
|
|
950
|
+
};
|
|
951
|
+
}
|
|
952
|
+
/** Update only discardable positional prices and the pre-assistant view. */
|
|
953
|
+
_foldEvent(state, event) {
|
|
954
|
+
if (event.type === "request/header") state.header = {
|
|
955
|
+
seq: event.seq,
|
|
956
|
+
value: canonicalHeader(event.data.header)
|
|
957
|
+
};
|
|
958
|
+
if (event.type === "image/offload") {
|
|
959
|
+
const offloaded = new Map(event.data.targets.map((target) => [target.seq, new Set(target.imageIndexes)]));
|
|
960
|
+
state.surface = state.surface.map((node) => {
|
|
961
|
+
const indexes = offloaded.get(node.seq);
|
|
962
|
+
if (indexes === void 0) return node;
|
|
963
|
+
return {
|
|
964
|
+
...node,
|
|
965
|
+
images: node.images.map((image, index) => indexes.has(index) ? {
|
|
966
|
+
...image,
|
|
967
|
+
offloaded: true
|
|
968
|
+
} : image)
|
|
969
|
+
};
|
|
970
|
+
});
|
|
971
|
+
}
|
|
972
|
+
const plan = isSurfaceEvent(event) ? planSurfaceTokens(state.surface, event) : void 0;
|
|
973
|
+
if (event.type === "assistant/message") {
|
|
974
|
+
state.anchorNodes = [...state.surface];
|
|
975
|
+
state.anchorHeader = state.header;
|
|
976
|
+
}
|
|
977
|
+
if (plan !== void 0) commitSurfaceTokens(state.surface, plan);
|
|
978
|
+
}
|
|
979
|
+
};
|
|
980
|
+
//#endregion
|
|
981
|
+
export { TokenMeter, TokenMeter as default };
|