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

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