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