@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
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DeepSeek
4
+ Modifications copyright (c) 2026 open33
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
@@ -0,0 +1,64 @@
1
+ # Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading
2
+ # section, a hash of its English and Chinese blocks outside code blocks and generated regions.
3
+ # After editing either side, bring the other along and re-record with:
4
+ # pnpm run verify-translation-pairing --write packages/llm/token-meter/README.md
5
+ /:
6
+ en: 6eda56ef696001df
7
+ zh: 13f961071e8609a7
8
+ /open33-harness-token-meter:
9
+ en: e6822ff6cc445ab0
10
+ zh: 8518669af523dce8
11
+ /open33-harness-token-meter/summary:
12
+ en: 7f5142b836b0338a
13
+ zh: 2735005241e2aae2
14
+ /open33-harness-token-meter/table-of-contents:
15
+ en: d152484eb41ac6b4
16
+ zh: 09388d293f9be9cb
17
+ /open33-harness-token-meter/use-this-package:
18
+ en: 5907ef1472773a47
19
+ zh: 06f1e988290a32c6
20
+ /open33-harness-token-meter/use-this-package/when-to-choose-it:
21
+ en: e8c4cd1e945f86ba
22
+ zh: 133c1f1a85179d30
23
+ /open33-harness-token-meter/use-this-package/measuring-pressure:
24
+ en: 58de3b364ab5af6b
25
+ zh: c5440af43d321e56
26
+ /open33-harness-token-meter/use-this-package/session-projections:
27
+ en: 880f4fde933fb526
28
+ zh: 7990c753d756eb46
29
+ /open33-harness-token-meter/use-this-package/composition:
30
+ en: 6e02e3ffe3119dc9
31
+ zh: a05a9769aa2032f0
32
+ /open33-harness-token-meter/use-this-package/reading-the-numbers:
33
+ en: 7950203e0c146123
34
+ zh: 4fe421b2268f12a9
35
+ /open33-harness-token-meter/understand-the-implementation:
36
+ en: 9630d7e26193a512
37
+ zh: 94222c2a487c4b8c
38
+ /open33-harness-token-meter/understand-the-implementation/design-philosophy:
39
+ en: 6b046d9d3bce7483
40
+ zh: 5d3a62f785757842
41
+ /open33-harness-token-meter/understand-the-implementation/source-map:
42
+ en: aac2e9f658341c2f
43
+ zh: 98c5da95d1b55115
44
+ /open33-harness-token-meter/understand-the-implementation/fold-flow:
45
+ en: c97959d84cf8a1a4
46
+ zh: f17570caa42a1a8e
47
+ /open33-harness-token-meter/understand-the-implementation/projection-semantics:
48
+ en: 73d6d3a8778f47c9
49
+ zh: fdefe0f0c1218074
50
+ /open33-harness-token-meter/further-exploration:
51
+ en: beaaa1c14fd01fca
52
+ zh: 42c3b47eecd1e2ea
53
+ /open33-harness-token-meter/model-experience:
54
+ en: e758d71d0564742f
55
+ zh: 7166feabd811d45f
56
+ /open33-harness-token-meter/model-experience/kv-cache-effect:
57
+ en: 40294c1c31b74824
58
+ zh: c2284876b56d2dbc
59
+ /open33-harness-token-meter/known-limitations-and-deferred-work:
60
+ en: 4866aeeed470fc89
61
+ zh: cbbd4b641a979d4d
62
+ /open33-harness-token-meter/known-limitations-and-deferred-work/dev-note:
63
+ en: 50b57427bfda172e
64
+ zh: 48d666dcc8c7290f
package/README.md CHANGED
@@ -1,3 +1,163 @@
1
- # Temporary Holding Version
1
+ ---
2
+ description: "Replay-aware token and context-pressure measurement for users and maintainers sizing prompts or building compaction and occupancy displays."
3
+ kind: "package-reference"
4
+ ---
2
5
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
6
+ # @open33/harness-token-meter
7
+
8
+ English | [中文](README.zh.md)
9
+
10
+ ## Summary
11
+
12
+ Use `ctx.tokenMeter` to estimate a session's current request and context pressure or price one message. Measurements replay the durable session log, remain deterministic, and make no model calls, so compaction, occupancy displays, and telemetry can share one result. The service requires session projections; consumers can read `tokenUsage`, `contextPressure`, and `contextBreakdown`; text and routes without image pricing use an approximate fixed heuristic, declared visual-token pricing applies when available, and files are priced as model-visible handle text. Provider-reported usage is reused only for an identical request envelope; the package adds no model-visible content and makes no loop decisions.
13
+
14
+ ## Table of Contents
15
+
16
+ - [Use this package](#use-this-package)
17
+ - [Understand the implementation](#understand-the-implementation)
18
+ - [Further Exploration](#further-exploration)
19
+ - [Model Experience](#model-experience)
20
+ - [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
21
+ - [Dev Note](#dev-note)
22
+
23
+ -----
24
+
25
+ <a id="use-this-package"></a>
26
+ ## Use this package
27
+
28
+ Mount this plugin when a consumer needs token or context pressure for compaction decisions, occupancy displays, or telemetry. The estimator has no settings and adds no model-visible surface; model capacity belongs to the adapter that owns the exact provider/model route and is available through `ctx.llm.resolveModelInfo().context`.
29
+
30
+ ### When to choose it
31
+
32
+ Choose it when several plugins should agree on one replay-based measurement — compaction planning, occupancy UIs, and pressure checks all read the same fold. The measurements replay the durable session log, so they are deterministic, cost no model calls, and reflect exactly what is logged. Text and undeclared image routes use a fixed heuristic; reach for a provider tokenizer when a deployment needs exact billing-grade counts.
33
+
34
+ ### Measuring pressure
35
+
36
+ `ctx.tokenMeter` exposes two operations. `measure(session, requestHeader?)` returns a detached, deeply immutable snapshot at one consumed-log revision: `totalTokens` is request-and-response pressure, and `surfaceTokens` is the surface-only route-priced total equal to the sum of `nodes[].tokens`. An optional `requestHeader` override selects the priced route and pressure fields; the node set still describes the current session. `estimateMessage(message)` prices one message with the fixed heuristic. Every call clones the positional surface nodes, so measurement is O(surface).
37
+
38
+ ```text
39
+ const { totalTokens, surfaceTokens, nodes } = ctx.tokenMeter.measure(session)
40
+ const price = ctx.tokenMeter.estimateMessage(message)
41
+ ```
42
+
43
+ Each measurement resolves the effective envelope's provider/model through the optional `llm` service. Image occurrences use the routed request's visual-token price plus model-visible text when the adapter declares pricing, and occurrences selected by an `image/offload` event are priced as the route's placeholder text exactly as the surface sends them; other routes keep the fixed heuristic. File occurrences use the exact route-independent handle text that the same `llm` service resolves for adapter dispatch, including its current execution-world path or explicit no-path message. Each node also carries route-independent `heuristicTokens` for replacement shadow prices. Provider usage is reused only when the latest successful call's canonical request envelope matches the measured envelope and its total is no lower than that call's full route-priced anchor; otherwise the complete current envelope and surface are estimated. Surface changes stay signed relative to a matching anchor repriced under the same route, including negative deltas after shrinking replacements.
44
+
45
+ The measurement anchor includes the priced surface immediately before the successful `assistant/message`, including system and user messages admitted after `step/start` and replacements made before a retry. With unchanged durable output, the completed call has zero surface delta: its prompt is already included in provider usage. Later surface changes remain signed deltas against that anchor.
46
+
47
+ ### Session projections
48
+
49
+ Token-meter registers three client-view projection units and one host-only unit through its required `ctx.sessionProjections` service. Host consumers call `ctx.tokenMeter.contextPressure(session)` to read the latest provider-reported prompt size and route capacity synchronously; the registration handle stays private. `tokenUsage` carries the complete durable log's `uncachedInputTokens`, `outputTokens`, `cacheReadTokens`, and `cacheWriteTokens`. A final assistant-message sample replaces streaming usage from the same attempt; `llm/retry-started` ends that replacement scope, so a retry in the same step contributes another billed attempt. `contextPressure` carries optional `pressureTokens` (the newest provider-reported prompt size), optional `projectedTokens` (what the next request's prompt would cost), and optional `contextWindow` from the newest `request/context` record. `contextBreakdown` carries heuristic `systemTokens`, `toolsTokens`, and `messageTokens` — the context's composition, not its provider-billed size. Unloading the plugin removes all four keys. The host-only `tokenMeasurement` state saves header references, the open step, and the latest successful call's usage and output price. It contains no message arrays, tool schemas, attachment data, or price caches. Invalid measurement history records only its first failed position; unrelated projection updates and checkpoints continue. `measure()` reports the original error at that event, before committing prices or advancing its cursor. State version 2 discards older measurement rows and rebuilds from the journal.
50
+
51
+ Image offload reprices existing node identities while preserving prior usage anchors. The fixed reference heuristic excludes `offloaded` metadata, so an offload decision does not change `contextBreakdown` or the scalar heuristic total; route-aware measurement replaces the selected visual prices with placeholder text.
52
+
53
+ `contextBreakdown` classifies the last nonempty surviving `system/message` in surface order as `systemTokens`; empty dormant nodes contribute nothing, and no nonempty system means zero. `messageTokens` includes every other visible node, including superseded prompts. Their sum equals `measure().nodes[].heuristicTokens` after appends, metered compaction and pruning, and system-prompt rewrites or clearing; an unmetered replacement of a non-system range folds at zero delta, like `contextPressure`. `toolsTokens` follows the latest `request/header`. All three use the fixed heuristic, not route image pricing or file-handle projection; they are approximate composition, not billing or `projectedTokens`.
54
+
55
+ `deriveTurnTokenUsage(events)` folds one complete turn into exact per-attempt and whole-turn usage for browser consumers. It returns no result when lifecycle evidence is missing, counts are unsafe, or exact totals conflict; each corresponding aggregate appears only when every participating attempt reports its optional cache, reasoning, or route value.
56
+
57
+ ### Composition
58
+
59
+ ```yaml
60
+ - name: '@open33/harness-token-meter'
61
+ - name: '@open33/harness-compaction-basic'
62
+ ```
63
+
64
+ Both plugins have usable defaults. The meter consumes only the optional `llm` service, and only to resolve route-declared request-image pricing; compaction remains optional. A deployment configures capacity and image pricing on its LLM adapter and compaction policy on `open33-compaction-basic`.
65
+
66
+ ### Reading the numbers
67
+
68
+ Occupancy is a reference figure, not a billing record: nothing in the harness makes decisions from it, and compaction reads `measure()` instead. A UI computes occupancy by dividing measured pressure by the separately resolved capacity for the selected model. The `contextBreakdown` figures are estimates that will not sum to `projectedTokens`, whose provider anchor carries exactly the heuristic error — CJK text and JSON schemas underprice badly at four characters per token.
69
+
70
+ -----
71
+
72
+ <a id="understand-the-implementation"></a>
73
+ ## Understand the implementation
74
+
75
+ <details>
76
+ <summary>Implementation internals — click to expand</summary>
77
+
78
+ This section explains the design behind the service; the observable behavior is fully covered in [Use this package](#use-this-package).
79
+
80
+ ### Design philosophy
81
+
82
+ The service separates fixed-size recovery facts from rebuildable positional prices. `tokenMeasurement` preserves one current header reference, one step boundary, and one usage anchor. The private price cache retains the current and pre-assistant node prices and their two header payloads. Restoring the projection folds only later events; a cold price cache can still scan the complete log. Synchronous reads before plugin activation use the same pure metadata fold locally.
83
+
84
+ Provider usage anchors a measurement only when its canonical envelope matches and its total is no lower than the full route-priced cost of the same call; otherwise the complete envelope and surface are estimated. Both surfaces are repriced per measurement, including current image prices and file-handle text. No projection fold performs I/O or invokes runtime hooks.
85
+
86
+ ### Source map
87
+
88
+ | File | Role |
89
+ |---|---|
90
+ | [`src/index.ts`](src/index.ts) | The `TokenMeter` service: replay state, fold, `measure()` and `estimateMessage()` |
91
+ | [`src/estimate.ts`](src/estimate.ts) | The fixed heuristic: four characters per token plus block and role overhead |
92
+ | [`src/measurement-projection.ts`](src/measurement-projection.ts) | Fixed-size host recovery facts; no positional caches |
93
+ | [`src/surface-fold.ts`](src/surface-fold.ts) | The positional surface fold shared with `measure()` |
94
+ | [`src/surface-projection.ts`](src/surface-projection.ts) | Shadow-price protocol for the O(1) projection units |
95
+ | [`src/usage-projection.ts`](src/usage-projection.ts) | `tokenUsage` and `contextPressure` projection definitions |
96
+ | [`src/breakdown-projection.ts`](src/breakdown-projection.ts) | `contextBreakdown` projection definition |
97
+ | [`src/client.ts`](src/client.ts) | Browser-safe client surface for projection consumers |
98
+ | [`src/turn-usage.ts`](src/turn-usage.ts) | Pure fold for exact per-attempt and per-Turn usage |
99
+
100
+ ### Fold flow
101
+
102
+ Each `measure()` call synchronizes the fold to the current durable tail, then reads one coherent snapshot. The fold tracks full request-header snapshots, step boundaries, surface appends and replacements, successful assistant messages, and provider usage. Provider output for a usage anchor is reassembled from the assistant message's exact embedded stream, independently of listener rewrites to durable content; empty assembled content costs zero.
103
+
104
+ ### Projection semantics
105
+
106
+ `contextBreakdown` retains only the surviving `system/message` nodes with their heuristic prices, one running surface total, and at most one armed shadow-price claim; a replacement subtracts the adjacent claim, whose `shadowedSeqs` also name the system prompts it removes, or the retained price of the one system prompt it rewrites ([decision](../../../.agents/notes/implemented/architecture/2026-10-13-context-breakdown-system-prompt-state.md)). Its state follows the number of surviving system prompts, not the message count; state version 6 invalidates positional checkpoints. `contextPressure` is the other scalar shadow-price consumer: replacements without adjacent claims contribute zero delta. The usage fold retains one last-sample slot because legal logs never report usage for an earlier step after a later step reports usage.
107
+
108
+ `./estimate` exports the stateless text/content estimators used by tool-result retention. Model adapters supply request-image costs through `imageRequestPricing`.
109
+
110
+ </details>
111
+
112
+ -----
113
+
114
+ <a id="further-exploration"></a>
115
+ ## Further Exploration
116
+
117
+ Read these pages when the package-level contract is not enough. They move from the measurement service to the compaction consumer and the shared types.
118
+
119
+ - [Token meter subsystem](../../../docs/subsystems/token-meter.md) — the measurement semantics behind `ctx.tokenMeter`.
120
+ - [open33-llm service](../llm/README.md) — the model-call service whose capacity metadata `resolveModelInfo()` serves.
121
+ - [Compaction capability](../../../docs/subsystems/compaction.md) — the pressure-sensitive consumer that reads `measure()`.
122
+ - [Projected token usage](../../../.agents/notes/implemented/architecture/2026-07-29-projected-token-usage-and-request-context.md) — the design behind `projectedTokens` and the rejected atomic-pair comparison.
123
+ - [LLM streaming subsystem](../../../docs/subsystems/llm-streaming.md) — the message and block types this service prices.
124
+
125
+ -----
126
+
127
+ <a id="model-experience"></a>
128
+ ## Model Experience
129
+
130
+ Indirectly, through consumers such as `open33-compaction-basic`; the service itself adds no prompt, message, schema, tool, or model call.
131
+
132
+ #### KV Cache effect
133
+
134
+ No direct invalidation; the named consumer owns any request-prefix changes.
135
+
136
+ ## Known Limitations and Deferred Work
137
+
138
+ <a id="known-limitations-and-deferred-work"></a>
139
+
140
+
141
+ These limits define where the measurement stops and future work begins. They are current package constraints, not a general token-accounting comparison or a task backlog.
142
+
143
+ - **The fixed heuristic is approximate** — text without reusable provider usage is priced by character count plus structural overhead, not an exact provider tokenizer or request serializer; only image occurrences on routes with declared pricing carry provider-exact visual tokens.
144
+ - **A cold price cache can scan the complete log** — the fixed-size checkpoint restores measurement facts, not positional prices or the old anchor's messages. Header payloads are rebuilt with the price cache; warm reads need no new history access. Measurement recovery can still read the log prefix. A header reference that does not match the rebuilt journal cache discards that cache and repeats the original calculation from the beginning.
145
+ - **Every measurement clones the current surface** — coherent immutable snapshots make reads O(surface), including below-threshold pressure checks.
146
+ - **Provider usage is only reusable for an identical canonical envelope** — tools, provider, model, or call-config changes deliberately fall back to full heuristic estimation; system-prompt changes are signed surface deltas until the next successful call.
147
+ - **A system-prompt rewrite carries no shadow price** — the loop replaces a system node without an adjacent metering event, so `contextPressure.projectedTokens` folds that replacement at zero delta until the next usage sample; `contextBreakdown.systemTokens` and `measure()` reprice the new prompt immediately.
148
+ - **Composition checkpoints retain the current surface** — exact system/message classification needs positional entries; checkpoint size and surface-event folding are O(current retained surface).
149
+
150
+ <a id="dev-note"></a>
151
+ ### Dev Note
152
+
153
+ <details>
154
+ <summary>Working context for maintainers — click to expand</summary>
155
+
156
+ This Dev Note is non-authoritative working context: notes for maintainers and open questions. Shipped behavior and accepted rationale live in the sections above, the package code, and the linked Agent Notes.
157
+
158
+ - The fixed four-characters-per-token heuristic underprices CJK text and JSON schemas; the provider anchor carries exactly that error when usage is reused. Present the composition rows as an approximate composition, never as a total.
159
+ - A per-provider exact tokenizer is not decided; keeping one deterministic heuristic is what makes every consumer's measurement agree and replay-stable.
160
+
161
+ </details>
162
+
163
+ Usage folds replace samples within each attempt; totals need not be monotone. Composition and measurement share the positional replacement planner and fixed estimator, so their heuristic surface totals agree by construction. Route-priced totals deliberately differ.
package/README.zh.md ADDED
@@ -0,0 +1,163 @@
1
+ ---
2
+ description: "面向用户与维护者的具备回放感知的 token 与上下文压力计量说明:评估提示词规模或构建压缩(compaction)与占用显示。"
3
+ kind: "package-reference"
4
+ ---
5
+
6
+ # @open33/harness-token-meter
7
+
8
+ [English](README.md) | 中文
9
+
10
+ ## 概述
11
+
12
+ 使用 `ctx.tokenMeter` 估算会话当前的请求与上下文压力,或为单条消息计价。测量会回放持久会话日志,结果确定且不进行模型调用,因此压缩、占用显示与遥测可以共享同一结果。该服务依赖会话投影;消费方可以读取 `tokenUsage`、`contextPressure` 与 `contextBreakdown`;文本和没有图片定价的路由采用近似的固定启发式规则,存在声明时应用视觉 token 定价,文件则按模型可见的句柄文本计价。只有请求 envelope 完全相同时才复用提供方报告的用量;本包不添加模型可见内容,也不在 loop 中做决策。
13
+
14
+ ## 目录
15
+
16
+ - [使用本包](#use-this-package)
17
+ - [理解实现](#understand-the-implementation)
18
+ - [进一步探索](#further-exploration)
19
+ - [模型体验](#model-experience)
20
+ - [已知限制与延期工作](#known-limitations-and-deferred-work)
21
+ - [开发备注](#dev-note)
22
+
23
+ -----
24
+
25
+ <a id="use-this-package"></a>
26
+ ## 使用本包
27
+
28
+ 当消费方需要为压缩决策、占用显示或遥测获取 token 或上下文压力时挂载本插件。估算器没有任何配置,也不添加模型可见表面;模型容量属于拥有精确提供方/模型路由的适配器,可通过 `ctx.llm.resolveModelInfo().context` 获取。
29
+
30
+ ### 何时选择
31
+
32
+ 当多个插件应该就同一种基于回放的测量达成一致时选择它——压缩规划、占用 UI 与压力检查都读取同一个 fold。测量回放持久会话日志,因此确定、无需模型调用,并精确反映已记录内容。文本和未声明图片定价的路由使用固定启发式规则;当部署需要精确到计费级别的计数时,使用提供方分词器。
33
+
34
+ ### 测量压力
35
+
36
+ `ctx.tokenMeter` 暴露两个操作。`measure(session, requestHeader?)` 在同一个已消费日志 revision 上返回独立、深度不可变的快照:`totalTokens` 是请求与响应压力,`surfaceTokens` 是仅表面的路由定价总量,等于 `nodes[].tokens` 之和。可选 `requestHeader` 覆盖会选择计价路由与压力字段;节点集合仍描述当前会话。`estimateMessage(message)` 用固定启发式规则为一条消息计价。每次调用都会克隆带位置的表面节点,因此测量是 O(surface)。
37
+
38
+ ```text
39
+ const { totalTokens, surfaceTokens, nodes } = ctx.tokenMeter.measure(session)
40
+ const price = ctx.tokenMeter.estimateMessage(message)
41
+ ```
42
+
43
+ 每次测量都会通过可选的 `llm` 服务解析生效 envelope 的提供方/模型。适配器声明图片定价时,图片出现处使用路由请求的视觉 token 价格加模型可见文本,`image/offload` 事件选中的出现位置则按路由的占位文本计价,与表层实际发送的一致;其他路由保持固定启发式规则。文件出现处使用同一个 `llm` 服务为适配器分发解析的确切、与路由无关的 句柄文本,其中包含当前执行世界路径或明确的无路径说明。每个节点还携带与路由无关的 `heuristicTokens`,供替换影子价使用。只有当最新成功调用的规范请求 envelope 与已测量 envelope 匹配、且其总量不低于该调用完整路由定价锚点时,才复用提供方用量;否则会对完整当前 envelope 与表面做估算。表面变更保持相对于按同一路由重新定价的匹配锚点的带符号值,包括缩减替换后的负 delta。
44
+
45
+ 测量锚点包含成功的 `assistant/message` 之前的已计价表面,包括 `step/start` 之后接纳的系统与用户消息,以及重试之前执行的替换。持久输出未变时,完成调用的表面增量为零:其提示词已包含在提供方用量中。后续表面变更仍是相对于该锚点的带符号增量。
46
+
47
+ ### 会话投影
48
+
49
+ token-meter 通过必需的 `ctx.sessionProjections` 服务注册三个客户端投影单元和一个仅供宿主使用的单元。Host 消费方调用 `ctx.tokenMeter.contextPressure(session)` 同步读取提供方报告的最新提示词规模和路由容量;注册句柄保留在内部。`tokenUsage` 携带完整持久日志中的 `uncachedInputTokens`、`outputTokens`、`cacheReadTokens` 与 `cacheWriteTokens`。最终 assistant 消息样本会替换同一次尝试的流式用量;`llm/retry-started` 会结束该替换范围,因此同一步骤中的重试会贡献另一次计费用量。`contextPressure` 携带可选 `pressureTokens`(提供方报告的最新提示词规模)、可选 `projectedTokens`(下一个请求的提示词将花费多少)与来自最新一条 `request/context` 记录的可选 `contextWindow`。`contextBreakdown` 携带启发式 `systemTokens`、`toolsTokens` 与 `messageTokens`——上下文的构成,而非提供方计费规模。卸载插件会移除全部四个键。仅宿主使用的 `tokenMeasurement` 保存请求头引用、未结束的步骤,以及最近一次成功调用的用量和输出价格。它不保存消息数组、工具定义、附件数据或价格缓存。计量历史有误时,只记录首次失败的位置,其他投影更新和检查点仍可继续;`measure()` 在该事件处报告原有错误,不提交价格或推进读取位置。状态版本 2 会丢弃旧版计量记录,再从日志重建。
50
+
51
+ 图片省略重新计算现有节点的价格,同时保留此前的用量锚点。固定引用启发式规则不计入 `offloaded` 元数据,因此一次省略决定不改变 `contextBreakdown` 或标量启发式总量,按路由的测量则把所选图片的视觉价格换成占位文本价格。
52
+
53
+ `contextBreakdown` 把 surface 顺序中最后一个非空且存活的 `system/message` 归入 `systemTokens`;休眠的空节点不贡献 token,没有非空系统消息时为零。`messageTokens` 包含其余所有可见节点,包括被取代的提示词。在追加、已计量的压缩与裁剪、系统提示词改写或清空之后,两者之和等于 `measure().nodes[].heuristicTokens`;对非系统范围的未计量替换以零增量折叠,与 `contextPressure` 相同。`toolsTokens` 跟随最新 `request/header`。三个数字都使用固定启发式规则,而非路由图片定价或文件句柄投影;它们是近似构成,不是计费数据或 `projectedTokens`。
54
+
55
+ `deriveTurnTokenUsage(events)` 为浏览器消费方把一个完整轮次折叠为精确的逐次尝试与整轮用量。生命周期证据缺失、计数不安全或精确总量矛盾时不返回结果;只有每次参与的尝试都报告可选缓存、推理或路由值时,相应汇总才会出现。
56
+
57
+ ### 组合
58
+
59
+ ```yaml
60
+ - name: '@open33/harness-token-meter'
61
+ - name: '@open33/harness-compaction-basic'
62
+ ```
63
+
64
+ 两个插件都有可用默认值。meter 只消费可选的 `llm` 服务,且仅用于解析路由声明的请求图片定价;压缩保持可选。部署会在 LLM(大语言模型)适配器上配置容量与图片定价,并在 `open33-compaction-basic` 上配置压缩策略。
65
+
66
+ ### 解读数字
67
+
68
+ 占用是参考数字,不是计费记录:harness 中没有任何机制依据它做决定,压缩读取的是 `measure()`。UI 用测量压力除以所选模型独立解析的容量来计算占用。`contextBreakdown` 数字是估算值,其总和不会等于 `projectedTokens`;后者的提供方锚点恰好携带启发式误差——CJK 文本与 JSON schema 在每 token 四字符下严重低估。
69
+
70
+ -----
71
+
72
+ <a id="understand-the-implementation"></a>
73
+ ## 理解实现
74
+
75
+ <details>
76
+ <summary>实现细节——点击展开</summary>
77
+
78
+ 本节解释服务背后的设计;可观察行为已在[使用本包](#use-this-package)中完整说明。
79
+
80
+ ### 设计理念
81
+
82
+ 服务将固定大小的恢复信息与可重建的逐节点价格分开。`tokenMeasurement` 保存一个当前请求头引用、一个步骤边界和一个用量锚点。内部价格缓存保留当前节点、assistant 消息提交前的节点价格,以及两者对应的请求头内容。恢复投影只处理检查点后的事件;价格缓存为空时仍可扫描完整日志。插件激活前的同步读取在本地使用相同的纯计量信息折叠函数。
83
+
84
+ 只有请求头相同、且提供方用量不低于同一次调用的完整路由估算时,才用它作为测量基准;否则估算完整请求头和当前内容。每次测量都重新计算当前内容和旧锚点的价格,包括当前图片价格与文件句柄文本。投影折叠不执行 I/O,也不调用运行时 hook。
85
+
86
+ ### 源码地图
87
+
88
+ | 文件 | 职责 |
89
+ |---|---|
90
+ | [`src/index.ts`](src/index.ts) | `TokenMeter` 服务:回放状态、fold、`measure()` 与 `estimateMessage()` |
91
+ | [`src/estimate.ts`](src/estimate.ts) | 固定启发式规则:每 token 四字符加块与角色开销 |
92
+ | [`src/measurement-projection.ts`](src/measurement-projection.ts) | 固定大小的宿主恢复信息,不含逐节点缓存 |
93
+ | [`src/surface-fold.ts`](src/surface-fold.ts) | 与 `measure()` 共享的位置表面 fold |
94
+ | [`src/surface-projection.ts`](src/surface-projection.ts) | O(1) 投影单元的影价协议 |
95
+ | [`src/usage-projection.ts`](src/usage-projection.ts) | `tokenUsage` 与 `contextPressure` 投影定义 |
96
+ | [`src/breakdown-projection.ts`](src/breakdown-projection.ts) | `contextBreakdown` 投影定义 |
97
+ | [`src/client.ts`](src/client.ts) | 面向投影消费方、可安全用于浏览器的客户端接口 |
98
+ | [`src/turn-usage.ts`](src/turn-usage.ts) | 精确逐次尝试与逐 Turn 用量的纯 fold |
99
+
100
+ ### Fold 流程
101
+
102
+ 每次 `measure()` 调用都把 fold 同步到当前持久尾部,然后读取一份连贯快照。fold 跟踪完整请求标头快照、步骤边界、表面追加与替换、成功 assistant 消息及提供方用量。用量锚点的提供方输出从 assistant 消息的精确内嵌流重新组装,与监听器对持久内容的改写相互独立;空的重组内容计价为零。
103
+
104
+ ### 投影语义
105
+
106
+ `contextBreakdown` 只保留存活的 `system/message` 节点及其启发式价格、一个 surface 运行总量,以及至多一个已武装的影子价 claim;替换减去紧邻的 claim(其 `shadowedSeqs` 同时列出被移除的系统提示词),或减去被改写的那个系统提示词的保留价格([决策](../../../.agents/notes/implemented/architecture/2026-10-13-context-breakdown-system-prompt-state.zh.md))。其状态取决于存活系统提示词的数量,而非消息数;状态版本 6 使位置检查点失效。`contextPressure` 是另一个标量影子价消费方:没有相邻 claim 的替换贡献零增量。用量 fold 保留一个最后样本槽,因为合法日志不会在更晚步骤报告用量后再次报告更早步骤的用量。
107
+
108
+ `./estimate` 导出无服务状态的文字与内容估算函数,供工具结果保留复用。图片的实际请求成本由模型适配器的 `imageRequestPricing` 提供。
109
+
110
+ </details>
111
+
112
+ -----
113
+
114
+ <a id="further-exploration"></a>
115
+ ## 进一步探索
116
+
117
+ 当包级约定不够用时阅读以下页面。它们从计量服务逐步进入压缩消费方与共享类型。
118
+
119
+ - [Token 计量子系统](../../../docs/subsystems/token-meter.zh.md)——`ctx.tokenMeter` 背后的测量语义。
120
+ - [open33-llm 服务](../llm/README.zh.md)——其容量元数据由 `resolveModelInfo()` 提供的模型调用服务。
121
+ - [压缩能力](../../../docs/subsystems/compaction.zh.md)——读取 `measure()` 的压力敏感消费方。
122
+ - [投影 token 用量](../../../.agents/notes/implemented/architecture/2026-07-29-projected-token-usage-and-request-context.zh.md)——`projectedTokens` 背后的设计与被否决的原子配对比较。
123
+ - [LLM 流式子系统](../../../docs/subsystems/llm-streaming.zh.md)——本服务计价的消息与块类型。
124
+
125
+ -----
126
+
127
+ <a id="model-experience"></a>
128
+ ## 模型体验
129
+
130
+ 间接地,通过 `open33-compaction-basic` 等消费方;服务本身不添加任何提示词、消息、schema、工具或模型调用。
131
+
132
+ #### KV Cache 影响
133
+
134
+ 不直接失效;任何请求前缀变更都由点名的消费方负责。
135
+
136
+ ## 已知限制与延期工作
137
+
138
+ <a id="known-limitations-and-deferred-work"></a>
139
+
140
+
141
+ 这些限制说明计量在哪里停止、由未来工作接续。它们是当前包约束,不是通用 token 计量对比或任务积压。
142
+
143
+ - **固定启发式规则是近似值**——没有可复用提供方用量的文本按字符数加结构开销计价,而非精确提供方分词器或请求序列化器;只有声明了定价的路由上的图片出现处携带提供方精确的视觉 token。
144
+ - **价格缓存为空时可扫描完整日志**——固定大小检查点恢复计量信息,不恢复逐节点价格或旧锚点的消息。请求头内容随价格缓存一起重建;热读取不增加日志访问。测量恢复仍可能读取检查点之前的日志。请求头引用与按日志重建的缓存不符时,会丢弃该缓存,从头执行原有计算。
145
+ - **每次测量都克隆当前表面**——连贯不可变快照让读取为 O(surface),包括低于阈值的压力检查。
146
+ - **提供方用量只在规范 envelope 完全相同时可复用**——工具、提供方、模型或调用配置变化会刻意回退到完整启发式估算;系统提示词变更在下一次成功调用之前按带符号的表面增量计量。
147
+ - **系统提示词改写不带影子价**——循环替换 system 节点时没有紧邻的计量事件,因此 `contextPressure.projectedTokens` 以零增量折叠该替换,直到下一个用量样本;`contextBreakdown.systemTokens` 与 `measure()` 会立即按新提示词重新计价。
148
+ - **构成检查点保留当前 surface**——精确的 system/message 分类需要位置条目;检查点大小和 surface 事件折叠成本为 O(当前保留 surface)。
149
+
150
+ <a id="dev-note"></a>
151
+ ### 开发备注
152
+
153
+ <details>
154
+ <summary>维护者的工作上下文——点击展开</summary>
155
+
156
+ 本开发备注是不具权威性的工作上下文:维护者备注与开放问题。已交付的行为与既定理由以上文、包代码和相关 Agent Note 为准。
157
+
158
+ - 固定每 token 四字符启发式规则会低估 CJK 文本与 JSON schema;复用用量时提供方锚点恰好携带该误差,请把构成行呈现为近似构成,绝不呈现为总量。
159
+ - 按提供方的精确分词器尚未决定;保持单一确定性启发式规则,正是让每个消费方的测量一致且回放稳定的原因。
160
+
161
+ </details>
162
+
163
+ 用量 fold 在每次尝试内替换样本,总量不必单调。构成和测量共享位置替换规划器与固定估算器,因此启发式 surface 总量按构造一致。路由定价总量有意与之不同。