dsh-context-compression-improved 0.5.6 → 0.5.8

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 (183) hide show
  1. package/.gitattributes +2 -2
  2. package/.githooks/pre-push +37 -37
  3. package/.github/workflows/ci.yml +39 -39
  4. package/CHANGELOG.ja.md +169 -169
  5. package/CHANGELOG.ko.md +167 -167
  6. package/CHANGELOG.md +323 -304
  7. package/CHANGELOG.zh.md +152 -152
  8. package/CONTRIBUTING.md +22 -22
  9. package/LICENSE +21 -21
  10. package/README.ja.md +85 -85
  11. package/README.ko.md +85 -85
  12. package/README.md +94 -94
  13. package/README.zh.md +85 -85
  14. package/SECURITY.md +18 -18
  15. package/THIRD_PARTY_NOTICES.md +14 -14
  16. package/docs/compat-0.1.5-report.md +77 -77
  17. package/docs/installation.ja.md +78 -78
  18. package/docs/installation.ko.md +78 -78
  19. package/docs/installation.md +103 -103
  20. package/docs/installation.zh.md +100 -100
  21. package/docs/repair-log.md +657 -657
  22. package/eslint.config.js +30 -30
  23. package/package.json +163 -164
  24. package/packages/selector/LICENSE +21 -21
  25. package/packages/selector/README.md +26 -26
  26. package/packages/selector/README.zh.md +24 -24
  27. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -32
  28. package/packages/selector/cordis.patch.yml +27 -27
  29. package/packages/selector/docs/history-tool-call-working-set-spec.md +112 -112
  30. package/packages/selector/docs/native-tool-result-selector-spec.md +34 -34
  31. package/packages/selector/docs/subagent-cache-reuse-spec.md +46 -46
  32. package/packages/selector/dsh.plugin.json +16 -16
  33. package/packages/selector/lib/client.d.ts +59 -0
  34. package/packages/selector/lib/client.js +1738 -10
  35. package/packages/selector/lib/{advisor-state.js → config.js} +816 -65
  36. package/packages/selector/lib/index.d.ts +13 -1
  37. package/packages/selector/lib/index.js +295 -3
  38. package/packages/selector/lib/pruner.d.ts +65 -0
  39. package/packages/selector/lib/pruner.js +497 -262
  40. package/packages/selector/lib/style.css +88 -46
  41. package/packages/selector/package.json +114 -114
  42. package/packages/selector/screenshots.json +3 -3
  43. package/packages/selector/src/client/CompressionProfileControls.tsx +293 -226
  44. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  45. package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -83
  46. package/packages/selector/src/client/CustomPolicyEditor.tsx +216 -216
  47. package/packages/selector/src/client/EstimatorControls.tsx +277 -277
  48. package/packages/selector/src/client/decode.ts +57 -49
  49. package/packages/selector/src/client/index.ts +240 -149
  50. package/packages/selector/src/client/locales/de.ts +141 -0
  51. package/packages/selector/src/client/locales/es.ts +141 -0
  52. package/packages/selector/src/client/locales/fr.ts +141 -0
  53. package/packages/selector/src/client/locales/it.ts +141 -0
  54. package/packages/selector/src/client/locales/ja.ts +141 -0
  55. package/packages/selector/src/client/locales/ko.ts +141 -0
  56. package/packages/selector/src/client/locales/ru.ts +141 -0
  57. package/packages/selector/src/client/locales.ts +282 -196
  58. package/packages/selector/src/client/monitor-fab.ts +336 -0
  59. package/packages/selector/src/client/preset-options.ts +88 -88
  60. package/packages/selector/src/client/savings-card.tsx +150 -0
  61. package/packages/selector/src/client/settings-section.tsx +140 -124
  62. package/packages/selector/src/css-modules.d.ts +6 -6
  63. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -205
  64. package/packages/selector/src/estimator-catalog.ts +104 -104
  65. package/packages/selector/src/index.ts +673 -463
  66. package/packages/selector/src/invariant.ts +113 -113
  67. package/packages/selector/src/preset-overlay.ts +626 -626
  68. package/packages/selector/src/profiles.ts +431 -394
  69. package/packages/selector/src/pruner/content.ts +201 -201
  70. package/packages/selector/src/pruner/session.ts +94 -94
  71. package/packages/selector/src/pruner/state.ts +57 -50
  72. package/packages/selector/src/pruner/tuning.ts +23 -23
  73. package/packages/selector/src/pruner/types.ts +78 -78
  74. package/packages/selector/src/pruner.ts +2736 -2402
  75. package/packages/selector/src/runtime/adaptive-cost.ts +205 -205
  76. package/packages/selector/src/runtime/audit.ts +303 -286
  77. package/packages/selector/src/runtime/config.ts +756 -706
  78. package/packages/selector/src/runtime/custom-policy.ts +278 -278
  79. package/packages/selector/src/runtime/deepseek-official-pricing.ts +298 -298
  80. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +254 -254
  81. package/packages/selector/src/runtime/measurement.ts +436 -436
  82. package/packages/selector/src/runtime/monitor.ts +235 -0
  83. package/packages/selector/src/runtime/reducers.ts +1674 -1674
  84. package/packages/selector/src/runtime/retrieve.ts +479 -457
  85. package/packages/selector/src/runtime/savings.ts +337 -0
  86. package/packages/selector/src/runtime/session-events.ts +30 -30
  87. package/packages/selector/src/runtime/summary-command.ts +127 -0
  88. package/packages/selector/src/runtime/tail-trim.ts +166 -166
  89. package/packages/selector/src/runtime/token-count.ts +72 -72
  90. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -188
  91. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -149
  92. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -419
  93. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -200
  94. package/packages/selector/src/runtime/tokenpilot/dedup.ts +81 -81
  95. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -151
  96. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  97. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  98. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  99. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  100. package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -128
  101. package/packages/selector/src/runtime/tokenpilot/read-state.ts +98 -98
  102. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -303
  103. package/packages/selector/src/runtime/toolclass.ts +103 -103
  104. package/packages/selector/src/runtime/types.ts +365 -346
  105. package/packages/selector/src/runtime/value.ts +48 -48
  106. package/packages/selector/tests/advisor-report.host.spec.ts +223 -223
  107. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -213
  108. package/packages/selector/tests/built/client-artifact.spec.ts +59 -59
  109. package/packages/selector/tests/cache-prefix-audit.spec.ts +123 -123
  110. package/packages/selector/tests/code-skeleton.client.spec.ts +91 -90
  111. package/packages/selector/tests/custom-contract.client.spec.ts +205 -204
  112. package/packages/selector/tests/estimator-catalog.spec.ts +70 -70
  113. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -252
  114. package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -188
  115. package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -206
  116. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  117. package/packages/selector/tests/preset-options-write.client.spec.ts +207 -206
  118. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -201
  119. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -246
  120. package/packages/selector/tests/profiles.client.spec.tsx +436 -434
  121. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -78
  122. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +167 -167
  123. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -232
  124. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -272
  125. package/packages/selector/tests/runtime/advisor.spec.ts +226 -226
  126. package/packages/selector/tests/runtime/audit.spec.ts +275 -274
  127. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -523
  128. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -30
  129. package/packages/selector/tests/runtime/code-skeleton.spec.ts +152 -152
  130. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +186 -186
  131. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -122
  132. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +122 -122
  133. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -96
  134. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +273 -273
  135. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +106 -106
  136. package/packages/selector/tests/runtime/fixtures/vision-golden.json +459 -459
  137. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -74
  138. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -212
  139. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  140. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  141. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -153
  142. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  143. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -133
  144. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2724
  145. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -33
  146. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  147. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -110
  148. package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
  149. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -241
  150. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  151. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -159
  152. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +53 -53
  153. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -217
  154. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +52 -52
  155. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -79
  156. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +76 -76
  157. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -116
  158. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +82 -82
  159. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -156
  160. package/packages/selector/tests/runtime/value.spec.ts +23 -23
  161. package/packages/selector/tests/settings-seat.client.spec.ts +130 -118
  162. package/packages/selector/tests/standing-generation.host.spec.ts +697 -697
  163. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -253
  164. package/packages/selector/tests/support/cache-prefix-audit.ts +105 -105
  165. package/packages/selector/tests/support/mock-adapter.ts +37 -37
  166. package/packages/selector/tests/support/ui-primitives.tsx +34 -34
  167. package/packages/selector/tsconfig.json +11 -11
  168. package/packages/selector/tsdown.client.config.ts +102 -102
  169. package/packages/selector/tsdown.config.ts +20 -20
  170. package/pnpm-workspace.yaml +66 -66
  171. package/scripts/capture-profile-baseline.mjs +42 -42
  172. package/scripts/generate-tokenizer-fixtures.py +81 -81
  173. package/scripts/generate-vision-fixtures.py +208 -208
  174. package/scripts/packed-components-smoke.mjs +732 -732
  175. package/scripts/packed-install-e2e.mjs +1273 -1273
  176. package/scripts/toolclass-corpus-replay.mjs +281 -281
  177. package/scripts/verify-release.mjs +318 -317
  178. package/tests/TEST_INVENTORY.md +41 -41
  179. package/tsconfig.base.json +18 -18
  180. package/tsconfig.json +7 -7
  181. package/tsconfig.tests.json +15 -15
  182. package/vitest.built.config.ts +9 -9
  183. package/vitest.config.ts +43 -43
@@ -1,436 +1,436 @@
1
- /** Public-API-only measurement adapter for the standalone runtime. */
2
-
3
- import type { Context } from '@deepseek-ai/cordis'
4
- import type { ContentBlock, TokenUsage } from '@deepseek-ai/dsh-llm'
5
- import { deriveEventMessage } from '@deepseek-ai/dsh-session'
6
- import { sessionEvents } from './session-events.ts'
7
- import type { Session } from '@deepseek-ai/dsh-session'
8
- import type {} from '@deepseek-ai/dsh-token-meter'
9
- import type { TokenMeasurement } from '@deepseek-ai/dsh-token-meter'
10
- import {
11
- DEEPSEEK_VISION_TOKENIZER_ARTIFACT,
12
- deepSeekV4TokenizerForModel,
13
- } from '../deepseek-v4-tokenizer.ts'
14
- import {
15
- DEEPSEEK_VISION_IMAGE_ESTIMATOR,
16
- estimateDeepSeekVisionImageTokens,
17
- } from './deepseek-v4-vision-tokens.ts'
18
- import { unavailableTokenCount } from './token-count.ts'
19
- import { pressureCost } from '../pruner/content.ts'
20
- import type {
21
- CanonicalTextTokenCounter,
22
- ExactTokenizerTokenCount,
23
- TokenCount,
24
- TokenizerEstimateTokenCount,
25
- } from './token-count.ts'
26
-
27
- export type { TokenCount } from './token-count.ts'
28
-
29
- /**
30
- * Character pressure of one model-visible content array, measured on the same
31
- * level `SnapshotCandidate.characterPressure` uses: a tool/result message is
32
- * measured by its inner tool-result content, never by the wrapper block, so the
33
- * node-level and candidate-level figures stay directly comparable.
34
- * @param content - the node's model-visible content blocks.
35
- * @returns character pressure in Unicode code points, plus rich-block costs.
36
- */
37
- function nodeCharacterPressure(content: readonly ContentBlock[]): number {
38
- const only = content.length === 1 ? content[0] : undefined
39
- return pressureCost(only?.type === 'tool-result' ? only.content : content)
40
- }
41
-
42
- /** Request identity retained only when every dimension is publicly known. */
43
- export interface ProviderMeasurementKey {
44
- readonly provider: string
45
- readonly baseUrlClass: string
46
- readonly apiRoute: string
47
- readonly modelId: string
48
- readonly requestTemplateRevision: string
49
- readonly tokenizerRevision: string
50
- readonly modality: string
51
- }
52
-
53
- /** Rich request observation used by Adaptive when a future public API supplies it. */
54
- export interface ObservedPromptUsage {
55
- readonly attemptId: string
56
- readonly providerRequestOrdinal: number
57
- readonly startedAtMs: number
58
- readonly completedAtMs: number
59
- readonly measurement: TokenCount
60
- readonly observedPromptTokens: number
61
- readonly observedOutputTokens?: number
62
- readonly responseModelId?: string
63
- readonly cacheStatus?: 'complete' | 'unknown'
64
- readonly cacheReadTokens?: number
65
- readonly cacheMissTokens?: number
66
- readonly key?: ProviderMeasurementKey
67
- }
68
-
69
- /** Metadata-only image dimensions; the pixel payload is never read or logged. */
70
- export interface CanonicalImageAttachment {
71
- readonly width: number
72
- readonly height: number
73
- }
74
-
75
- /**
76
- * Intrinsic-grid diagnostic attached to nodes whose count estimates images.
77
- * It reports ONLY the official block
78
- * arithmetic evaluated on the attachment's intrinsic dimensions at the two
79
- * alignment-padding extremes (compress-pad 0 and 3). It is NOT a request-token
80
- * bound: the adapter may still re-project the image (per-route pixel-budget
81
- * or image-detail overrides, byte-cap reprojection), which can move the real
82
- * count below the diagnostic minimum. It never participates in exact gates,
83
- * rewrite proofs, or any lossy decision.
84
- */
85
- export interface IntrinsicImageBlockDiagnostic {
86
- readonly paddingMinimumTokens: number
87
- readonly paddingMaximumTokens: number
88
- }
89
-
90
- /** One same-revision surface node with exact, estimated, or unavailable count. */
91
- export interface MeasuredTokenSurfaceNode {
92
- readonly seq: number
93
- readonly count: TokenCount
94
- /**
95
- * Authoritative decision metric for this node: character pressure in
96
- * Unicode code points (same convention as SnapshotCandidate.characterPressure).
97
- */
98
- readonly characterPressure: number
99
- /** Intrinsic-grid diagnostic when usable image dimensions were available. */
100
- readonly intrinsicImageBlockEstimate?: IntrinsicImageBlockDiagnostic
101
- }
102
-
103
- /** Compression view derived only from published Session and TokenMeter methods. */
104
- export interface CompactionTokenView extends TokenMeasurement {
105
- readonly providerRoute?: string
106
- readonly modelId?: string
107
- readonly measuredNodes: readonly MeasuredTokenSurfaceNode[]
108
- readonly currentSurface: TokenCount
109
- /**
110
- * Exact character analogue of `currentSurface`: sum of per-node
111
- * `characterPressure` over the same nodes `currentSurface` covers.
112
- */
113
- readonly currentSurfaceChars: number
114
- /** Sum of per-node intrinsic padding minima; a diagnostic, not a token bound. */
115
- readonly intrinsicImageBlockEstimateTokens: number
116
- readonly latestEnvelopeKey?: ProviderMeasurementKey
117
- readonly lastCompletedUsage?: ObservedPromptUsage
118
- countCanonicalText(text: string): TokenCount
119
- }
120
-
121
- /** Text plus image gating for one durable request target. */
122
- interface CanonicalCounter {
123
- readonly countText: CanonicalTextTokenCounter
124
- readonly countImage: (attachment: CanonicalImageAttachment) => TokenCount
125
- }
126
-
127
- const VISION_MODEL_ID = DEEPSEEK_VISION_TOKENIZER_ARTIFACT.modelIds[0] as string
128
-
129
- /**
130
- * Capture one route-bound view without calling patched Harness methods.
131
- * Official `measure()` remains authoritative for request pressure; the bundled
132
- * tokenizer supplies exact canonical content counts used by safe rewrites.
133
- */
134
- export function measureForCompaction(ctx: Context, session: Session): CompactionTokenView {
135
- const header = session.requestHeader()
136
- const measurement = ctx.tokenMeter.measure(session, header)
137
- const target = header?.config
138
- const counter = bindCounter(target?.provider, target?.model)
139
- const events = sessionEvents(session)
140
- // 0.1.5 surface nodes are positional and may replace earlier ranges, so
141
- // their seq values are not guaranteed to equal the snapshot array index:
142
- // resolve events by seq, never by position.
143
- const eventsBySeq = new Map(events.map(event => [Number(event.seq), event]))
144
- const measuredNodes = measurement.nodes.map((node): MeasuredTokenSurfaceNode => {
145
- const event = eventsBySeq.get(Number(node.seq))
146
- if (event === undefined) {
147
- // The node's content is not model-visible, so it carries no character
148
- // pressure on the decision surface.
149
- return { seq: node.seq, count: unavailableTokenCount(`surface node ${String(node.seq)} is missing`), characterPressure: 0 }
150
- }
151
- const message = deriveEventMessage(event)
152
- if (message === null) {
153
- return { seq: node.seq, count: unavailableTokenCount(`surface node ${String(node.seq)} is not model-visible`), characterPressure: 0 }
154
- }
155
- const count = countCanonicalContent(message.content, counter, `surface node ${String(node.seq)}`)
156
- const intrinsicImageBlockEstimate = count.kind === 'tokenizer-estimate'
157
- ? intrinsicImageDiagnostic(message.content, target)
158
- : undefined
159
- return {
160
- seq: node.seq,
161
- count,
162
- characterPressure: nodeCharacterPressure(message.content),
163
- ...intrinsicImageBlockEstimate === undefined ? {} : { intrinsicImageBlockEstimate },
164
- }
165
- })
166
- const currentSurface = countSurfaceCounts(
167
- measuredNodes.map(node => node.count),
168
- 'current surface',
169
- )
170
- const currentSurfaceChars = measuredNodes.reduce((sum, node) => sum + node.characterPressure, 0)
171
- const intrinsicImageBlockEstimateTokens = measuredNodes.reduce(
172
- (sum, node) => sum + (node.intrinsicImageBlockEstimate?.paddingMinimumTokens ?? 0),
173
- 0,
174
- )
175
- return Object.freeze({
176
- ...measurement,
177
- ...(target === undefined ? {} : { providerRoute: target.provider, modelId: target.model }),
178
- measuredNodes: Object.freeze(measuredNodes),
179
- currentSurface,
180
- currentSurfaceChars,
181
- intrinsicImageBlockEstimateTokens,
182
- countCanonicalText: counter.countText,
183
- })
184
- }
185
-
186
- /** Request-level usage exposed by official TokenMeter, without invented route attribution. */
187
- export function officialRequestUsage(view: CompactionTokenView): Readonly<TokenUsage> | undefined {
188
- return view.baseline.kind === 'usage' ? view.baseline.usage : undefined
189
- }
190
-
191
- /**
192
- * Count one canonical content walk in canonical field order.
193
- *
194
- * Text, reasoning, tool-call names/arguments, and nested text tool results are
195
- * counted exactly with one tokenizer identity. Image blocks produce a bounded
196
- * estimate because the absolute prompt position and the adapter's final
197
- * projection are not publicly observable. A mixed text/image node is therefore
198
- * an estimate and never qualifies for an exact rewrite proof.
199
- */
200
- function countCanonicalContent(
201
- blocks: readonly ContentBlock[],
202
- counter: CanonicalCounter,
203
- subject: string,
204
- ): TokenCount {
205
- let identity: ExactTokenizerTokenCount | undefined
206
- let estimateIdentity: Pick<TokenizerEstimateTokenCount, 'estimatorId' | 'estimatorRevision'> | undefined
207
- let tokens = 0
208
- let upperBoundTokens = 0
209
- let firstRefusal: TokenCount | undefined
210
- const absorb = (count: TokenCount): boolean => {
211
- if (count.kind === 'unavailable') {
212
- firstRefusal ??= count
213
- return false
214
- }
215
- if (count.kind === 'exact-tokenizer') {
216
- if (identity !== undefined
217
- && (identity.tokenizerId !== count.tokenizerId
218
- || identity.tokenizerRevision !== count.tokenizerRevision)) {
219
- firstRefusal ??= unavailableTokenCount(`${subject}: tokenizer identity changed within one measurement`)
220
- return false
221
- }
222
- identity ??= count
223
- tokens += count.tokens
224
- upperBoundTokens += count.tokens
225
- } else {
226
- if (estimateIdentity !== undefined
227
- && (estimateIdentity.estimatorId !== count.estimatorId
228
- || estimateIdentity.estimatorRevision !== count.estimatorRevision)) {
229
- firstRefusal ??= unavailableTokenCount(`${subject}: image estimator identity changed within one measurement`)
230
- return false
231
- }
232
- estimateIdentity ??= {
233
- estimatorId: count.estimatorId,
234
- estimatorRevision: count.estimatorRevision,
235
- }
236
- tokens += count.tokens
237
- upperBoundTokens += count.upperBoundTokens
238
- }
239
- return Number.isSafeInteger(tokens) && tokens >= 0
240
- && Number.isSafeInteger(upperBoundTokens) && upperBoundTokens >= tokens
241
- }
242
- const walk = (content: readonly ContentBlock[]): boolean => {
243
- for (const block of content) {
244
- switch (block.type) {
245
- case 'text':
246
- case 'reasoning': {
247
- if (!absorb(counter.countText(block.text))) return false
248
- break
249
- }
250
- case 'tool-call': {
251
- if (!absorb(counter.countText(block.name))) return false
252
- if (!absorb(counter.countText(block.arguments))) return false
253
- break
254
- }
255
- case 'tool-result': {
256
- if (!walk(block.content)) return false
257
- break
258
- }
259
- case 'image': {
260
- if (!absorb(counter.countImage(block.attachment))) return false
261
- break
262
- }
263
- default: {
264
- firstRefusal ??= unavailableTokenCount(`${subject}: contains an unsupported content block`)
265
- return false
266
- }
267
- }
268
- }
269
- return true
270
- }
271
- if (!walk(blocks)) {
272
- if (firstRefusal?.kind === 'unavailable') {
273
- return unavailableTokenCount(`${subject}: ${firstRefusal.reason}`)
274
- }
275
- return unavailableTokenCount(`${subject}: contains content the canonical counter cannot count exactly`)
276
- }
277
- if (identity === undefined && estimateIdentity === undefined) {
278
- // Empty content is a legal durable shape; it keeps the exact-0 count with
279
- // the bound tokenizer identity instead of fail-opening the whole surface.
280
- const empty = counter.countText('')
281
- if (empty.kind !== 'exact-tokenizer') return empty
282
- return empty
283
- }
284
- if (!Number.isSafeInteger(tokens) || tokens < 0) {
285
- return unavailableTokenCount(`${subject}: invalid token sum`)
286
- }
287
- if (estimateIdentity !== undefined) {
288
- return Object.freeze({
289
- kind: 'tokenizer-estimate',
290
- ...estimateIdentity,
291
- tokens,
292
- upperBoundTokens,
293
- })
294
- }
295
- if (identity === undefined) return unavailableTokenCount(`${subject}: no tokenizer identity`)
296
- return Object.freeze({ ...identity, tokens })
297
- }
298
-
299
- function bindCounter(provider: string | undefined, model: string | undefined): CanonicalCounter {
300
- if (provider === undefined || model === undefined) {
301
- const unavailable = () => unavailableTokenCount('canonical text: no durable provider/model request header')
302
- return { countText: unavailable, countImage: () => unavailableTokenCount('canonical image: no durable provider/model request header') }
303
- }
304
- if (provider !== 'deepseek' && provider !== 'deepseek-official') {
305
- const reason = `canonical text: provider "${provider}" is not the supported DeepSeek route`
306
- return { countText: () => unavailableTokenCount(reason), countImage: () => unavailableTokenCount(`canonical image: provider "${provider}" is not the supported DeepSeek route`) }
307
- }
308
- const tokenizer = deepSeekV4TokenizerForModel(model)
309
- if (tokenizer === undefined) {
310
- const reason = `canonical text: no verified bundled tokenizer for model "${model}"`
311
- return {
312
- countText: () => unavailableTokenCount(reason),
313
- // Image arithmetic is independently pinned and does not need the text
314
- // tokenizer asset. A pure-image node can therefore retain its estimate
315
- // even when text measurement fails closed.
316
- countImage: attachment => countCanonicalImage(model, attachment),
317
- }
318
- }
319
- return {
320
- countText: (text: string) => tokenizer.countText(text),
321
- countImage: attachment => countCanonicalImage(model, attachment),
322
- }
323
- }
324
-
325
- /**
326
- * Images never claim an exact count. The official expansion depends on the
327
- * absolute prompt position (system prompt, chat-template framing, adapter
328
- * image handles) and on the adapter's final request-image projection, neither
329
- * of which is exposed through a public API; a route may even override the
330
- * pixel budget or re-project under the byte cap. Valid dimensions therefore
331
- * use the midpoint of the four alignment residues as a bounded estimate;
332
- * malformed dimensions use a fixed default. Estimate-bearing nodes remain
333
- * ineligible for exact rewrite proofs.
334
- */
335
- function countCanonicalImage(
336
- model: string,
337
- attachment: CanonicalImageAttachment,
338
- ): TokenCount {
339
- if (model !== VISION_MODEL_ID) {
340
- return unavailableTokenCount(`canonical image: model "${model}" has no vision image counter`)
341
- }
342
- const estimate = estimateDeepSeekVisionImageTokens(attachment.width, attachment.height)
343
- return Object.freeze({
344
- kind: 'tokenizer-estimate',
345
- tokens: estimate.tokens,
346
- upperBoundTokens: estimate.upperBoundTokens,
347
- estimatorId: DEEPSEEK_VISION_IMAGE_ESTIMATOR.id,
348
- estimatorRevision: DEEPSEEK_VISION_IMAGE_ESTIMATOR.revision,
349
- })
350
- }
351
-
352
- /**
353
- * Intrinsic-grid diagnostic for one content walk: the official block
354
- * arithmetic on intrinsic dimensions at both alignment extremes. Only images
355
- * on the pinned DeepSeek vision route with usable metadata contribute.
356
- */
357
- function intrinsicImageDiagnostic(
358
- blocks: readonly ContentBlock[],
359
- target: { readonly provider: string, readonly model: string } | undefined,
360
- ): IntrinsicImageBlockDiagnostic | undefined {
361
- // Mirror the gating route: only the DeepSeek vision route carries the
362
- // official-arithmetic bounds.
363
- if (target === undefined
364
- || (target.provider !== 'deepseek' && target.provider !== 'deepseek-official')
365
- || target.model !== VISION_MODEL_ID) return undefined
366
- let paddingMinimumTokens = 0
367
- let paddingMaximumTokens = 0
368
- let seen = false
369
- const walk = (content: readonly ContentBlock[]): void => {
370
- for (const block of content) {
371
- if (block.type === 'image') {
372
- const { width, height } = block.attachment
373
- const estimate = estimateDeepSeekVisionImageTokens(width, height)
374
- if (estimate.source !== 'intrinsic-grid'
375
- || estimate.paddingMinimumTokens === undefined
376
- || estimate.paddingMaximumTokens === undefined) continue
377
- paddingMinimumTokens += estimate.paddingMinimumTokens
378
- paddingMaximumTokens += estimate.paddingMaximumTokens
379
- seen = true
380
- } else if (block.type === 'tool-result') {
381
- walk(block.content)
382
- }
383
- }
384
- }
385
- walk(blocks)
386
- return seen ? Object.freeze({ paddingMinimumTokens, paddingMaximumTokens }) : undefined
387
- }
388
-
389
- function countSurfaceCounts(counts: readonly TokenCount[], subject: string): TokenCount {
390
- if (counts.length === 0) return unavailableTokenCount(`${subject}: no surface nodes`)
391
- let identity: Extract<TokenCount, { kind: 'exact-tokenizer' }> | undefined
392
- let estimateIdentity: Pick<TokenizerEstimateTokenCount, 'estimatorId' | 'estimatorRevision'> | undefined
393
- let tokens = 0
394
- let upperBoundTokens = 0
395
- for (const count of counts) {
396
- if (count.kind === 'unavailable') {
397
- return unavailableTokenCount(`${subject}: ${count.reason}`)
398
- }
399
- if (count.kind === 'exact-tokenizer') {
400
- if (identity !== undefined
401
- && (identity.tokenizerId !== count.tokenizerId
402
- || identity.tokenizerRevision !== count.tokenizerRevision)) {
403
- return unavailableTokenCount(`${subject}: tokenizer identity changed within one measurement`)
404
- }
405
- identity ??= count
406
- tokens += count.tokens
407
- upperBoundTokens += count.tokens
408
- } else {
409
- if (estimateIdentity !== undefined
410
- && (estimateIdentity.estimatorId !== count.estimatorId
411
- || estimateIdentity.estimatorRevision !== count.estimatorRevision)) {
412
- return unavailableTokenCount(`${subject}: image estimator identity changed within one measurement`)
413
- }
414
- estimateIdentity ??= {
415
- estimatorId: count.estimatorId,
416
- estimatorRevision: count.estimatorRevision,
417
- }
418
- tokens += count.tokens
419
- upperBoundTokens += count.upperBoundTokens
420
- }
421
- }
422
- if (!Number.isSafeInteger(tokens) || tokens < 0
423
- || !Number.isSafeInteger(upperBoundTokens) || upperBoundTokens < tokens) {
424
- return unavailableTokenCount(`${subject}: invalid token sum`)
425
- }
426
- if (estimateIdentity !== undefined) {
427
- return Object.freeze({
428
- kind: 'tokenizer-estimate',
429
- ...estimateIdentity,
430
- tokens,
431
- upperBoundTokens,
432
- })
433
- }
434
- if (identity === undefined) return unavailableTokenCount(`${subject}: no tokenizer identity`)
435
- return Object.freeze({ ...identity, tokens })
436
- }
1
+ /** Public-API-only measurement adapter for the standalone runtime. */
2
+
3
+ import type { Context } from '@deepseek-ai/cordis'
4
+ import type { ContentBlock, TokenUsage } from '@deepseek-ai/dsh-llm'
5
+ import { deriveEventMessage } from '@deepseek-ai/dsh-session'
6
+ import { sessionEvents } from './session-events.ts'
7
+ import type { Session } from '@deepseek-ai/dsh-session'
8
+ import type {} from '@deepseek-ai/dsh-token-meter'
9
+ import type { TokenMeasurement } from '@deepseek-ai/dsh-token-meter'
10
+ import {
11
+ DEEPSEEK_VISION_TOKENIZER_ARTIFACT,
12
+ deepSeekV4TokenizerForModel,
13
+ } from '../deepseek-v4-tokenizer.ts'
14
+ import {
15
+ DEEPSEEK_VISION_IMAGE_ESTIMATOR,
16
+ estimateDeepSeekVisionImageTokens,
17
+ } from './deepseek-v4-vision-tokens.ts'
18
+ import { unavailableTokenCount } from './token-count.ts'
19
+ import { pressureCost } from '../pruner/content.ts'
20
+ import type {
21
+ CanonicalTextTokenCounter,
22
+ ExactTokenizerTokenCount,
23
+ TokenCount,
24
+ TokenizerEstimateTokenCount,
25
+ } from './token-count.ts'
26
+
27
+ export type { TokenCount } from './token-count.ts'
28
+
29
+ /**
30
+ * Character pressure of one model-visible content array, measured on the same
31
+ * level `SnapshotCandidate.characterPressure` uses: a tool/result message is
32
+ * measured by its inner tool-result content, never by the wrapper block, so the
33
+ * node-level and candidate-level figures stay directly comparable.
34
+ * @param content - the node's model-visible content blocks.
35
+ * @returns character pressure in Unicode code points, plus rich-block costs.
36
+ */
37
+ function nodeCharacterPressure(content: readonly ContentBlock[]): number {
38
+ const only = content.length === 1 ? content[0] : undefined
39
+ return pressureCost(only?.type === 'tool-result' ? only.content : content)
40
+ }
41
+
42
+ /** Request identity retained only when every dimension is publicly known. */
43
+ export interface ProviderMeasurementKey {
44
+ readonly provider: string
45
+ readonly baseUrlClass: string
46
+ readonly apiRoute: string
47
+ readonly modelId: string
48
+ readonly requestTemplateRevision: string
49
+ readonly tokenizerRevision: string
50
+ readonly modality: string
51
+ }
52
+
53
+ /** Rich request observation used by Adaptive when a future public API supplies it. */
54
+ export interface ObservedPromptUsage {
55
+ readonly attemptId: string
56
+ readonly providerRequestOrdinal: number
57
+ readonly startedAtMs: number
58
+ readonly completedAtMs: number
59
+ readonly measurement: TokenCount
60
+ readonly observedPromptTokens: number
61
+ readonly observedOutputTokens?: number
62
+ readonly responseModelId?: string
63
+ readonly cacheStatus?: 'complete' | 'unknown'
64
+ readonly cacheReadTokens?: number
65
+ readonly cacheMissTokens?: number
66
+ readonly key?: ProviderMeasurementKey
67
+ }
68
+
69
+ /** Metadata-only image dimensions; the pixel payload is never read or logged. */
70
+ export interface CanonicalImageAttachment {
71
+ readonly width: number
72
+ readonly height: number
73
+ }
74
+
75
+ /**
76
+ * Intrinsic-grid diagnostic attached to nodes whose count estimates images.
77
+ * It reports ONLY the official block
78
+ * arithmetic evaluated on the attachment's intrinsic dimensions at the two
79
+ * alignment-padding extremes (compress-pad 0 and 3). It is NOT a request-token
80
+ * bound: the adapter may still re-project the image (per-route pixel-budget
81
+ * or image-detail overrides, byte-cap reprojection), which can move the real
82
+ * count below the diagnostic minimum. It never participates in exact gates,
83
+ * rewrite proofs, or any lossy decision.
84
+ */
85
+ export interface IntrinsicImageBlockDiagnostic {
86
+ readonly paddingMinimumTokens: number
87
+ readonly paddingMaximumTokens: number
88
+ }
89
+
90
+ /** One same-revision surface node with exact, estimated, or unavailable count. */
91
+ export interface MeasuredTokenSurfaceNode {
92
+ readonly seq: number
93
+ readonly count: TokenCount
94
+ /**
95
+ * Authoritative decision metric for this node: character pressure in
96
+ * Unicode code points (same convention as SnapshotCandidate.characterPressure).
97
+ */
98
+ readonly characterPressure: number
99
+ /** Intrinsic-grid diagnostic when usable image dimensions were available. */
100
+ readonly intrinsicImageBlockEstimate?: IntrinsicImageBlockDiagnostic
101
+ }
102
+
103
+ /** Compression view derived only from published Session and TokenMeter methods. */
104
+ export interface CompactionTokenView extends TokenMeasurement {
105
+ readonly providerRoute?: string
106
+ readonly modelId?: string
107
+ readonly measuredNodes: readonly MeasuredTokenSurfaceNode[]
108
+ readonly currentSurface: TokenCount
109
+ /**
110
+ * Exact character analogue of `currentSurface`: sum of per-node
111
+ * `characterPressure` over the same nodes `currentSurface` covers.
112
+ */
113
+ readonly currentSurfaceChars: number
114
+ /** Sum of per-node intrinsic padding minima; a diagnostic, not a token bound. */
115
+ readonly intrinsicImageBlockEstimateTokens: number
116
+ readonly latestEnvelopeKey?: ProviderMeasurementKey
117
+ readonly lastCompletedUsage?: ObservedPromptUsage
118
+ countCanonicalText(text: string): TokenCount
119
+ }
120
+
121
+ /** Text plus image gating for one durable request target. */
122
+ interface CanonicalCounter {
123
+ readonly countText: CanonicalTextTokenCounter
124
+ readonly countImage: (attachment: CanonicalImageAttachment) => TokenCount
125
+ }
126
+
127
+ const VISION_MODEL_ID = DEEPSEEK_VISION_TOKENIZER_ARTIFACT.modelIds[0] as string
128
+
129
+ /**
130
+ * Capture one route-bound view without calling patched Harness methods.
131
+ * Official `measure()` remains authoritative for request pressure; the bundled
132
+ * tokenizer supplies exact canonical content counts used by safe rewrites.
133
+ */
134
+ export function measureForCompaction(ctx: Context, session: Session): CompactionTokenView {
135
+ const header = session.requestHeader()
136
+ const measurement = ctx.tokenMeter.measure(session, header)
137
+ const target = header?.config
138
+ const counter = bindCounter(target?.provider, target?.model)
139
+ const events = sessionEvents(session)
140
+ // 0.1.5 surface nodes are positional and may replace earlier ranges, so
141
+ // their seq values are not guaranteed to equal the snapshot array index:
142
+ // resolve events by seq, never by position.
143
+ const eventsBySeq = new Map(events.map(event => [Number(event.seq), event]))
144
+ const measuredNodes = measurement.nodes.map((node): MeasuredTokenSurfaceNode => {
145
+ const event = eventsBySeq.get(Number(node.seq))
146
+ if (event === undefined) {
147
+ // The node's content is not model-visible, so it carries no character
148
+ // pressure on the decision surface.
149
+ return { seq: node.seq, count: unavailableTokenCount(`surface node ${String(node.seq)} is missing`), characterPressure: 0 }
150
+ }
151
+ const message = deriveEventMessage(event)
152
+ if (message === null) {
153
+ return { seq: node.seq, count: unavailableTokenCount(`surface node ${String(node.seq)} is not model-visible`), characterPressure: 0 }
154
+ }
155
+ const count = countCanonicalContent(message.content, counter, `surface node ${String(node.seq)}`)
156
+ const intrinsicImageBlockEstimate = count.kind === 'tokenizer-estimate'
157
+ ? intrinsicImageDiagnostic(message.content, target)
158
+ : undefined
159
+ return {
160
+ seq: node.seq,
161
+ count,
162
+ characterPressure: nodeCharacterPressure(message.content),
163
+ ...intrinsicImageBlockEstimate === undefined ? {} : { intrinsicImageBlockEstimate },
164
+ }
165
+ })
166
+ const currentSurface = countSurfaceCounts(
167
+ measuredNodes.map(node => node.count),
168
+ 'current surface',
169
+ )
170
+ const currentSurfaceChars = measuredNodes.reduce((sum, node) => sum + node.characterPressure, 0)
171
+ const intrinsicImageBlockEstimateTokens = measuredNodes.reduce(
172
+ (sum, node) => sum + (node.intrinsicImageBlockEstimate?.paddingMinimumTokens ?? 0),
173
+ 0,
174
+ )
175
+ return Object.freeze({
176
+ ...measurement,
177
+ ...(target === undefined ? {} : { providerRoute: target.provider, modelId: target.model }),
178
+ measuredNodes: Object.freeze(measuredNodes),
179
+ currentSurface,
180
+ currentSurfaceChars,
181
+ intrinsicImageBlockEstimateTokens,
182
+ countCanonicalText: counter.countText,
183
+ })
184
+ }
185
+
186
+ /** Request-level usage exposed by official TokenMeter, without invented route attribution. */
187
+ export function officialRequestUsage(view: CompactionTokenView): Readonly<TokenUsage> | undefined {
188
+ return view.baseline.kind === 'usage' ? view.baseline.usage : undefined
189
+ }
190
+
191
+ /**
192
+ * Count one canonical content walk in canonical field order.
193
+ *
194
+ * Text, reasoning, tool-call names/arguments, and nested text tool results are
195
+ * counted exactly with one tokenizer identity. Image blocks produce a bounded
196
+ * estimate because the absolute prompt position and the adapter's final
197
+ * projection are not publicly observable. A mixed text/image node is therefore
198
+ * an estimate and never qualifies for an exact rewrite proof.
199
+ */
200
+ function countCanonicalContent(
201
+ blocks: readonly ContentBlock[],
202
+ counter: CanonicalCounter,
203
+ subject: string,
204
+ ): TokenCount {
205
+ let identity: ExactTokenizerTokenCount | undefined
206
+ let estimateIdentity: Pick<TokenizerEstimateTokenCount, 'estimatorId' | 'estimatorRevision'> | undefined
207
+ let tokens = 0
208
+ let upperBoundTokens = 0
209
+ let firstRefusal: TokenCount | undefined
210
+ const absorb = (count: TokenCount): boolean => {
211
+ if (count.kind === 'unavailable') {
212
+ firstRefusal ??= count
213
+ return false
214
+ }
215
+ if (count.kind === 'exact-tokenizer') {
216
+ if (identity !== undefined
217
+ && (identity.tokenizerId !== count.tokenizerId
218
+ || identity.tokenizerRevision !== count.tokenizerRevision)) {
219
+ firstRefusal ??= unavailableTokenCount(`${subject}: tokenizer identity changed within one measurement`)
220
+ return false
221
+ }
222
+ identity ??= count
223
+ tokens += count.tokens
224
+ upperBoundTokens += count.tokens
225
+ } else {
226
+ if (estimateIdentity !== undefined
227
+ && (estimateIdentity.estimatorId !== count.estimatorId
228
+ || estimateIdentity.estimatorRevision !== count.estimatorRevision)) {
229
+ firstRefusal ??= unavailableTokenCount(`${subject}: image estimator identity changed within one measurement`)
230
+ return false
231
+ }
232
+ estimateIdentity ??= {
233
+ estimatorId: count.estimatorId,
234
+ estimatorRevision: count.estimatorRevision,
235
+ }
236
+ tokens += count.tokens
237
+ upperBoundTokens += count.upperBoundTokens
238
+ }
239
+ return Number.isSafeInteger(tokens) && tokens >= 0
240
+ && Number.isSafeInteger(upperBoundTokens) && upperBoundTokens >= tokens
241
+ }
242
+ const walk = (content: readonly ContentBlock[]): boolean => {
243
+ for (const block of content) {
244
+ switch (block.type) {
245
+ case 'text':
246
+ case 'reasoning': {
247
+ if (!absorb(counter.countText(block.text))) return false
248
+ break
249
+ }
250
+ case 'tool-call': {
251
+ if (!absorb(counter.countText(block.name))) return false
252
+ if (!absorb(counter.countText(block.arguments))) return false
253
+ break
254
+ }
255
+ case 'tool-result': {
256
+ if (!walk(block.content)) return false
257
+ break
258
+ }
259
+ case 'image': {
260
+ if (!absorb(counter.countImage(block.attachment))) return false
261
+ break
262
+ }
263
+ default: {
264
+ firstRefusal ??= unavailableTokenCount(`${subject}: contains an unsupported content block`)
265
+ return false
266
+ }
267
+ }
268
+ }
269
+ return true
270
+ }
271
+ if (!walk(blocks)) {
272
+ if (firstRefusal?.kind === 'unavailable') {
273
+ return unavailableTokenCount(`${subject}: ${firstRefusal.reason}`)
274
+ }
275
+ return unavailableTokenCount(`${subject}: contains content the canonical counter cannot count exactly`)
276
+ }
277
+ if (identity === undefined && estimateIdentity === undefined) {
278
+ // Empty content is a legal durable shape; it keeps the exact-0 count with
279
+ // the bound tokenizer identity instead of fail-opening the whole surface.
280
+ const empty = counter.countText('')
281
+ if (empty.kind !== 'exact-tokenizer') return empty
282
+ return empty
283
+ }
284
+ if (!Number.isSafeInteger(tokens) || tokens < 0) {
285
+ return unavailableTokenCount(`${subject}: invalid token sum`)
286
+ }
287
+ if (estimateIdentity !== undefined) {
288
+ return Object.freeze({
289
+ kind: 'tokenizer-estimate',
290
+ ...estimateIdentity,
291
+ tokens,
292
+ upperBoundTokens,
293
+ })
294
+ }
295
+ if (identity === undefined) return unavailableTokenCount(`${subject}: no tokenizer identity`)
296
+ return Object.freeze({ ...identity, tokens })
297
+ }
298
+
299
+ function bindCounter(provider: string | undefined, model: string | undefined): CanonicalCounter {
300
+ if (provider === undefined || model === undefined) {
301
+ const unavailable = () => unavailableTokenCount('canonical text: no durable provider/model request header')
302
+ return { countText: unavailable, countImage: () => unavailableTokenCount('canonical image: no durable provider/model request header') }
303
+ }
304
+ if (provider !== 'deepseek' && provider !== 'deepseek-official') {
305
+ const reason = `canonical text: provider "${provider}" is not the supported DeepSeek route`
306
+ return { countText: () => unavailableTokenCount(reason), countImage: () => unavailableTokenCount(`canonical image: provider "${provider}" is not the supported DeepSeek route`) }
307
+ }
308
+ const tokenizer = deepSeekV4TokenizerForModel(model)
309
+ if (tokenizer === undefined) {
310
+ const reason = `canonical text: no verified bundled tokenizer for model "${model}"`
311
+ return {
312
+ countText: () => unavailableTokenCount(reason),
313
+ // Image arithmetic is independently pinned and does not need the text
314
+ // tokenizer asset. A pure-image node can therefore retain its estimate
315
+ // even when text measurement fails closed.
316
+ countImage: attachment => countCanonicalImage(model, attachment),
317
+ }
318
+ }
319
+ return {
320
+ countText: (text: string) => tokenizer.countText(text),
321
+ countImage: attachment => countCanonicalImage(model, attachment),
322
+ }
323
+ }
324
+
325
+ /**
326
+ * Images never claim an exact count. The official expansion depends on the
327
+ * absolute prompt position (system prompt, chat-template framing, adapter
328
+ * image handles) and on the adapter's final request-image projection, neither
329
+ * of which is exposed through a public API; a route may even override the
330
+ * pixel budget or re-project under the byte cap. Valid dimensions therefore
331
+ * use the midpoint of the four alignment residues as a bounded estimate;
332
+ * malformed dimensions use a fixed default. Estimate-bearing nodes remain
333
+ * ineligible for exact rewrite proofs.
334
+ */
335
+ function countCanonicalImage(
336
+ model: string,
337
+ attachment: CanonicalImageAttachment,
338
+ ): TokenCount {
339
+ if (model !== VISION_MODEL_ID) {
340
+ return unavailableTokenCount(`canonical image: model "${model}" has no vision image counter`)
341
+ }
342
+ const estimate = estimateDeepSeekVisionImageTokens(attachment.width, attachment.height)
343
+ return Object.freeze({
344
+ kind: 'tokenizer-estimate',
345
+ tokens: estimate.tokens,
346
+ upperBoundTokens: estimate.upperBoundTokens,
347
+ estimatorId: DEEPSEEK_VISION_IMAGE_ESTIMATOR.id,
348
+ estimatorRevision: DEEPSEEK_VISION_IMAGE_ESTIMATOR.revision,
349
+ })
350
+ }
351
+
352
+ /**
353
+ * Intrinsic-grid diagnostic for one content walk: the official block
354
+ * arithmetic on intrinsic dimensions at both alignment extremes. Only images
355
+ * on the pinned DeepSeek vision route with usable metadata contribute.
356
+ */
357
+ function intrinsicImageDiagnostic(
358
+ blocks: readonly ContentBlock[],
359
+ target: { readonly provider: string, readonly model: string } | undefined,
360
+ ): IntrinsicImageBlockDiagnostic | undefined {
361
+ // Mirror the gating route: only the DeepSeek vision route carries the
362
+ // official-arithmetic bounds.
363
+ if (target === undefined
364
+ || (target.provider !== 'deepseek' && target.provider !== 'deepseek-official')
365
+ || target.model !== VISION_MODEL_ID) return undefined
366
+ let paddingMinimumTokens = 0
367
+ let paddingMaximumTokens = 0
368
+ let seen = false
369
+ const walk = (content: readonly ContentBlock[]): void => {
370
+ for (const block of content) {
371
+ if (block.type === 'image') {
372
+ const { width, height } = block.attachment
373
+ const estimate = estimateDeepSeekVisionImageTokens(width, height)
374
+ if (estimate.source !== 'intrinsic-grid'
375
+ || estimate.paddingMinimumTokens === undefined
376
+ || estimate.paddingMaximumTokens === undefined) continue
377
+ paddingMinimumTokens += estimate.paddingMinimumTokens
378
+ paddingMaximumTokens += estimate.paddingMaximumTokens
379
+ seen = true
380
+ } else if (block.type === 'tool-result') {
381
+ walk(block.content)
382
+ }
383
+ }
384
+ }
385
+ walk(blocks)
386
+ return seen ? Object.freeze({ paddingMinimumTokens, paddingMaximumTokens }) : undefined
387
+ }
388
+
389
+ function countSurfaceCounts(counts: readonly TokenCount[], subject: string): TokenCount {
390
+ if (counts.length === 0) return unavailableTokenCount(`${subject}: no surface nodes`)
391
+ let identity: Extract<TokenCount, { kind: 'exact-tokenizer' }> | undefined
392
+ let estimateIdentity: Pick<TokenizerEstimateTokenCount, 'estimatorId' | 'estimatorRevision'> | undefined
393
+ let tokens = 0
394
+ let upperBoundTokens = 0
395
+ for (const count of counts) {
396
+ if (count.kind === 'unavailable') {
397
+ return unavailableTokenCount(`${subject}: ${count.reason}`)
398
+ }
399
+ if (count.kind === 'exact-tokenizer') {
400
+ if (identity !== undefined
401
+ && (identity.tokenizerId !== count.tokenizerId
402
+ || identity.tokenizerRevision !== count.tokenizerRevision)) {
403
+ return unavailableTokenCount(`${subject}: tokenizer identity changed within one measurement`)
404
+ }
405
+ identity ??= count
406
+ tokens += count.tokens
407
+ upperBoundTokens += count.tokens
408
+ } else {
409
+ if (estimateIdentity !== undefined
410
+ && (estimateIdentity.estimatorId !== count.estimatorId
411
+ || estimateIdentity.estimatorRevision !== count.estimatorRevision)) {
412
+ return unavailableTokenCount(`${subject}: image estimator identity changed within one measurement`)
413
+ }
414
+ estimateIdentity ??= {
415
+ estimatorId: count.estimatorId,
416
+ estimatorRevision: count.estimatorRevision,
417
+ }
418
+ tokens += count.tokens
419
+ upperBoundTokens += count.upperBoundTokens
420
+ }
421
+ }
422
+ if (!Number.isSafeInteger(tokens) || tokens < 0
423
+ || !Number.isSafeInteger(upperBoundTokens) || upperBoundTokens < tokens) {
424
+ return unavailableTokenCount(`${subject}: invalid token sum`)
425
+ }
426
+ if (estimateIdentity !== undefined) {
427
+ return Object.freeze({
428
+ kind: 'tokenizer-estimate',
429
+ ...estimateIdentity,
430
+ tokens,
431
+ upperBoundTokens,
432
+ })
433
+ }
434
+ if (identity === undefined) return unavailableTokenCount(`${subject}: no tokenizer identity`)
435
+ return Object.freeze({ ...identity, tokens })
436
+ }