@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,239 @@
1
+ /**
2
+ * Single replay-aware token-meter service for request and surface pressure.
3
+ *
4
+ * @module @open33/harness-token-meter
5
+ */
6
+ import { Service } from '@open33/cordis';
7
+ import z from '@open33/schemastery';
8
+ import { deepFreeze } from '@open33/harness-util-values';
9
+ import { canonicalHeader, headerEquals, isSurfaceEvent, SessionLogOffset, SessionSeq, } from '@open33/harness-session';
10
+ import { contextBreakdownProjectionDefinition } from "./breakdown-projection.js";
11
+ import { contextPressureProjectionDefinition, tokenUsageProjectionDefinition } from "./usage-projection.js";
12
+ import { estimateMessage, estimateToolsTokens } from "./estimate.js";
13
+ import { advanceMeasurement, measurementProjectionDefinition } from "./measurement-projection.js";
14
+ import { commitSurfaceTokens, planSurfaceTokens } from "./surface-fold.js";
15
+ import { priceSurface } from "./route-pricing.js";
16
+ /** Sum disjoint provider usage buckets without double-counting reasoning output. */
17
+ function usageTokens(usage) {
18
+ return usage.inputTokens
19
+ + (usage.cacheReadTokens ?? 0)
20
+ + (usage.cacheWriteTokens ?? 0)
21
+ + usage.outputTokens;
22
+ }
23
+ /** Compare optional envelopes so a headerless estimate can track later surface deltas. */
24
+ function optionalHeaderEquals(left, right) {
25
+ if (left === undefined || right === undefined)
26
+ return left === right;
27
+ return headerEquals(left, right);
28
+ }
29
+ /** Reject stale or misspelled keys before defaults can hide them. */
30
+ function validateConfigKeys(config) {
31
+ for (const key of Object.keys(config)) {
32
+ throw new Error(`TokenMeterConfig: unknown key "${key}" (no settings are supported)`);
33
+ }
34
+ }
35
+ /** Replay owner for one service-wide estimator and isolated per-session folds. */
36
+ export class TokenMeter extends Service {
37
+ // Schemastery preserves untrusted loader keys on an empty object schema;
38
+ // the public type excludes settings while validateConfigKeys rejects them.
39
+ static Config = z.object({});
40
+ static inject = ['sessionProjections'];
41
+ states = new WeakMap();
42
+ measurementProjectionHandle;
43
+ contextPressureProjectionHandle;
44
+ constructor(ctx, config = {}) {
45
+ super(ctx, 'tokenMeter');
46
+ validateConfigKeys(config);
47
+ }
48
+ async [Service.init]() {
49
+ const ctx = this.ctx;
50
+ this.measurementProjectionHandle = await ctx.sessionProjections.register(measurementProjectionDefinition);
51
+ await ctx.sessionProjections.register(tokenUsageProjectionDefinition);
52
+ this.contextPressureProjectionHandle = await ctx.sessionProjections.register(contextPressureProjectionDefinition);
53
+ await ctx.sessionProjections.register(contextBreakdownProjectionDefinition);
54
+ // Readers catch up independently, while eager observation bounds ordinary
55
+ // read latency without creating state for sessions no consumer has read.
56
+ ctx.on('session/event', (session) => {
57
+ if (this.states.has(session))
58
+ this._sync(session);
59
+ });
60
+ }
61
+ /**
62
+ * Read the latest logged provider prompt size and route capacity.
63
+ * @param session - Session whose committed usage and request capacity are read.
64
+ * @returns context pressure; fields remain absent until their source events are recorded.
65
+ */
66
+ contextPressure(session) {
67
+ const { pressureTokens, contextWindow } = this.contextPressureProjectionHandle.stateOf(session);
68
+ return {
69
+ ...pressureTokens === undefined ? {} : { pressureTokens },
70
+ ...contextWindow === undefined ? {} : { contextWindow },
71
+ };
72
+ }
73
+ /**
74
+ * Measure current request pressure and surface through the durable tail.
75
+ *
76
+ * The effective envelope's routed provider/model selects the request-image
77
+ * pricing every node is priced under: a route whose adapter declares image
78
+ * pricing charges each retained image its visual tokens plus its
79
+ * model-visible text, while other routes keep the fixed heuristic. Provider
80
+ * usage is reused only when the latest successful call's canonical request
81
+ * envelope matches `requestHeader` and its total is no lower than that
82
+ * call's full route-priced anchor; otherwise the complete envelope and
83
+ * surface are repriced. The anchor includes all surface nodes immediately
84
+ * before the assistant message, including inputs admitted after step/start.
85
+ *
86
+ * `requestHeader` replaces the latest logged envelope for pressure and node
87
+ * pricing; the node set always describes the current session surface. Every
88
+ * call clones those positional nodes, so measurement is O(surface).
89
+ *
90
+ * @param session - session to replay through its current durable tail.
91
+ * @param requestHeader - optional effective request envelope replacing the latest logged header.
92
+ * @returns a detached deeply immutable pressure and surface measurement.
93
+ */
94
+ measure(session, requestHeader) {
95
+ const { prices: state, measurement } = this._sync(session);
96
+ const header = requestHeader === undefined
97
+ ? this._cachedHeader(state, measurement.headerSeq)
98
+ : canonicalHeader(requestHeader);
99
+ const pricing = this._routeImagePricing(header);
100
+ const fileText = this._fileRequestText();
101
+ const surface = priceSurface(state.surface, pricing, fileText);
102
+ const anchor = measurement.anchor;
103
+ let baseline;
104
+ let surfaceDeltaTokens;
105
+ if (anchor !== null && optionalHeaderEquals(this._cachedHeader(state, anchor.headerSeq), header)) {
106
+ // Matching headers share one route, so the anchored snapshot reprices
107
+ // under the same pricing as the current surface and the signed delta
108
+ // compares like with like.
109
+ const anchorSurfaceTokens = priceSurface(state.anchorNodes, pricing, fileText).surfaceTokens
110
+ + anchor.assistantTokens;
111
+ const estimatedAnchorTokens = estimateToolsTokens(header) + anchorSurfaceTokens;
112
+ const usage = anchor.usage;
113
+ // Signed heuristic deltas remain conservative only from an anchor
114
+ // that is at least as large as the matching full heuristic price.
115
+ baseline = usage !== null && usageTokens(usage) >= estimatedAnchorTokens
116
+ ? { kind: 'usage', tokens: usageTokens(usage), usage }
117
+ : { kind: 'estimated', tokens: estimatedAnchorTokens };
118
+ surfaceDeltaTokens = surface.surfaceTokens - anchorSurfaceTokens;
119
+ }
120
+ else if (header === undefined && surface.surfaceTokens === 0) {
121
+ baseline = { kind: 'none', tokens: 0 };
122
+ surfaceDeltaTokens = 0;
123
+ }
124
+ else {
125
+ baseline = {
126
+ kind: 'estimated',
127
+ tokens: estimateToolsTokens(header) + surface.surfaceTokens,
128
+ };
129
+ surfaceDeltaTokens = 0;
130
+ }
131
+ return deepFreeze(structuredClone({
132
+ logRevision: state.consumedEvents,
133
+ baseline,
134
+ surfaceDeltaTokens,
135
+ totalTokens: Math.max(0, baseline.tokens + surfaceDeltaTokens),
136
+ surfaceTokens: surface.surfaceTokens,
137
+ nodes: surface.nodes,
138
+ }));
139
+ }
140
+ /** Resolve the routed model's image pricing, when the llm service and route declare one. */
141
+ _routeImagePricing(header) {
142
+ const config = header?.config;
143
+ if (config === undefined)
144
+ return undefined;
145
+ return this.ctx.get('llm')?.imageRequestPricing(config.provider, config.model);
146
+ }
147
+ /** Resolve request-time file projection when an LLM service is mounted. */
148
+ _fileRequestText() {
149
+ const llm = this.ctx.get('llm');
150
+ return llm === undefined ? undefined : ref => llm.fileRequestText(ref);
151
+ }
152
+ /**
153
+ * Heuristically price one model-visible message (instance face of the pure
154
+ * `estimateMessage` export from `estimate.ts`).
155
+ * @param message - message to price without mutation.
156
+ * @returns content and role-framing tokens under the fixed service heuristic.
157
+ */
158
+ estimateMessage(message) {
159
+ return estimateMessage(message);
160
+ }
161
+ /** Resolve one of the two header payloads retained by the rebuildable price cache. */
162
+ _cachedHeader(state, seq) {
163
+ if (seq === null)
164
+ return undefined;
165
+ if (state.header?.seq === seq)
166
+ return state.header.value;
167
+ return state.anchorHeader?.value;
168
+ }
169
+ /** Catch rebuildable prices up to the current durable tail. */
170
+ _sync(session, useProjection = true) {
171
+ let state = this.states.get(session);
172
+ if (state === undefined) {
173
+ state = {
174
+ consumedEvents: SessionLogOffset(0),
175
+ surface: [],
176
+ header: undefined,
177
+ anchorHeader: undefined,
178
+ anchorNodes: [],
179
+ pendingMeasurement: measurementProjectionDefinition.init(),
180
+ };
181
+ this.states.set(session, state);
182
+ }
183
+ const projected = useProjection ? this.measurementProjectionHandle?.stateOf(session) : undefined;
184
+ while (state.consumedEvents < session.seq) {
185
+ // Cold price caches may replay resident history.
186
+ // oxlint-disable-next-line typescript/no-non-null-assertion, typescript/no-deprecated
187
+ const event = session.eventAt(SessionSeq(state.consumedEvents));
188
+ const next = projected !== undefined
189
+ ? undefined
190
+ : measurementProjectionDefinition.apply(state.pendingMeasurement, event);
191
+ const measurement = next ?? projected;
192
+ if (measurement?.invalidSeq === event.seq) {
193
+ // Match the original assistant validation order before committing any prices.
194
+ if (event.type === 'assistant/message')
195
+ planSurfaceTokens(state.surface, event);
196
+ advanceMeasurement(measurement, event);
197
+ }
198
+ this._foldEvent(state, event);
199
+ if (next !== undefined)
200
+ state.pendingMeasurement = next;
201
+ state.consumedEvents = SessionLogOffset(state.consumedEvents + 1);
202
+ }
203
+ if (projected !== undefined && (projected.headerSeq !== (state.header?.seq ?? null)
204
+ || (projected.anchor !== null && projected.anchor.headerSeq !== (state.anchorHeader?.seq ?? null)))) {
205
+ // A checkpoint reference must match the original journal. Discard the
206
+ // rebuildable cache and use the same calculation from the beginning.
207
+ this.states.delete(session);
208
+ return this._sync(session, false);
209
+ }
210
+ // An initialized registration supplies `projected`; earlier reads keep the same pure fold locally.
211
+ return { prices: state, measurement: projected ?? state.pendingMeasurement };
212
+ }
213
+ /** Update only discardable positional prices and the pre-assistant view. */
214
+ _foldEvent(state, event) {
215
+ if (event.type === 'request/header')
216
+ state.header = { seq: event.seq, value: canonicalHeader(event.data.header) };
217
+ if (event.type === 'image/offload') {
218
+ const offloaded = new Map(event.data.targets.map(target => [target.seq, new Set(target.imageIndexes)]));
219
+ state.surface = state.surface.map((node) => {
220
+ const indexes = offloaded.get(node.seq);
221
+ if (indexes === undefined)
222
+ return node;
223
+ return {
224
+ ...node,
225
+ images: node.images.map((image, index) => (indexes.has(index) ? { ...image, offloaded: true } : image)),
226
+ };
227
+ });
228
+ }
229
+ const plan = isSurfaceEvent(event) ? planSurfaceTokens(state.surface, event) : undefined;
230
+ if (event.type === 'assistant/message') {
231
+ state.anchorNodes = [...state.surface];
232
+ state.anchorHeader = state.header;
233
+ }
234
+ if (plan !== undefined)
235
+ commitSurfaceTokens(state.surface, plan);
236
+ }
237
+ }
238
+ export default TokenMeter;
239
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAW,OAAO,EAAE,MAAM,gBAAgB,CAAA;AAEjD,OAAO,CAAC,MAAM,qBAAqB,CAAA;AAEnC,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAA;AAQxD,OAAO,EACL,eAAe,EACf,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,UAAU,GACX,MAAM,yBAAyB,CAAA;AAQhC,OAAO,EAAE,oCAAoC,EAAE,MAAM,2BAA2B,CAAA;AAChF,OAAO,EAAE,mCAAmC,EAAE,8BAA8B,EAAE,MAAM,uBAAuB,CAAA;AAE3G,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAA;AACpE,OAAO,EAAE,kBAAkB,EAAE,+BAA+B,EAAE,MAAM,6BAA6B,CAAA;AAEjG,OAAO,EAAE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AAK,mBAAmB,EAAE,CAAC;YACvC,KAAK,CAAC,WAAW,GAAG,CAAC,GAAG,KAAK,CAAC,OAAO,CAAC,CAAA;YACtC,KAAK,CAAC,YAAY,GAAG,KAAK,CAAC,MAAM,CAAA;QACnC,CAAC;QACD,IAAI,IAAI,KAAK,SAAS;YAAE,mBAAmB,CAAC,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;IAClE,CAAC;;AAGH,eAAe,UAAU,CAAA"}
@@ -0,0 +1,74 @@
1
+ /** Fixed-size recovery facts; positional attachment prices remain a rebuildable cache. */
2
+ import { z } from 'zod';
3
+ import type { TokenUsage } from '@open33/harness-llm';
4
+ import { SessionSeq } from '@open33/harness-session';
5
+ import type { SessionEvent } from '@open33/harness-session';
6
+ declare const measurementStateSchema: z.ZodObject<{
7
+ headerSeq: z.ZodNullable<z.ZodPipe<z.ZodNumber, z.ZodTransform<SessionSeq, number>>>;
8
+ stepStart: z.ZodNullable<z.ZodObject<{
9
+ turn: z.ZodNumber;
10
+ step: z.ZodNumber;
11
+ }, z.core.$strict>>;
12
+ anchor: z.ZodNullable<z.ZodObject<{
13
+ headerSeq: z.ZodNullable<z.ZodPipe<z.ZodNumber, z.ZodTransform<SessionSeq, number>>>;
14
+ assistantTokens: z.ZodNumber;
15
+ usage: z.ZodNullable<z.ZodCustom<TokenUsage, TokenUsage>>;
16
+ }, z.core.$strict>>;
17
+ invalidSeq: z.ZodNullable<z.ZodPipe<z.ZodNumber, z.ZodTransform<SessionSeq, number>>>;
18
+ }, z.core.$strict>;
19
+ /** One header reference, one open step, and the latest successful call's usage facts. */
20
+ export type MeasurementState = z.infer<typeof measurementStateSchema>;
21
+ /**
22
+ * Advance one measurement prefix without mutating its previous state.
23
+ * @param state - measurement facts before the candidate event.
24
+ * @param event - next committed journal event.
25
+ * @returns updated measurement facts.
26
+ * @throws the original measurement error for invalid boundaries or payloads.
27
+ */
28
+ export declare function advanceMeasurement(state: MeasurementState, event: SessionEvent): MeasurementState;
29
+ /** Host-only measurement facts, independent of session and surface length. */
30
+ export declare const measurementProjectionDefinition: {
31
+ key: "tokenMeasurement";
32
+ stateVersion: number;
33
+ stateSchema: z.ZodObject<{
34
+ headerSeq: z.ZodNullable<z.ZodPipe<z.ZodNumber, z.ZodTransform<SessionSeq, number>>>;
35
+ stepStart: z.ZodNullable<z.ZodObject<{
36
+ turn: z.ZodNumber;
37
+ step: z.ZodNumber;
38
+ }, z.core.$strict>>;
39
+ anchor: z.ZodNullable<z.ZodObject<{
40
+ headerSeq: z.ZodNullable<z.ZodPipe<z.ZodNumber, z.ZodTransform<SessionSeq, number>>>;
41
+ assistantTokens: z.ZodNumber;
42
+ usage: z.ZodNullable<z.ZodCustom<TokenUsage, TokenUsage>>;
43
+ }, z.core.$strict>>;
44
+ invalidSeq: z.ZodNullable<z.ZodPipe<z.ZodNumber, z.ZodTransform<SessionSeq, number>>>;
45
+ }, z.core.$strict>;
46
+ init: () => MeasurementState;
47
+ apply: (state: NoInfer<{
48
+ headerSeq: SessionSeq | null;
49
+ stepStart: {
50
+ turn: number;
51
+ step: number;
52
+ } | null;
53
+ anchor: {
54
+ headerSeq: SessionSeq | null;
55
+ assistantTokens: number;
56
+ usage: TokenUsage | null;
57
+ } | null;
58
+ invalidSeq: SessionSeq | null;
59
+ }>, event: SessionEvent) => {
60
+ headerSeq: SessionSeq | null;
61
+ stepStart: {
62
+ turn: number;
63
+ step: number;
64
+ } | null;
65
+ anchor: {
66
+ headerSeq: SessionSeq | null;
67
+ assistantTokens: number;
68
+ usage: TokenUsage | null;
69
+ } | null;
70
+ invalidSeq: SessionSeq | null;
71
+ };
72
+ };
73
+ export {};
74
+ //# sourceMappingURL=measurement-projection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"measurement-projection.d.ts","sourceRoot":"","sources":["../../src/measurement-projection.ts"],"names":[],"mappings":"AAAA,0FAA0F;AAC1F,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAEvB,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;AACrD,OAAO,EAAuC,UAAU,EAAE,MAAM,yBAAyB,CAAA;AACzF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAA;AAiB3D,QAAA,MAAM,sBAAsB;;;;;;;;;;;;kBASjB,CAAA;AAEX,yFAAyF;AACzF,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,sBAAsB,CAAC,CAAA;AAErE;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,gBAAgB,EAAE,KAAK,EAAE,YAAY,GAAG,gBAAgB,CAsCjG;AAED,8EAA8E;AAC9E,eAAO,MAAM,+BAA+B;;;;;;;;;;;;;;;;gBAIhC,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;CAW0C,CAAA"}
@@ -0,0 +1,94 @@
1
+ /** Fixed-size recovery facts; positional attachment prices remain a rebuildable cache. */
2
+ import { z } from 'zod';
3
+ import { assembleAssistantStream } from '@open33/harness-llm';
4
+ import { canonicalHeader, deriveEventMessage, SessionSeq } from '@open33/harness-session';
5
+ import { estimateContent, estimateMessage, ROLE_OVERHEAD } from "./estimate.js";
6
+ const seqSchema = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).transform(SessionSeq);
7
+ const countSchema = z.number();
8
+ const usageFields = z.looseObject({
9
+ inputTokens: countSchema,
10
+ outputTokens: countSchema,
11
+ totalTokens: countSchema.optional(),
12
+ cacheReadTokens: countSchema.optional(),
13
+ cacheWriteTokens: countSchema.optional(),
14
+ reasoningTokens: countSchema.optional(),
15
+ });
16
+ // Keep provider fields and optional-property presence exactly as recorded.
17
+ const usageSchema = z.custom(value => usageFields.safeParse(value).success);
18
+ const measurementStateSchema = z.object({
19
+ headerSeq: seqSchema.nullable(),
20
+ stepStart: z.object({ turn: z.number(), step: z.number() }).strict().nullable(),
21
+ anchor: z.object({
22
+ headerSeq: seqSchema.nullable(),
23
+ assistantTokens: countSchema,
24
+ usage: usageSchema.nullable(),
25
+ }).strict().nullable(),
26
+ invalidSeq: seqSchema.nullable(),
27
+ }).strict();
28
+ /**
29
+ * Advance one measurement prefix without mutating its previous state.
30
+ * @param state - measurement facts before the candidate event.
31
+ * @param event - next committed journal event.
32
+ * @returns updated measurement facts.
33
+ * @throws the original measurement error for invalid boundaries or payloads.
34
+ */
35
+ export function advanceMeasurement(state, event) {
36
+ switch (event.type) {
37
+ case 'request/header':
38
+ canonicalHeader(event.data.header);
39
+ return { ...state, headerSeq: event.seq };
40
+ case 'step/start':
41
+ if (state.stepStart !== null) {
42
+ throw new Error(`token meter: step/start at seq ${event.seq} arrived before turn ${state.stepStart.turn}/step ${state.stepStart.step} ended`);
43
+ }
44
+ return { ...state, stepStart: { turn: event.data.turn, step: event.data.step } };
45
+ case 'step/end':
46
+ if (state.stepStart === null
47
+ || state.stepStart.turn !== event.data.turn
48
+ || state.stepStart.step !== event.data.step) {
49
+ throw new Error(`token meter: step/end at seq ${event.seq} has no matching step/start event`);
50
+ }
51
+ return { ...state, stepStart: null };
52
+ case 'assistant/message': {
53
+ if (state.stepStart === null
54
+ || state.stepStart.turn !== event.data.turn
55
+ || state.stepStart.step !== event.data.step) {
56
+ throw new Error(`token meter: assistant/message at seq ${event.seq} has no matching step/start event`);
57
+ }
58
+ let assistantTokens;
59
+ let usage = null;
60
+ if (event.data.usage !== undefined && state.headerSeq !== null) {
61
+ const content = assembleAssistantStream(event.data.stream).blocks();
62
+ assistantTokens = content.length === 0 ? 0 : estimateContent(content) + ROLE_OVERHEAD;
63
+ usage = event.data.usage;
64
+ }
65
+ else {
66
+ const message = deriveEventMessage(event);
67
+ assistantTokens = message === null ? 0 : estimateMessage(message);
68
+ }
69
+ return { ...state, anchor: { headerSeq: state.headerSeq, assistantTokens, usage } };
70
+ }
71
+ default:
72
+ return state;
73
+ }
74
+ }
75
+ /** Host-only measurement facts, independent of session and surface length. */
76
+ export const measurementProjectionDefinition = {
77
+ key: 'tokenMeasurement',
78
+ stateVersion: 2,
79
+ stateSchema: measurementStateSchema,
80
+ init: () => ({ headerSeq: null, stepStart: null, anchor: null, invalidSeq: null }),
81
+ apply: (state, event) => {
82
+ if (state.invalidSeq !== null)
83
+ return state;
84
+ try {
85
+ return advanceMeasurement(state, event);
86
+ }
87
+ catch (_error) {
88
+ // Retain the first failed position. measure() repeats the calculation there
89
+ // to report its original error without blocking unrelated projection units.
90
+ return { ...state, invalidSeq: event.seq };
91
+ }
92
+ },
93
+ };
94
+ //# sourceMappingURL=measurement-projection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"measurement-projection.js","sourceRoot":"","sources":["../../src/measurement-projection.ts"],"names":[],"mappings":"AAAA,0FAA0F;AAC1F,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AACvB,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAA;AAE7D,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAA;AAGzF,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,eAAe,CAAA;AAE/E,MAAM,SAAS,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC,SAAS,CAAC,UAAU,CAAC,CAAA;AACnG,MAAM,WAAW,GAAG,CAAC,CAAC,MAAM,EAAE,CAAA;AAC9B,MAAM,WAAW,GAAG,CAAC,CAAC,WAAW,CAAC;IAChC,WAAW,EAAE,WAAW;IACxB,YAAY,EAAE,WAAW;IACzB,WAAW,EAAE,WAAW,CAAC,QAAQ,EAAE;IACnC,eAAe,EAAE,WAAW,CAAC,QAAQ,EAAE;IACvC,gBAAgB,EAAE,WAAW,CAAC,QAAQ,EAAE;IACxC,eAAe,EAAE,WAAW,CAAC,QAAQ,EAAE;CACxC,CAAC,CAAA;AACF,2EAA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* Durable cumulative provider usage for a complete session log.
8
+ *
9
+ * The four buckets are disjoint. In particular, reasoning tokens are already
10
+ * included in `outputTokens` and are not accumulated again.
11
+ */
12
+ export interface TokenUsageProjection {
13
+ uncachedInputTokens: number;
14
+ outputTokens: number;
15
+ cacheReadTokens: number;
16
+ cacheWriteTokens: number;
17
+ }
18
+ /**
19
+ * Approximate context occupancy for a status display.
20
+ *
21
+ * The fields, when present, are deliberately NOT one atomic request
22
+ * observation: each is a last-wins record of a different moment. Switching
23
+ * models can therefore pair a fresh capacity with the previous route's
24
+ * pressure until the next request reports usage. This is an intentional trade
25
+ * — the value is a user-facing reference, not a billing or gating input. See
26
+ * the token-meter README for the full rationale.
27
+ */
28
+ export interface ContextPressureProjection {
29
+ /**
30
+ * Provider-reported prompt size of the most recent request: uncached input
31
+ * plus cache reads and writes. Response output is excluded, so this does not
32
+ * grow as the current turn streams. Absent until a provider reports usage.
33
+ */
34
+ pressureTokens?: number;
35
+ /**
36
+ * What the NEXT request's prompt would cost: {@link pressureTokens} plus the
37
+ * heuristic repricing of everything the surface gained or lost since that
38
+ * sample. Only the delta is estimated, so the figure stays anchored to the
39
+ * provider while still reacting the moment a compaction shadows a span —
40
+ * which `pressureTokens` alone cannot do, since compaction reports no usage
41
+ * of its own. Absent until a provider reports usage.
42
+ */
43
+ projectedTokens?: number;
44
+ /** Newest recorded route capacity; absent when no adapter advertised one. */
45
+ contextWindow?: number;
46
+ }
47
+ /**
48
+ * Heuristic composition of the next request's context: what the prompt is
49
+ * made of, not what it costs. All three figures use the meter's fixed
50
+ * density estimate, so they will not sum to the provider-anchored
51
+ * `projectedTokens`: the estimator systematically underprices CJK text and
52
+ * JSON schemas, which is exactly the error the anchoring in
53
+ * {@link ContextPressureProjection.projectedTokens} keeps out of the occupancy
54
+ * figure. Present these as approximations of composition, never as a total.
55
+ */
56
+ export interface ContextBreakdownProjection {
57
+ /** Heuristic tokens of the last nonempty surviving system prompt in surface order; 0 when none exists. */
58
+ systemTokens: number;
59
+ /** Heuristic tokens of the newest request envelope's tool schemas; 0 before any request. */
60
+ toolsTokens: number;
61
+ /** Heuristic tokens of every other visible surface node, including superseded system prompts. */
62
+ messageTokens: number;
63
+ }
64
+ declare module '@open33/harness-session-projection/types' {
65
+ interface SessionProjectionMap {
66
+ /** Provider-reported usage accumulated across the complete durable log. */
67
+ tokenUsage: TokenUsageProjection;
68
+ /** Newest request pressure paired with the newest known route capacity. */
69
+ contextPressure: SessionProjectionSummaryExcluded<ContextPressureProjection>;
70
+ /** Heuristic system/tools/message composition of the next request. */
71
+ contextBreakdown: SessionProjectionSummaryExcluded<ContextBreakdownProjection>;
72
+ }
73
+ }
74
+ //# sourceMappingURL=projection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"projection.d.ts","sourceRoot":"","sources":["../../src/projection.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH;;;;;GAKG;AACH,MAAM,WAAW,oBAAoB;IACnC,mBAAmB,EAAE,MAAM,CAAA;IAC3B,YAAY,EAAE,MAAM,CAAA;IACpB,eAAe,EAAE,MAAM,CAAA;IACvB,gBAAgB,EAAE,MAAM,CAAA;CACzB;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,yBAAyB;IACxC;;;;OAIG;IACH,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB;;;;;;;OAOG;IACH,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,6EAA6E;IAC7E,aAAa,CAAC,EAAE,MAAM,CAAA;CACvB;AAED;;;;;;;;GAQG;AACH,MAAM,WAAW,0BAA0B;IACzC,0GAA0G;IAC1G,YAAY,EAAE,MAAM,CAAA;IACpB,4FAA4F;IAC5F,WAAW,EAAE,MAAM,CAAA;IACnB,iGAAiG;IACjG,aAAa,EAAE,MAAM,CAAA;CACtB;AAED,OAAO,QAAQ,0CAA0C,CAAC;IACxD,UAAU,oBAAoB;QAC5B,2EAA2E;QAC3E,UAAU,EAAE,oBAAoB,CAAA;QAChC,2EAA2E;QAC3E,eAAe,EAAE,gCAAgC,CAAC,yBAAyB,CAAC,CAAA;QAC5E,sEAAsE;QACtE,gBAAgB,EAAE,gCAAgC,CAAC,0BAA0B,CAAC,CAAA;KAC/E;CACF"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Pure client-safe token-projection vocabulary.
3
+ *
4
+ * @module @open33/harness-token-meter/projection
5
+ */
6
+ export {};
7
+ //# sourceMappingURL=projection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"projection.js","sourceRoot":"","sources":["../../src/projection.ts"],"names":[],"mappings":"AAAA;;;;GAIG"}
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Request-projected surface pricing: replaces attachment-block heuristics with
3
+ * the image and file representations sent to the routed model.
4
+ *
5
+ * @module @open33/harness-token-meter/route-pricing
6
+ */
7
+ import type { ContentBlock, LlmImageRequestPricing } from '@open33/harness-llm';
8
+ import type { MeterSurfaceNode } from './surface-fold.ts';
9
+ import type { TokenSurfaceNode } from './types.ts';
10
+ type FileAttachmentRef = Extract<ContentBlock, {
11
+ type: 'file';
12
+ }>['attachment'];
13
+ /** One surface priced for a request route: public nodes plus their total. */
14
+ export interface PricedSurface {
15
+ /** Positional nodes carrying both the route price and the fixed-heuristic price. */
16
+ readonly nodes: TokenSurfaceNode[];
17
+ /** Sum of the route prices across the surface. */
18
+ readonly surfaceTokens: number;
19
+ }
20
+ /**
21
+ * Price one ordered surface under its model-request attachment projection.
22
+ * @param nodes - the fold's current or snapshotted surface, in model-visible order.
23
+ * @param pricing - the routed model's image pricing, or undefined to keep the fixed heuristic.
24
+ * @param fileText - exact file handle projection used by the mounted LLM service.
25
+ * @returns detached public nodes and their route-priced total.
26
+ * @throws when the pricing answers a different occurrence count than it was
27
+ * asked — misalignment would silently misprice nodes, so it must fail loud.
28
+ */
29
+ export declare function priceSurface(nodes: readonly MeterSurfaceNode[], pricing: LlmImageRequestPricing | undefined, fileText?: (ref: FileAttachmentRef) => string): PricedSurface;
30
+ export {};
31
+ //# sourceMappingURL=route-pricing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route-pricing.d.ts","sourceRoot":"","sources":["../../src/route-pricing.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAA;AAE/E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAA;AACzD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAElD,KAAK,iBAAiB,GAAG,OAAO,CAAC,YAAY,EAAE;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC,YAAY,CAAC,CAAA;AAE9E,6EAA6E;AAC7E,MAAM,WAAW,aAAa;IAC5B,oFAAoF;IACpF,QAAQ,CAAC,KAAK,EAAE,gBAAgB,EAAE,CAAA;IAClC,kDAAkD;IAClD,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAA;CAC/B;AAED;;;;;;;;GAQG;AACH,wBAAgB,YAAY,CAC1B,KAAK,EAAE,SAAS,gBAAgB,EAAE,EAClC,OAAO,EAAE,sBAAsB,GAAG,SAAS,EAC3C,QAAQ,CAAC,EAAE,CAAC,GAAG,EAAE,iBAAiB,KAAK,MAAM,GAC5C,aAAa,CAwCf"}
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Request-projected surface pricing: replaces attachment-block heuristics with
3
+ * the image and file representations sent to the routed model.
4
+ *
5
+ * @module @open33/harness-token-meter/route-pricing
6
+ */
7
+ import { estimateContent } from "./estimate.js";
8
+ /**
9
+ * Price one ordered surface under its model-request attachment projection.
10
+ * @param nodes - the fold's current or snapshotted surface, in model-visible order.
11
+ * @param pricing - the routed model's image pricing, or undefined to keep the fixed heuristic.
12
+ * @param fileText - exact file handle projection used by the mounted LLM service.
13
+ * @returns detached public nodes and their route-priced total.
14
+ * @throws when the pricing answers a different occurrence count than it was
15
+ * asked — misalignment would silently misprice nodes, so it must fail loud.
16
+ */
17
+ export function priceSurface(nodes, pricing, fileText) {
18
+ const images = pricing === undefined ? [] : nodes.flatMap(node => node.images);
19
+ const hasFiles = fileText !== undefined && nodes.some(node => node.files.length > 0);
20
+ if ((pricing === undefined || images.length === 0) && !hasFiles) {
21
+ let surfaceTokens = 0;
22
+ const publicNodes = nodes.map((node) => {
23
+ surfaceTokens += node.heuristicTokens;
24
+ return { seq: node.seq, tokens: node.heuristicTokens, heuristicTokens: node.heuristicTokens };
25
+ });
26
+ return { nodes: publicNodes, surfaceTokens };
27
+ }
28
+ const prices = pricing === undefined ? [] : pricing.priceImages(images);
29
+ if (pricing !== undefined && prices.length !== images.length) {
30
+ throw new Error(`token meter: route image pricing answered ${prices.length} prices for ${images.length} occurrences`);
31
+ }
32
+ let cursor = 0;
33
+ let surfaceTokens = 0;
34
+ const publicNodes = nodes.map((node) => {
35
+ let tokens = node.heuristicTokens;
36
+ if (fileText !== undefined && node.files.length > 0) {
37
+ tokens -= node.fileStructuralTokens;
38
+ for (const file of node.files) {
39
+ tokens += estimateContent([{ type: 'text', text: fileText(file) }]);
40
+ }
41
+ }
42
+ if (pricing !== undefined && node.images.length > 0) {
43
+ tokens -= node.imageStructuralTokens;
44
+ for (let occurrence = 0; occurrence < node.images.length; occurrence += 1) {
45
+ // oxlint-disable-next-line typescript/no-non-null-assertion -- length equality is asserted above
46
+ const price = prices[cursor];
47
+ cursor += 1;
48
+ tokens += price.visualTokens + estimateContent([{ type: 'text', text: price.text }]);
49
+ }
50
+ }
51
+ surfaceTokens += tokens;
52
+ return { seq: node.seq, tokens, heuristicTokens: node.heuristicTokens };
53
+ });
54
+ return { nodes: publicNodes, surfaceTokens };
55
+ }
56
+ //# sourceMappingURL=route-pricing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route-pricing.js","sourceRoot":"","sources":["../../src/route-pricing.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAA;AAc/C;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