dsh-context-compression-improved 0.2.4 → 0.2.5

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