dsh-context-compression-improved 0.12.0 → 0.13.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 (330) hide show
  1. package/.agents/plans/improve/checklist.md +32 -0
  2. package/.agents/plans/improve/findings.md +102 -0
  3. package/.agents/plans/improve/spec.md +53 -0
  4. package/.agents/plans/improve/tasks.md +70 -0
  5. package/.gitattributes +2 -0
  6. package/.githooks/pre-push +37 -0
  7. package/.github/workflows/ci.yml +47 -0
  8. package/CHANGELOG.de.md +580 -0
  9. package/CHANGELOG.es.md +588 -0
  10. package/CHANGELOG.fr.md +576 -0
  11. package/CHANGELOG.it.md +577 -0
  12. package/CHANGELOG.ja.md +261 -0
  13. package/CHANGELOG.ko.md +254 -0
  14. package/CHANGELOG.md +582 -0
  15. package/CHANGELOG.pt.md +167 -0
  16. package/CHANGELOG.ru.md +554 -0
  17. package/CHANGELOG.zh.md +247 -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 +128 -22
  26. package/README.pt.md +96 -0
  27. package/README.ru.md +96 -0
  28. package/README.zh.md +114 -24
  29. package/SECURITY.md +18 -0
  30. package/THIRD_PARTY_NOTICES.md +7 -25
  31. package/assets/board.png +0 -0
  32. package/assets/context.png +0 -0
  33. package/assets/dshfind-card.svg +33 -0
  34. package/docs/assets/context-compression-selector-profiles.jpg +0 -0
  35. package/docs/assets/context-compression-selector-settings.png +0 -0
  36. package/docs/compat-0.1.5-report.md +77 -0
  37. package/docs/installation.de.md +104 -0
  38. package/docs/installation.es.md +104 -0
  39. package/docs/installation.fr.md +104 -0
  40. package/docs/installation.it.md +104 -0
  41. package/docs/installation.ja.md +78 -0
  42. package/docs/installation.ko.md +78 -0
  43. package/docs/installation.md +103 -0
  44. package/docs/installation.ru.md +104 -0
  45. package/docs/installation.zh.md +100 -0
  46. package/docs/repair-log.md +657 -0
  47. package/docs/shallow-teaching-preset-template.md +46 -0
  48. package/eslint.config.js +30 -0
  49. package/package.json +112 -127
  50. package/packages/selector/LICENSE +21 -0
  51. package/packages/selector/README.md +26 -0
  52. package/packages/selector/README.zh.md +24 -0
  53. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -0
  54. package/packages/selector/docs/history-tool-call-working-set-spec.md +112 -0
  55. package/packages/selector/docs/native-tool-result-selector-spec.md +34 -0
  56. package/packages/selector/docs/subagent-cache-reuse-spec.md +46 -0
  57. package/{dsh.plugin.json → packages/selector/dsh.plugin.json} +1 -1
  58. package/{lib → packages/selector/lib}/client.js +18 -10
  59. package/packages/selector/lib/style.css +350 -0
  60. package/packages/selector/package.json +180 -0
  61. package/packages/selector/screenshots.json +3 -0
  62. package/packages/selector/src/client/CompressionProfileControls.tsx +352 -0
  63. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -0
  64. package/packages/selector/src/client/CompressionProfileSelector.tsx +89 -0
  65. package/packages/selector/src/client/CustomPolicyEditor.tsx +216 -0
  66. package/packages/selector/src/client/EstimatorControls.tsx +277 -0
  67. package/packages/selector/src/client/bridge-scope.ts +125 -0
  68. package/packages/selector/src/client/decode.ts +68 -0
  69. package/packages/selector/src/client/fab-pos.ts +71 -0
  70. package/packages/selector/src/client/guide-steps.ts +50 -0
  71. package/packages/selector/src/client/guide.tsx +368 -0
  72. package/packages/selector/src/client/index.ts +456 -0
  73. package/packages/selector/src/client/locales/de.ts +167 -0
  74. package/packages/selector/src/client/locales/es.ts +167 -0
  75. package/packages/selector/src/client/locales/fr.ts +167 -0
  76. package/packages/selector/src/client/locales/it.ts +167 -0
  77. package/packages/selector/src/client/locales/ja.ts +167 -0
  78. package/packages/selector/src/client/locales/ko.ts +167 -0
  79. package/packages/selector/src/client/locales/pt.ts +167 -0
  80. package/packages/selector/src/client/locales/ru.ts +167 -0
  81. package/packages/selector/src/client/locales.ts +334 -0
  82. package/packages/selector/src/client/monitor-fab.ts +445 -0
  83. package/packages/selector/src/client/preset-options.ts +88 -0
  84. package/packages/selector/src/client/savings-card.tsx +269 -0
  85. package/packages/selector/src/client/scope-face.ts +24 -0
  86. package/packages/selector/src/client/settings-section.tsx +171 -0
  87. package/packages/selector/src/compat/host-generation.ts +96 -0
  88. package/packages/selector/src/compat/llm-messages.ts +50 -0
  89. package/packages/selector/src/compat/settings-lease.ts +108 -0
  90. package/packages/selector/src/compat/tool-result.ts +91 -0
  91. package/packages/selector/src/css-modules.d.ts +6 -0
  92. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -0
  93. package/packages/selector/src/estimator-catalog.ts +104 -0
  94. package/packages/selector/src/index.ts +909 -0
  95. package/packages/selector/src/invariant.ts +113 -0
  96. package/packages/selector/src/preset-overlay.ts +749 -0
  97. package/packages/selector/src/profiles.ts +554 -0
  98. package/packages/selector/src/pruner/content.ts +199 -0
  99. package/packages/selector/src/pruner/session.ts +97 -0
  100. package/packages/selector/src/pruner/state.ts +61 -0
  101. package/packages/selector/src/pruner/tuning.ts +23 -0
  102. package/packages/selector/src/pruner/types.ts +78 -0
  103. package/packages/selector/src/pruner.ts +3222 -0
  104. package/packages/selector/src/runtime/adaptive-cost.ts +205 -0
  105. package/packages/selector/src/runtime/audit.ts +321 -0
  106. package/packages/selector/src/runtime/config.ts +887 -0
  107. package/packages/selector/src/runtime/custom-policy.ts +300 -0
  108. package/packages/selector/src/runtime/deepseek-official-pricing.ts +298 -0
  109. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +254 -0
  110. package/packages/selector/src/runtime/display-prefs.ts +98 -0
  111. package/packages/selector/src/runtime/fold-router.ts +143 -0
  112. package/packages/selector/src/runtime/measurement.ts +444 -0
  113. package/packages/selector/src/runtime/monitor.ts +341 -0
  114. package/packages/selector/src/runtime/panel-command.ts +213 -0
  115. package/packages/selector/src/runtime/reducers.ts +1755 -0
  116. package/packages/selector/src/runtime/retrieve.ts +505 -0
  117. package/packages/selector/src/runtime/savings-integral.ts +117 -0
  118. package/packages/selector/src/runtime/savings-projection.ts +229 -0
  119. package/packages/selector/src/runtime/savings-verify.ts +446 -0
  120. package/packages/selector/src/runtime/savings.ts +526 -0
  121. package/packages/selector/src/runtime/sediment-card.ts +126 -0
  122. package/packages/selector/src/runtime/sediment-clock.ts +87 -0
  123. package/packages/selector/src/runtime/sediment-guard.ts +136 -0
  124. package/packages/selector/src/runtime/sediment-publish.ts +144 -0
  125. package/packages/selector/src/runtime/sediment-span.ts +170 -0
  126. package/packages/selector/src/runtime/sediment.ts +209 -0
  127. package/packages/selector/src/runtime/session-events.ts +30 -0
  128. package/packages/selector/src/runtime/session-file-decode.ts +523 -0
  129. package/packages/selector/src/runtime/shallow-tools.ts +342 -0
  130. package/packages/selector/src/runtime/stats-backfill.ts +541 -0
  131. package/packages/selector/src/runtime/stats-db.ts +492 -0
  132. package/packages/selector/src/runtime/stats-schema.ts +123 -0
  133. package/packages/selector/src/runtime/stats-sync.ts +307 -0
  134. package/packages/selector/src/runtime/summary-command.ts +127 -0
  135. package/packages/selector/src/runtime/tail-trim.ts +177 -0
  136. package/packages/selector/src/runtime/token-count.ts +72 -0
  137. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
  138. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
  139. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
  140. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
  141. package/packages/selector/src/runtime/tokenpilot/dedup.ts +82 -0
  142. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -0
  143. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  144. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  145. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  146. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  147. package/packages/selector/src/runtime/tokenpilot/locator.ts +129 -0
  148. package/packages/selector/src/runtime/tokenpilot/read-state.ts +98 -0
  149. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -0
  150. package/packages/selector/src/runtime/tool-names.ts +42 -0
  151. package/packages/selector/src/runtime/toolclass.ts +103 -0
  152. package/packages/selector/src/runtime/triage/masks.ts +128 -0
  153. package/packages/selector/src/runtime/triage/shallow.ts +132 -0
  154. package/packages/selector/src/runtime/triage/signals.ts +167 -0
  155. package/packages/selector/src/runtime/triage/types.ts +125 -0
  156. package/packages/selector/src/runtime/types.ts +396 -0
  157. package/packages/selector/src/runtime/value.ts +48 -0
  158. package/packages/selector/src/settings-bridge.ts +175 -0
  159. package/packages/selector/src/tui-command.ts +99 -0
  160. package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
  161. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -0
  162. package/packages/selector/tests/built/client-artifact.spec.ts +56 -0
  163. package/packages/selector/tests/cache-prefix-audit.spec.ts +123 -0
  164. package/packages/selector/tests/code-skeleton.client.spec.ts +98 -0
  165. package/packages/selector/tests/compat/compat-narrow-waist.spec.ts +150 -0
  166. package/packages/selector/tests/custom-contract.client.spec.ts +226 -0
  167. package/packages/selector/tests/estimator-catalog.spec.ts +70 -0
  168. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -0
  169. package/packages/selector/tests/estimator-route-registration.host.spec.ts +202 -0
  170. package/packages/selector/tests/fab-pos.client.spec.ts +47 -0
  171. package/packages/selector/tests/fixtures/sediment-pool/52adc205-cloud-5.orig.txt +231 -0
  172. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-25.orig.txt +236 -0
  173. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-38.orig.txt +220 -0
  174. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-42.orig.txt +140 -0
  175. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-53.orig.txt +117 -0
  176. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-local-10.orig.txt +67 -0
  177. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-45.orig.txt +119 -0
  178. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-49.orig.txt +119 -0
  179. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-63.orig.txt +131 -0
  180. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-75.orig.txt +196 -0
  181. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-76.orig.txt +71 -0
  182. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-85.orig.txt +126 -0
  183. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-86.orig.txt +86 -0
  184. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-87.orig.txt +50 -0
  185. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-96.orig.txt +102 -0
  186. package/packages/selector/tests/helpers/legacy-namespace.ts +35 -0
  187. package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -0
  188. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -0
  189. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -0
  190. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -0
  191. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -0
  192. package/packages/selector/tests/host-preset-overlay.host.spec.ts +204 -0
  193. package/packages/selector/tests/monitor-fab.client.spec.ts +240 -0
  194. package/packages/selector/tests/preset-options-write.client.spec.ts +192 -0
  195. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +200 -0
  196. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -0
  197. package/packages/selector/tests/profiles.client.spec.tsx +436 -0
  198. package/packages/selector/tests/ptc-custom-write.client.spec.ts +86 -0
  199. package/packages/selector/tests/public/package-contract.client.spec.ts +91 -0
  200. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +167 -0
  201. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +230 -0
  202. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
  203. package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
  204. package/packages/selector/tests/runtime/audit.spec.ts +275 -0
  205. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -0
  206. package/packages/selector/tests/runtime/behavior-lock-profiles.spec.ts +128 -0
  207. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -0
  208. package/packages/selector/tests/runtime/code-skeleton.spec.ts +152 -0
  209. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +186 -0
  210. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -0
  211. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +122 -0
  212. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
  213. package/packages/selector/tests/runtime/fallback-diversity.spec.ts +75 -0
  214. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +273 -0
  215. package/packages/selector/tests/runtime/fixtures/session-v4-dump.jsonl +46 -0
  216. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +106 -0
  217. package/packages/selector/tests/runtime/fixtures/vision-golden.json +459 -0
  218. package/packages/selector/tests/runtime/fold-router.spec.ts +140 -0
  219. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -0
  220. package/packages/selector/tests/runtime/fresh-gate.spec.ts +43 -0
  221. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -0
  222. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  223. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  224. package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +79 -0
  225. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -0
  226. package/packages/selector/tests/runtime/monitor.spec.ts +354 -0
  227. package/packages/selector/tests/runtime/panel-command.spec.ts +101 -0
  228. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -0
  229. package/packages/selector/tests/runtime/ptc-profile.spec.ts +133 -0
  230. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2795 -0
  231. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -0
  232. package/packages/selector/tests/runtime/savings-accounting.spec.ts +291 -0
  233. package/packages/selector/tests/runtime/savings-integral.spec.ts +169 -0
  234. package/packages/selector/tests/runtime/savings-projection.spec.ts +89 -0
  235. package/packages/selector/tests/runtime/savings-verify.spec.ts +226 -0
  236. package/packages/selector/tests/runtime/savings.spec.ts +139 -0
  237. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -0
  238. package/packages/selector/tests/runtime/sediment-card.spec.ts +111 -0
  239. package/packages/selector/tests/runtime/sediment-config.spec.ts +56 -0
  240. package/packages/selector/tests/runtime/sediment-guard.spec.ts +71 -0
  241. package/packages/selector/tests/runtime/sediment-masks.spec.ts +95 -0
  242. package/packages/selector/tests/runtime/sediment-orchestrator.spec.ts +166 -0
  243. package/packages/selector/tests/runtime/sediment-pool-share.spec.ts +65 -0
  244. package/packages/selector/tests/runtime/sediment-publish.spec.ts +142 -0
  245. package/packages/selector/tests/runtime/sediment-real-shapes.spec.ts +158 -0
  246. package/packages/selector/tests/runtime/sediment-settings.spec.ts +73 -0
  247. package/packages/selector/tests/runtime/sediment-signals.spec.ts +124 -0
  248. package/packages/selector/tests/runtime/sediment-span.spec.ts +92 -0
  249. package/packages/selector/tests/runtime/session-events.spec.ts +27 -0
  250. package/packages/selector/tests/runtime/session-file-decode.spec.ts +281 -0
  251. package/packages/selector/tests/runtime/settings-unwrap.spec.ts +58 -0
  252. package/packages/selector/tests/runtime/shallow-primitives.spec.ts +135 -0
  253. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -0
  254. package/packages/selector/tests/runtime/source-kind-audit.spec.ts +79 -0
  255. package/packages/selector/tests/runtime/stats-backfill-scheduler.spec.ts +167 -0
  256. package/packages/selector/tests/runtime/stats-backfill.spec.ts +350 -0
  257. package/packages/selector/tests/runtime/stats-db.spec.ts +361 -0
  258. package/packages/selector/tests/runtime/stats-privacy.spec.ts +55 -0
  259. package/packages/selector/tests/runtime/stats-sync.spec.ts +278 -0
  260. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  261. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -0
  262. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +53 -0
  263. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
  264. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +52 -0
  265. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -0
  266. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +76 -0
  267. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +121 -0
  268. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +82 -0
  269. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -0
  270. package/packages/selector/tests/runtime/value.spec.ts +23 -0
  271. package/packages/selector/tests/savings-sessions.client.spec.tsx +140 -0
  272. package/packages/selector/tests/settings-seat.client.spec.ts +215 -0
  273. package/packages/selector/tests/standing-generation.host.spec.ts +729 -0
  274. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +269 -0
  275. package/packages/selector/tests/support/cache-prefix-audit.ts +105 -0
  276. package/packages/selector/tests/support/mock-adapter.ts +37 -0
  277. package/packages/selector/tests/support/ui-primitives.tsx +34 -0
  278. package/packages/selector/tsconfig.json +11 -0
  279. package/packages/selector/tsdown.client.config.ts +102 -0
  280. package/packages/selector/tsdown.config.ts +20 -0
  281. package/pnpm-workspace.yaml +76 -0
  282. package/screenshots.json +6 -3
  283. package/scripts/capture-profile-baseline.mjs +42 -0
  284. package/scripts/cell-browser-e2e.mjs +354 -0
  285. package/scripts/generate-tokenizer-fixtures.py +81 -0
  286. package/scripts/generate-vision-fixtures.py +208 -0
  287. package/scripts/hosts.d.mts +3 -0
  288. package/scripts/hosts.mjs +81 -0
  289. package/scripts/packed-components-smoke.mjs +763 -0
  290. package/scripts/packed-install-e2e.mjs +1346 -0
  291. package/scripts/sediment-latency-report.mjs +63 -0
  292. package/scripts/sync-hosts.mjs +176 -0
  293. package/scripts/toolclass-corpus-replay.mjs +281 -0
  294. package/scripts/verify-release.mjs +342 -0
  295. package/tests/TEST_INVENTORY.md +41 -0
  296. package/tsconfig.base.json +18 -0
  297. package/tsconfig.json +7 -0
  298. package/tsconfig.tests.json +15 -0
  299. package/vitest.built.config.ts +9 -0
  300. package/vitest.config.ts +54 -0
  301. /package/{assets → packages/selector/assets}/deepseek-v4/LICENSE.DeepSeek-V4-Pro.txt +0 -0
  302. /package/{assets → packages/selector/assets}/deepseek-v4/manifest.json +0 -0
  303. /package/{assets → packages/selector/assets}/deepseek-v4/tokenizer.json +0 -0
  304. /package/{assets → packages/selector/assets}/deepseek-v4/tokenizer_config.json +0 -0
  305. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/LICENSE.DeepSeek-V4-Flash-Vision-Exp.txt +0 -0
  306. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/manifest.json +0 -0
  307. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/tokenizer.json +0 -0
  308. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/tokenizer_config.json +0 -0
  309. /package/{cordis.patch.yml → packages/selector/cordis.patch.yml} +0 -0
  310. /package/{lib → packages/selector/lib}/client.d.ts +0 -0
  311. /package/{lib → packages/selector/lib}/index.d.ts +0 -0
  312. /package/{lib → packages/selector/lib}/index.js +0 -0
  313. /package/{lib → packages/selector/lib}/invariant.d.ts +0 -0
  314. /package/{lib → packages/selector/lib}/invariant.js +0 -0
  315. /package/{lib → packages/selector/lib}/profiles.d.ts +0 -0
  316. /package/{lib → packages/selector/lib}/pruner.d.ts +0 -0
  317. /package/{lib → packages/selector/lib}/pruner.js +0 -0
  318. /package/{lib → packages/selector/lib}/savings-integral.js +0 -0
  319. /package/{lib → packages/selector/lib}/tail-trim.js +0 -0
  320. /package/{lib → packages/selector/lib}/tool-result.js +0 -0
  321. /package/{locale → packages/selector/locale}/de.json +0 -0
  322. /package/{locale → packages/selector/locale}/en.json +0 -0
  323. /package/{locale → packages/selector/locale}/es.json +0 -0
  324. /package/{locale → packages/selector/locale}/fr.json +0 -0
  325. /package/{locale → packages/selector/locale}/it.json +0 -0
  326. /package/{locale → packages/selector/locale}/ja.json +0 -0
  327. /package/{locale → packages/selector/locale}/ko.json +0 -0
  328. /package/{locale → packages/selector/locale}/pt.json +0 -0
  329. /package/{locale → packages/selector/locale}/ru.json +0 -0
  330. /package/{locale → packages/selector/locale}/zh.json +0 -0
@@ -0,0 +1,887 @@
1
+ /** Configuration resolution for the mixed deterministic context-compression selector. */
2
+
3
+ import z from '@deepseek-ai/schemastery'
4
+ import type {
5
+ AutoCompactSettings,
6
+ CodeSkeletonSettings,
7
+ CompressionPolicy,
8
+ IntentSummarySettings,
9
+ MonitorPanelSettings,
10
+ SedimentSettings,
11
+ CompressionProfile,
12
+ CustomCompressionPolicy,
13
+ PresetOptions,
14
+ PresetOptionsSettings,
15
+ ContextCompressionSettings,
16
+ ResolvedConfig,
17
+ ToolResultPruneConfig,
18
+ } from './types.ts'
19
+ import { COMPRESSION_PROFILES } from './types.ts'
20
+ import {
21
+ CustomCompressionPolicySchema,
22
+ DEFAULT_CUSTOM_COMPRESSION_POLICY,
23
+ DEFAULT_PTC_COMPRESSION_POLICY,
24
+ resolveCustomPolicy,
25
+ type CustomPolicyResolutionOptions,
26
+ } from './custom-policy.ts'
27
+ import { deepFreeze } from './value.ts'
28
+
29
+ /** Settings namespace shared by the Host service and browser selector. */
30
+ export const CONTEXT_COMPRESSION_SETTINGS_NAMESPACE = 'context-compression'
31
+
32
+ /** Fixed native fallback marker. */
33
+ export const PRUNE_MARKER = '\n\n[... tool result middle pruned ...]\n\n'
34
+
35
+ /**
36
+ * The one Auto Compact threshold contract shared by the settings UI, the
37
+ * persisted settings schema, and the runtime resolver. Every integer in the
38
+ * range is valid and entered directly in the UI.
39
+ */
40
+ export const AUTO_COMPACT_THRESHOLD_LIMITS = deepFreeze({
41
+ min: 50,
42
+ max: 90,
43
+ step: 1,
44
+ default: 80,
45
+ } as const)
46
+
47
+ /** Narrow one untrusted value to a valid Auto Compact threshold percent. */
48
+ export function isValidAutoCompactThresholdPercent(value: unknown): value is number {
49
+ return typeof value === 'number'
50
+ && Number.isSafeInteger(value)
51
+ && value >= AUTO_COMPACT_THRESHOLD_LIMITS.min
52
+ && value <= AUTO_COMPACT_THRESHOLD_LIMITS.max
53
+ }
54
+
55
+ const AUTO_COMPACT_DEFAULT: AutoCompactSettings = deepFreeze({ thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default })
56
+
57
+ /** Accept JSON-object records while rejecting class instances and exotic prototypes. */
58
+ function isPlainRecord(value: unknown): value is Record<string, unknown> {
59
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
60
+ const prototype = Object.getPrototypeOf(value) as object | null
61
+ return prototype === Object.prototype || prototype === null
62
+ }
63
+
64
+ /** Reject exotic prototypes anywhere in the JSON-like settings tree. */
65
+ function assertPlainDataTree(value: unknown, seen: WeakSet<object> = new WeakSet()): void {
66
+ if (value === null || typeof value !== 'object') return
67
+ if (seen.has(value)) return
68
+ seen.add(value)
69
+ if (Array.isArray(value)) {
70
+ for (const entry of value) assertPlainDataTree(entry, seen)
71
+ return
72
+ }
73
+ if (!isPlainRecord(value)) {
74
+ throw new TypeError('Context-compression settings must contain only plain objects')
75
+ }
76
+ for (const entry of Object.values(value)) assertPlainDataTree(entry, seen)
77
+ }
78
+
79
+ /**
80
+ * Strictly parse the persisted autoCompact section. Schemastery object
81
+ * defaults silently absorb null, empty, and extra-key sections, so this stays
82
+ * hand-validated beside the top-level unknown-key check.
83
+ */
84
+ function parseAutoCompactSettings(value: unknown): AutoCompactSettings {
85
+ if (value === undefined) return AUTO_COMPACT_DEFAULT
86
+ if (!isPlainRecord(value)) {
87
+ throw new TypeError('Context-compression autoCompact must be a plain object')
88
+ }
89
+ const keys = Object.keys(value)
90
+ if (keys.length !== 1 || keys[0] !== 'thresholdPercent') {
91
+ throw new TypeError(`Context-compression autoCompact: expected exactly "thresholdPercent", got "${keys.join('", "')}"`)
92
+ }
93
+ const thresholdPercent = (value as Record<string, unknown>).thresholdPercent
94
+ if (!isValidAutoCompactThresholdPercent(thresholdPercent)) {
95
+ throw new TypeError(`Context-compression autoCompact.thresholdPercent (${String(thresholdPercent)}) must be an integer between ${String(AUTO_COMPACT_THRESHOLD_LIMITS.min)} and ${String(AUTO_COMPACT_THRESHOLD_LIMITS.max)}`)
96
+ }
97
+ return { thresholdPercent }
98
+ }
99
+
100
+ /**
101
+ * Strictly parse the persisted codeSkeleton section. The gate is orthogonal
102
+ * to every profile: absent inherits the lossless `false` default, while a
103
+ * present-but-invalid section is an explicitly invalid document.
104
+ */
105
+ function parseCodeSkeletonSettings(value: unknown): CodeSkeletonSettings {
106
+ if (value === undefined) return { enabled: false }
107
+ if (!isPlainRecord(value)) {
108
+ throw new TypeError('Context-compression codeSkeleton must be a plain object')
109
+ }
110
+ const keys = Object.keys(value)
111
+ if (keys.length !== 1 || keys[0] !== 'enabled') {
112
+ throw new TypeError(`Context-compression codeSkeleton: expected exactly "enabled", got "${keys.join('", "')}"`)
113
+ }
114
+ const enabled = (value as Record<string, unknown>).enabled
115
+ if (typeof enabled !== 'boolean') {
116
+ throw new TypeError('Context-compression codeSkeleton.enabled must be a boolean')
117
+ }
118
+ return { enabled }
119
+ }
120
+
121
+ /**
122
+ * Strictly parse the persisted intentSummary section. Mirrors the codeSkeleton
123
+ * section semantics: absent inherits the lossless `false` default, while a
124
+ * present-but-invalid section is an explicitly invalid document.
125
+ */
126
+ function parseIntentSummarySettings(value: unknown): IntentSummarySettings {
127
+ if (value === undefined) return { enabled: false }
128
+ if (!isPlainRecord(value)) {
129
+ throw new TypeError('Context-compression intentSummary must be a plain object')
130
+ }
131
+ const keys = Object.keys(value)
132
+ if (keys.length !== 1 || keys[0] !== 'enabled') {
133
+ throw new TypeError(`Context-compression intentSummary: expected exactly "enabled", got "${keys.join('", "')}"`)
134
+ }
135
+ const enabled = (value as Record<string, unknown>).enabled
136
+ if (typeof enabled !== 'boolean') {
137
+ throw new TypeError('Context-compression intentSummary.enabled must be a boolean')
138
+ }
139
+ return { enabled }
140
+ }
141
+
142
+ /**
143
+ * Strictly parse the persisted monitorPanel section. Mirrors the intentSummary
144
+ * section semantics: absent inherits the hidden default, while a
145
+ * present-but-invalid section is an explicitly invalid document.
146
+ */
147
+ function parseMonitorPanelSettings(value: unknown): MonitorPanelSettings {
148
+ if (value === undefined) return { enabled: false }
149
+ if (!isPlainRecord(value)) {
150
+ throw new TypeError('Context-compression monitorPanel must be a plain object')
151
+ }
152
+ const keys = Object.keys(value)
153
+ if (keys.length !== 1 || keys[0] !== 'enabled') {
154
+ throw new TypeError(`Context-compression monitorPanel: expected exactly "enabled", got "${keys.join('", "')}"`)
155
+ }
156
+ const enabled = (value as Record<string, unknown>).enabled
157
+ if (typeof enabled !== 'boolean') {
158
+ throw new TypeError('Context-compression monitorPanel.enabled must be a boolean')
159
+ }
160
+ return { enabled }
161
+ }
162
+
163
+ /** Off defaults for the sediment gate; mirrored browser-side in profiles.ts DEFAULT_SEDIMENT_SETTINGS. */
164
+ export const DEFAULT_SEDIMENT_SETTINGS: SedimentSettings = {
165
+ enabled: false,
166
+ granularity: 'turn',
167
+ minClosingTokens: 120,
168
+ rewriteGuardRatio: 3,
169
+ maxTurnSpanTokens: 32_000,
170
+ }
171
+
172
+ const SEDIMENT_KEYS: ReadonlySet<string> = new Set([
173
+ 'enabled', 'granularity', 'minClosingTokens', 'rewriteGuardRatio', 'maxTurnSpanTokens', 'extraSignalPatterns',
174
+ 'foldMode', 'foldBaseUrl', 'foldBaseUrlKey', 'foldStrataProvider', 'foldStrataModel', 'foldLocal35Provider', 'foldLocal35Model',
175
+ ])
176
+
177
+ function isSafeSignalPatternSource(entry: unknown): boolean {
178
+ return typeof entry === 'string' && entry.length > 0 && entry.length <= 200
179
+ && (() => { try { new RegExp(entry); return true } catch { return false } })()
180
+ }
181
+
182
+ /**
183
+ * Strictly parse the persisted sediment section (plan cci-sedimentation-triage
184
+ * T0.2/T0.3): absent inherits the off defaults; present-but-invalid values
185
+ * throw — never coerced, never silently dropped.
186
+ */
187
+ function parseSedimentSettings(value: unknown): SedimentSettings {
188
+ if (value === undefined) return { ...DEFAULT_SEDIMENT_SETTINGS }
189
+ if (!isPlainRecord(value)) {
190
+ throw new TypeError('Context-compression sediment must be a plain object')
191
+ }
192
+ const unknownKey = Object.keys(value).find(key => !SEDIMENT_KEYS.has(key))
193
+ if (unknownKey !== undefined) {
194
+ throw new TypeError(`Context-compression sediment: unknown key "${unknownKey}"`)
195
+ }
196
+ if (value.enabled !== undefined && typeof value.enabled !== 'boolean') {
197
+ throw new TypeError('Context-compression sediment.enabled must be a boolean')
198
+ }
199
+ if (value.granularity !== undefined && value.granularity !== 'turn' && value.granularity !== 'span') {
200
+ throw new TypeError('Context-compression sediment.granularity must be "turn" or "span"')
201
+ }
202
+ const bounded: Array<[string, unknown, number, number]> = [
203
+ ['minClosingTokens', value.minClosingTokens, 40, 2_000],
204
+ ['rewriteGuardRatio', value.rewriteGuardRatio, 1, 10],
205
+ ['maxTurnSpanTokens', value.maxTurnSpanTokens, 4_000, 64_000],
206
+ ]
207
+ for (const [name, entry, min, max] of bounded) {
208
+ if (entry !== undefined
209
+ && (typeof entry !== 'number' || !Number.isSafeInteger(entry) || entry < min || entry > max)) {
210
+ throw new TypeError(`Context-compression sediment.${name} must be an integer in [${min}, ${max}]`)
211
+ }
212
+ }
213
+ if (value.extraSignalPatterns !== undefined) {
214
+ if (!Array.isArray(value.extraSignalPatterns)
215
+ || value.extraSignalPatterns.some(entry => !isSafeSignalPatternSource(entry))) {
216
+ throw new TypeError('Context-compression sediment.extraSignalPatterns must be parseable non-empty patterns')
217
+ }
218
+ }
219
+ if (value.foldMode !== undefined && value.foldMode !== '' && value.foldMode !== 'host' && value.foldMode !== 'direct') {
220
+ throw new TypeError('Context-compression sediment.foldMode must be "", "host", or "direct"')
221
+ }
222
+ for (const key of ['foldBaseUrl', 'foldBaseUrlKey', 'foldStrataProvider', 'foldStrataModel', 'foldLocal35Provider', 'foldLocal35Model'] as const) {
223
+ if (value[key] !== undefined && typeof value[key] !== 'string') {
224
+ throw new TypeError(`Context-compression sediment.${key} must be a string`)
225
+ }
226
+ }
227
+ return {
228
+ enabled: value.enabled as boolean | undefined ?? DEFAULT_SEDIMENT_SETTINGS.enabled,
229
+ granularity: value.granularity as 'turn' | 'span' | undefined ?? DEFAULT_SEDIMENT_SETTINGS.granularity,
230
+ minClosingTokens: value.minClosingTokens as number | undefined ?? DEFAULT_SEDIMENT_SETTINGS.minClosingTokens,
231
+ rewriteGuardRatio: value.rewriteGuardRatio as number | undefined ?? DEFAULT_SEDIMENT_SETTINGS.rewriteGuardRatio,
232
+ maxTurnSpanTokens: value.maxTurnSpanTokens as number | undefined ?? DEFAULT_SEDIMENT_SETTINGS.maxTurnSpanTokens,
233
+ ...value.extraSignalPatterns === undefined
234
+ ? {}
235
+ : { extraSignalPatterns: [...value.extraSignalPatterns as string[]] },
236
+ ...(value.foldMode === undefined ? {} : { foldMode: value.foldMode as '' | 'host' | 'direct' }),
237
+ ...(value.foldBaseUrl === undefined ? {} : { foldBaseUrl: value.foldBaseUrl as string }),
238
+ ...(value.foldBaseUrlKey === undefined ? {} : { foldBaseUrlKey: value.foldBaseUrlKey as string }),
239
+ ...(value.foldStrataProvider === undefined ? {} : { foldStrataProvider: value.foldStrataProvider as string }),
240
+ ...(value.foldStrataModel === undefined ? {} : { foldStrataModel: value.foldStrataModel as string }),
241
+ ...(value.foldLocal35Provider === undefined ? {} : { foldLocal35Provider: value.foldLocal35Provider as string }),
242
+ ...(value.foldLocal35Model === undefined ? {} : { foldLocal35Model: value.foldLocal35Model as string }),
243
+ }
244
+ }
245
+
246
+ /**
247
+ * Parse the optional tokenpilot-inspired preset sub-capability section. Absent
248
+ * inherits the preset defaults; present-but-invalid is rejected, mirroring the
249
+ * codeSkeleton section semantics.
250
+ */
251
+ export function parsePresetOptionsSettings(value: unknown): PresetOptionsSettings | undefined {
252
+ if (value === undefined) return undefined
253
+ if (!isPlainRecord(value)) {
254
+ throw new TypeError('Context-compression presetOptions must be a plain object')
255
+ }
256
+ const allowed = new Set([
257
+ 'dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState', 'estimatorMode',
258
+ 'estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey', 'estimatorTimeoutMs',
259
+ // Legacy keys of the retired human-gated review pipeline. They stay in the
260
+ // ACCEPTED set on purpose: the keys are persisted in existing settings
261
+ // documents, and rejecting them would make this plugin fail to load on an
262
+ // upgrade. They are read by nothing — the gate they configured no longer
263
+ // exists, and a reduction never blocks automatic processing.
264
+ 'reviewMode', 'reviewTimeoutTurns', 'cacheHitDiscountAlpha', 'reviewHighImpactTokens',
265
+ 'advisorMode', 'advisorTimeoutMs', 'advisorRefreshTurns', 'advisorScoreThreshold', 'advisorSampleLimit',
266
+ 'advisorMinTokens',
267
+ ])
268
+ const unknown = Object.keys(value).find(key => !allowed.has(key))
269
+ if (unknown !== undefined) {
270
+ throw new TypeError(`Context-compression presetOptions: unknown key "${unknown}"`)
271
+ }
272
+ const booleans = ['dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState'] as const
273
+ for (const key of booleans) {
274
+ const entry = value[key]
275
+ if (entry !== undefined && typeof entry !== 'boolean') {
276
+ throw new TypeError(`Context-compression presetOptions.${key} must be a boolean`)
277
+ }
278
+ }
279
+ const estimatorMode = value.estimatorMode
280
+ if (estimatorMode !== undefined && estimatorMode !== '' && estimatorMode !== 'host' && estimatorMode !== 'direct') {
281
+ throw new TypeError('Context-compression presetOptions.estimatorMode must be "", "host", or "direct"')
282
+ }
283
+ const advisorMode = value.advisorMode
284
+ if (advisorMode !== undefined && advisorMode !== '' && advisorMode !== 'host' && advisorMode !== 'direct') {
285
+ throw new TypeError('Context-compression presetOptions.advisorMode must be "", "host", or "direct"')
286
+ }
287
+ const advisorTimeoutMs = value.advisorTimeoutMs
288
+ if (advisorTimeoutMs !== undefined
289
+ && (typeof advisorTimeoutMs !== 'number' || !Number.isSafeInteger(advisorTimeoutMs)
290
+ || advisorTimeoutMs < 100 || advisorTimeoutMs > 60_000)) {
291
+ throw new TypeError('Context-compression presetOptions.advisorTimeoutMs must be an integer between 100 and 60000')
292
+ }
293
+ const advisorRefreshTurns = value.advisorRefreshTurns
294
+ if (advisorRefreshTurns !== undefined
295
+ && (typeof advisorRefreshTurns !== 'number' || !Number.isSafeInteger(advisorRefreshTurns)
296
+ || advisorRefreshTurns < 1)) {
297
+ throw new TypeError('Context-compression presetOptions.advisorRefreshTurns must be an integer of at least 1')
298
+ }
299
+ const advisorScoreThreshold = value.advisorScoreThreshold
300
+ if (advisorScoreThreshold !== undefined
301
+ && (typeof advisorScoreThreshold !== 'number' || !Number.isFinite(advisorScoreThreshold)
302
+ || advisorScoreThreshold <= 0 || advisorScoreThreshold >= 1)) {
303
+ throw new TypeError('Context-compression presetOptions.advisorScoreThreshold must be a number strictly between 0 and 1')
304
+ }
305
+ const advisorSampleLimit = value.advisorSampleLimit
306
+ if (advisorSampleLimit !== undefined
307
+ && (typeof advisorSampleLimit !== 'number' || !Number.isSafeInteger(advisorSampleLimit)
308
+ || advisorSampleLimit < 1 || advisorSampleLimit > 64)) {
309
+ throw new TypeError('Context-compression presetOptions.advisorSampleLimit must be an integer between 1 and 64')
310
+ }
311
+ const advisorMinTokens = value.advisorMinTokens
312
+ if (advisorMinTokens !== undefined
313
+ && (typeof advisorMinTokens !== 'number' || !Number.isSafeInteger(advisorMinTokens) || advisorMinTokens < 1)) {
314
+ throw new TypeError('Context-compression presetOptions.advisorMinTokens must be a positive integer')
315
+ }
316
+ const estimatorTimeoutMs = value.estimatorTimeoutMs
317
+ if (estimatorTimeoutMs !== undefined
318
+ && (typeof estimatorTimeoutMs !== 'number' || !Number.isSafeInteger(estimatorTimeoutMs)
319
+ || estimatorTimeoutMs < 100 || estimatorTimeoutMs > 60_000)) {
320
+ throw new TypeError('Context-compression presetOptions.estimatorTimeoutMs must be an integer between 100 and 60000')
321
+ }
322
+ for (const key of ['estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey'] as const) {
323
+ const entry = value[key]
324
+ if (entry !== undefined && typeof entry !== 'string') {
325
+ throw new TypeError(`Context-compression presetOptions.${key} must be a string`)
326
+ }
327
+ }
328
+ const result: {
329
+ -readonly [K in keyof PresetOptionsSettings]: PresetOptionsSettings[K]
330
+ } = {}
331
+ if (value.dedupeToolResults !== undefined) result.dedupeToolResults = value.dedupeToolResults as boolean
332
+ if (value.summaryLocator !== undefined) result.summaryLocator = value.summaryLocator as boolean
333
+ if (value.prefixStabilizer !== undefined) result.prefixStabilizer = value.prefixStabilizer as boolean
334
+ if (value.readState !== undefined) result.readState = value.readState as boolean
335
+ if (estimatorMode !== undefined) result.estimatorMode = estimatorMode as '' | 'host' | 'direct'
336
+ if (value.estimatorProvider !== undefined) result.estimatorProvider = value.estimatorProvider as string
337
+ if (value.estimatorModel !== undefined) result.estimatorModel = value.estimatorModel as string
338
+ if (value.estimatorBaseUrl !== undefined) result.estimatorBaseUrl = value.estimatorBaseUrl as string
339
+ if (value.estimatorApiKey !== undefined) result.estimatorApiKey = value.estimatorApiKey as string
340
+ if (estimatorTimeoutMs !== undefined) result.estimatorTimeoutMs = estimatorTimeoutMs as number
341
+ if (advisorMode !== undefined) result.advisorMode = advisorMode as '' | 'host' | 'direct'
342
+ if (advisorTimeoutMs !== undefined) result.advisorTimeoutMs = advisorTimeoutMs as number
343
+ if (advisorRefreshTurns !== undefined) result.advisorRefreshTurns = advisorRefreshTurns as number
344
+ if (advisorScoreThreshold !== undefined) result.advisorScoreThreshold = advisorScoreThreshold as number
345
+ if (advisorSampleLimit !== undefined) result.advisorSampleLimit = advisorSampleLimit as number
346
+ if (advisorMinTokens !== undefined) result.advisorMinTokens = advisorMinTokens as number
347
+ return result
348
+ }
349
+
350
+ /** Settings schema used by the user-facing profile selector. */
351
+ const contextCompressionSettingsInputSchema = z.object({
352
+ profile: z.union([...COMPRESSION_PROFILES]).default('balanced'),
353
+ custom: CustomCompressionPolicySchema.default(DEFAULT_CUSTOM_COMPRESSION_POLICY),
354
+ ptcCustom: CustomCompressionPolicySchema.default(DEFAULT_PTC_COMPRESSION_POLICY),
355
+ })
356
+
357
+ /**
358
+ * Reject a section that is PRESENT but not a usable value. Schemastery
359
+ * `.default(...)` silently substitutes null and undefined, which would turn a
360
+ * hand-corrupted store into the (lossy) default policy; only genuinely absent
361
+ * keys may inherit defaults, and that distinction must be made before any
362
+ * default can fire.
363
+ */
364
+ function assertPresentSection(
365
+ candidate: Record<string, unknown>,
366
+ key: 'profile' | 'custom' | 'ptcCustom',
367
+ valid: (value: unknown) => boolean,
368
+ ): void {
369
+ if (!Object.hasOwn(candidate, key)) return
370
+ if (!valid(candidate[key])) {
371
+ throw new TypeError(`Context-compression settings: "${key}" is present but invalid (${String(candidate[key])})`)
372
+ }
373
+ }
374
+
375
+ const isSupportedProfile = (value: unknown): boolean =>
376
+ typeof value === 'string' && (COMPRESSION_PROFILES as readonly string[]).includes(value)
377
+
378
+ const isUsableCustomDocument = (value: unknown): boolean =>
379
+ isPlainRecord(value)
380
+
381
+ export const DEFAULT_CONTEXT_COMPRESSION_SETTINGS: ContextCompressionSettings = {
382
+ profile: 'balanced',
383
+ custom: structuredClone(DEFAULT_CUSTOM_COMPRESSION_POLICY),
384
+ ptcCustom: structuredClone(DEFAULT_PTC_COMPRESSION_POLICY),
385
+ autoCompact: { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default },
386
+ codeSkeleton: { enabled: false },
387
+ intentSummary: { enabled: false },
388
+ monitorPanel: { enabled: false },
389
+ sediment: { ...DEFAULT_SEDIMENT_SETTINGS },
390
+ }
391
+
392
+ /**
393
+ * Parse one settings document with the persisted-section semantics: `undefined`
394
+ * inherits the defaults (an absent section), while `null` is an explicitly
395
+ * invalid document and must never silently become the default policy.
396
+ */
397
+ export function parseContextCompressionSettings(value: unknown): ContextCompressionSettings {
398
+ if (!isPlainRecord(value)) {
399
+ throw new TypeError('Context-compression settings must be a plain object')
400
+ }
401
+ const keys = Object.keys(value)
402
+ // Documents surfaced by the settings service are always schema-resolved and
403
+ // complete; anything thinner is a hand-edited store and must not silently
404
+ // become a default (possibly lossy) policy.
405
+ if (keys.length === 0 || !keys.includes('profile') || !keys.includes('custom')) {
406
+ throw new TypeError('Context-compression settings document is missing its complete shape')
407
+ }
408
+ return ContextCompressionSettingsSchema(value as never)
409
+ }
410
+
411
+ /** Settings schema used by the user-facing profile selector. */
412
+ export const ContextCompressionSettingsSchema: z<ContextCompressionSettings> = z.transform(
413
+ z.any().required(),
414
+ (value: unknown): ContextCompressionSettings => {
415
+ if (!isPlainRecord(value)) {
416
+ throw new TypeError('Context-compression settings must be a plain object')
417
+ }
418
+ // Validate prototypes before cloning, then parse a detached mutable copy:
419
+ // SettingsProvider returns frozen records, while structuredClone would
420
+ // otherwise erase exotic prototypes before this boundary can reject them.
421
+ assertPlainDataTree(value)
422
+ const candidate = structuredClone(value)
423
+ // Settings stored before the autoCompact or codeSkeleton sections existed
424
+ // remain valid and inherit their defaults; the sections themselves stay
425
+ // strictly shaped.
426
+ const unknown = Object.keys(candidate).find(key =>
427
+ key !== 'profile' && key !== 'custom' && key !== 'ptcCustom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'intentSummary' && key !== 'monitorPanel' && key !== 'sediment' && key !== 'presetOptions')
428
+ if (unknown !== undefined) {
429
+ throw new TypeError(`Context-compression settings: unknown key "${unknown}"`)
430
+ }
431
+ // Present-but-invalid sections must never fall through to the Schemastery
432
+ // defaults below: `profile: null` silently becoming the lossy `balanced`
433
+ // default is exactly the corruption the lossless-off fallback exists for.
434
+ // Only genuinely absent sections (internal partial fallbacks) may inherit.
435
+ assertPresentSection(candidate, 'profile', isSupportedProfile)
436
+ assertPresentSection(candidate, 'custom', isUsableCustomDocument)
437
+ assertPresentSection(candidate, 'ptcCustom', isUsableCustomDocument)
438
+ const autoCompact = parseAutoCompactSettings(candidate.autoCompact)
439
+ const codeSkeleton = parseCodeSkeletonSettings(candidate.codeSkeleton)
440
+ const intentSummary = parseIntentSummarySettings(candidate.intentSummary)
441
+ const monitorPanel = parseMonitorPanelSettings(candidate.monitorPanel)
442
+ const sediment = parseSedimentSettings(candidate.sediment)
443
+ const presetOptions = parsePresetOptionsSettings(candidate.presetOptions)
444
+ return {
445
+ ...contextCompressionSettingsInputSchema(candidate),
446
+ autoCompact,
447
+ codeSkeleton,
448
+ intentSummary,
449
+ monitorPanel,
450
+ sediment,
451
+ ...presetOptions === undefined ? {} : { presetOptions },
452
+ }
453
+ },
454
+ ).default(DEFAULT_CONTEXT_COMPRESSION_SETTINGS) as z<ContextCompressionSettings>
455
+
456
+ /** Low-friction defaults; token budgets live in resolved profile policy. */
457
+ export const DEFAULTS: ResolvedConfig = deepFreeze({
458
+ profile: 'balanced',
459
+ headChars: 4096,
460
+ tailChars: 1024,
461
+ })
462
+
463
+ const CONFIG_KEYS: ReadonlySet<string> = new Set([
464
+ 'profile',
465
+ 'headChars',
466
+ 'tailChars',
467
+ 'nativeTriggerTokens',
468
+ 'nativeTargetTokens',
469
+ 'freshTriggerTokens',
470
+ 'freshTargetTokens',
471
+ 'aggregateTriggerTokens',
472
+ 'aggregateTargetTokens',
473
+ 'historyTriggerTokens',
474
+ 'historyKeepRecentToolCalls',
475
+ 'historyKeepRecentTokens',
476
+ 'historyMinReclaimTokens',
477
+ 'readInputCapChars',
478
+ 'autoCompactThresholdPercent',
479
+ 'presetOptions',
480
+ ])
481
+
482
+ const LEGACY_GATE_REPLACEMENTS: Readonly<Record<string, string>> = Object.freeze({
483
+ thresholdChars: 'nativeTriggerTokens',
484
+ freshThresholdChars: 'freshTriggerTokens',
485
+ freshTargetChars: 'freshTargetTokens',
486
+ freshBatchTriggerChars: 'aggregateTriggerTokens',
487
+ freshBatchTargetChars: 'aggregateTargetTokens',
488
+ historyTriggerChars: 'historyTriggerTokens',
489
+ historyKeepRecentChars: 'historyKeepRecentTokens',
490
+ historyMinReclaimChars: 'historyMinReclaimTokens',
491
+ historyKeepRecentTurns: 'historyKeepRecentToolCalls',
492
+ })
493
+
494
+ /**
495
+ * Count Unicode code points without splitting surrogate pairs.
496
+ * @param text - text whose code points are counted.
497
+ * @returns the number of Unicode code points.
498
+ */
499
+ export function codePointLength(text: string): number {
500
+ let length = 0
501
+ for (const _point of text) length++
502
+ return length
503
+ }
504
+
505
+ /**
506
+ * Conservative upper bound on characters per token. Same convention the
507
+ * readInputCapChars invariant already uses (see resolvePolicy): English
508
+ * code runs approximately four characters per token at the upper bound.
509
+ */
510
+ export const CHARS_PER_TOKEN = 4.0
511
+
512
+ /** Express one token-named policy gate on the character basis. */
513
+ export function charsForTokens(tokens: number): number {
514
+ return tokens * CHARS_PER_TOKEN
515
+ }
516
+
517
+ /** Derive the telemetry-only token figure from a character measurement. */
518
+ export function charsToTokens(chars: number): number {
519
+ if (!Number.isFinite(chars) || chars <= 0) return 0
520
+ return Math.max(1, Math.round(chars / CHARS_PER_TOKEN))
521
+ }
522
+
523
+ /**
524
+ * Test whether a settings value names a supported compression profile.
525
+ * @param value - untrusted settings value.
526
+ * @returns whether the value is a supported compression profile.
527
+ */
528
+ export function isCompressionProfile(value: unknown): value is CompressionProfile {
529
+ return typeof value === 'string' && (COMPRESSION_PROFILES as readonly string[]).includes(value)
530
+ }
531
+
532
+ /**
533
+ * Resolve and validate plugin configuration.
534
+ * @param config - optional composition overrides.
535
+ * @returns a detached, deeply immutable configuration snapshot.
536
+ */
537
+ export function resolveConfig(config: ToolResultPruneConfig = {}): ResolvedConfig {
538
+ for (const key of Object.keys(config)) {
539
+ const replacement = LEGACY_GATE_REPLACEMENTS[key]
540
+ if (replacement !== undefined) {
541
+ throw new Error(
542
+ `ToolResultPruneConfig: legacy gate "${key}" is no longer accepted; `
543
+ + `choose "${replacement}" manually in tokens (no character conversion is applied)`,
544
+ )
545
+ }
546
+ if (!CONFIG_KEYS.has(key)) {
547
+ throw new Error(`ToolResultPruneConfig: unknown key "${key}"`)
548
+ }
549
+ }
550
+ const resolved: ResolvedConfig = {
551
+ profile: config.profile ?? DEFAULTS.profile,
552
+ headChars: config.headChars ?? DEFAULTS.headChars,
553
+ tailChars: config.tailChars ?? DEFAULTS.tailChars,
554
+ ...config.nativeTriggerTokens === undefined ? {} : { nativeTriggerTokens: config.nativeTriggerTokens },
555
+ ...config.nativeTargetTokens === undefined ? {} : { nativeTargetTokens: config.nativeTargetTokens },
556
+ ...config.freshTriggerTokens === undefined ? {} : { freshTriggerTokens: config.freshTriggerTokens },
557
+ ...config.freshTargetTokens === undefined ? {} : { freshTargetTokens: config.freshTargetTokens },
558
+ ...config.aggregateTriggerTokens === undefined ? {} : { aggregateTriggerTokens: config.aggregateTriggerTokens },
559
+ ...config.aggregateTargetTokens === undefined ? {} : { aggregateTargetTokens: config.aggregateTargetTokens },
560
+ ...config.historyTriggerTokens === undefined ? {} : { historyTriggerTokens: config.historyTriggerTokens },
561
+ ...config.historyKeepRecentToolCalls === undefined ? {} : { historyKeepRecentToolCalls: config.historyKeepRecentToolCalls },
562
+ ...config.historyKeepRecentTokens === undefined ? {} : { historyKeepRecentTokens: config.historyKeepRecentTokens },
563
+ ...config.historyMinReclaimTokens === undefined ? {} : { historyMinReclaimTokens: config.historyMinReclaimTokens },
564
+ ...config.readInputCapChars === undefined ? {} : { readInputCapChars: config.readInputCapChars },
565
+ ...config.autoCompactThresholdPercent === undefined ? {} : { autoCompactThresholdPercent: config.autoCompactThresholdPercent },
566
+ ...config.presetOptions === undefined ? {} : { presetOptions: config.presetOptions },
567
+ }
568
+ if (!isCompressionProfile(resolved.profile)) {
569
+ throw new Error(`ToolResultPruneConfig: unsupported profile "${String(resolved.profile)}"`)
570
+ }
571
+ assertNonNegativeInteger('headChars', resolved.headChars)
572
+ assertNonNegativeInteger('tailChars', resolved.tailChars)
573
+ for (const key of [
574
+ 'nativeTriggerTokens', 'nativeTargetTokens', 'freshTriggerTokens', 'freshTargetTokens',
575
+ 'aggregateTriggerTokens', 'aggregateTargetTokens', 'historyTriggerTokens',
576
+ 'historyMinReclaimTokens', 'readInputCapChars',
577
+ ] as const) {
578
+ const value = resolved[key]
579
+ if (value !== undefined) assertPositiveInteger(key, value)
580
+ }
581
+ if (resolved.historyKeepRecentToolCalls !== undefined) {
582
+ assertNonNegativeInteger('historyKeepRecentToolCalls', resolved.historyKeepRecentToolCalls)
583
+ }
584
+ if (resolved.historyKeepRecentTokens !== undefined) {
585
+ assertNonNegativeInteger('historyKeepRecentTokens', resolved.historyKeepRecentTokens)
586
+ }
587
+ if (resolved.autoCompactThresholdPercent !== undefined
588
+ && !isValidAutoCompactThresholdPercent(resolved.autoCompactThresholdPercent)) {
589
+ throw new Error(`ToolResultPruneConfig: autoCompactThresholdPercent (${String(resolved.autoCompactThresholdPercent)}) must be an integer between ${String(AUTO_COMPACT_THRESHOLD_LIMITS.min)} and ${String(AUTO_COMPACT_THRESHOLD_LIMITS.max)}`)
590
+ }
591
+ assertTargetBelowTrigger('native', resolved.nativeTargetTokens, resolved.nativeTriggerTokens)
592
+ assertTargetBelowTrigger('fresh', resolved.freshTargetTokens, resolved.freshTriggerTokens)
593
+ assertTargetBelowTrigger('aggregate', resolved.aggregateTargetTokens, resolved.aggregateTriggerTokens)
594
+ return deepFreeze(structuredClone(resolved))
595
+ }
596
+
597
+ /** Per-profile History linkage ratios applied to the Auto Compact watermark. */
598
+ const AUTO_COMPACT_HISTORY_RATIOS: Readonly<Record<string, Readonly<{
599
+ trigger: number
600
+ minReclaim: number
601
+ keepRecentTokens: number
602
+ }>>> = Object.freeze({
603
+ balanced: Object.freeze({ trigger: 0.625, minReclaim: 0.12, keepRecentTokens: 0.08 }),
604
+ savings: Object.freeze({ trigger: 0.50, minReclaim: 0.16, keepRecentTokens: 0.08 }),
605
+ 'cache-strict': Object.freeze({ trigger: 0.75, minReclaim: 0.16, keepRecentTokens: 0.08 }),
606
+ adaptive: Object.freeze({ trigger: 0.625, minReclaim: 0.12, keepRecentTokens: 0.08 }),
607
+ 'tokenpilot-inspired': Object.freeze({ trigger: 0.625, minReclaim: 0.12, keepRecentTokens: 0.08 }),
608
+ })
609
+
610
+ /** Micro-compact last-chance ratio: `D = floor(A × 0.875)`. */
611
+ const MICRO_DEADLINE_RATIO = 0.875
612
+
613
+ /**
614
+ * TokenPilot-inspired sub-capability defaults. Every capability is on except
615
+ * the estimator, which requires an explicit endpoint channel (host or direct)
616
+ * before any consumer may leave its rule-only fallback.
617
+ */
618
+ const PRESET_OPTION_DEFAULTS: PresetOptions = deepFreeze({
619
+ noNetSavingsGuard: true,
620
+ skipReductionRecovery: true,
621
+ dedupeToolResults: true,
622
+ summaryLocator: true,
623
+ prefixStabilizer: true,
624
+ readState: true,
625
+ estimator: { mode: '' },
626
+ // Advisory advisor ships off: statistics and suggestions only, never a gate.
627
+ advisor: {
628
+ mode: '',
629
+ timeoutMs: 8_000,
630
+ refreshTurns: 8,
631
+ scoreThreshold: 0.35,
632
+ sampleLimit: 16,
633
+ minTokens: 250,
634
+ },
635
+ })
636
+
637
+ /**
638
+ * Merge persisted presetOptions overrides over the tokenpilot-inspired
639
+ * defaults. Persisted booleans are three-state (undefined = inherit); the
640
+ * estimator channel overrides the default empty mode wholesale.
641
+ */
642
+ function mergePresetOptions(overrides: PresetOptionsSettings | undefined): PresetOptions {
643
+ if (overrides === undefined) return PRESET_OPTION_DEFAULTS
644
+ return deepFreeze({
645
+ noNetSavingsGuard: true,
646
+ skipReductionRecovery: true,
647
+ dedupeToolResults: overrides.dedupeToolResults ?? PRESET_OPTION_DEFAULTS.dedupeToolResults,
648
+ summaryLocator: overrides.summaryLocator ?? PRESET_OPTION_DEFAULTS.summaryLocator,
649
+ prefixStabilizer: overrides.prefixStabilizer ?? PRESET_OPTION_DEFAULTS.prefixStabilizer,
650
+ readState: overrides.readState ?? PRESET_OPTION_DEFAULTS.readState,
651
+ estimator: { mode: overrides.estimatorMode ?? PRESET_OPTION_DEFAULTS.estimator.mode },
652
+ advisor: {
653
+ mode: overrides.advisorMode ?? PRESET_OPTION_DEFAULTS.advisor.mode,
654
+ timeoutMs: overrides.advisorTimeoutMs ?? PRESET_OPTION_DEFAULTS.advisor.timeoutMs,
655
+ refreshTurns: overrides.advisorRefreshTurns ?? PRESET_OPTION_DEFAULTS.advisor.refreshTurns,
656
+ scoreThreshold: overrides.advisorScoreThreshold ?? PRESET_OPTION_DEFAULTS.advisor.scoreThreshold,
657
+ sampleLimit: overrides.advisorSampleLimit ?? PRESET_OPTION_DEFAULTS.advisor.sampleLimit,
658
+ minTokens: overrides.advisorMinTokens ?? PRESET_OPTION_DEFAULTS.advisor.minTokens,
659
+ },
660
+ })
661
+ }
662
+
663
+ /**
664
+ * Resolve the Auto-Compact-linked History watermarks for one standard profile.
665
+ *
666
+ * `A = floor(C × a)` is the Auto Compact token watermark for the routed
667
+ * context window `C` and the user threshold `a = p / 100`; the History
668
+ * trigger, minimum reclaim, and recent-token tail scale with `A`, and the
669
+ * micro-compact last-chance deadline is `D = floor(A × 0.875)`. At the shipped
670
+ * defaults (`C = 1,000,000`, `p = 80`) the ratios reproduce the previous fixed
671
+ * preset numbers exactly. Custom stays manual and Off/Native run no History,
672
+ * so none of them link.
673
+ */
674
+ function resolveAutoCompactLinkage(
675
+ profile: CompressionProfile,
676
+ options: CustomPolicyResolutionOptions,
677
+ ): { autoCompactTokens: number, microDeadlineTokens: number, historyTriggerTokens: number,
678
+ historyMinReclaimTokens: number, historyKeepRecentTokens: number } | undefined {
679
+ const ratios = profile === 'custom' ? undefined : AUTO_COMPACT_HISTORY_RATIOS[profile]
680
+ const contextWindow = options.contextWindowTokens
681
+ const threshold = options.autoCompactThresholdPercent
682
+ if (ratios === undefined) return undefined
683
+ if (!isValidAutoCompactThresholdPercent(threshold)) return undefined
684
+ if (!Number.isSafeInteger(contextWindow) || contextWindow === undefined || contextWindow <= 0) return undefined
685
+ // Mirror compaction-basic's evaluation order exactly: it multiplies by the
686
+ // generated ratio float (p / 100), and integer-first division differs by
687
+ // one token on some window/percent pairs (200k x 57).
688
+ const autoCompactTokens = Math.floor(contextWindow * (threshold / 100))
689
+ if (!Number.isSafeInteger(autoCompactTokens) || autoCompactTokens <= 0) return undefined
690
+ const linked = {
691
+ autoCompactTokens,
692
+ microDeadlineTokens: Math.floor(autoCompactTokens * MICRO_DEADLINE_RATIO),
693
+ historyTriggerTokens: Math.floor(ratios.trigger * autoCompactTokens),
694
+ historyMinReclaimTokens: Math.floor(ratios.minReclaim * autoCompactTokens),
695
+ historyKeepRecentTokens: Math.floor(ratios.keepRecentTokens * autoCompactTokens),
696
+ }
697
+ for (const value of Object.values(linked)) {
698
+ if (!Number.isSafeInteger(value) || value <= 0) return undefined
699
+ }
700
+ return linked
701
+ }
702
+
703
+ /**
704
+ * Resolve one public profile into a complete mixed-strategy policy.
705
+ * @param config - validated composition configuration.
706
+ * @param profile - profile frozen for the target Session.
707
+ * @param custom - versioned Custom document used only by the `custom` profile.
708
+ * @param options - routed capacity and the frozen Auto Compact threshold used
709
+ * to resolve context-percent Custom values and standard-profile linkage.
710
+ * @returns the effective deterministic compression policy.
711
+ */
712
+ export function resolvePolicy(
713
+ config: ResolvedConfig,
714
+ profile: CompressionProfile,
715
+ custom: CustomCompressionPolicy = DEFAULT_CUSTOM_COMPRESSION_POLICY,
716
+ options: CustomPolicyResolutionOptions = {},
717
+ ptcCustom: CustomCompressionPolicy = DEFAULT_PTC_COMPRESSION_POLICY,
718
+ ): CompressionPolicy {
719
+ if (profile === 'custom') return resolveCustomPolicy(custom, options)
720
+ if (profile === 'ptc') {
721
+ const resolved = resolveCustomPolicy(ptcCustom, options)
722
+ const policy: CompressionPolicy = {
723
+ ...resolved,
724
+ profile: 'ptc',
725
+ freshTriggerTokens: config.freshTriggerTokens ?? resolved.freshTriggerTokens,
726
+ freshTargetTokens: config.freshTargetTokens ?? resolved.freshTargetTokens,
727
+ aggregateTriggerTokens: config.aggregateTriggerTokens ?? resolved.aggregateTriggerTokens,
728
+ aggregateTargetTokens: config.aggregateTargetTokens ?? resolved.aggregateTargetTokens,
729
+ historyTriggerTokens: config.historyTriggerTokens ?? resolved.historyTriggerTokens,
730
+ historyKeepRecentToolCalls: config.historyKeepRecentToolCalls ?? resolved.historyKeepRecentToolCalls,
731
+ historyKeepRecentTokens: config.historyKeepRecentTokens ?? resolved.historyKeepRecentTokens,
732
+ historyMinReclaimTokens: config.historyMinReclaimTokens ?? resolved.historyMinReclaimTokens,
733
+ ...config.readInputCapChars === undefined ? {} : { readInputCapChars: config.readInputCapChars },
734
+ }
735
+ if (policy.freshTargetTokens >= policy.freshTriggerTokens && policy.freshEnabled) {
736
+ throw new Error('context compression policy: fresh target must be below trigger')
737
+ }
738
+ if (policy.aggregateTargetTokens >= policy.aggregateTriggerTokens && policy.aggregateEnabled) {
739
+ throw new Error('context compression policy: aggregate target must be below trigger')
740
+ }
741
+ if (policy.readInputCapChars !== undefined && policy.readInputCapChars <= policy.freshTriggerTokens * 4.0) {
742
+ throw new Error('context compression policy: read input cap would silence the fresh path')
743
+ }
744
+ return deepFreeze(policy)
745
+ }
746
+ if (profile === 'tokenpilot-inspired') {
747
+ const resolved = resolveCustomPolicy(custom, options)
748
+ const policy: CompressionPolicy = {
749
+ ...resolved,
750
+ profile: 'tokenpilot-inspired',
751
+ freshTriggerTokens: config.freshTriggerTokens ?? resolved.freshTriggerTokens,
752
+ freshTargetTokens: config.freshTargetTokens ?? resolved.freshTargetTokens,
753
+ aggregateTriggerTokens: config.aggregateTriggerTokens ?? resolved.aggregateTriggerTokens,
754
+ aggregateTargetTokens: config.aggregateTargetTokens ?? resolved.aggregateTargetTokens,
755
+ historyTriggerTokens: config.historyTriggerTokens ?? resolved.historyTriggerTokens,
756
+ historyKeepRecentToolCalls: config.historyKeepRecentToolCalls ?? resolved.historyKeepRecentToolCalls,
757
+ historyKeepRecentTokens: config.historyKeepRecentTokens ?? resolved.historyKeepRecentTokens,
758
+ historyMinReclaimTokens: config.historyMinReclaimTokens ?? resolved.historyMinReclaimTokens,
759
+ ...config.readInputCapChars === undefined ? {} : { readInputCapChars: config.readInputCapChars },
760
+ presetOptions: mergePresetOptions(config.presetOptions),
761
+ }
762
+ if (policy.freshTargetTokens >= policy.freshTriggerTokens && policy.freshEnabled) {
763
+ throw new Error('context compression policy: fresh target must be below trigger')
764
+ }
765
+ if (policy.aggregateTargetTokens >= policy.aggregateTriggerTokens && policy.aggregateEnabled) {
766
+ throw new Error('context compression policy: aggregate target must be below trigger')
767
+ }
768
+ return deepFreeze(policy)
769
+ }
770
+ const presets: Record<Exclude<CompressionProfile, 'custom' | 'tokenpilot-inspired' | 'ptc'>, Omit<CompressionPolicy, 'profile'>> = {
771
+ off: {
772
+ nativeToolResultEnabled: false, freshEnabled: false, aggregateEnabled: false, historyMode: 'disabled',
773
+ nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
774
+ freshTriggerTokens: Number.MAX_SAFE_INTEGER, freshTargetTokens: Number.MAX_SAFE_INTEGER,
775
+ aggregateTriggerTokens: Number.MAX_SAFE_INTEGER, aggregateTargetTokens: Number.MAX_SAFE_INTEGER,
776
+ historyTriggerTokens: Number.MAX_SAFE_INTEGER, historyKeepRecentToolCalls: 10,
777
+ historyKeepRecentTokens: 64_000, historyMinReclaimTokens: Number.MAX_SAFE_INTEGER,
778
+ },
779
+ native: {
780
+ nativeToolResultEnabled: true, freshEnabled: false, aggregateEnabled: false, historyMode: 'disabled',
781
+ nativeTriggerTokens: 4_096, nativeTargetTokens: 2_048,
782
+ freshTriggerTokens: Number.MAX_SAFE_INTEGER, freshTargetTokens: Number.MAX_SAFE_INTEGER,
783
+ aggregateTriggerTokens: Number.MAX_SAFE_INTEGER, aggregateTargetTokens: Number.MAX_SAFE_INTEGER,
784
+ historyTriggerTokens: Number.MAX_SAFE_INTEGER, historyKeepRecentToolCalls: 10,
785
+ historyKeepRecentTokens: 64_000, historyMinReclaimTokens: Number.MAX_SAFE_INTEGER,
786
+ },
787
+ balanced: {
788
+ nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'routine',
789
+ nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
790
+ freshTriggerTokens: 8_192, freshTargetTokens: 3_072,
791
+ aggregateTriggerTokens: 32_768, aggregateTargetTokens: 12_288,
792
+ historyTriggerTokens: 500_000, historyKeepRecentToolCalls: 10,
793
+ historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 96_000,
794
+ },
795
+ 'cache-strict': {
796
+ nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'capacity-pressure',
797
+ nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
798
+ freshTriggerTokens: 8_192, freshTargetTokens: 3_072,
799
+ aggregateTriggerTokens: 32_768, aggregateTargetTokens: 12_288,
800
+ historyTriggerTokens: 600_000, historyKeepRecentToolCalls: 10,
801
+ historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 128_000,
802
+ },
803
+ savings: {
804
+ nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'routine',
805
+ nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
806
+ freshTriggerTokens: 4_096, freshTargetTokens: 1_536,
807
+ aggregateTriggerTokens: 16_384, aggregateTargetTokens: 4_096,
808
+ historyTriggerTokens: 400_000, historyKeepRecentToolCalls: 10,
809
+ historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 128_000,
810
+ },
811
+ adaptive: {
812
+ nativeToolResultEnabled: false, freshEnabled: true, aggregateEnabled: true, historyMode: 'adaptive',
813
+ nativeTriggerTokens: Number.MAX_SAFE_INTEGER, nativeTargetTokens: Number.MAX_SAFE_INTEGER,
814
+ freshTriggerTokens: 8_192, freshTargetTokens: 3_072,
815
+ aggregateTriggerTokens: 32_768, aggregateTargetTokens: 12_288,
816
+ historyTriggerTokens: 500_000, historyKeepRecentToolCalls: 10,
817
+ historyKeepRecentTokens: 64_000, historyMinReclaimTokens: 96_000,
818
+ },
819
+ }
820
+ const preset = presets[profile]
821
+ const linkage = resolveAutoCompactLinkage(profile, options)
822
+ const policy: CompressionPolicy = {
823
+ profile,
824
+ ...preset,
825
+ nativeTriggerTokens: config.nativeTriggerTokens ?? preset.nativeTriggerTokens,
826
+ nativeTargetTokens: config.nativeTargetTokens ?? preset.nativeTargetTokens,
827
+ freshTriggerTokens: config.freshTriggerTokens ?? preset.freshTriggerTokens,
828
+ freshTargetTokens: config.freshTargetTokens ?? preset.freshTargetTokens,
829
+ aggregateTriggerTokens: config.aggregateTriggerTokens ?? preset.aggregateTriggerTokens,
830
+ aggregateTargetTokens: config.aggregateTargetTokens ?? preset.aggregateTargetTokens,
831
+ historyTriggerTokens: config.historyTriggerTokens
832
+ ?? linkage?.historyTriggerTokens ?? preset.historyTriggerTokens,
833
+ historyKeepRecentToolCalls: config.historyKeepRecentToolCalls ?? preset.historyKeepRecentToolCalls,
834
+ historyKeepRecentTokens: config.historyKeepRecentTokens
835
+ ?? linkage?.historyKeepRecentTokens ?? preset.historyKeepRecentTokens,
836
+ historyMinReclaimTokens: config.historyMinReclaimTokens
837
+ ?? linkage?.historyMinReclaimTokens ?? preset.historyMinReclaimTokens,
838
+ ...config.readInputCapChars === undefined ? {} : { readInputCapChars: config.readInputCapChars },
839
+ ...linkage === undefined ? {} : {
840
+ autoCompactTokens: linkage.autoCompactTokens,
841
+ microDeadlineTokens: linkage.microDeadlineTokens,
842
+ },
843
+ }
844
+ if (policy.nativeTargetTokens >= policy.nativeTriggerTokens && profile === 'native') {
845
+ throw new Error('context compression policy: native target must be below trigger')
846
+ }
847
+ if (policy.freshTargetTokens >= policy.freshTriggerTokens && policy.freshEnabled) {
848
+ throw new Error('context compression policy: fresh target must be below trigger')
849
+ }
850
+ if (policy.aggregateTargetTokens >= policy.aggregateTriggerTokens && policy.freshEnabled) {
851
+ throw new Error('context compression policy: aggregate target must be below trigger')
852
+ }
853
+ // G2 invariant: the fresh trigger is in TOKENS while a read input cap is in
854
+ // CHARACTERS. English code runs ≈4.0 chars/token at the conservative upper
855
+ // bound, so a cap at or below `freshTriggerTokens × 4.0` would truncate every
856
+ // read result below the trigger and silently silence the fresh path.
857
+ if (policy.readInputCapChars !== undefined
858
+ && policy.readInputCapChars <= policy.freshTriggerTokens * 4.0) {
859
+ throw new Error('context compression policy: read input cap would silence the fresh path')
860
+ }
861
+ return deepFreeze(policy)
862
+ }
863
+
864
+ function assertTargetBelowTrigger(
865
+ label: string,
866
+ target: number | undefined,
867
+ trigger: number | undefined,
868
+ ): void {
869
+ if ((target === undefined) !== (trigger === undefined)) {
870
+ throw new Error(`ToolResultPruneConfig: ${label} target and trigger tokens must be provided together`)
871
+ }
872
+ if (target !== undefined && trigger !== undefined && target >= trigger) {
873
+ throw new Error(`ToolResultPruneConfig: ${label} target tokens must be below trigger tokens`)
874
+ }
875
+ }
876
+
877
+ function assertPositiveInteger(name: string, value: number): void {
878
+ if (!Number.isSafeInteger(value) || value <= 0) {
879
+ throw new Error(`ToolResultPruneConfig: ${name} (${String(value)}) must be a positive safe integer`)
880
+ }
881
+ }
882
+
883
+ function assertNonNegativeInteger(name: string, value: number): void {
884
+ if (!Number.isSafeInteger(value) || value < 0) {
885
+ throw new Error(`ToolResultPruneConfig: ${name} (${String(value)}) must be a non-negative safe integer`)
886
+ }
887
+ }