dsh-context-compression-improved 0.9.7 → 0.9.9-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (240) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +15 -98
  3. package/README.zh.md +14 -92
  4. package/THIRD_PARTY_NOTICES.md +32 -14
  5. package/{packages/selector/cordis.patch.yml → cordis.patch.yml} +27 -27
  6. package/{packages/selector/dsh.plugin.json → dsh.plugin.json} +2 -2
  7. package/{packages/selector/lib → lib}/client.d.ts +16 -0
  8. package/{packages/selector/lib → lib}/client.js +393 -116
  9. package/{packages/selector/lib → lib}/index.js +829 -10
  10. package/{packages/selector/lib → lib}/invariant.js +2 -1
  11. package/{packages/selector/lib → lib}/pruner.d.ts +1 -1
  12. package/{packages/selector/lib → lib}/pruner.js +77 -983
  13. package/lib/savings-integral.js +4515 -0
  14. package/{packages/selector/lib → lib}/tail-trim.js +2 -90
  15. package/lib/tool-result.js +150 -0
  16. package/package.json +129 -116
  17. package/screenshots.json +3 -6
  18. package/.gitattributes +0 -2
  19. package/.githooks/pre-push +0 -37
  20. package/.github/workflows/ci.yml +0 -39
  21. package/CHANGELOG.de.md +0 -580
  22. package/CHANGELOG.es.md +0 -588
  23. package/CHANGELOG.fr.md +0 -576
  24. package/CHANGELOG.it.md +0 -577
  25. package/CHANGELOG.ja.md +0 -261
  26. package/CHANGELOG.ko.md +0 -254
  27. package/CHANGELOG.md +0 -532
  28. package/CHANGELOG.ru.md +0 -554
  29. package/CHANGELOG.zh.md +0 -236
  30. package/CONTRIBUTING.md +0 -22
  31. package/README.de.md +0 -96
  32. package/README.es.md +0 -96
  33. package/README.fr.md +0 -96
  34. package/README.it.md +0 -96
  35. package/README.ja.md +0 -102
  36. package/README.ko.md +0 -102
  37. package/README.ru.md +0 -96
  38. package/SECURITY.md +0 -18
  39. package/assets/board.png +0 -0
  40. package/assets/context.png +0 -0
  41. package/docs/assets/context-compression-selector-profiles.jpg +0 -0
  42. package/docs/assets/context-compression-selector-settings.png +0 -0
  43. package/docs/compat-0.1.5-report.md +0 -77
  44. package/docs/installation.de.md +0 -104
  45. package/docs/installation.es.md +0 -104
  46. package/docs/installation.fr.md +0 -104
  47. package/docs/installation.it.md +0 -104
  48. package/docs/installation.ja.md +0 -78
  49. package/docs/installation.ko.md +0 -78
  50. package/docs/installation.md +0 -103
  51. package/docs/installation.ru.md +0 -104
  52. package/docs/installation.zh.md +0 -100
  53. package/docs/repair-log.md +0 -657
  54. package/eslint.config.js +0 -30
  55. package/packages/selector/LICENSE +0 -21
  56. package/packages/selector/README.md +0 -26
  57. package/packages/selector/README.zh.md +0 -24
  58. package/packages/selector/THIRD_PARTY_NOTICES.md +0 -32
  59. package/packages/selector/docs/history-tool-call-working-set-spec.md +0 -112
  60. package/packages/selector/docs/native-tool-result-selector-spec.md +0 -34
  61. package/packages/selector/docs/subagent-cache-reuse-spec.md +0 -46
  62. package/packages/selector/lib/config.js +0 -1777
  63. package/packages/selector/lib/host-generation.js +0 -62
  64. package/packages/selector/lib/style.css +0 -350
  65. package/packages/selector/package.json +0 -174
  66. package/packages/selector/screenshots.json +0 -3
  67. package/packages/selector/src/client/CompressionProfileControls.tsx +0 -293
  68. package/packages/selector/src/client/CompressionProfileSelector.module.css +0 -199
  69. package/packages/selector/src/client/CompressionProfileSelector.tsx +0 -85
  70. package/packages/selector/src/client/CustomPolicyEditor.tsx +0 -216
  71. package/packages/selector/src/client/EstimatorControls.tsx +0 -277
  72. package/packages/selector/src/client/bridge-scope.ts +0 -125
  73. package/packages/selector/src/client/decode.ts +0 -57
  74. package/packages/selector/src/client/index.ts +0 -421
  75. package/packages/selector/src/client/locales/de.ts +0 -142
  76. package/packages/selector/src/client/locales/es.ts +0 -142
  77. package/packages/selector/src/client/locales/fr.ts +0 -142
  78. package/packages/selector/src/client/locales/it.ts +0 -142
  79. package/packages/selector/src/client/locales/ja.ts +0 -142
  80. package/packages/selector/src/client/locales/ko.ts +0 -142
  81. package/packages/selector/src/client/locales/ru.ts +0 -142
  82. package/packages/selector/src/client/locales.ts +0 -284
  83. package/packages/selector/src/client/monitor-fab.ts +0 -349
  84. package/packages/selector/src/client/preset-options.ts +0 -88
  85. package/packages/selector/src/client/savings-card.tsx +0 -150
  86. package/packages/selector/src/client/scope-face.ts +0 -24
  87. package/packages/selector/src/client/settings-section.tsx +0 -140
  88. package/packages/selector/src/compat/host-generation.ts +0 -96
  89. package/packages/selector/src/compat/llm-messages.ts +0 -50
  90. package/packages/selector/src/compat/settings-lease.ts +0 -108
  91. package/packages/selector/src/compat/tool-result.ts +0 -91
  92. package/packages/selector/src/css-modules.d.ts +0 -6
  93. package/packages/selector/src/deepseek-v4-tokenizer.ts +0 -205
  94. package/packages/selector/src/estimator-catalog.ts +0 -104
  95. package/packages/selector/src/index.ts +0 -655
  96. package/packages/selector/src/invariant.ts +0 -113
  97. package/packages/selector/src/preset-overlay.ts +0 -749
  98. package/packages/selector/src/profiles.ts +0 -431
  99. package/packages/selector/src/pruner/content.ts +0 -198
  100. package/packages/selector/src/pruner/session.ts +0 -97
  101. package/packages/selector/src/pruner/state.ts +0 -61
  102. package/packages/selector/src/pruner/tuning.ts +0 -23
  103. package/packages/selector/src/pruner/types.ts +0 -78
  104. package/packages/selector/src/pruner.ts +0 -2868
  105. package/packages/selector/src/runtime/adaptive-cost.ts +0 -205
  106. package/packages/selector/src/runtime/audit.ts +0 -303
  107. package/packages/selector/src/runtime/config.ts +0 -756
  108. package/packages/selector/src/runtime/custom-policy.ts +0 -278
  109. package/packages/selector/src/runtime/deepseek-official-pricing.ts +0 -298
  110. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +0 -254
  111. package/packages/selector/src/runtime/measurement.ts +0 -444
  112. package/packages/selector/src/runtime/monitor.ts +0 -235
  113. package/packages/selector/src/runtime/reducers.ts +0 -1754
  114. package/packages/selector/src/runtime/retrieve.ts +0 -484
  115. package/packages/selector/src/runtime/savings-projection.ts +0 -226
  116. package/packages/selector/src/runtime/savings.ts +0 -417
  117. package/packages/selector/src/runtime/session-events.ts +0 -30
  118. package/packages/selector/src/runtime/summary-command.ts +0 -127
  119. package/packages/selector/src/runtime/tail-trim.ts +0 -176
  120. package/packages/selector/src/runtime/token-count.ts +0 -72
  121. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +0 -233
  122. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +0 -204
  123. package/packages/selector/src/runtime/tokenpilot/advisor.ts +0 -419
  124. package/packages/selector/src/runtime/tokenpilot/benefit.ts +0 -200
  125. package/packages/selector/src/runtime/tokenpilot/dedup.ts +0 -81
  126. package/packages/selector/src/runtime/tokenpilot/estimator.ts +0 -151
  127. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +0 -53
  128. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +0 -65
  129. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +0 -125
  130. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +0 -37
  131. package/packages/selector/src/runtime/tokenpilot/locator.ts +0 -128
  132. package/packages/selector/src/runtime/tokenpilot/read-state.ts +0 -98
  133. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +0 -303
  134. package/packages/selector/src/runtime/toolclass.ts +0 -103
  135. package/packages/selector/src/runtime/types.ts +0 -365
  136. package/packages/selector/src/runtime/value.ts +0 -48
  137. package/packages/selector/src/settings-bridge.ts +0 -175
  138. package/packages/selector/tests/advisor-report.host.spec.ts +0 -223
  139. package/packages/selector/tests/auto-compact.client.spec.tsx +0 -214
  140. package/packages/selector/tests/built/client-artifact.spec.ts +0 -56
  141. package/packages/selector/tests/cache-prefix-audit.spec.ts +0 -123
  142. package/packages/selector/tests/code-skeleton.client.spec.ts +0 -98
  143. package/packages/selector/tests/compat/compat-narrow-waist.spec.ts +0 -150
  144. package/packages/selector/tests/custom-contract.client.spec.ts +0 -226
  145. package/packages/selector/tests/estimator-catalog.spec.ts +0 -70
  146. package/packages/selector/tests/estimator-channel.client.spec.tsx +0 -253
  147. package/packages/selector/tests/estimator-route-registration.host.spec.ts +0 -199
  148. package/packages/selector/tests/helpers/legacy-namespace.ts +0 -35
  149. package/packages/selector/tests/helpers/legacy-settings/index.ts +0 -15
  150. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +0 -41
  151. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +0 -647
  152. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +0 -78
  153. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +0 -234
  154. package/packages/selector/tests/host-preset-overlay.host.spec.ts +0 -204
  155. package/packages/selector/tests/monitor-fab.client.spec.ts +0 -138
  156. package/packages/selector/tests/preset-options-write.client.spec.ts +0 -192
  157. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +0 -200
  158. package/packages/selector/tests/preset-overlay.host.spec.ts +0 -246
  159. package/packages/selector/tests/profiles.client.spec.tsx +0 -436
  160. package/packages/selector/tests/public/package-contract.client.spec.ts +0 -86
  161. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +0 -167
  162. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +0 -230
  163. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +0 -272
  164. package/packages/selector/tests/runtime/advisor.spec.ts +0 -226
  165. package/packages/selector/tests/runtime/audit.spec.ts +0 -275
  166. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +0 -523
  167. package/packages/selector/tests/runtime/char-basis.spec.ts +0 -30
  168. package/packages/selector/tests/runtime/code-skeleton.spec.ts +0 -152
  169. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +0 -186
  170. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +0 -122
  171. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +0 -122
  172. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +0 -96
  173. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +0 -273
  174. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +0 -106
  175. package/packages/selector/tests/runtime/fixtures/vision-golden.json +0 -459
  176. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +0 -74
  177. package/packages/selector/tests/runtime/fresh-gate.spec.ts +0 -43
  178. package/packages/selector/tests/runtime/html-reducer.spec.ts +0 -212
  179. package/packages/selector/tests/runtime/intent-gate.spec.ts +0 -62
  180. package/packages/selector/tests/runtime/intent-summary.spec.ts +0 -156
  181. package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +0 -79
  182. package/packages/selector/tests/runtime/line-mapping.spec.ts +0 -153
  183. package/packages/selector/tests/runtime/monitor.spec.ts +0 -301
  184. package/packages/selector/tests/runtime/prose-reducers.spec.ts +0 -133
  185. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +0 -2782
  186. package/packages/selector/tests/runtime/read-input-cap.spec.ts +0 -33
  187. package/packages/selector/tests/runtime/savings-projection.spec.ts +0 -89
  188. package/packages/selector/tests/runtime/savings.spec.ts +0 -139
  189. package/packages/selector/tests/runtime/search-reducer.spec.ts +0 -110
  190. package/packages/selector/tests/runtime/session-events.spec.ts +0 -27
  191. package/packages/selector/tests/runtime/settings-unwrap.spec.ts +0 -58
  192. package/packages/selector/tests/runtime/sidechannel.spec.ts +0 -241
  193. package/packages/selector/tests/runtime/summary-command.spec.ts +0 -154
  194. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +0 -159
  195. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +0 -53
  196. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +0 -217
  197. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +0 -52
  198. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +0 -79
  199. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +0 -76
  200. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +0 -119
  201. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +0 -82
  202. package/packages/selector/tests/runtime/toolclass.spec.ts +0 -156
  203. package/packages/selector/tests/runtime/value.spec.ts +0 -23
  204. package/packages/selector/tests/settings-seat.client.spec.ts +0 -215
  205. package/packages/selector/tests/standing-generation.host.spec.ts +0 -724
  206. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +0 -269
  207. package/packages/selector/tests/support/cache-prefix-audit.ts +0 -105
  208. package/packages/selector/tests/support/mock-adapter.ts +0 -37
  209. package/packages/selector/tests/support/ui-primitives.tsx +0 -34
  210. package/packages/selector/tsconfig.json +0 -11
  211. package/packages/selector/tsdown.client.config.ts +0 -102
  212. package/packages/selector/tsdown.config.ts +0 -20
  213. package/pnpm-workspace.yaml +0 -72
  214. package/scripts/capture-profile-baseline.mjs +0 -42
  215. package/scripts/cell-browser-e2e.mjs +0 -354
  216. package/scripts/generate-tokenizer-fixtures.py +0 -81
  217. package/scripts/generate-vision-fixtures.py +0 -208
  218. package/scripts/hosts.mjs +0 -77
  219. package/scripts/packed-components-smoke.mjs +0 -763
  220. package/scripts/packed-install-e2e.mjs +0 -1346
  221. package/scripts/sync-hosts.mjs +0 -174
  222. package/scripts/toolclass-corpus-replay.mjs +0 -281
  223. package/scripts/verify-release.mjs +0 -335
  224. package/tests/TEST_INVENTORY.md +0 -41
  225. package/tsconfig.base.json +0 -18
  226. package/tsconfig.json +0 -7
  227. package/tsconfig.tests.json +0 -15
  228. package/vitest.built.config.ts +0 -9
  229. package/vitest.config.ts +0 -46
  230. /package/{packages/selector/assets → assets}/deepseek-v4/LICENSE.DeepSeek-V4-Pro.txt +0 -0
  231. /package/{packages/selector/assets → assets}/deepseek-v4/manifest.json +0 -0
  232. /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer.json +0 -0
  233. /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer_config.json +0 -0
  234. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/LICENSE.DeepSeek-V4-Flash-Vision-Exp.txt +0 -0
  235. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/manifest.json +0 -0
  236. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer.json +0 -0
  237. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer_config.json +0 -0
  238. /package/{packages/selector/lib → lib}/index.d.ts +0 -0
  239. /package/{packages/selector/lib → lib}/invariant.d.ts +0 -0
  240. /package/{packages/selector/lib → lib}/profiles.d.ts +0 -0
@@ -1,735 +1,10 @@
1
- import { B as decimalRateNanoUnits, F as recordIntentFold, H as resolveOfficialDeepSeekPrice, I as recordRecertified, L as recordScore, M as getSummaryOverride, N as invalidateOnTaskChange, O as evaluateIntentGate, P as observeIntentEnabled, T as observeContextUsage, U as getSavingsLedger, V as priceOfficialDeepSeekUsage, W as savingsHash, _ as resolveCustomPolicy, b as COMPRESSION_PROFILES, c as charsToTokens, d as isValidAutoCompactThresholdPercent, f as parseContextCompressionSettings, g as DEFAULT_CUSTOM_COMPRESSION_POLICY, h as CustomCompressionPolicySchema, i as DEFAULTS, k as getAdvisorState, l as codePointLength, m as resolvePolicy, n as CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, o as PRUNE_MARKER, p as resolveConfig, r as ContextCompressionSettingsSchema, s as charsForTokens, t as AUTO_COMPACT_THRESHOLD_LIMITS, u as isCompressionProfile, v as assertNever, y as deepFreeze, z as DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION } from "./config.js";
2
- import { a as validatePublishedTailTrim, c as eventBySeq, d as freezeMessage, i as tailTrimStub, l as sessionEvents, n as tailTrimMessage, o as compressionMessageSource, r as tailTrimRef, s as viewToolResult, t as parseTailTrimRef, u as createUserMessage } from "./tail-trim.js";
1
+ import { $ as isValidAutoCompactThresholdPercent, A as officialRequestUsage, At as recordRecertified, B as unavailableCount, Ct as getAdvisorState, D as dedupePlaceholder, Dt as invalidateOnTaskChange, E as dedupeHash, Et as getSummaryOverride, F as onlyTextBlocks, Ft as priceOfficialDeepSeekUsage, G as ContextCompressionSettingsSchema, H as countOmittedLines, I as pressureCost, It as resolveOfficialDeepSeekPrice, J as PRUNE_MARKER, K as DEFAULTS, L as recoveryMarker, Lt as getSavingsLedger, M as emptyResult, N as nativePruneContent, Nt as DEEPSEEK_OFFICIAL_PRICE_CATALOG_VERSION, O as flattenPlainText, Ot as observeIntentEnabled, P as onlyTextBlock, Pt as decimalRateNanoUnits, Q as isCompressionProfile, R as sameProviderMeasurementKey, St as evaluateIntentGate, T as DedupeTable, U as AUTO_COMPACT_THRESHOLD_LIMITS, V as CAPACITY_PRESSURE_RATIO, W as CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, X as charsToTokens, Y as charsForTokens, Z as codePointLength, _ as scheduleUsageFlush, at as resolveCustomPolicy, ct as COMPRESSION_PROFILES, d as claimFromLand, et as parseContextCompressionSettings, f as claimOffset, ft as deepSeekV4TokenizerForModel, g as reclaimFromTailTrim, it as DEFAULT_CUSTOM_COMPRESSION_POLICY, j as countToolContent, jt as recordScore, k as measureForCompaction, kt as recordIntentFold, lt as countExactCanonicalTextFields, m as flushUsageOnDispose, n as sampleIntegralBoundary, nt as resolvePolicy, o as kickStatsBackfillOnDispose, ot as assertNever, rt as CustomCompressionPolicySchema, st as deepFreeze, tt as resolveConfig, v as setStatsLivePathBusy, w as projectSessionSavings, yt as observeContextUsage, z as summarize } from "./savings-integral.js";
2
+ import { n as viewToolResult, o as eventBySeq, s as sessionEvents, t as compressionMessageSource } from "./tool-result.js";
3
+ import { a as validatePublishedTailTrim, i as tailTrimStub, n as tailTrimMessage, o as createUserMessage, r as tailTrimRef, s as freezeMessage, t as parseTailTrimRef } from "./tail-trim.js";
3
4
  import z from "@deepseek-ai/schemastery";
4
- import { createHash } from "node:crypto";
5
- import { Service } from "@deepseek-ai/cordis";
6
5
  import * as dshSessionNamespace from "@deepseek-ai/dsh-session";
7
- import { readFileSync } from "node:fs";
8
- import { Tokenizer } from "@huggingface/tokenizers";
6
+ import { Service } from "@deepseek-ai/cordis";
9
7
  import { defineTool } from "@deepseek-ai/dsh-tools";
10
- //#region src/deepseek-v4-tokenizer.ts
11
- /** Offline DeepSeek tokenizers backed by pinned official Hugging Face assets. */
12
- const TOKENIZER_ID = "deepseek-ai/DeepSeek-V4-Pro";
13
- const TOKENIZER_REVISION = "0e1a0e5e52aea73055f50fef6f2423db370265b6";
14
- const TOKENIZER_SHA256 = "8f9f37ca37fdc4f5fd36d5cf4d3b0e8392edb4e894fd10cc0d70b4957c8633cf";
15
- const CONFIG_SHA256 = "6ac8c8dc065ed118161d02dd532749ae3f52c243deac27872134fae2f50d8547";
16
- const VISION_TOKENIZER_ID = "deepseek-ai/DeepSeek-V4-Flash-Vision-Exp";
17
- const VISION_TOKENIZER_REVISION = "6821d6ad3681a4b137b066b76094fa82ebd0a380";
18
- const VISION_TOKENIZER_SHA256 = "c90dfa01249db1be4245780a052ede752e1361c612ac6d08e2bdada7d599476b";
19
- const VISION_CONFIG_SHA256 = "6ac8c8dc065ed118161d02dd532749ae3f52c243deac27872134fae2f50d8547";
20
- /** Auditable origin and compatibility mapping for the bundled V4 Pro tokenizer. */
21
- const DEEPSEEK_V4_TOKENIZER_ARTIFACT = Object.freeze({
22
- repository: TOKENIZER_ID,
23
- revision: TOKENIZER_REVISION,
24
- license: "MIT",
25
- tokenizerSha256: TOKENIZER_SHA256,
26
- tokenizerConfigSha256: CONFIG_SHA256,
27
- modelIds: Object.freeze(["deepseek-v4-flash", "deepseek-v4-pro"])
28
- });
29
- /**
30
- * Auditable origin and compatibility mapping for the bundled V4 Flash Vision
31
- * tokenizer. The vision repository ships a distinct `tokenizer.json` (it adds
32
- * the `<|deepseek_image|>` special token), so the vision model must never be
33
- * mapped onto the V4 Pro tokenizer as an alias.
34
- */
35
- const DEEPSEEK_VISION_TOKENIZER_ARTIFACT = Object.freeze({
36
- repository: VISION_TOKENIZER_ID,
37
- revision: VISION_TOKENIZER_REVISION,
38
- license: "MIT",
39
- tokenizerSha256: VISION_TOKENIZER_SHA256,
40
- tokenizerConfigSha256: VISION_CONFIG_SHA256,
41
- modelIds: Object.freeze(["deepseek-v4-flash-vision-exp"])
42
- });
43
- /**
44
- * Every bundled artifact is registered with independent asset roots, integrity
45
- * manifests, and cache entries: one corrupted artifact must never disable the
46
- * tokenizer serving the other model family.
47
- */
48
- const ARTIFACTS = Object.freeze([Object.freeze({
49
- origin: DEEPSEEK_V4_TOKENIZER_ARTIFACT,
50
- assetRoot: new URL("../assets/deepseek-v4/", import.meta.url),
51
- integrity: Object.freeze({
52
- tokenizer: Object.freeze({
53
- bytes: 6367146,
54
- sha256: TOKENIZER_SHA256
55
- }),
56
- config: Object.freeze({
57
- bytes: 801,
58
- sha256: CONFIG_SHA256
59
- })
60
- })
61
- }), Object.freeze({
62
- origin: DEEPSEEK_VISION_TOKENIZER_ARTIFACT,
63
- assetRoot: new URL("../assets/deepseek-v4-vision-exp/", import.meta.url),
64
- integrity: Object.freeze({
65
- tokenizer: Object.freeze({
66
- bytes: 6367257,
67
- sha256: VISION_TOKENIZER_SHA256
68
- }),
69
- config: Object.freeze({
70
- bytes: 801,
71
- sha256: VISION_CONFIG_SHA256
72
- })
73
- })
74
- })]);
75
- const registryCache = /* @__PURE__ */ new Map();
76
- function artifactForModel(modelId) {
77
- return ARTIFACTS.find((artifact) => artifact.origin.modelIds.includes(modelId));
78
- }
79
- /**
80
- * Resolve the shared offline tokenizer for one compatible API model.
81
- * Unknown models and a cached asset/runtime failure return `undefined`; callers
82
- * must report unavailable instead of manufacturing a character estimate.
83
- * @param modelId - exact DeepSeek API wire model id.
84
- * @returns the shared verified tokenizer, or undefined when unsupported/unavailable.
85
- */
86
- function deepSeekV4TokenizerForModel(modelId) {
87
- const artifact = artifactForModel(modelId);
88
- if (artifact === void 0) return void 0;
89
- const cached = registryCache.get(artifact.origin);
90
- if (cached !== void 0) return cached.tokenizer;
91
- let entry;
92
- try {
93
- entry = { tokenizer: createDeepSeekV4TokenizerFromAssets(artifact.assetRoot, artifact.integrity, artifact.origin) };
94
- } catch (error) {
95
- entry = { failure: error instanceof Error ? error.message : String(error) };
96
- }
97
- registryCache.set(artifact.origin, entry);
98
- return entry.tokenizer;
99
- }
100
- /**
101
- * Build a tokenizer from one local asset directory after byte/hash validation.
102
- * This provider-private seam exists so tests can prove every failure branch
103
- * without mutating the committed artifact.
104
- * @param assetRoot - local URL containing tokenizer.json and tokenizer_config.json.
105
- * @param integrity - expected byte length and SHA-256 for both files.
106
- * @param origin - auditable identity recorded on every returned count.
107
- * @returns a synchronous exact text counter.
108
- * @internal
109
- */
110
- function createDeepSeekV4TokenizerFromAssets(assetRoot, integrity, origin = DEEPSEEK_V4_TOKENIZER_ARTIFACT) {
111
- const tokenizerJson = readVerifiedJson(assetRoot, "tokenizer.json", integrity.tokenizer);
112
- const tokenizerConfig = readVerifiedJson(assetRoot, "tokenizer_config.json", integrity.config);
113
- const runtime = new Tokenizer(tokenizerJson, tokenizerConfig);
114
- return Object.freeze({ countText(text) {
115
- const tokens = runtime.encode(text, { add_special_tokens: false }).ids.length;
116
- return Object.freeze({
117
- kind: "exact-tokenizer",
118
- tokens,
119
- tokenizerId: origin.repository,
120
- tokenizerRevision: origin.revision
121
- });
122
- } });
123
- }
124
- function readVerifiedJson(assetRoot, name, descriptor) {
125
- const bytes = readFileSync(new URL(name, assetRoot));
126
- if (bytes.byteLength !== descriptor.bytes) throw new Error(`DeepSeek tokenizer asset ${name} has ${String(bytes.byteLength)} bytes; expected ${String(descriptor.bytes)}`);
127
- if (createHash("sha256").update(bytes).digest("hex") !== descriptor.sha256) throw new Error(`DeepSeek tokenizer asset ${name} failed SHA-256 verification`);
128
- const parsed = JSON.parse(bytes.toString("utf8"));
129
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error(`DeepSeek tokenizer asset ${name} must contain a JSON object`);
130
- return parsed;
131
- }
132
- //#endregion
133
- //#region src/runtime/deepseek-v4-vision-tokens.ts
134
- /**
135
- * Exact DeepSeek V4 Flash Vision image-token arithmetic.
136
- *
137
- * Every rule in this module is a line-by-line port of the official
138
- * `inference/image_processor.py` published by
139
- * `deepseek-ai/DeepSeek-V4-Flash-Vision-Exp` at the pinned immutable revision
140
- * recorded below. The golden fixtures in `tests/fixtures/vision-golden.json`
141
- * are generated by executing that official implementation, so any change here
142
- * must keep the Node counts byte-identical to the reference output.
143
- *
144
- * These arithmetic results back intrinsic-grid estimates, never exact counts
145
- * of the final request. The official expansion
146
- * depends on the absolute serialized prompt position (system prompt,
147
- * chat-template framing, adapter image handles) and on the adapter's final
148
- * request-image projection — including per-route pixel-budget or image-detail
149
- * overrides and byte-cap reprojection — none of which is published through a
150
- * public API, and a projected image can count FEWER tokens than its intrinsic
151
- * grid suggests. The measurement layer therefore labels image-bearing nodes
152
- * as estimates and keeps them outside exact rewrite proofs; the 640,000-pixel
153
- * budget below documents the adapter default rather than establishing
154
- * exactness.
155
- */
156
- /** Official projection parameters pinned from the model repository config. */
157
- const DEEPSEEK_VISION_PROJECTION = Object.freeze({
158
- sourceRepository: "deepseek-ai/DeepSeek-V4-Flash-Vision-Exp",
159
- sourceRevision: "6821d6ad3681a4b137b066b76094fa82ebd0a380",
160
- /** `vision_patch_size` from the official config. */
161
- visionPatchSize: 14,
162
- /** `vision_downsample_ratio` from the official config. */
163
- visionDownsampleRatio: 3,
164
- /** `vision_max_n_token`: post-preprocessing cap per image, not a fixed value. */
165
- visionMaxNTokens: 384,
166
- /** `vision_min_pixels`: tiny images are upscaled before patching. */
167
- visionMinPixels: 147456,
168
- /** `vision_max_wh_ratio`: wider-than-ratio images are width-clamped. */
169
- visionMaxWhRatio: 8,
170
- /**
171
- * Default per-image pixel budget used by the DeepSeek adapter's normal
172
- * attachment projection (`DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET` in
173
- * `@deepseek-ai/dsh-llm-deepseek`). Route overrides remain unobservable to
174
- * this estimator.
175
- */
176
- requestImagePixelBudget: 64e4
177
- });
178
- /** Stable identity for the deliberately approximate image-token counter. */
179
- const DEEPSEEK_VISION_IMAGE_ESTIMATOR = Object.freeze({
180
- id: `${DEEPSEEK_VISION_PROJECTION.sourceRepository}/image-token-estimate`,
181
- revision: `${DEEPSEEK_VISION_PROJECTION.sourceRevision}:v1`
182
- });
183
- /** Official `COMPRESS_PAD_TO` alignment constant from image_processor.py. */
184
- const COMPRESS_PAD_TO = 4;
185
- /**
186
- * Estimate one image without claiming an exact serialized position or final
187
- * adapter projection. Valid intrinsic dimensions use the midpoint of the four
188
- * possible alignment residues. Invalid or unsafe metadata uses the documented
189
- * fixed fallback. In both cases the official per-image budget is retained as
190
- * a conservative upper bound.
191
- */
192
- function estimateDeepSeekVisionImageTokens(width, height) {
193
- if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width <= 0 || height <= 0 || !Number.isSafeInteger(width * height)) return Object.freeze({
194
- tokens: 256,
195
- upperBoundTokens: DEEPSEEK_VISION_PROJECTION.visionMaxNTokens,
196
- source: "default"
197
- });
198
- try {
199
- const grid = deepSeekVisionImageGrid(width, height);
200
- const counts = [
201
- 0,
202
- 1,
203
- 2,
204
- 3
205
- ].map((position) => deepSeekVisionImageBlockTokens(grid.nLlmH, grid.nLlmW, position));
206
- const paddingMinimumTokens = Math.min(...counts);
207
- const paddingMaximumTokens = Math.max(...counts);
208
- return Object.freeze({
209
- tokens: Math.round((paddingMinimumTokens + paddingMaximumTokens) / 2),
210
- upperBoundTokens: DEEPSEEK_VISION_PROJECTION.visionMaxNTokens,
211
- source: "intrinsic-grid",
212
- paddingMinimumTokens,
213
- paddingMaximumTokens
214
- });
215
- } catch {
216
- return Object.freeze({
217
- tokens: 256,
218
- upperBoundTokens: DEEPSEEK_VISION_PROJECTION.visionMaxNTokens,
219
- source: "default"
220
- });
221
- }
222
- }
223
- /**
224
- * Resolve the aligner grid for one image's intrinsic dimensions.
225
- *
226
- * Port of the arithmetic path of the official `load_image`: aspect-ratio
227
- * clamp, minimum-pixel upscale, patch-grid ceiling, and the `safe_resize`
228
- * budget loop.
229
- */
230
- function deepSeekVisionImageGrid(width, height) {
231
- const { visionPatchSize: patch, visionMaxWhRatio, visionMinPixels } = DEEPSEEK_VISION_PROJECTION;
232
- let effectiveWidth = width;
233
- let effectiveHeight = height;
234
- if (visionMaxWhRatio !== void 0 && effectiveWidth > effectiveHeight * visionMaxWhRatio) effectiveWidth = effectiveHeight * visionMaxWhRatio;
235
- if (effectiveWidth * effectiveHeight > 0 && effectiveWidth * effectiveHeight < visionMinPixels) {
236
- const ratio = (visionMinPixels / (effectiveWidth * effectiveHeight)) ** .5;
237
- effectiveWidth = Math.trunc(effectiveWidth * ratio);
238
- effectiveHeight = Math.trunc(effectiveHeight * ratio);
239
- }
240
- const bestWidth = Math.ceil(effectiveWidth / patch) * patch;
241
- const bestHeight = Math.ceil(effectiveHeight / patch) * patch;
242
- const resolved = safeResize(effectiveHeight, effectiveWidth, bestHeight, bestWidth);
243
- return Object.freeze({ ...resolved });
244
- }
245
- /**
246
- * Token count of one expanded image block, port of `build_image_block` length.
247
- * @internal exported for direct golden-fixture comparison.
248
- */
249
- function deepSeekVisionImageBlockTokens(nLlmH, nLlmW, startTokenPos) {
250
- const compressPad = 3 - startTokenPos % COMPRESS_PAD_TO;
251
- const rows = nLlmH + nLlmH % 2;
252
- const rowLen = nLlmW + 1;
253
- const padLast = Math.floor(rows / 2) * rowLen % 2 * 2;
254
- return compressPad + 1 + rows * rowLen + padLast + 1;
255
- }
256
- /** Port of the official `grid_tokens` N-layout occupancy check. */
257
- function gridTokens(bestHeight, bestWidth) {
258
- const { visionPatchSize: patch, visionDownsampleRatio: downsample } = DEEPSEEK_VISION_PROJECTION;
259
- const nLlmH = Math.ceil(Math.floor(bestHeight / patch) / downsample);
260
- const nLlmW = Math.ceil(Math.floor(bestWidth / patch) / downsample);
261
- let numTokens = nLlmH * (nLlmW + 1) + 2;
262
- if (nLlmH % 2 === 1) numTokens += nLlmW + 1;
263
- numTokens += Math.floor((nLlmH + 1) / 2) * (nLlmW + 1) % 2 * 2;
264
- return {
265
- nLlmH,
266
- nLlmW,
267
- numTokens
268
- };
269
- }
270
- /** Port of the official `solve_resize_ratio` budget solver. */
271
- function solveResizeRatio(height, width, maxNTokens) {
272
- const { visionPatchSize: patch, visionDownsampleRatio: downsample } = DEEPSEEK_VISION_PROJECTION;
273
- const ratio = height / width;
274
- const maxWFloat = Math.sqrt((maxNTokens - 2) / ratio + .25) - .5;
275
- const maxHFloat = maxWFloat * ratio;
276
- let bestWidth;
277
- let bestHeight;
278
- if (maxWFloat < 1) {
279
- const maxW = 1;
280
- let maxH = Math.floor((maxNTokens - 2) / 2);
281
- if (maxH % 2 === 1) maxH -= 1;
282
- bestWidth = maxW * patch * downsample;
283
- bestHeight = maxH * patch * downsample;
284
- } else if (maxHFloat < 2) {
285
- const maxH = 2;
286
- const maxW = Math.floor((maxNTokens - 2) / maxH) - 1;
287
- if (maxW <= 1) throw new Error("DeepSeek vision resize solver produced an invalid width");
288
- bestWidth = maxW * patch * downsample;
289
- bestHeight = maxH * patch * downsample;
290
- } else {
291
- const maxW = Math.floor(maxWFloat);
292
- let maxH = Math.floor(maxHFloat);
293
- if (maxH % 2 === 1) maxH -= 1;
294
- const beta = Math.min(maxW * patch * downsample / width, maxH * patch * downsample / height);
295
- bestWidth = Math.floor(width * beta / patch) * patch;
296
- bestHeight = Math.floor(height * beta / patch) * patch;
297
- }
298
- const grid = gridTokens(bestHeight, bestWidth);
299
- return {
300
- nLlmH: grid.nLlmH,
301
- nLlmW: grid.nLlmW,
302
- bestHeight,
303
- bestWidth
304
- };
305
- }
306
- /** Port of the official `safe_resize` loop with the compress-pad budget. */
307
- function safeResize(height, width, initialBestHeight, initialBestWidth) {
308
- const { visionMaxNTokens } = DEEPSEEK_VISION_PROJECTION;
309
- let budget = visionMaxNTokens - 3;
310
- let grid = gridTokens(initialBestHeight, initialBestWidth);
311
- let bestHeight = initialBestHeight;
312
- let bestWidth = initialBestWidth;
313
- while (grid.numTokens > budget) {
314
- const solved = solveResizeRatio(height, width, budget);
315
- grid = gridTokens(solved.bestHeight, solved.bestWidth);
316
- bestHeight = solved.bestHeight;
317
- bestWidth = solved.bestWidth;
318
- budget -= 1;
319
- }
320
- return {
321
- nLlmH: grid.nLlmH,
322
- nLlmW: grid.nLlmW,
323
- bestHeight,
324
- bestWidth
325
- };
326
- }
327
- //#endregion
328
- //#region src/runtime/token-count.ts
329
- /** Build an explicit unavailable result without inventing an estimate. */
330
- function unavailableTokenCount(reason) {
331
- if (reason.length === 0) throw new TypeError("unavailable token count requires a reason");
332
- return Object.freeze({
333
- kind: "unavailable",
334
- reason
335
- });
336
- }
337
- /** Sum independent canonical fields only when every count has one identity. */
338
- function countExactCanonicalTextFields(fields, counter, subject) {
339
- if (subject.length === 0) throw new TypeError("canonical text field count requires a subject");
340
- const values = fields.length === 0 ? [""] : fields;
341
- let identity;
342
- let tokens = 0;
343
- for (const value of values) {
344
- const count = counter(value);
345
- if (count.kind !== "exact-tokenizer") return unavailableTokenCount(`${subject}: ${count.kind === "unavailable" ? count.reason : "canonical content requires an exact tokenizer count"}`);
346
- if (identity !== void 0 && (identity.tokenizerId !== count.tokenizerId || identity.tokenizerRevision !== count.tokenizerRevision)) return unavailableTokenCount(`${subject}: tokenizer identity changed within one measurement`);
347
- identity ??= count;
348
- tokens += count.tokens;
349
- if (!Number.isSafeInteger(tokens) || tokens < 0) return unavailableTokenCount(`${subject}: token sum is outside the safe integer range`);
350
- }
351
- if (identity === void 0) return unavailableTokenCount(`${subject}: no tokenizer identity`);
352
- return Object.freeze({
353
- ...identity,
354
- tokens
355
- });
356
- }
357
- /** Count the lines present in the original but absent from the replacement. */
358
- function countOmittedLines(original, replacement) {
359
- const omitted = original.split("\n").length - replacement.split("\n").length;
360
- return omitted > 0 ? omitted : void 0;
361
- }
362
- /** Routed-context utilization required before capacity-pressure History may age sent history. */
363
- const CAPACITY_PRESSURE_RATIO = .7;
364
- //#endregion
365
- //#region src/pruner/content.ts
366
- function onlyTextBlock(blocks) {
367
- return blocks.length === 1 && blocks[0]?.type === "text" ? blocks[0] : null;
368
- }
369
- function onlyTextBlocks(blocks) {
370
- return blocks.every((block) => block.type === "text") ? blocks : null;
371
- }
372
- function countToolContent(blocks, view) {
373
- const text = onlyTextBlocks(blocks);
374
- if (text === null) return unavailableCount("tool result contains unsupported rich content");
375
- return countExactCanonicalTextFields(text.map((block) => block.text), (candidate) => view.countCanonicalText(candidate), "tool result replacement");
376
- }
377
- function sameProviderMeasurementKey(left, right) {
378
- return left.provider === right.provider && left.baseUrlClass === right.baseUrlClass && left.apiRoute === right.apiRoute && left.modelId === right.modelId && left.requestTemplateRevision === right.requestTemplateRevision && left.tokenizerRevision === right.tokenizerRevision && left.modality === right.modality;
379
- }
380
- function unavailableCount(reason) {
381
- return Object.freeze({
382
- kind: "unavailable",
383
- reason
384
- });
385
- }
386
- function recoveryMarker(sourceRef, label, startLine) {
387
- return `\n\n[... ${label}; source=${sourceRef}; ${startLine === void 0 ? "use context_compression_retrieve with a query or narrow start_line/max_lines if needed (avoid re-reading the whole result)" : `retrieve with context_compression_retrieve({"ref":"${sourceRef}","start_line":${String(startLine)},"max_lines":80})`} ...]\n\n`;
388
- }
389
- /**
390
- * Measure text content in Unicode code points; non-text blocks cost zero.
391
- * @param blocks - tool-result content to measure.
392
- * @returns total Unicode code points across text blocks.
393
- */
394
- function measureContent(blocks) {
395
- let chars = 0;
396
- for (const block of blocks) if (block.type === "text") chars += codePointLength(block.text);
397
- return chars;
398
- }
399
- function pressureCost(blocks) {
400
- let cost = 0;
401
- for (const block of blocks) switch (block.type) {
402
- case "text":
403
- case "reasoning":
404
- cost += codePointLength(block.text);
405
- break;
406
- case "tool-call":
407
- cost += 256 + codePointLength(block.name) + codePointLength(block.arguments);
408
- break;
409
- default: {
410
- const serialized = JSON.stringify(block);
411
- cost += Math.max(256, codePointLength(serialized));
412
- }
413
- }
414
- return cost;
415
- }
416
- function nativePruneContent(blocks, thresholdChars, headChars, tailChars, marker = PRUNE_MARKER) {
417
- const totalChars = measureContent(blocks);
418
- if (totalChars <= thresholdChars) return null;
419
- const markerChars = codePointLength(typeof marker === "function" ? marker(1) : marker);
420
- const safeHead = Math.max(0, Math.min(headChars, thresholdChars - markerChars));
421
- const safeTail = Math.max(0, Math.min(tailChars, thresholdChars - markerChars - safeHead));
422
- const removedStart = safeHead;
423
- const removedEnd = totalChars - safeTail;
424
- const pruned = [];
425
- let consumed = 0;
426
- let markerInserted = false;
427
- let newlinesBefore = 0;
428
- for (const block of blocks) {
429
- if (block.type !== "text") {
430
- pruned.push(block);
431
- newlinesBefore += 1;
432
- continue;
433
- }
434
- const points = Array.from(block.text);
435
- const blockStart = consumed;
436
- const blockEnd = blockStart + points.length;
437
- const headEnd = Math.min(points.length, Math.max(0, removedStart - blockStart));
438
- const tailStart = Math.min(points.length, Math.max(0, removedEnd - blockStart));
439
- const intersectsRemoved = blockStart < removedEnd && blockEnd > removedStart;
440
- const headText = points.slice(0, headEnd).join("");
441
- const insertion = intersectsRemoved && !markerInserted && typeof marker === "function" ? marker(1 + newlinesBefore + headText.split("\n").length - 1) : intersectsRemoved && !markerInserted ? marker : "";
442
- if (insertion !== "") markerInserted = true;
443
- const text = points.slice(0, headEnd).join("") + insertion + points.slice(tailStart).join("");
444
- if (text !== "") pruned.push({
445
- ...block,
446
- text
447
- });
448
- newlinesBefore += block.text.split("\n").length - 1 + 1;
449
- consumed = blockEnd;
450
- }
451
- if (!markerInserted) return null;
452
- const charsAfter = measureContent(pruned);
453
- return charsAfter <= thresholdChars && charsAfter < totalChars ? pruned : null;
454
- }
455
- function summarize(entries) {
456
- return {
457
- pruned: entries,
458
- charsRemoved: entries.reduce((sum, entry) => sum + entry.charsBefore - entry.charsAfter, 0),
459
- tokensRemoved: entries.reduce((sum, entry) => sum + entry.tokensBefore - entry.tokensAfter, 0)
460
- };
461
- }
462
- function emptyResult() {
463
- return {
464
- pruned: [],
465
- charsRemoved: 0,
466
- tokensRemoved: 0
467
- };
468
- }
469
- //#endregion
470
- //#region src/runtime/measurement.ts
471
- const dshSessionSoft$1 = dshSessionNamespace;
472
- const deriveEventMessage = dshSessionSoft$1.deriveEventMessage ?? dshSessionSoft$1.default?.deriveEventMessage ?? (() => null);
473
- /**
474
- * Character pressure of one model-visible content array, measured on the same
475
- * level `SnapshotCandidate.characterPressure` uses: a tool/result message is
476
- * measured by its inner tool-result content, never by the wrapper block, so the
477
- * node-level and candidate-level figures stay directly comparable.
478
- * @param content - the node's model-visible content blocks.
479
- * @returns character pressure in Unicode code points, plus rich-block costs.
480
- */
481
- function nodeCharacterPressure(content) {
482
- return pressureCost(content);
483
- }
484
- const VISION_MODEL_ID = DEEPSEEK_VISION_TOKENIZER_ARTIFACT.modelIds[0];
485
- /**
486
- * Capture one route-bound view without calling patched Harness methods.
487
- * Official `measure()` remains authoritative for request pressure; the bundled
488
- * tokenizer supplies exact canonical content counts used by safe rewrites.
489
- */
490
- function measureForCompaction(ctx, session) {
491
- const header = session.requestHeader();
492
- const measurement = ctx.tokenMeter.measure(session, header);
493
- const target = header?.config;
494
- const counter = bindCounter(target?.provider, target?.model);
495
- const events = sessionEvents(session);
496
- const eventsBySeq = new Map(events.map((event) => [Number(event.seq), event]));
497
- const measuredNodes = measurement.nodes.map((node) => {
498
- const event = eventsBySeq.get(Number(node.seq));
499
- if (event === void 0) return {
500
- seq: node.seq,
501
- count: unavailableTokenCount(`surface node ${String(node.seq)} is missing`),
502
- characterPressure: 0
503
- };
504
- const message = deriveEventMessage(event);
505
- if (message === null) return {
506
- seq: node.seq,
507
- count: unavailableTokenCount(`surface node ${String(node.seq)} is not model-visible`),
508
- characterPressure: 0
509
- };
510
- const count = countCanonicalContent(message.content, counter, `surface node ${String(node.seq)}`);
511
- const intrinsicImageBlockEstimate = count.kind === "tokenizer-estimate" ? intrinsicImageDiagnostic(message.content, target) : void 0;
512
- return {
513
- seq: node.seq,
514
- count,
515
- characterPressure: nodeCharacterPressure(message.content),
516
- ...intrinsicImageBlockEstimate === void 0 ? {} : { intrinsicImageBlockEstimate }
517
- };
518
- });
519
- const currentSurface = countSurfaceCounts(measuredNodes.map((node) => node.count), "current surface");
520
- const currentSurfaceChars = measuredNodes.reduce((sum, node) => sum + node.characterPressure, 0);
521
- const intrinsicImageBlockEstimateTokens = measuredNodes.reduce((sum, node) => sum + (node.intrinsicImageBlockEstimate?.paddingMinimumTokens ?? 0), 0);
522
- return Object.freeze({
523
- ...measurement,
524
- ...target === void 0 ? {} : {
525
- providerRoute: target.provider,
526
- modelId: target.model
527
- },
528
- measuredNodes: Object.freeze(measuredNodes),
529
- currentSurface,
530
- currentSurfaceChars,
531
- intrinsicImageBlockEstimateTokens,
532
- countCanonicalText: counter.countText
533
- });
534
- }
535
- /** Request-level usage exposed by official TokenMeter, without invented route attribution. */
536
- function officialRequestUsage(view) {
537
- return view.baseline.kind === "usage" ? view.baseline.usage : void 0;
538
- }
539
- /**
540
- * Count one canonical content walk in canonical field order.
541
- *
542
- * Text, reasoning, tool-call names/arguments, and nested text tool results are
543
- * counted exactly with one tokenizer identity. Image blocks produce a bounded
544
- * estimate because the absolute prompt position and the adapter's final
545
- * projection are not publicly observable. A mixed text/image node is therefore
546
- * an estimate and never qualifies for an exact rewrite proof.
547
- */
548
- function countCanonicalContent(blocks, counter, subject) {
549
- let identity;
550
- let estimateIdentity;
551
- let tokens = 0;
552
- let upperBoundTokens = 0;
553
- let firstRefusal;
554
- const absorb = (count) => {
555
- if (count.kind === "unavailable") {
556
- firstRefusal ??= count;
557
- return false;
558
- }
559
- if (count.kind === "exact-tokenizer") {
560
- if (identity !== void 0 && (identity.tokenizerId !== count.tokenizerId || identity.tokenizerRevision !== count.tokenizerRevision)) {
561
- firstRefusal ??= unavailableTokenCount(`${subject}: tokenizer identity changed within one measurement`);
562
- return false;
563
- }
564
- identity ??= count;
565
- tokens += count.tokens;
566
- upperBoundTokens += count.tokens;
567
- } else {
568
- if (estimateIdentity !== void 0 && (estimateIdentity.estimatorId !== count.estimatorId || estimateIdentity.estimatorRevision !== count.estimatorRevision)) {
569
- firstRefusal ??= unavailableTokenCount(`${subject}: image estimator identity changed within one measurement`);
570
- return false;
571
- }
572
- estimateIdentity ??= {
573
- estimatorId: count.estimatorId,
574
- estimatorRevision: count.estimatorRevision
575
- };
576
- tokens += count.tokens;
577
- upperBoundTokens += count.upperBoundTokens;
578
- }
579
- return Number.isSafeInteger(tokens) && tokens >= 0 && Number.isSafeInteger(upperBoundTokens) && upperBoundTokens >= tokens;
580
- };
581
- const walk = (content) => {
582
- for (const block of content) switch (block.type) {
583
- case "text":
584
- case "reasoning":
585
- if (!absorb(counter.countText(block.text))) return false;
586
- break;
587
- case "tool-call":
588
- if (!absorb(counter.countText(block.name))) return false;
589
- if (!absorb(counter.countText(block.arguments))) return false;
590
- break;
591
- case "image":
592
- if (!absorb(counter.countImage(block.attachment))) return false;
593
- break;
594
- default:
595
- firstRefusal ??= unavailableTokenCount(`${subject}: contains an unsupported content block`);
596
- return false;
597
- }
598
- return true;
599
- };
600
- if (!walk(blocks)) {
601
- if (firstRefusal?.kind === "unavailable") return unavailableTokenCount(`${subject}: ${firstRefusal.reason}`);
602
- return unavailableTokenCount(`${subject}: contains content the canonical counter cannot count exactly`);
603
- }
604
- if (identity === void 0 && estimateIdentity === void 0) {
605
- const empty = counter.countText("");
606
- if (empty.kind !== "exact-tokenizer") return empty;
607
- return empty;
608
- }
609
- if (!Number.isSafeInteger(tokens) || tokens < 0) return unavailableTokenCount(`${subject}: invalid token sum`);
610
- if (estimateIdentity !== void 0) return Object.freeze({
611
- kind: "tokenizer-estimate",
612
- ...estimateIdentity,
613
- tokens,
614
- upperBoundTokens
615
- });
616
- if (identity === void 0) return unavailableTokenCount(`${subject}: no tokenizer identity`);
617
- return Object.freeze({
618
- ...identity,
619
- tokens
620
- });
621
- }
622
- function bindCounter(provider, model) {
623
- if (provider === void 0 || model === void 0) {
624
- const unavailable = () => unavailableTokenCount("canonical text: no durable provider/model request header");
625
- return {
626
- countText: unavailable,
627
- countImage: () => unavailableTokenCount("canonical image: no durable provider/model request header")
628
- };
629
- }
630
- if (provider !== "deepseek" && provider !== "deepseek-official") {
631
- const reason = `canonical text: provider "${provider}" is not the supported DeepSeek route`;
632
- return {
633
- countText: () => unavailableTokenCount(reason),
634
- countImage: () => unavailableTokenCount(`canonical image: provider "${provider}" is not the supported DeepSeek route`)
635
- };
636
- }
637
- const tokenizer = deepSeekV4TokenizerForModel(model);
638
- if (tokenizer === void 0) {
639
- const reason = `canonical text: no verified bundled tokenizer for model "${model}"`;
640
- return {
641
- countText: () => unavailableTokenCount(reason),
642
- countImage: (attachment) => countCanonicalImage(model, attachment)
643
- };
644
- }
645
- return {
646
- countText: (text) => tokenizer.countText(text),
647
- countImage: (attachment) => countCanonicalImage(model, attachment)
648
- };
649
- }
650
- /**
651
- * Images never claim an exact count. The official expansion depends on the
652
- * absolute prompt position (system prompt, chat-template framing, adapter
653
- * image handles) and on the adapter's final request-image projection, neither
654
- * of which is exposed through a public API; a route may even override the
655
- * pixel budget or re-project under the byte cap. Valid dimensions therefore
656
- * use the midpoint of the four alignment residues as a bounded estimate;
657
- * malformed dimensions use a fixed default. Estimate-bearing nodes remain
658
- * ineligible for exact rewrite proofs.
659
- */
660
- function countCanonicalImage(model, attachment) {
661
- if (model !== VISION_MODEL_ID) return unavailableTokenCount(`canonical image: model "${model}" has no vision image counter`);
662
- const estimate = estimateDeepSeekVisionImageTokens(attachment.width, attachment.height);
663
- return Object.freeze({
664
- kind: "tokenizer-estimate",
665
- tokens: estimate.tokens,
666
- upperBoundTokens: estimate.upperBoundTokens,
667
- estimatorId: DEEPSEEK_VISION_IMAGE_ESTIMATOR.id,
668
- estimatorRevision: DEEPSEEK_VISION_IMAGE_ESTIMATOR.revision
669
- });
670
- }
671
- /**
672
- * Intrinsic-grid diagnostic for one content walk: the official block
673
- * arithmetic on intrinsic dimensions at both alignment extremes. Only images
674
- * on the pinned DeepSeek vision route with usable metadata contribute.
675
- */
676
- function intrinsicImageDiagnostic(blocks, target) {
677
- if (target === void 0 || target.provider !== "deepseek" && target.provider !== "deepseek-official" || target.model !== VISION_MODEL_ID) return void 0;
678
- let paddingMinimumTokens = 0;
679
- let paddingMaximumTokens = 0;
680
- let seen = false;
681
- const walk = (content) => {
682
- for (const block of content) if (block.type === "image") {
683
- const { width, height } = block.attachment;
684
- const estimate = estimateDeepSeekVisionImageTokens(width, height);
685
- if (estimate.source !== "intrinsic-grid" || estimate.paddingMinimumTokens === void 0 || estimate.paddingMaximumTokens === void 0) continue;
686
- paddingMinimumTokens += estimate.paddingMinimumTokens;
687
- paddingMaximumTokens += estimate.paddingMaximumTokens;
688
- seen = true;
689
- }
690
- };
691
- walk(blocks);
692
- return seen ? Object.freeze({
693
- paddingMinimumTokens,
694
- paddingMaximumTokens
695
- }) : void 0;
696
- }
697
- function countSurfaceCounts(counts, subject) {
698
- if (counts.length === 0) return unavailableTokenCount(`${subject}: no surface nodes`);
699
- let identity;
700
- let estimateIdentity;
701
- let tokens = 0;
702
- let upperBoundTokens = 0;
703
- for (const count of counts) {
704
- if (count.kind === "unavailable") return unavailableTokenCount(`${subject}: ${count.reason}`);
705
- if (count.kind === "exact-tokenizer") {
706
- if (identity !== void 0 && (identity.tokenizerId !== count.tokenizerId || identity.tokenizerRevision !== count.tokenizerRevision)) return unavailableTokenCount(`${subject}: tokenizer identity changed within one measurement`);
707
- identity ??= count;
708
- tokens += count.tokens;
709
- upperBoundTokens += count.tokens;
710
- } else {
711
- if (estimateIdentity !== void 0 && (estimateIdentity.estimatorId !== count.estimatorId || estimateIdentity.estimatorRevision !== count.estimatorRevision)) return unavailableTokenCount(`${subject}: image estimator identity changed within one measurement`);
712
- estimateIdentity ??= {
713
- estimatorId: count.estimatorId,
714
- estimatorRevision: count.estimatorRevision
715
- };
716
- tokens += count.tokens;
717
- upperBoundTokens += count.upperBoundTokens;
718
- }
719
- }
720
- if (!Number.isSafeInteger(tokens) || tokens < 0 || !Number.isSafeInteger(upperBoundTokens) || upperBoundTokens < tokens) return unavailableTokenCount(`${subject}: invalid token sum`);
721
- if (estimateIdentity !== void 0) return Object.freeze({
722
- kind: "tokenizer-estimate",
723
- ...estimateIdentity,
724
- tokens,
725
- upperBoundTokens
726
- });
727
- if (identity === void 0) return unavailableTokenCount(`${subject}: no tokenizer identity`);
728
- return Object.freeze({
729
- ...identity,
730
- tokens
731
- });
732
- }
733
8
  z.object({
734
9
  maxChars: z.number().step(1).min(1).default(12e3),
735
10
  maxScanChars: z.number().step(1).min(1).default(25e4),
@@ -793,20 +68,25 @@ function installContextCompressionRetrieve(ctx, config = {}) {
793
68
  const match = REF_PATTERN.exec(args.ref);
794
69
  const tailTrimRef = parseTailTrimRef(args.ref);
795
70
  if (match === null && tailTrimRef === null) throw new Error("context_compression_retrieve: ref must be session://<session-id>/(event|tailtrim)/<seq>");
796
- if ((match?.[1] ?? tailTrimRef?.sessionId) !== String(exec.agent.id)) throw new Error("context_compression_retrieve: a compression reference may only read the caller's current session");
71
+ if ((match?.[1] ?? tailTrimRef?.sessionId) !== String(exec.agent.session.id)) throw new Error("context_compression_retrieve: a compression reference may only read the caller's current session");
797
72
  if (tailTrimRef !== null) {
798
- const sessionId = String(exec.agent.id);
73
+ const sessionId = String(exec.agent.session.id);
799
74
  return Promise.resolve(recoverTailTrim(exec.agent.session, args.ref, tailTrimRef.manifestSeq, args.query, args.start_line, args.max_lines, {
800
75
  maxChars,
801
76
  maxScanChars,
802
77
  maxQueryChars
803
78
  })).then((text) => {
804
- getSavingsLedger().recordOffset({
79
+ const offsetTokens = Math.ceil(codePointLength$1(text) / 4);
80
+ getSavingsLedger().foldRecall(sessionId, tailTrimRef.manifestSeq, offsetTokens, "characters", {
81
+ component: "tailtrim-retrieve",
82
+ note: `tailtrim/${tailTrimRef.manifestSeq} 回读`
83
+ });
84
+ claimOffset({
805
85
  sessionId,
806
86
  component: "tailtrim-retrieve",
807
- tokens: Math.ceil(codePointLength$1(text) / 4),
87
+ tokens: offsetTokens,
808
88
  basis: "characters",
809
- note: `tailtrim/${tailTrimRef.manifestSeq} 回读`
89
+ sourceSeq: tailTrimRef.manifestSeq
810
90
  });
811
91
  return text;
812
92
  });
@@ -833,13 +113,18 @@ function installContextCompressionRetrieve(ctx, config = {}) {
833
113
  selected.omitted ? query === void 0 || query === "" ? "note: additional source lines were omitted" : "note: additional matching or neighboring lines were omitted" : "",
834
114
  "--- original tool result ---"
835
115
  ].filter(Boolean).join("\n")}\n${selected.text}`, maxChars);
836
- getSavingsLedger().recordOffset({
837
- sessionId: String(exec.agent.id),
116
+ const offsetTokens = Math.ceil(codePointLength$1(bounded) / 4);
117
+ getSavingsLedger().foldRecall(String(exec.agent.session.id), seq, offsetTokens, "characters", {
838
118
  component: "retrieve",
839
- tokens: Math.ceil(codePointLength$1(bounded) / 4),
840
- basis: "characters",
841
119
  note: `event/${String(seq)} 回读`
842
120
  });
121
+ claimOffset({
122
+ sessionId: String(exec.agent.session.id),
123
+ component: "retrieve",
124
+ tokens: offsetTokens,
125
+ basis: "characters",
126
+ sourceSeq: seq
127
+ });
843
128
  return Promise.resolve(bounded);
844
129
  }
845
130
  }));
@@ -3842,236 +3127,6 @@ function renderIntentFoldBlock(pending, seq) {
3842
3127
  return `${INTENT_FOLD_MARKER} folded into the batch summary above (seq ${start}..${end})] ${face}`;
3843
3128
  }
3844
3129
  //#endregion
3845
- //#region src/runtime/tokenpilot/dedup.ts
3846
- /**
3847
- * TokenPilot-inspired A1: byte-identical repeated tool-result dedup.
3848
- *
3849
- * Pure helpers behind the ToolResultPruner fresh pass. The per-session table
3850
- * maps a canonical-content SHA-256 to the first surface seq that produced it;
3851
- * later identical results may be replaced with a pointer placeholder that the
3852
- * recovery tool can resolve back to the original full text via the append-only
3853
- * session log. Only hash+seq metadata is stored — never content.
3854
- */
3855
- /** Per-session dedup index with insertion-order eviction. */
3856
- var DedupeTable = class {
3857
- maxEntries;
3858
- entries = /* @__PURE__ */ new Map();
3859
- constructor(maxEntries = 2048) {
3860
- this.maxEntries = maxEntries;
3861
- }
3862
- /** Look up the first occurrence for one canonical hash, if any. */
3863
- get(hash) {
3864
- return this.entries.get(hash);
3865
- }
3866
- /** Record a first occurrence; existing hashes only refresh insertion order. */
3867
- record(hash, entry) {
3868
- if (this.entries.has(hash)) return;
3869
- while (this.entries.size >= this.maxEntries) {
3870
- const oldest = this.entries.keys().next().value;
3871
- if (oldest === void 0) break;
3872
- this.entries.delete(oldest);
3873
- }
3874
- this.entries.set(hash, entry);
3875
- }
3876
- };
3877
- /** Canonicalize tool-result text for hashing. */
3878
- function canonicalizeForDedupe(text, mode) {
3879
- if (mode === "exact") return text;
3880
- return text.replace(/[ \t]+\r?\n/g, "\n").replace(/(^\s+)|(\s+$)/g, "");
3881
- }
3882
- /** SHA-256 hex of the canonicalized text. */
3883
- function dedupeHash(text, mode) {
3884
- return createHash("sha256").update(canonicalizeForDedupe(text, mode), "utf8").digest("hex");
3885
- }
3886
- /** Concatenated text of an all-text content block list; null when rich. */
3887
- function flattenPlainText(content) {
3888
- let text = "";
3889
- for (const block of content) {
3890
- if (block.type !== "text") return void 0;
3891
- text += block.text;
3892
- }
3893
- return text;
3894
- }
3895
- /** Pointer placeholder pointing at the first occurrence's original event. */
3896
- function dedupePlaceholder(entry, originalChars) {
3897
- return [
3898
- `[... identical to the earlier ${entry.toolName} result; first seen at ${entry.sourceRef};`,
3899
- `original_chars=${String(originalChars)};`,
3900
- "retrieve with context_compression_retrieve({\"ref\":\"" + entry.sourceRef + "\",\"start_line\":1}) if the omitted evidence is necessary.]"
3901
- ].join(" ");
3902
- }
3903
- //#endregion
3904
- //#region src/runtime/savings-projection.ts
3905
- const EMPTY = Object.freeze({
3906
- savings: [],
3907
- offsets: [],
3908
- registry: []
3909
- });
3910
- function blocksOf(event) {
3911
- if (event.type !== "tool/result") return void 0;
3912
- return viewToolResult(event.data.message).blocks;
3913
- }
3914
- function textOf(event) {
3915
- const blocks = blocksOf(event);
3916
- return blocks === void 0 ? void 0 : flattenPlainText(blocks);
3917
- }
3918
- /** 与 pruner 的 `plan()` 同口径定价:全文本块可精确,否则字符口径。 */
3919
- function priceEvent(event, countText) {
3920
- const blocks = blocksOf(event);
3921
- if (blocks === void 0) return void 0;
3922
- const chars = pressureCost(blocks);
3923
- if (chars <= 0) return void 0;
3924
- const texts = blocks.map((block) => block.type === "text" ? block.text : void 0);
3925
- if (texts.every((text) => text !== void 0)) {
3926
- const count = countExactCanonicalTextFields(texts, countText, "savings projection");
3927
- if (count.kind === "exact-tokenizer") return {
3928
- tokens: count.tokens,
3929
- basis: "exact-tokenizer",
3930
- chars
3931
- };
3932
- }
3933
- return {
3934
- tokens: Math.max(1, charsToTokens(chars)),
3935
- basis: "characters",
3936
- chars
3937
- };
3938
- }
3939
- /** 替换事件的被替换 span;非替换节点(或畸形 op)返回 undefined。 */
3940
- function replacedSpan(event) {
3941
- const op = event.surfaceOp;
3942
- if (typeof op !== "object" || op === null || op.op !== "replace") return void 0;
3943
- const start = Number(op.startSeq);
3944
- const end = Number(op.endSeq);
3945
- if (!Number.isFinite(start) || !Number.isFinite(end) || end < start) return void 0;
3946
- return {
3947
- start,
3948
- end
3949
- };
3950
- }
3951
- function originalText(bySeq, span) {
3952
- const parts = [];
3953
- for (let seq = span.start; seq <= span.end; seq++) {
3954
- const event = bySeq.get(seq);
3955
- const text = event === void 0 ? void 0 : textOf(event);
3956
- if (text !== void 0 && text.length > 0) parts.push(text);
3957
- }
3958
- return parts.join("\n");
3959
- }
3960
- /**
3961
- * 一个替换节点"压掉了多少"(与实时 `plan()` 同口径:差额>0 才算)。
3962
- * 原始价 = span 内原始事件之和;替换价 = 替换事件。
3963
- */
3964
- function computeDelta(bySeq, replacement, span, counter) {
3965
- const after = priceEvent(replacement, counter);
3966
- if (after === void 0) return void 0;
3967
- let beforeChars = 0;
3968
- let beforeExactTokens = 0;
3969
- let beforeExact = true;
3970
- let any = false;
3971
- for (let seq = span.start; seq <= span.end; seq++) {
3972
- const original = bySeq.get(seq);
3973
- const priced = original === void 0 ? void 0 : priceEvent(original, counter);
3974
- if (priced === void 0) continue;
3975
- any = true;
3976
- beforeChars += priced.chars;
3977
- beforeExactTokens += priced.tokens;
3978
- if (priced.basis !== "exact-tokenizer") beforeExact = false;
3979
- }
3980
- if (!any) return void 0;
3981
- const exact = after.basis === "exact-tokenizer" && beforeExact;
3982
- const basis = exact ? "exact-tokenizer" : "characters";
3983
- const delta = (exact ? beforeExactTokens : charsToTokens(beforeChars)) - (exact ? after.tokens : charsToTokens(after.chars));
3984
- if (delta <= 0) return void 0;
3985
- return {
3986
- tokens: delta,
3987
- basis
3988
- };
3989
- }
3990
- /**
3991
- * 纯核心:给定事件流、当前 surface 节点与计价计数器,重算节省投影。
3992
- * @param input - events/surfaceNodes/counter,均为实时路径的只读快照。
3993
- * @returns savings(当前生效毛节省)/ offsets(每次重读惩罚)/ registry(原文配对键)。
3994
- */
3995
- function projectSavingsCore(input) {
3996
- const { events, surfaceNodes, counter } = input;
3997
- if (events.length === 0) return EMPTY;
3998
- const bySeq = /* @__PURE__ */ new Map();
3999
- for (const event of events) bySeq.set(Number(event.seq), event);
4000
- const savings = [];
4001
- for (const rawSeq of surfaceNodes) {
4002
- const seq = Number(rawSeq);
4003
- const replacement = bySeq.get(seq);
4004
- if (replacement === void 0) continue;
4005
- const span = replacedSpan(replacement);
4006
- if (span === void 0) continue;
4007
- const delta = computeDelta(bySeq, replacement, span, counter);
4008
- if (delta === void 0) continue;
4009
- savings.push({
4010
- component: "projection",
4011
- tokens: delta.tokens,
4012
- basis: delta.basis,
4013
- at: Number(replacement.time) || 0,
4014
- replacementSeq: seq
4015
- });
4016
- }
4017
- const offsets = [];
4018
- const registry = [];
4019
- const owned = /* @__PURE__ */ new Map();
4020
- for (const event of events) {
4021
- if (event.type !== "tool/result") continue;
4022
- const span = replacedSpan(event);
4023
- if (span !== void 0) {
4024
- const groupText = originalText(bySeq, span);
4025
- if (groupText.length === 0) continue;
4026
- const delta = computeDelta(bySeq, event, span, counter);
4027
- if (delta === void 0) continue;
4028
- const hash = savingsHash(groupText);
4029
- owned.set(hash, {
4030
- claimedTokens: delta.tokens,
4031
- basis: delta.basis,
4032
- sourceSeq: span.start
4033
- });
4034
- registry.push({
4035
- hash,
4036
- claimedTokens: delta.tokens,
4037
- basis: delta.basis,
4038
- sourceSeq: span.start
4039
- });
4040
- continue;
4041
- }
4042
- const text = textOf(event);
4043
- if (text === void 0 || text.length === 0) continue;
4044
- const hit = owned.get(savingsHash(text));
4045
- if (hit === void 0) continue;
4046
- const priced = priceEvent(event, counter);
4047
- if (priced === void 0) continue;
4048
- offsets.push({
4049
- component: "full-read",
4050
- tokens: priced.tokens,
4051
- basis: priced.basis,
4052
- at: Number(event.time) || 0,
4053
- note: `#${hit.sourceSeq} 的原文被全文重读(投影重建)`
4054
- });
4055
- }
4056
- return {
4057
- savings,
4058
- offsets,
4059
- registry
4060
- };
4061
- }
4062
- /**
4063
- * 从会话快照投影节省账。`measureForCompaction` 提供与实时同口径的 tokenizer
4064
- * 计数器;失败时向上抛,由调用方 fail-open。
4065
- */
4066
- function projectSessionSavings(ctx, session) {
4067
- const view = measureForCompaction(ctx, session);
4068
- return projectSavingsCore({
4069
- events: sessionEvents(session),
4070
- surfaceNodes: session.surface.nodes,
4071
- counter: (candidate) => view.countCanonicalText(candidate)
4072
- });
4073
- }
4074
- //#endregion
4075
3130
  //#region src/runtime/adaptive-cost.ts
4076
3131
  /**
4077
3132
  * Bound Adaptive's benefit and cache-loss exposure without attributing the
@@ -4202,6 +3257,10 @@ function emitCompressionAudit(logger, record) {
4202
3257
  logger.info(formatCompressionAudit(record));
4203
3258
  } catch {}
4204
3259
  }
3260
+ function sanitizeAuditMessage(error) {
3261
+ const collapsed = ((error instanceof Error ? error.message : String(error)).split(/\r?\n/u, 1)[0] ?? "").replace(/[\p{Cc}]/gu, " ").trim();
3262
+ return collapsed.length > 200 ? collapsed.slice(0, 200) : collapsed;
3263
+ }
4205
3264
  //#endregion
4206
3265
  //#region src/pruner.ts
4207
3266
  /**
@@ -4301,6 +3360,8 @@ var ToolResultPruner = class extends Service {
4301
3360
  try {
4302
3361
  ctx.on("session/disposed", (session) => {
4303
3362
  try {
3363
+ flushUsageOnDispose(session);
3364
+ kickStatsBackfillOnDispose();
4304
3365
  const line = getSavingsLedger().sessionSummaryLine(String(session.id));
4305
3366
  if (line.includes("requests=0") === false || line.includes("net=0(exact)/0(est)") === false) ctx.logger.info("context-compression session savings (%s): %s", String(session.id), line);
4306
3367
  } catch {}
@@ -4388,9 +3449,24 @@ var ToolResultPruner = class extends Service {
4388
3449
  const profile = policy.profile;
4389
3450
  const view = measureForCompaction(this.ctx, session);
4390
3451
  if (stage === "fresh") {
4391
- const usage = officialRequestUsage(view);
4392
- if (usage !== void 0) getSavingsLedger().recordUsage(String(session.id), usage);
4393
- return this.decideFreshStep(session, options, policy, view);
3452
+ setStatsLivePathBusy(true);
3453
+ try {
3454
+ const usage = officialRequestUsage(view);
3455
+ if (usage !== void 0) getSavingsLedger().recordUsage(String(session.id), usage);
3456
+ scheduleUsageFlush(session);
3457
+ try {
3458
+ const integralSessionId = String(session.id);
3459
+ sampleIntegralBoundary({
3460
+ sessionId: integralSessionId,
3461
+ session,
3462
+ net: getSavingsLedger().snapshot(integralSessionId).net,
3463
+ usage
3464
+ });
3465
+ } catch {}
3466
+ return this.decideFreshStep(session, options, policy, view);
3467
+ } finally {
3468
+ setStatsLivePathBusy(false);
3469
+ }
4394
3470
  }
4395
3471
  if (profile === "off") return emptyResult();
4396
3472
  const landed = [];
@@ -5356,7 +4432,8 @@ var ToolResultPruner = class extends Service {
5356
4432
  let head = this.state.config.headChars;
5357
4433
  let tail = this.state.config.tailChars;
5358
4434
  for (let attempt = 0; attempt < 10; attempt += 1) {
5359
- const content = nativePruneContent(resultContent, head + codePointLength(marker(1)) + tail, head, tail, marker);
4435
+ const threshold = head + codePointLength(marker(1)) + tail;
4436
+ const content = nativePruneContent(resultContent, threshold, head, tail, marker);
5360
4437
  if (content !== null) {
5361
4438
  const plan = this.plan(candidate, content, sourceSeq, "native-head-tail", stage, "native-tool-result", void 0, view);
5362
4439
  if (plan !== null && plan.tokensAfter <= policy.nativeTargetTokens) return plan;
@@ -5774,16 +4851,25 @@ var ToolResultPruner = class extends Service {
5774
4851
  tokenizerRevision: exact === true && exactSurface !== void 0 ? exactSurface.tokenizerRevision : "chars-per-token-4.0"
5775
4852
  });
5776
4853
  const groupText = shadowedSeqs.map((seq) => sessionEvents(session)[seq]).filter((event) => event?.type === "tool/result").map((event) => flattenPlainText(viewToolResult(event.data.message).blocks)).filter((text) => text !== void 0).join("\n");
5777
- if (groupText.length > 0) getSavingsLedger().recordSaving({
5778
- sessionId: String(session.id),
5779
- component: "tail-trim",
5780
- tokensBefore,
5781
- tokensAfter,
5782
- basis: exact ? "exact-tokenizer" : "characters",
5783
- sourceSeq: manifestSeq,
5784
- replacementSeq: Number(replacement.seq),
5785
- originalText: groupText
5786
- });
4854
+ if (groupText.length > 0) {
4855
+ getSavingsLedger().recordSaving({
4856
+ sessionId: String(session.id),
4857
+ component: "tail-trim",
4858
+ tokensBefore,
4859
+ tokensAfter,
4860
+ basis: exact ? "exact-tokenizer" : "characters",
4861
+ sourceSeq: manifestSeq,
4862
+ replacementSeq: Number(replacement.seq),
4863
+ originalText: groupText
4864
+ });
4865
+ reclaimFromTailTrim({
4866
+ sessionId: String(session.id),
4867
+ tokensBefore,
4868
+ tokensAfter,
4869
+ basis: exact ? "exact-tokenizer" : "characters",
4870
+ replacementSeq: Number(replacement.seq)
4871
+ });
4872
+ }
5787
4873
  return;
5788
4874
  }
5789
4875
  this.auditComponent(session, policy, "tail-trim", "pressure", "skipped", "no-safe-eligible-tool-group", {
@@ -5926,6 +5012,14 @@ var ToolResultPruner = class extends Service {
5926
5012
  replacementSeq: Number(replacement.seq),
5927
5013
  ...pairedOriginal === void 0 ? {} : { originalText: pairedOriginal }
5928
5014
  });
5015
+ claimFromLand({
5016
+ sessionId: String(session.id),
5017
+ component: plan.component,
5018
+ tokensBefore: plan.tokensBefore,
5019
+ tokensAfter: plan.tokensAfter,
5020
+ basis: plan.measurementBasis,
5021
+ replacementSeq: Number(replacement.seq)
5022
+ });
5929
5023
  return {
5930
5024
  originalSeq: candidate.seq,
5931
5025
  sourceSeq: plan.sourceSeq,
@@ -6063,7 +5157,7 @@ var ToolResultPruner = class extends Service {
6063
5157
  stage,
6064
5158
  operation,
6065
5159
  errorName: error instanceof Error ? error.name : "UnknownError",
6066
- errorMessage: error instanceof Error ? error.message : String(error)
5160
+ errorMessage: sanitizeAuditMessage(error)
6067
5161
  });
6068
5162
  }
6069
5163
  auditPublicationFailure(session, stage, component, manifestSeq, error) {