dsh-context-compression-improved 0.10.4 → 0.10.5

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