dsh-context-compression-improved 0.10.4 → 0.10.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 (268) hide show
  1. package/$null +1 -0
  2. package/.agents/plans/improve/checklist.md +32 -0
  3. package/.agents/plans/improve/findings.md +102 -0
  4. package/.agents/plans/improve/spec.md +53 -0
  5. package/.agents/plans/improve/tasks.md +70 -0
  6. package/.gitattributes +2 -0
  7. package/.githooks/pre-push +37 -0
  8. package/.github/workflows/ci.yml +47 -0
  9. package/CHANGELOG.de.md +580 -0
  10. package/CHANGELOG.es.md +588 -0
  11. package/CHANGELOG.fr.md +576 -0
  12. package/CHANGELOG.it.md +577 -0
  13. package/CHANGELOG.ja.md +261 -0
  14. package/CHANGELOG.ko.md +254 -0
  15. package/CHANGELOG.md +549 -0
  16. package/CHANGELOG.ru.md +554 -0
  17. package/CHANGELOG.zh.md +238 -0
  18. package/CONTRIBUTING.md +22 -0
  19. package/README.de.md +96 -0
  20. package/README.es.md +96 -0
  21. package/README.fr.md +96 -0
  22. package/README.it.md +96 -0
  23. package/README.ja.md +102 -0
  24. package/README.ko.md +102 -0
  25. package/README.md +110 -15
  26. package/README.ru.md +96 -0
  27. package/README.zh.md +104 -14
  28. package/SECURITY.md +18 -0
  29. package/THIRD_PARTY_NOTICES.md +7 -25
  30. package/assets/board.png +0 -0
  31. package/assets/context.png +0 -0
  32. package/docs/assets/context-compression-selector-profiles.jpg +0 -0
  33. package/docs/assets/context-compression-selector-settings.png +0 -0
  34. package/docs/compat-0.1.5-report.md +77 -0
  35. package/docs/installation.de.md +104 -0
  36. package/docs/installation.es.md +104 -0
  37. package/docs/installation.fr.md +104 -0
  38. package/docs/installation.it.md +104 -0
  39. package/docs/installation.ja.md +78 -0
  40. package/docs/installation.ko.md +78 -0
  41. package/docs/installation.md +103 -0
  42. package/docs/installation.ru.md +104 -0
  43. package/docs/installation.zh.md +100 -0
  44. package/docs/repair-log.md +657 -0
  45. package/eslint.config.js +30 -0
  46. package/package.json +113 -126
  47. package/packages/selector/LICENSE +21 -0
  48. package/packages/selector/README.md +26 -0
  49. package/packages/selector/README.zh.md +24 -0
  50. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -0
  51. package/packages/selector/docs/history-tool-call-working-set-spec.md +112 -0
  52. package/packages/selector/docs/native-tool-result-selector-spec.md +34 -0
  53. package/packages/selector/docs/subagent-cache-reuse-spec.md +46 -0
  54. package/packages/selector/lib/style.css +350 -0
  55. package/packages/selector/package.json +178 -0
  56. package/packages/selector/screenshots.json +3 -0
  57. package/packages/selector/src/client/CompressionProfileControls.tsx +319 -0
  58. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -0
  59. package/packages/selector/src/client/CompressionProfileSelector.tsx +87 -0
  60. package/packages/selector/src/client/CustomPolicyEditor.tsx +216 -0
  61. package/packages/selector/src/client/EstimatorControls.tsx +277 -0
  62. package/packages/selector/src/client/bridge-scope.ts +125 -0
  63. package/packages/selector/src/client/decode.ts +64 -0
  64. package/packages/selector/src/client/fab-pos.ts +71 -0
  65. package/packages/selector/src/client/index.ts +434 -0
  66. package/packages/selector/src/client/locales/de.ts +160 -0
  67. package/packages/selector/src/client/locales/es.ts +160 -0
  68. package/packages/selector/src/client/locales/fr.ts +160 -0
  69. package/packages/selector/src/client/locales/it.ts +160 -0
  70. package/packages/selector/src/client/locales/ja.ts +160 -0
  71. package/packages/selector/src/client/locales/ko.ts +160 -0
  72. package/packages/selector/src/client/locales/ru.ts +160 -0
  73. package/packages/selector/src/client/locales.ts +320 -0
  74. package/packages/selector/src/client/monitor-fab.ts +431 -0
  75. package/packages/selector/src/client/preset-options.ts +88 -0
  76. package/packages/selector/src/client/savings-card.tsx +269 -0
  77. package/packages/selector/src/client/scope-face.ts +24 -0
  78. package/packages/selector/src/client/settings-section.tsx +149 -0
  79. package/packages/selector/src/compat/host-generation.ts +96 -0
  80. package/packages/selector/src/compat/llm-messages.ts +50 -0
  81. package/packages/selector/src/compat/settings-lease.ts +108 -0
  82. package/packages/selector/src/compat/tool-result.ts +91 -0
  83. package/packages/selector/src/css-modules.d.ts +6 -0
  84. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -0
  85. package/packages/selector/src/estimator-catalog.ts +104 -0
  86. package/packages/selector/src/index.ts +890 -0
  87. package/packages/selector/src/invariant.ts +113 -0
  88. package/packages/selector/src/preset-overlay.ts +749 -0
  89. package/packages/selector/src/profiles.ts +451 -0
  90. package/packages/selector/src/pruner/content.ts +199 -0
  91. package/packages/selector/src/pruner/session.ts +97 -0
  92. package/packages/selector/src/pruner/state.ts +61 -0
  93. package/packages/selector/src/pruner/tuning.ts +23 -0
  94. package/packages/selector/src/pruner/types.ts +78 -0
  95. package/packages/selector/src/pruner.ts +2916 -0
  96. package/packages/selector/src/runtime/adaptive-cost.ts +205 -0
  97. package/packages/selector/src/runtime/audit.ts +320 -0
  98. package/packages/selector/src/runtime/config.ts +800 -0
  99. package/packages/selector/src/runtime/custom-policy.ts +300 -0
  100. package/packages/selector/src/runtime/deepseek-official-pricing.ts +298 -0
  101. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +254 -0
  102. package/packages/selector/src/runtime/display-prefs.ts +98 -0
  103. package/packages/selector/src/runtime/measurement.ts +444 -0
  104. package/packages/selector/src/runtime/monitor.ts +310 -0
  105. package/packages/selector/src/runtime/panel-command.ts +213 -0
  106. package/packages/selector/src/runtime/reducers.ts +1755 -0
  107. package/packages/selector/src/runtime/retrieve.ts +505 -0
  108. package/packages/selector/src/runtime/savings-integral.ts +117 -0
  109. package/packages/selector/src/runtime/savings-projection.ts +229 -0
  110. package/packages/selector/src/runtime/savings-verify.ts +446 -0
  111. package/packages/selector/src/runtime/savings.ts +526 -0
  112. package/packages/selector/src/runtime/session-events.ts +30 -0
  113. package/packages/selector/src/runtime/session-file-decode.ts +523 -0
  114. package/packages/selector/src/runtime/stats-backfill.ts +541 -0
  115. package/packages/selector/src/runtime/stats-db.ts +492 -0
  116. package/packages/selector/src/runtime/stats-schema.ts +123 -0
  117. package/packages/selector/src/runtime/stats-sync.ts +307 -0
  118. package/packages/selector/src/runtime/summary-command.ts +127 -0
  119. package/packages/selector/src/runtime/tail-trim.ts +177 -0
  120. package/packages/selector/src/runtime/token-count.ts +72 -0
  121. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
  122. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
  123. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
  124. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
  125. package/packages/selector/src/runtime/tokenpilot/dedup.ts +82 -0
  126. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -0
  127. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  128. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  129. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  130. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  131. package/packages/selector/src/runtime/tokenpilot/locator.ts +129 -0
  132. package/packages/selector/src/runtime/tokenpilot/read-state.ts +98 -0
  133. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -0
  134. package/packages/selector/src/runtime/tool-names.ts +36 -0
  135. package/packages/selector/src/runtime/toolclass.ts +103 -0
  136. package/packages/selector/src/runtime/types.ts +368 -0
  137. package/packages/selector/src/runtime/value.ts +48 -0
  138. package/packages/selector/src/settings-bridge.ts +175 -0
  139. package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
  140. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -0
  141. package/packages/selector/tests/built/client-artifact.spec.ts +56 -0
  142. package/packages/selector/tests/cache-prefix-audit.spec.ts +123 -0
  143. package/packages/selector/tests/code-skeleton.client.spec.ts +98 -0
  144. package/packages/selector/tests/compat/compat-narrow-waist.spec.ts +150 -0
  145. package/packages/selector/tests/custom-contract.client.spec.ts +226 -0
  146. package/packages/selector/tests/estimator-catalog.spec.ts +70 -0
  147. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -0
  148. package/packages/selector/tests/estimator-route-registration.host.spec.ts +202 -0
  149. package/packages/selector/tests/fab-pos.client.spec.ts +47 -0
  150. package/packages/selector/tests/helpers/legacy-namespace.ts +35 -0
  151. package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -0
  152. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -0
  153. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -0
  154. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -0
  155. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -0
  156. package/packages/selector/tests/host-preset-overlay.host.spec.ts +204 -0
  157. package/packages/selector/tests/monitor-fab.client.spec.ts +240 -0
  158. package/packages/selector/tests/preset-options-write.client.spec.ts +192 -0
  159. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +200 -0
  160. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -0
  161. package/packages/selector/tests/profiles.client.spec.tsx +436 -0
  162. package/packages/selector/tests/ptc-custom-write.client.spec.ts +86 -0
  163. package/packages/selector/tests/public/package-contract.client.spec.ts +86 -0
  164. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +167 -0
  165. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +230 -0
  166. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
  167. package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
  168. package/packages/selector/tests/runtime/audit.spec.ts +275 -0
  169. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -0
  170. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -0
  171. package/packages/selector/tests/runtime/code-skeleton.spec.ts +152 -0
  172. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +186 -0
  173. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -0
  174. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +122 -0
  175. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
  176. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +273 -0
  177. package/packages/selector/tests/runtime/fixtures/session-v4-dump.jsonl +46 -0
  178. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +106 -0
  179. package/packages/selector/tests/runtime/fixtures/vision-golden.json +459 -0
  180. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -0
  181. package/packages/selector/tests/runtime/fresh-gate.spec.ts +43 -0
  182. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -0
  183. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  184. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  185. package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +79 -0
  186. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -0
  187. package/packages/selector/tests/runtime/monitor.spec.ts +354 -0
  188. package/packages/selector/tests/runtime/panel-command.spec.ts +101 -0
  189. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -0
  190. package/packages/selector/tests/runtime/ptc-profile.spec.ts +133 -0
  191. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2795 -0
  192. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -0
  193. package/packages/selector/tests/runtime/savings-accounting.spec.ts +291 -0
  194. package/packages/selector/tests/runtime/savings-integral.spec.ts +169 -0
  195. package/packages/selector/tests/runtime/savings-projection.spec.ts +89 -0
  196. package/packages/selector/tests/runtime/savings-verify.spec.ts +226 -0
  197. package/packages/selector/tests/runtime/savings.spec.ts +139 -0
  198. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -0
  199. package/packages/selector/tests/runtime/session-events.spec.ts +27 -0
  200. package/packages/selector/tests/runtime/session-file-decode.spec.ts +281 -0
  201. package/packages/selector/tests/runtime/settings-unwrap.spec.ts +58 -0
  202. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -0
  203. package/packages/selector/tests/runtime/stats-backfill-scheduler.spec.ts +167 -0
  204. package/packages/selector/tests/runtime/stats-backfill.spec.ts +350 -0
  205. package/packages/selector/tests/runtime/stats-db.spec.ts +361 -0
  206. package/packages/selector/tests/runtime/stats-privacy.spec.ts +55 -0
  207. package/packages/selector/tests/runtime/stats-sync.spec.ts +278 -0
  208. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  209. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -0
  210. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +53 -0
  211. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
  212. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +52 -0
  213. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -0
  214. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +76 -0
  215. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +121 -0
  216. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +82 -0
  217. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -0
  218. package/packages/selector/tests/runtime/value.spec.ts +23 -0
  219. package/packages/selector/tests/savings-sessions.client.spec.tsx +140 -0
  220. package/packages/selector/tests/settings-seat.client.spec.ts +215 -0
  221. package/packages/selector/tests/standing-generation.host.spec.ts +724 -0
  222. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +269 -0
  223. package/packages/selector/tests/support/cache-prefix-audit.ts +105 -0
  224. package/packages/selector/tests/support/mock-adapter.ts +37 -0
  225. package/packages/selector/tests/support/ui-primitives.tsx +34 -0
  226. package/packages/selector/tsconfig.json +11 -0
  227. package/packages/selector/tsdown.client.config.ts +102 -0
  228. package/packages/selector/tsdown.config.ts +20 -0
  229. package/pnpm-workspace.yaml +76 -0
  230. package/screenshots.json +6 -3
  231. package/scripts/capture-profile-baseline.mjs +42 -0
  232. package/scripts/cell-browser-e2e.mjs +354 -0
  233. package/scripts/generate-tokenizer-fixtures.py +81 -0
  234. package/scripts/generate-vision-fixtures.py +208 -0
  235. package/scripts/hosts.mjs +79 -0
  236. package/scripts/packed-components-smoke.mjs +763 -0
  237. package/scripts/packed-install-e2e.mjs +1346 -0
  238. package/scripts/sync-hosts.mjs +174 -0
  239. package/scripts/toolclass-corpus-replay.mjs +281 -0
  240. package/scripts/verify-release.mjs +338 -0
  241. package/tests/TEST_INVENTORY.md +41 -0
  242. package/tsconfig.base.json +18 -0
  243. package/tsconfig.json +7 -0
  244. package/tsconfig.tests.json +15 -0
  245. package/vitest.built.config.ts +9 -0
  246. package/vitest.config.ts +54 -0
  247. /package/{assets → packages/selector/assets}/deepseek-v4/LICENSE.DeepSeek-V4-Pro.txt +0 -0
  248. /package/{assets → packages/selector/assets}/deepseek-v4/manifest.json +0 -0
  249. /package/{assets → packages/selector/assets}/deepseek-v4/tokenizer.json +0 -0
  250. /package/{assets → packages/selector/assets}/deepseek-v4/tokenizer_config.json +0 -0
  251. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/LICENSE.DeepSeek-V4-Flash-Vision-Exp.txt +0 -0
  252. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/manifest.json +0 -0
  253. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/tokenizer.json +0 -0
  254. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/tokenizer_config.json +0 -0
  255. /package/{cordis.patch.yml → packages/selector/cordis.patch.yml} +0 -0
  256. /package/{dsh.plugin.json → packages/selector/dsh.plugin.json} +0 -0
  257. /package/{lib → packages/selector/lib}/client.d.ts +0 -0
  258. /package/{lib → packages/selector/lib}/client.js +0 -0
  259. /package/{lib → packages/selector/lib}/index.d.ts +0 -0
  260. /package/{lib → packages/selector/lib}/index.js +0 -0
  261. /package/{lib → packages/selector/lib}/invariant.d.ts +0 -0
  262. /package/{lib → packages/selector/lib}/invariant.js +0 -0
  263. /package/{lib → packages/selector/lib}/profiles.d.ts +0 -0
  264. /package/{lib → packages/selector/lib}/pruner.d.ts +0 -0
  265. /package/{lib → packages/selector/lib}/pruner.js +0 -0
  266. /package/{lib → packages/selector/lib}/savings-integral.js +0 -0
  267. /package/{lib → packages/selector/lib}/tail-trim.js +0 -0
  268. /package/{lib → packages/selector/lib}/tool-result.js +0 -0
@@ -0,0 +1,451 @@
1
+ /** Public context-compression choices shared by the Host schema and browser selector. */
2
+ export const COMPRESSION_PROFILES = [
3
+ 'off',
4
+ 'native',
5
+ 'balanced',
6
+ 'cache-strict',
7
+ 'savings',
8
+ 'adaptive',
9
+ 'tokenpilot-inspired',
10
+ 'ptc',
11
+ 'custom',
12
+ ] as const
13
+
14
+ /** One supported context-compression profile. */
15
+ export type CompressionProfile = typeof COMPRESSION_PROFILES[number]
16
+
17
+ /** Single canonical unit stored by a version-1 browser Custom document. */
18
+ export type CustomCompressionUnit = 'tokens' | 'context-percent'
19
+
20
+ /** Whether Custom History may routinely rewrite an already-sent prefix. */
21
+ export type CustomPrefixPolicy = 'preserve' | 'pressure-break'
22
+
23
+ /** Browser representation of one independently enabled Fresh or Aggregate budget. */
24
+ export interface CustomCompressionBudget {
25
+ enabled: boolean
26
+ trigger: number
27
+ target: number
28
+ }
29
+
30
+ /** Legacy browser representation of the Custom History working set. */
31
+ export interface LegacyCustomHistoryPolicy {
32
+ enabled: boolean
33
+ trigger: number
34
+ keepRecentTurns: number
35
+ keepRecent: number
36
+ minReclaim: number
37
+ }
38
+
39
+ /** Browser representation of Custom History tool-call and token-tail protection. */
40
+ export interface CustomHistoryPolicy {
41
+ enabled: boolean
42
+ trigger: number
43
+ keepRecentToolCalls: number
44
+ keepRecentTokens: number
45
+ minReclaim: number
46
+ }
47
+
48
+ /** Browser representation of the Custom-only Experimental TailTrim gate. */
49
+ export interface CustomTailTrimPolicy {
50
+ enabled: boolean
51
+ trigger: number
52
+ }
53
+
54
+ interface CustomCompressionPolicyCommon<HistoryPolicy> {
55
+ unit: CustomCompressionUnit
56
+ fresh: CustomCompressionBudget
57
+ aggregate: CustomCompressionBudget
58
+ history: HistoryPolicy
59
+ prefixPolicy: CustomPrefixPolicy
60
+ }
61
+
62
+ /** Legacy public Custom document; accepted and normalized before editing. */
63
+ export interface CustomCompressionPolicyV1 extends CustomCompressionPolicyCommon<LegacyCustomHistoryPolicy> {
64
+ version: 1
65
+ }
66
+
67
+ /** Legacy Custom document with a default-disabled TailTrim stage. */
68
+ export interface CustomCompressionPolicyV2 extends CustomCompressionPolicyCommon<LegacyCustomHistoryPolicy> {
69
+ version: 2
70
+ tailTrim: CustomTailTrimPolicy
71
+ }
72
+
73
+ /** Public Custom document with tool-call working-set protection. */
74
+ export interface CustomCompressionPolicyV3 extends CustomCompressionPolicyCommon<CustomHistoryPolicy> {
75
+ version: 3
76
+ tailTrim: CustomTailTrimPolicy
77
+ }
78
+
79
+ /** Exact public Custom document accepted by the Host and browser boundary. */
80
+ export type CustomCompressionPolicy = CustomCompressionPolicyV1 | CustomCompressionPolicyV2 | CustomCompressionPolicyV3
81
+
82
+ /** Browser-safe mirror of the Host's Balanced-equivalent Custom default. */
83
+ export const DEFAULT_CUSTOM_COMPRESSION_POLICY: CustomCompressionPolicyV3 = {
84
+ version: 3,
85
+ unit: 'tokens',
86
+ fresh: { enabled: true, trigger: 8_192, target: 3_072 },
87
+ aggregate: { enabled: true, trigger: 32_768, target: 12_288 },
88
+ history: {
89
+ enabled: true,
90
+ trigger: 500_000,
91
+ keepRecentToolCalls: 10,
92
+ keepRecentTokens: 64_000,
93
+ minReclaim: 96_000,
94
+ },
95
+ prefixPolicy: 'pressure-break',
96
+ tailTrim: { enabled: false, trigger: 700_000 },
97
+ }
98
+
99
+ /** Browser-safe mirror of the runtime PTC default policy (absolute, window-independent). */
100
+ export const DEFAULT_PTC_COMPRESSION_POLICY: CustomCompressionPolicyV3 = {
101
+ version: 3,
102
+ unit: 'tokens',
103
+ fresh: { enabled: true, trigger: 4_096, target: 1_536 },
104
+ aggregate: { enabled: true, trigger: 16_384, target: 4_096 },
105
+ history: {
106
+ enabled: true,
107
+ trigger: 20_000,
108
+ keepRecentToolCalls: 8,
109
+ keepRecentTokens: 8_000,
110
+ minReclaim: 6_000,
111
+ },
112
+ prefixPolicy: 'pressure-break',
113
+ tailTrim: { enabled: false, trigger: 700_000 },
114
+ }
115
+
116
+ /** User-tunable Auto Compact coordination preferences. */
117
+ export interface AutoCompactSettings {
118
+ thresholdPercent: number
119
+ }
120
+
121
+ /**
122
+ * Orthogonal code-skeleton reducer gate, mirrored browser-safe from the
123
+ * runtime: independent of every profile, default off.
124
+ */
125
+ export interface CodeSkeletonSettings {
126
+ enabled: boolean
127
+ }
128
+
129
+ /**
130
+ * Orthogonal turn-tail intent-summary gate, mirrored browser-safe from the
131
+ * runtime: independent of every profile, default off.
132
+ */
133
+ export interface IntentSummarySettings {
134
+ enabled: boolean
135
+ }
136
+
137
+ /** Floating compression-monitor panel (FAB); visibility switch. */
138
+ export interface MonitorPanelSettings {
139
+ enabled: boolean
140
+ }
141
+
142
+ /**
143
+ * Decode the persisted codeSkeleton section with exactly the runtime schema's
144
+ * strictness: absent means the lossless off default; present values must be a
145
+ * plain object carrying only a boolean `enabled`. Anything else is invalid,
146
+ * never silently coerced.
147
+ */
148
+ export function decodeCodeSkeletonSettings(value: unknown): CodeSkeletonSettings | undefined {
149
+ if (value === undefined) return { enabled: false }
150
+ if (!isPlainRecord(value)) return undefined
151
+ const keys = Object.keys(value)
152
+ if (keys.length !== 1 || keys[0] !== 'enabled') return undefined
153
+ const enabled = (value as Record<string, unknown>).enabled
154
+ return typeof enabled === 'boolean' ? { enabled } : undefined
155
+ }
156
+
157
+ /** Browser-safe mirror of the runtime intentSummary section (absent inherits off). */
158
+ export function decodeIntentSummarySettings(value: unknown): IntentSummarySettings | undefined {
159
+ if (value === undefined) return { enabled: false }
160
+ if (!isPlainRecord(value)) return undefined
161
+ const keys = Object.keys(value)
162
+ if (keys.length !== 1 || keys[0] !== 'enabled') return undefined
163
+ const enabled = (value as Record<string, unknown>).enabled
164
+ return typeof enabled === 'boolean' ? { enabled } : undefined
165
+ }
166
+
167
+ /** Browser-safe mirror of the runtime monitorPanel section (absent inherits hidden). */
168
+ export function decodeMonitorPanelSettings(value: unknown): MonitorPanelSettings | undefined {
169
+ if (value === undefined) return { enabled: false }
170
+ if (!isPlainRecord(value)) return undefined
171
+ const keys = Object.keys(value)
172
+ if (keys.length !== 1 || keys[0] !== 'enabled') return undefined
173
+ const enabled = (value as Record<string, unknown>).enabled
174
+ return typeof enabled === 'boolean' ? { enabled } : undefined
175
+ }
176
+
177
+ /** Browser-safe mirror of the runtime presetOptions section. */
178
+ export interface PresetOptionsSettings {
179
+ readonly dedupeToolResults?: boolean
180
+ readonly summaryLocator?: boolean
181
+ readonly prefixStabilizer?: boolean
182
+ readonly readState?: boolean
183
+ readonly estimatorMode?: '' | 'host' | 'direct'
184
+ readonly estimatorProvider?: string
185
+ readonly estimatorModel?: string
186
+ readonly estimatorBaseUrl?: string
187
+ readonly estimatorApiKey?: string
188
+ readonly estimatorTimeoutMs?: number
189
+ /** Advisory advisor channel; `''` (the default) keeps the advisor off. */
190
+ readonly advisorMode?: '' | 'host' | 'direct'
191
+ readonly advisorTimeoutMs?: number
192
+ readonly advisorRefreshTurns?: number
193
+ readonly advisorScoreThreshold?: number
194
+ readonly advisorSampleLimit?: number
195
+ readonly advisorMinTokens?: number
196
+ }
197
+
198
+ /**
199
+ * Browser mirror of the runtime presetOptions section: absent inherits the
200
+ * preset defaults (decodes to `undefined`); present values must be a plain
201
+ * object carrying only the known keys with valid types.
202
+ */
203
+ export function decodePresetOptionsSettings(value: unknown): PresetOptionsSettings | undefined {
204
+ if (value === undefined) return undefined
205
+ if (!isPlainRecord(value)) return undefined
206
+ const allowed = new Set([
207
+ 'dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState', 'estimatorMode',
208
+ 'estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey', 'estimatorTimeoutMs',
209
+ // Legacy keys of the retired review gate: still ACCEPTED so an existing
210
+ // settings document keeps decoding (rejecting them would report the whole
211
+ // card unreadable), and ignored — nothing reads them any more.
212
+ 'reviewMode', 'reviewTimeoutTurns', 'cacheHitDiscountAlpha', 'reviewHighImpactTokens',
213
+ 'advisorMode', 'advisorTimeoutMs', 'advisorRefreshTurns', 'advisorScoreThreshold', 'advisorSampleLimit',
214
+ 'advisorMinTokens',
215
+ ])
216
+ if (Object.keys(value).some(key => !allowed.has(key))) return undefined
217
+ for (const key of ['dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState'] as const) {
218
+ const entry = value[key]
219
+ if (entry !== undefined && typeof entry !== 'boolean') return undefined
220
+ }
221
+ const estimatorMode = value.estimatorMode
222
+ if (estimatorMode !== undefined && estimatorMode !== '' && estimatorMode !== 'host' && estimatorMode !== 'direct') {
223
+ return undefined
224
+ }
225
+ const advisorMode = value.advisorMode
226
+ if (advisorMode !== undefined && advisorMode !== '' && advisorMode !== 'host' && advisorMode !== 'direct') {
227
+ return undefined
228
+ }
229
+ for (const key of ['estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey'] as const) {
230
+ const entry = value[key]
231
+ if (entry !== undefined && typeof entry !== 'string') return undefined
232
+ }
233
+ const estimatorTimeoutMs = value.estimatorTimeoutMs
234
+ if (estimatorTimeoutMs !== undefined
235
+ && (typeof estimatorTimeoutMs !== 'number' || !Number.isSafeInteger(estimatorTimeoutMs)
236
+ || estimatorTimeoutMs < 100 || estimatorTimeoutMs > 60_000)) {
237
+ return undefined
238
+ }
239
+ const advisorTimeoutMs = value.advisorTimeoutMs
240
+ if (advisorTimeoutMs !== undefined
241
+ && (typeof advisorTimeoutMs !== 'number' || !Number.isSafeInteger(advisorTimeoutMs)
242
+ || advisorTimeoutMs < 100 || advisorTimeoutMs > 60_000)) {
243
+ return undefined
244
+ }
245
+ const advisorRefreshTurns = value.advisorRefreshTurns
246
+ if (advisorRefreshTurns !== undefined
247
+ && (typeof advisorRefreshTurns !== 'number' || !Number.isSafeInteger(advisorRefreshTurns)
248
+ || advisorRefreshTurns < 1)) {
249
+ return undefined
250
+ }
251
+ const advisorScoreThreshold = value.advisorScoreThreshold
252
+ if (advisorScoreThreshold !== undefined
253
+ && (typeof advisorScoreThreshold !== 'number' || !Number.isFinite(advisorScoreThreshold)
254
+ || advisorScoreThreshold <= 0 || advisorScoreThreshold >= 1)) {
255
+ return undefined
256
+ }
257
+ const advisorSampleLimit = value.advisorSampleLimit
258
+ if (advisorSampleLimit !== undefined
259
+ && (typeof advisorSampleLimit !== 'number' || !Number.isSafeInteger(advisorSampleLimit)
260
+ || advisorSampleLimit < 1 || advisorSampleLimit > 64)) {
261
+ return undefined
262
+ }
263
+ const advisorMinTokens = value.advisorMinTokens
264
+ if (advisorMinTokens !== undefined
265
+ && (typeof advisorMinTokens !== 'number' || !Number.isSafeInteger(advisorMinTokens) || advisorMinTokens < 1)) {
266
+ return undefined
267
+ }
268
+ const decoded: {
269
+ -readonly [K in keyof PresetOptionsSettings]: PresetOptionsSettings[K]
270
+ } = {}
271
+ if (value.dedupeToolResults !== undefined) decoded.dedupeToolResults = value.dedupeToolResults as boolean
272
+ if (value.summaryLocator !== undefined) decoded.summaryLocator = value.summaryLocator as boolean
273
+ if (value.prefixStabilizer !== undefined) decoded.prefixStabilizer = value.prefixStabilizer as boolean
274
+ if (value.readState !== undefined) decoded.readState = value.readState as boolean
275
+ if (estimatorMode !== undefined) decoded.estimatorMode = estimatorMode as '' | 'host' | 'direct'
276
+ if (value.estimatorProvider !== undefined) decoded.estimatorProvider = value.estimatorProvider as string
277
+ if (value.estimatorModel !== undefined) decoded.estimatorModel = value.estimatorModel as string
278
+ if (value.estimatorBaseUrl !== undefined) decoded.estimatorBaseUrl = value.estimatorBaseUrl as string
279
+ if (value.estimatorApiKey !== undefined) decoded.estimatorApiKey = value.estimatorApiKey as string
280
+ if (estimatorTimeoutMs !== undefined) decoded.estimatorTimeoutMs = estimatorTimeoutMs as number
281
+ if (advisorMode !== undefined) decoded.advisorMode = advisorMode as '' | 'host' | 'direct'
282
+ if (advisorTimeoutMs !== undefined) decoded.advisorTimeoutMs = advisorTimeoutMs as number
283
+ if (advisorRefreshTurns !== undefined) decoded.advisorRefreshTurns = advisorRefreshTurns as number
284
+ if (advisorScoreThreshold !== undefined) decoded.advisorScoreThreshold = advisorScoreThreshold as number
285
+ if (advisorSampleLimit !== undefined) decoded.advisorSampleLimit = advisorSampleLimit as number
286
+ if (advisorMinTokens !== undefined) decoded.advisorMinTokens = advisorMinTokens as number
287
+ return decoded
288
+ }
289
+
290
+ /**
291
+ * The one threshold contract shared by the UI, the persisted settings, and the
292
+ * runtime resolver; mirrored browser-safe from the runtime package.
293
+ */
294
+ export const AUTO_COMPACT_THRESHOLD_LIMITS = Object.freeze({
295
+ min: 50,
296
+ max: 90,
297
+ step: 1,
298
+ default: 80,
299
+ } as const)
300
+
301
+ /** Narrow one unknown value to a valid Auto Compact threshold percent. */
302
+ export function isValidAutoCompactThresholdPercent(value: unknown): value is number {
303
+ return typeof value === 'number'
304
+ && Number.isSafeInteger(value)
305
+ && value >= AUTO_COMPACT_THRESHOLD_LIMITS.min
306
+ && value <= AUTO_COMPACT_THRESHOLD_LIMITS.max
307
+ }
308
+
309
+ /** Accept JSON-object records while rejecting class instances and exotic prototypes. */
310
+ export function isPlainRecord(value: unknown): value is Record<string, unknown> {
311
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
312
+ const prototype = Object.getPrototypeOf(value) as object | null
313
+ return prototype === Object.prototype || prototype === null
314
+ }
315
+
316
+ /**
317
+ * Decode the persisted autoCompact section with exactly the runtime schema's
318
+ * strictness: absent means the 80% default; present values must be a plain
319
+ * object carrying only a valid `thresholdPercent`. Anything else is invalid,
320
+ * never silently coerced.
321
+ */
322
+ export function decodeAutoCompactSettings(value: unknown): AutoCompactSettings | undefined {
323
+ if (value === undefined) return { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default }
324
+ if (!isPlainRecord(value)) return undefined
325
+ const keys = Object.keys(value)
326
+ if (keys.length !== 1 || keys[0] !== 'thresholdPercent') return undefined
327
+ const thresholdPercent = (value as Record<string, unknown>).thresholdPercent
328
+ return isValidAutoCompactThresholdPercent(thresholdPercent)
329
+ ? { thresholdPercent }
330
+ : undefined
331
+ }
332
+
333
+ /** Durable settings section owned by this package. */
334
+ export interface ContextCompressionSettings {
335
+ /** Default profile captured when each Session first reaches the pruner. */
336
+ profile: CompressionProfile
337
+ /** Complete canonical policy captured with `profile` when the runtime first observes a Session. */
338
+ custom: CustomCompressionPolicy
339
+ /** PTC profile's own editable policy, seeded from the ptc defaults; independent of `custom`. Optional like `monitorPanel`/`presetOptions`: schema-defaulted, always present after parse. */
340
+ ptcCustom?: CustomCompressionPolicy
341
+ /** Auto Compact trigger captured with `profile` when the runtime first observes a Session. */
342
+ autoCompact: AutoCompactSettings
343
+ /** Code-skeleton reducer gate captured independently of `profile`. */
344
+ codeSkeleton: CodeSkeletonSettings
345
+ /** Turn-tail intent-summary gate captured independently of `profile`. */
346
+ intentSummary: IntentSummarySettings
347
+ /** Floating compression-monitor panel (FAB); absent inherits hidden. */
348
+ monitorPanel?: MonitorPanelSettings
349
+ /** Optional tokenpilot-inspired sub-capability overrides (presence-validated only). */
350
+ presetOptions?: PresetOptionsSettings
351
+ }
352
+
353
+ /**
354
+ * Narrow an unknown settings value to a complete supported Custom policy.
355
+ * @param value - Candidate settings value received from the Host or edited locally.
356
+ * @returns Whether the value is a relation-valid Custom policy.
357
+ */
358
+ export function isCustomCompressionPolicy(value: unknown): value is CustomCompressionPolicy {
359
+ if (!hasExactKeys(
360
+ value,
361
+ value !== null && typeof value === 'object' && 'version' in value && value.version === 1
362
+ ? ['version', 'unit', 'fresh', 'aggregate', 'history', 'prefixPolicy']
363
+ : ['version', 'unit', 'fresh', 'aggregate', 'history', 'prefixPolicy', 'tailTrim'],
364
+ )) return false
365
+ if ((value.version !== 1 && value.version !== 2 && value.version !== 3)
366
+ || (value.unit !== 'tokens' && value.unit !== 'context-percent')) return false
367
+ if (value.prefixPolicy !== 'preserve' && value.prefixPolicy !== 'pressure-break') return false
368
+ if (!isBudget(value.fresh) || !isBudget(value.aggregate)) return false
369
+ const modernHistory = value.version === 3
370
+ if (!hasExactKeys(
371
+ value.history,
372
+ modernHistory
373
+ ? ['enabled', 'trigger', 'keepRecentToolCalls', 'keepRecentTokens', 'minReclaim']
374
+ : ['enabled', 'trigger', 'keepRecentTurns', 'keepRecent', 'minReclaim'],
375
+ )) return false
376
+ if (typeof value.history.enabled !== 'boolean'
377
+ || typeof value.history.trigger !== 'number'
378
+ || typeof value.history.minReclaim !== 'number') return false
379
+ const recent = modernHistory
380
+ ? value.history.keepRecentTokens
381
+ : value.history.keepRecent
382
+ const calls = modernHistory ? value.history.keepRecentToolCalls : value.history.keepRecentTurns
383
+ if (typeof recent !== 'number'
384
+ || typeof calls !== 'number'
385
+ || !Number.isSafeInteger(calls)
386
+ || calls < 0) return false
387
+ let tailTrimTrigger: number | undefined
388
+ if (value.version !== 1) {
389
+ const tailTrim = value.tailTrim
390
+ if (!hasExactKeys(tailTrim, ['enabled', 'trigger'])
391
+ || typeof tailTrim.enabled !== 'boolean'
392
+ || typeof tailTrim.trigger !== 'number') return false
393
+ tailTrimTrigger = tailTrim.trigger
394
+ }
395
+ const measured = [
396
+ value.fresh.trigger, value.fresh.target,
397
+ value.aggregate.trigger, value.aggregate.target,
398
+ value.history.trigger, recent, value.history.minReclaim,
399
+ ...tailTrimTrigger === undefined ? [] : [tailTrimTrigger],
400
+ ]
401
+ if (!measured.every(entry => typeof entry === 'number' && Number.isFinite(entry))) return false
402
+ if (value.fresh.trigger <= 0 || value.fresh.target <= 0
403
+ || value.aggregate.trigger <= 0 || value.aggregate.target <= 0
404
+ || value.history.trigger <= 0 || recent < 0
405
+ || value.history.minReclaim <= 0
406
+ || (tailTrimTrigger !== undefined && tailTrimTrigger <= 0)) return false
407
+ if (value.unit === 'tokens' && !measured.every(Number.isSafeInteger)) return false
408
+ if (value.unit === 'context-percent' && !measured.every(entry => entry <= 100)) return false
409
+ return value.fresh.target < value.fresh.trigger
410
+ && value.aggregate.target < value.aggregate.trigger
411
+ && value.history.minReclaim <= value.history.trigger
412
+ }
413
+
414
+ function isBudget(value: unknown): value is CustomCompressionBudget {
415
+ return hasExactKeys(value, ['enabled', 'trigger', 'target'])
416
+ && typeof value.enabled === 'boolean'
417
+ && typeof value.trigger === 'number'
418
+ && typeof value.target === 'number'
419
+ }
420
+
421
+ /**
422
+ * Canonicalize one validated Custom document to version 3, mirroring the
423
+ * runtime's `canonicalizeCustomPolicy` exactly so the browser and runtime
424
+ * boundaries hand the SAME complete document to the UI and the policy
425
+ * resolver: legacy v1/v2 History working sets upgrade to the 10-call default,
426
+ * and a v1 document gains the default-disabled TailTrim stage.
427
+ */
428
+ export function canonicalizeCustomPolicy(policy: CustomCompressionPolicy): CustomCompressionPolicyV3 {
429
+ if (policy.version === 3) return structuredClone(policy)
430
+ return {
431
+ version: 3,
432
+ unit: policy.unit,
433
+ fresh: structuredClone(policy.fresh),
434
+ aggregate: structuredClone(policy.aggregate),
435
+ history: {
436
+ enabled: policy.history.enabled,
437
+ trigger: policy.history.trigger,
438
+ keepRecentToolCalls: 10,
439
+ keepRecentTokens: policy.history.keepRecent,
440
+ minReclaim: policy.history.minReclaim,
441
+ },
442
+ prefixPolicy: policy.prefixPolicy,
443
+ tailTrim: policy.version === 1 ? { enabled: false, trigger: 700_000 } : structuredClone(policy.tailTrim),
444
+ }
445
+ }
446
+
447
+ function hasExactKeys(value: unknown, expected: readonly string[]): value is Record<string, unknown> {
448
+ if (!isPlainRecord(value)) return false
449
+ const keys = Object.keys(value)
450
+ return keys.length === expected.length && keys.every(key => expected.includes(key))
451
+ }
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Pure content-analysis functions extracted from ToolResultPruner.
3
+ *
4
+ * Every function here has ZERO `this` dependency — they receive all inputs
5
+ * as explicit arguments. Grouped by natural cohesion (content blocks →
6
+ * token counting → recovery helpers).
7
+ *
8
+ * @module dsh-context-compression-improved/pruner/content
9
+ */
10
+
11
+ import type { ContentBlock } from '@deepseek-ai/dsh-llm'
12
+ import { RUNTIME_TOOL_NAMES } from '../runtime/tool-names.ts'
13
+ import type {
14
+ CompactionTokenView,
15
+ ProviderMeasurementKey,
16
+ TokenCount,
17
+ } from '../runtime/measurement.ts'
18
+ import { countExactCanonicalTextFields } from '../runtime/token-count.ts'
19
+ import { codePointLength, PRUNE_MARKER } from '../runtime/config.ts'
20
+ import type { PrunedEntry, PruneResult } from '../runtime/types.ts'
21
+ import { RICH_BLOCK_PRESSURE_COST } from './tuning.ts'
22
+
23
+ // ── Content-block predicates ────────────────────────────────────────────
24
+
25
+ function onlyTextBlock(blocks: readonly ContentBlock[]): Extract<ContentBlock, { type: 'text' }> | null {
26
+ return blocks.length === 1 && blocks[0]?.type === 'text' ? blocks[0] : null
27
+ }
28
+
29
+ function onlyTextBlocks(blocks: readonly ContentBlock[]): readonly Extract<ContentBlock, { type: 'text' }>[] | null {
30
+ return blocks.every((block): block is Extract<ContentBlock, { type: 'text' }> => block.type === 'text')
31
+ ? blocks
32
+ : null
33
+ }
34
+
35
+ // ── Token counting ──────────────────────────────────────────────────────
36
+
37
+ function countToolContent(blocks: readonly ContentBlock[], view: CompactionTokenView): TokenCount {
38
+ const text = onlyTextBlocks(blocks)
39
+ if (text === null) return unavailableCount('tool result contains unsupported rich content')
40
+ return countExactCanonicalTextFields(
41
+ text.map(block => block.text),
42
+ candidate => view.countCanonicalText(candidate),
43
+ 'tool result replacement',
44
+ )
45
+ }
46
+
47
+ function exactTokens(count: TokenCount): number | undefined {
48
+ return count.kind === 'exact-tokenizer' ? count.tokens : undefined
49
+ }
50
+
51
+ // ── Provider measurement key comparison ─────────────────────────────────
52
+
53
+ function sameProviderMeasurementKey(
54
+ left: Readonly<ProviderMeasurementKey>,
55
+ right: Readonly<ProviderMeasurementKey>,
56
+ ): boolean {
57
+ return left.provider === right.provider
58
+ && left.baseUrlClass === right.baseUrlClass
59
+ && left.apiRoute === right.apiRoute
60
+ && left.modelId === right.modelId
61
+ && left.requestTemplateRevision === right.requestTemplateRevision
62
+ && left.tokenizerRevision === right.tokenizerRevision
63
+ && left.modality === right.modality
64
+ }
65
+
66
+ // ── Token helpers ───────────────────────────────────────────────────────
67
+
68
+ function unavailableCount(reason: string): TokenCount {
69
+ return Object.freeze({ kind: 'unavailable', reason })
70
+ }
71
+
72
+ // ── Recovery markers ────────────────────────────────────────────────────
73
+
74
+ function recoveryMarker(sourceRef: string, label: string, startLine?: number): string {
75
+ const hint = startLine === undefined
76
+ ? `use ${RUNTIME_TOOL_NAMES.RETRIEVE} with a query or narrow start_line/max_lines if needed (avoid re-reading the whole result)`
77
+ : `retrieve with ${RUNTIME_TOOL_NAMES.RETRIEVE}({"ref":"${sourceRef}","start_line":${String(startLine)},"max_lines":80})`
78
+ return `\n\n[... ${label}; source=${sourceRef}; ${hint} ...]\n\n`
79
+ }
80
+
81
+ // ── Content measurement ─────────────────────────────────────────────────
82
+
83
+ /**
84
+ * Measure text content in Unicode code points; non-text blocks cost zero.
85
+ * @param blocks - tool-result content to measure.
86
+ * @returns total Unicode code points across text blocks.
87
+ */
88
+ function measureContent(blocks: readonly ContentBlock[]): number {
89
+ let chars = 0
90
+ for (const block of blocks) {
91
+ if (block.type === 'text') chars += codePointLength(block.text)
92
+ }
93
+ return chars
94
+ }
95
+
96
+ function pressureCost(blocks: readonly ContentBlock[]): number {
97
+ let cost = 0
98
+ for (const block of blocks) {
99
+ switch (block.type) {
100
+ case 'text':
101
+ case 'reasoning':
102
+ cost += codePointLength(block.text)
103
+ break
104
+ case 'tool-call':
105
+ cost += RICH_BLOCK_PRESSURE_COST
106
+ + codePointLength(block.name)
107
+ + codePointLength(block.arguments)
108
+ break
109
+ default: {
110
+ // ContentBlockMap is merge-extensible. Unknown model-visible blocks
111
+ // scale with their durable JSON payload instead of receiving a fixed
112
+ // token that a large provider block could bypass.
113
+ const serialized = JSON.stringify(block)
114
+ cost += Math.max(RICH_BLOCK_PRESSURE_COST, codePointLength(serialized))
115
+ }
116
+ }
117
+ }
118
+ return cost
119
+ }
120
+
121
+ // ── Native content pruning ──────────────────────────────────────────────
122
+
123
+ function nativePruneContent(
124
+ blocks: readonly ContentBlock[],
125
+ thresholdChars: number,
126
+ headChars: number,
127
+ tailChars: number,
128
+ marker: string | ((startLine: number) => string) = PRUNE_MARKER,
129
+ ): ContentBlock[] | null {
130
+ const totalChars = measureContent(blocks)
131
+ if (totalChars <= thresholdChars) return null
132
+ const markerChars = codePointLength(typeof marker === 'function' ? marker(1) : marker)
133
+ const safeHead = Math.max(0, Math.min(headChars, thresholdChars - markerChars))
134
+ const safeTail = Math.max(0, Math.min(tailChars, thresholdChars - markerChars - safeHead))
135
+ const removedStart = safeHead
136
+ const removedEnd = totalChars - safeTail
137
+ const pruned: ContentBlock[] = []
138
+ let consumed = 0
139
+ let markerInserted = false
140
+ // '\n' count in the RAW event text before the current block (retrieve scans
141
+ // the original event; blocks are joined with '\n'). Line numbers therefore
142
+ // never depend on what the pruning removed.
143
+ let newlinesBefore = 0
144
+ for (const block of blocks) {
145
+ if (block.type !== 'text') {
146
+ pruned.push(block)
147
+ newlinesBefore += 1
148
+ continue
149
+ }
150
+ const points = Array.from(block.text)
151
+ const blockStart = consumed
152
+ const blockEnd = blockStart + points.length
153
+ const headEnd = Math.min(points.length, Math.max(0, removedStart - blockStart))
154
+ const tailStart = Math.min(points.length, Math.max(0, removedEnd - blockStart))
155
+ const intersectsRemoved = blockStart < removedEnd && blockEnd > removedStart
156
+ // The elided region starts on the event line after the retained head.
157
+ const headText = points.slice(0, headEnd).join('')
158
+ const insertion = intersectsRemoved && !markerInserted && typeof marker === 'function'
159
+ ? marker(1 + newlinesBefore + headText.split('\n').length - 1)
160
+ : intersectsRemoved && !markerInserted ? marker : ''
161
+ if (insertion !== '') markerInserted = true
162
+ const text = points.slice(0, headEnd).join('') + insertion + points.slice(tailStart).join('')
163
+ if (text !== '') pruned.push({ ...block, text })
164
+ newlinesBefore += block.text.split('\n').length - 1 + 1
165
+ consumed = blockEnd
166
+ }
167
+ if (!markerInserted) return null
168
+ const charsAfter = measureContent(pruned)
169
+ return charsAfter <= thresholdChars && charsAfter < totalChars ? pruned : null
170
+ }
171
+
172
+ // ── Result aggregation ──────────────────────────────────────────────────
173
+
174
+ function summarize(entries: readonly PrunedEntry[]): PruneResult {
175
+ return {
176
+ pruned: entries,
177
+ charsRemoved: entries.reduce((sum, entry) => sum + entry.charsBefore - entry.charsAfter, 0),
178
+ tokensRemoved: entries.reduce((sum, entry) => sum + entry.tokensBefore - entry.tokensAfter, 0),
179
+ }
180
+ }
181
+
182
+ function emptyResult(): PruneResult {
183
+ return { pruned: [], charsRemoved: 0, tokensRemoved: 0 }
184
+ }
185
+
186
+ export {
187
+ onlyTextBlock,
188
+ onlyTextBlocks,
189
+ countToolContent,
190
+ exactTokens,
191
+ sameProviderMeasurementKey,
192
+ unavailableCount,
193
+ recoveryMarker,
194
+ summarize,
195
+ emptyResult,
196
+ measureContent,
197
+ pressureCost,
198
+ nativePruneContent,
199
+ }