dsh-context-compression-improved 0.11.0 → 0.11.2

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 (310) hide show
  1. package/README.md +15 -110
  2. package/README.zh.md +14 -104
  3. package/THIRD_PARTY_NOTICES.md +25 -7
  4. package/{packages/selector/dsh.plugin.json → dsh.plugin.json} +2 -2
  5. package/{packages/selector/lib → lib}/index.js +101 -0
  6. package/package.json +129 -116
  7. package/screenshots.json +3 -6
  8. package/.agents/plans/improve/checklist.md +0 -32
  9. package/.agents/plans/improve/findings.md +0 -102
  10. package/.agents/plans/improve/spec.md +0 -53
  11. package/.agents/plans/improve/tasks.md +0 -70
  12. package/.gitattributes +0 -2
  13. package/.githooks/pre-push +0 -37
  14. package/.github/workflows/ci.yml +0 -47
  15. package/CHANGELOG.de.md +0 -580
  16. package/CHANGELOG.es.md +0 -588
  17. package/CHANGELOG.fr.md +0 -576
  18. package/CHANGELOG.it.md +0 -577
  19. package/CHANGELOG.ja.md +0 -261
  20. package/CHANGELOG.ko.md +0 -254
  21. package/CHANGELOG.md +0 -557
  22. package/CHANGELOG.ru.md +0 -554
  23. package/CHANGELOG.zh.md +0 -247
  24. package/CONTRIBUTING.md +0 -22
  25. package/README.de.md +0 -96
  26. package/README.es.md +0 -96
  27. package/README.fr.md +0 -96
  28. package/README.it.md +0 -96
  29. package/README.ja.md +0 -102
  30. package/README.ko.md +0 -102
  31. package/README.ru.md +0 -96
  32. package/SECURITY.md +0 -18
  33. package/assets/board.png +0 -0
  34. package/assets/context.png +0 -0
  35. package/docs/assets/context-compression-selector-profiles.jpg +0 -0
  36. package/docs/assets/context-compression-selector-settings.png +0 -0
  37. package/docs/compat-0.1.5-report.md +0 -77
  38. package/docs/installation.de.md +0 -104
  39. package/docs/installation.es.md +0 -104
  40. package/docs/installation.fr.md +0 -104
  41. package/docs/installation.it.md +0 -104
  42. package/docs/installation.ja.md +0 -78
  43. package/docs/installation.ko.md +0 -78
  44. package/docs/installation.md +0 -103
  45. package/docs/installation.ru.md +0 -104
  46. package/docs/installation.zh.md +0 -100
  47. package/docs/repair-log.md +0 -657
  48. package/docs/shallow-teaching-preset-template.md +0 -46
  49. package/eslint.config.js +0 -30
  50. package/packages/selector/LICENSE +0 -21
  51. package/packages/selector/README.md +0 -26
  52. package/packages/selector/README.zh.md +0 -24
  53. package/packages/selector/THIRD_PARTY_NOTICES.md +0 -32
  54. package/packages/selector/docs/history-tool-call-working-set-spec.md +0 -112
  55. package/packages/selector/docs/native-tool-result-selector-spec.md +0 -34
  56. package/packages/selector/docs/subagent-cache-reuse-spec.md +0 -46
  57. package/packages/selector/lib/style.css +0 -350
  58. package/packages/selector/package.json +0 -178
  59. package/packages/selector/screenshots.json +0 -3
  60. package/packages/selector/src/client/CompressionProfileControls.tsx +0 -352
  61. package/packages/selector/src/client/CompressionProfileSelector.module.css +0 -199
  62. package/packages/selector/src/client/CompressionProfileSelector.tsx +0 -89
  63. package/packages/selector/src/client/CustomPolicyEditor.tsx +0 -216
  64. package/packages/selector/src/client/EstimatorControls.tsx +0 -277
  65. package/packages/selector/src/client/bridge-scope.ts +0 -125
  66. package/packages/selector/src/client/decode.ts +0 -68
  67. package/packages/selector/src/client/fab-pos.ts +0 -71
  68. package/packages/selector/src/client/index.ts +0 -438
  69. package/packages/selector/src/client/locales/de.ts +0 -167
  70. package/packages/selector/src/client/locales/es.ts +0 -167
  71. package/packages/selector/src/client/locales/fr.ts +0 -167
  72. package/packages/selector/src/client/locales/it.ts +0 -167
  73. package/packages/selector/src/client/locales/ja.ts +0 -167
  74. package/packages/selector/src/client/locales/ko.ts +0 -167
  75. package/packages/selector/src/client/locales/ru.ts +0 -167
  76. package/packages/selector/src/client/locales.ts +0 -334
  77. package/packages/selector/src/client/monitor-fab.ts +0 -445
  78. package/packages/selector/src/client/preset-options.ts +0 -88
  79. package/packages/selector/src/client/savings-card.tsx +0 -269
  80. package/packages/selector/src/client/scope-face.ts +0 -24
  81. package/packages/selector/src/client/settings-section.tsx +0 -156
  82. package/packages/selector/src/compat/host-generation.ts +0 -96
  83. package/packages/selector/src/compat/llm-messages.ts +0 -50
  84. package/packages/selector/src/compat/settings-lease.ts +0 -108
  85. package/packages/selector/src/compat/tool-result.ts +0 -91
  86. package/packages/selector/src/css-modules.d.ts +0 -6
  87. package/packages/selector/src/deepseek-v4-tokenizer.ts +0 -205
  88. package/packages/selector/src/estimator-catalog.ts +0 -104
  89. package/packages/selector/src/index.ts +0 -890
  90. package/packages/selector/src/invariant.ts +0 -113
  91. package/packages/selector/src/preset-overlay.ts +0 -749
  92. package/packages/selector/src/profiles.ts +0 -554
  93. package/packages/selector/src/pruner/content.ts +0 -199
  94. package/packages/selector/src/pruner/session.ts +0 -97
  95. package/packages/selector/src/pruner/state.ts +0 -61
  96. package/packages/selector/src/pruner/tuning.ts +0 -23
  97. package/packages/selector/src/pruner/types.ts +0 -78
  98. package/packages/selector/src/pruner.ts +0 -3222
  99. package/packages/selector/src/runtime/adaptive-cost.ts +0 -205
  100. package/packages/selector/src/runtime/audit.ts +0 -321
  101. package/packages/selector/src/runtime/config.ts +0 -887
  102. package/packages/selector/src/runtime/custom-policy.ts +0 -300
  103. package/packages/selector/src/runtime/deepseek-official-pricing.ts +0 -298
  104. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +0 -254
  105. package/packages/selector/src/runtime/display-prefs.ts +0 -98
  106. package/packages/selector/src/runtime/fold-router.ts +0 -143
  107. package/packages/selector/src/runtime/measurement.ts +0 -444
  108. package/packages/selector/src/runtime/monitor.ts +0 -341
  109. package/packages/selector/src/runtime/panel-command.ts +0 -213
  110. package/packages/selector/src/runtime/reducers.ts +0 -1755
  111. package/packages/selector/src/runtime/retrieve.ts +0 -505
  112. package/packages/selector/src/runtime/savings-integral.ts +0 -117
  113. package/packages/selector/src/runtime/savings-projection.ts +0 -229
  114. package/packages/selector/src/runtime/savings-verify.ts +0 -446
  115. package/packages/selector/src/runtime/savings.ts +0 -526
  116. package/packages/selector/src/runtime/sediment-card.ts +0 -126
  117. package/packages/selector/src/runtime/sediment-clock.ts +0 -87
  118. package/packages/selector/src/runtime/sediment-guard.ts +0 -136
  119. package/packages/selector/src/runtime/sediment-publish.ts +0 -144
  120. package/packages/selector/src/runtime/sediment-span.ts +0 -170
  121. package/packages/selector/src/runtime/sediment.ts +0 -209
  122. package/packages/selector/src/runtime/session-events.ts +0 -30
  123. package/packages/selector/src/runtime/session-file-decode.ts +0 -523
  124. package/packages/selector/src/runtime/shallow-tools.ts +0 -342
  125. package/packages/selector/src/runtime/stats-backfill.ts +0 -541
  126. package/packages/selector/src/runtime/stats-db.ts +0 -492
  127. package/packages/selector/src/runtime/stats-schema.ts +0 -123
  128. package/packages/selector/src/runtime/stats-sync.ts +0 -307
  129. package/packages/selector/src/runtime/summary-command.ts +0 -127
  130. package/packages/selector/src/runtime/tail-trim.ts +0 -177
  131. package/packages/selector/src/runtime/token-count.ts +0 -72
  132. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +0 -233
  133. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +0 -204
  134. package/packages/selector/src/runtime/tokenpilot/advisor.ts +0 -419
  135. package/packages/selector/src/runtime/tokenpilot/benefit.ts +0 -200
  136. package/packages/selector/src/runtime/tokenpilot/dedup.ts +0 -82
  137. package/packages/selector/src/runtime/tokenpilot/estimator.ts +0 -151
  138. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +0 -53
  139. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +0 -65
  140. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +0 -125
  141. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +0 -37
  142. package/packages/selector/src/runtime/tokenpilot/locator.ts +0 -129
  143. package/packages/selector/src/runtime/tokenpilot/read-state.ts +0 -98
  144. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +0 -303
  145. package/packages/selector/src/runtime/tool-names.ts +0 -42
  146. package/packages/selector/src/runtime/toolclass.ts +0 -103
  147. package/packages/selector/src/runtime/triage/masks.ts +0 -128
  148. package/packages/selector/src/runtime/triage/shallow.ts +0 -132
  149. package/packages/selector/src/runtime/triage/signals.ts +0 -167
  150. package/packages/selector/src/runtime/triage/types.ts +0 -125
  151. package/packages/selector/src/runtime/types.ts +0 -396
  152. package/packages/selector/src/runtime/value.ts +0 -48
  153. package/packages/selector/src/settings-bridge.ts +0 -175
  154. package/packages/selector/tests/advisor-report.host.spec.ts +0 -223
  155. package/packages/selector/tests/auto-compact.client.spec.tsx +0 -214
  156. package/packages/selector/tests/built/client-artifact.spec.ts +0 -56
  157. package/packages/selector/tests/cache-prefix-audit.spec.ts +0 -123
  158. package/packages/selector/tests/code-skeleton.client.spec.ts +0 -98
  159. package/packages/selector/tests/compat/compat-narrow-waist.spec.ts +0 -150
  160. package/packages/selector/tests/custom-contract.client.spec.ts +0 -226
  161. package/packages/selector/tests/estimator-catalog.spec.ts +0 -70
  162. package/packages/selector/tests/estimator-channel.client.spec.tsx +0 -253
  163. package/packages/selector/tests/estimator-route-registration.host.spec.ts +0 -202
  164. package/packages/selector/tests/fab-pos.client.spec.ts +0 -47
  165. package/packages/selector/tests/fixtures/sediment-pool/52adc205-cloud-5.orig.txt +0 -231
  166. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-25.orig.txt +0 -236
  167. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-38.orig.txt +0 -220
  168. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-42.orig.txt +0 -140
  169. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-53.orig.txt +0 -117
  170. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-local-10.orig.txt +0 -67
  171. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-45.orig.txt +0 -119
  172. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-49.orig.txt +0 -119
  173. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-63.orig.txt +0 -131
  174. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-75.orig.txt +0 -196
  175. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-76.orig.txt +0 -71
  176. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-85.orig.txt +0 -126
  177. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-86.orig.txt +0 -86
  178. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-87.orig.txt +0 -50
  179. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-96.orig.txt +0 -102
  180. package/packages/selector/tests/helpers/legacy-namespace.ts +0 -35
  181. package/packages/selector/tests/helpers/legacy-settings/index.ts +0 -15
  182. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +0 -41
  183. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +0 -647
  184. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +0 -78
  185. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +0 -234
  186. package/packages/selector/tests/host-preset-overlay.host.spec.ts +0 -204
  187. package/packages/selector/tests/monitor-fab.client.spec.ts +0 -240
  188. package/packages/selector/tests/preset-options-write.client.spec.ts +0 -192
  189. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +0 -200
  190. package/packages/selector/tests/preset-overlay.host.spec.ts +0 -246
  191. package/packages/selector/tests/profiles.client.spec.tsx +0 -436
  192. package/packages/selector/tests/ptc-custom-write.client.spec.ts +0 -86
  193. package/packages/selector/tests/public/package-contract.client.spec.ts +0 -89
  194. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +0 -167
  195. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +0 -230
  196. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +0 -272
  197. package/packages/selector/tests/runtime/advisor.spec.ts +0 -226
  198. package/packages/selector/tests/runtime/audit.spec.ts +0 -275
  199. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +0 -523
  200. package/packages/selector/tests/runtime/char-basis.spec.ts +0 -30
  201. package/packages/selector/tests/runtime/code-skeleton.spec.ts +0 -152
  202. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +0 -186
  203. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +0 -122
  204. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +0 -122
  205. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +0 -96
  206. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +0 -273
  207. package/packages/selector/tests/runtime/fixtures/session-v4-dump.jsonl +0 -46
  208. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +0 -106
  209. package/packages/selector/tests/runtime/fixtures/vision-golden.json +0 -459
  210. package/packages/selector/tests/runtime/fold-router.spec.ts +0 -140
  211. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +0 -74
  212. package/packages/selector/tests/runtime/fresh-gate.spec.ts +0 -43
  213. package/packages/selector/tests/runtime/html-reducer.spec.ts +0 -212
  214. package/packages/selector/tests/runtime/intent-gate.spec.ts +0 -62
  215. package/packages/selector/tests/runtime/intent-summary.spec.ts +0 -156
  216. package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +0 -79
  217. package/packages/selector/tests/runtime/line-mapping.spec.ts +0 -153
  218. package/packages/selector/tests/runtime/monitor.spec.ts +0 -354
  219. package/packages/selector/tests/runtime/panel-command.spec.ts +0 -101
  220. package/packages/selector/tests/runtime/prose-reducers.spec.ts +0 -133
  221. package/packages/selector/tests/runtime/ptc-profile.spec.ts +0 -133
  222. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +0 -2795
  223. package/packages/selector/tests/runtime/read-input-cap.spec.ts +0 -33
  224. package/packages/selector/tests/runtime/savings-accounting.spec.ts +0 -291
  225. package/packages/selector/tests/runtime/savings-integral.spec.ts +0 -169
  226. package/packages/selector/tests/runtime/savings-projection.spec.ts +0 -89
  227. package/packages/selector/tests/runtime/savings-verify.spec.ts +0 -226
  228. package/packages/selector/tests/runtime/savings.spec.ts +0 -139
  229. package/packages/selector/tests/runtime/search-reducer.spec.ts +0 -110
  230. package/packages/selector/tests/runtime/sediment-card.spec.ts +0 -111
  231. package/packages/selector/tests/runtime/sediment-config.spec.ts +0 -56
  232. package/packages/selector/tests/runtime/sediment-guard.spec.ts +0 -71
  233. package/packages/selector/tests/runtime/sediment-masks.spec.ts +0 -95
  234. package/packages/selector/tests/runtime/sediment-orchestrator.spec.ts +0 -166
  235. package/packages/selector/tests/runtime/sediment-pool-share.spec.ts +0 -65
  236. package/packages/selector/tests/runtime/sediment-publish.spec.ts +0 -142
  237. package/packages/selector/tests/runtime/sediment-real-shapes.spec.ts +0 -158
  238. package/packages/selector/tests/runtime/sediment-settings.spec.ts +0 -73
  239. package/packages/selector/tests/runtime/sediment-signals.spec.ts +0 -124
  240. package/packages/selector/tests/runtime/sediment-span.spec.ts +0 -92
  241. package/packages/selector/tests/runtime/session-events.spec.ts +0 -27
  242. package/packages/selector/tests/runtime/session-file-decode.spec.ts +0 -281
  243. package/packages/selector/tests/runtime/settings-unwrap.spec.ts +0 -58
  244. package/packages/selector/tests/runtime/shallow-primitives.spec.ts +0 -135
  245. package/packages/selector/tests/runtime/sidechannel.spec.ts +0 -241
  246. package/packages/selector/tests/runtime/stats-backfill-scheduler.spec.ts +0 -167
  247. package/packages/selector/tests/runtime/stats-backfill.spec.ts +0 -350
  248. package/packages/selector/tests/runtime/stats-db.spec.ts +0 -361
  249. package/packages/selector/tests/runtime/stats-privacy.spec.ts +0 -55
  250. package/packages/selector/tests/runtime/stats-sync.spec.ts +0 -278
  251. package/packages/selector/tests/runtime/summary-command.spec.ts +0 -154
  252. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +0 -159
  253. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +0 -53
  254. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +0 -217
  255. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +0 -52
  256. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +0 -79
  257. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +0 -76
  258. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +0 -121
  259. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +0 -82
  260. package/packages/selector/tests/runtime/toolclass.spec.ts +0 -156
  261. package/packages/selector/tests/runtime/value.spec.ts +0 -23
  262. package/packages/selector/tests/savings-sessions.client.spec.tsx +0 -140
  263. package/packages/selector/tests/settings-seat.client.spec.ts +0 -215
  264. package/packages/selector/tests/standing-generation.host.spec.ts +0 -724
  265. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +0 -269
  266. package/packages/selector/tests/support/cache-prefix-audit.ts +0 -105
  267. package/packages/selector/tests/support/mock-adapter.ts +0 -37
  268. package/packages/selector/tests/support/ui-primitives.tsx +0 -34
  269. package/packages/selector/tsconfig.json +0 -11
  270. package/packages/selector/tsdown.client.config.ts +0 -102
  271. package/packages/selector/tsdown.config.ts +0 -20
  272. package/pnpm-workspace.yaml +0 -76
  273. package/scripts/capture-profile-baseline.mjs +0 -42
  274. package/scripts/cell-browser-e2e.mjs +0 -354
  275. package/scripts/generate-tokenizer-fixtures.py +0 -81
  276. package/scripts/generate-vision-fixtures.py +0 -208
  277. package/scripts/hosts.d.mts +0 -3
  278. package/scripts/hosts.mjs +0 -79
  279. package/scripts/packed-components-smoke.mjs +0 -763
  280. package/scripts/packed-install-e2e.mjs +0 -1346
  281. package/scripts/sediment-latency-report.mjs +0 -63
  282. package/scripts/sync-hosts.mjs +0 -174
  283. package/scripts/toolclass-corpus-replay.mjs +0 -281
  284. package/scripts/verify-release.mjs +0 -343
  285. package/tests/TEST_INVENTORY.md +0 -41
  286. package/tsconfig.base.json +0 -18
  287. package/tsconfig.json +0 -7
  288. package/tsconfig.tests.json +0 -15
  289. package/vitest.built.config.ts +0 -9
  290. package/vitest.config.ts +0 -54
  291. /package/{packages/selector/assets → assets}/deepseek-v4/LICENSE.DeepSeek-V4-Pro.txt +0 -0
  292. /package/{packages/selector/assets → assets}/deepseek-v4/manifest.json +0 -0
  293. /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer.json +0 -0
  294. /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer_config.json +0 -0
  295. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/LICENSE.DeepSeek-V4-Flash-Vision-Exp.txt +0 -0
  296. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/manifest.json +0 -0
  297. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer.json +0 -0
  298. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer_config.json +0 -0
  299. /package/{packages/selector/cordis.patch.yml → cordis.patch.yml} +0 -0
  300. /package/{packages/selector/lib → lib}/client.d.ts +0 -0
  301. /package/{packages/selector/lib → lib}/client.js +0 -0
  302. /package/{packages/selector/lib → lib}/index.d.ts +0 -0
  303. /package/{packages/selector/lib → lib}/invariant.d.ts +0 -0
  304. /package/{packages/selector/lib → lib}/invariant.js +0 -0
  305. /package/{packages/selector/lib → lib}/profiles.d.ts +0 -0
  306. /package/{packages/selector/lib → lib}/pruner.d.ts +0 -0
  307. /package/{packages/selector/lib → lib}/pruner.js +0 -0
  308. /package/{packages/selector/lib → lib}/savings-integral.js +0 -0
  309. /package/{packages/selector/lib → lib}/tail-trim.js +0 -0
  310. /package/{packages/selector/lib → lib}/tool-result.js +0 -0
@@ -1,887 +0,0 @@
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
- }