dsh-context-compression-improved 0.5.6 → 0.5.8

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 (183) hide show
  1. package/.gitattributes +2 -2
  2. package/.githooks/pre-push +37 -37
  3. package/.github/workflows/ci.yml +39 -39
  4. package/CHANGELOG.ja.md +169 -169
  5. package/CHANGELOG.ko.md +167 -167
  6. package/CHANGELOG.md +323 -304
  7. package/CHANGELOG.zh.md +152 -152
  8. package/CONTRIBUTING.md +22 -22
  9. package/LICENSE +21 -21
  10. package/README.ja.md +85 -85
  11. package/README.ko.md +85 -85
  12. package/README.md +94 -94
  13. package/README.zh.md +85 -85
  14. package/SECURITY.md +18 -18
  15. package/THIRD_PARTY_NOTICES.md +14 -14
  16. package/docs/compat-0.1.5-report.md +77 -77
  17. package/docs/installation.ja.md +78 -78
  18. package/docs/installation.ko.md +78 -78
  19. package/docs/installation.md +103 -103
  20. package/docs/installation.zh.md +100 -100
  21. package/docs/repair-log.md +657 -657
  22. package/eslint.config.js +30 -30
  23. package/package.json +163 -164
  24. package/packages/selector/LICENSE +21 -21
  25. package/packages/selector/README.md +26 -26
  26. package/packages/selector/README.zh.md +24 -24
  27. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -32
  28. package/packages/selector/cordis.patch.yml +27 -27
  29. package/packages/selector/docs/history-tool-call-working-set-spec.md +112 -112
  30. package/packages/selector/docs/native-tool-result-selector-spec.md +34 -34
  31. package/packages/selector/docs/subagent-cache-reuse-spec.md +46 -46
  32. package/packages/selector/dsh.plugin.json +16 -16
  33. package/packages/selector/lib/client.d.ts +59 -0
  34. package/packages/selector/lib/client.js +1738 -10
  35. package/packages/selector/lib/{advisor-state.js → config.js} +816 -65
  36. package/packages/selector/lib/index.d.ts +13 -1
  37. package/packages/selector/lib/index.js +295 -3
  38. package/packages/selector/lib/pruner.d.ts +65 -0
  39. package/packages/selector/lib/pruner.js +497 -262
  40. package/packages/selector/lib/style.css +88 -46
  41. package/packages/selector/package.json +114 -114
  42. package/packages/selector/screenshots.json +3 -3
  43. package/packages/selector/src/client/CompressionProfileControls.tsx +293 -226
  44. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  45. package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -83
  46. package/packages/selector/src/client/CustomPolicyEditor.tsx +216 -216
  47. package/packages/selector/src/client/EstimatorControls.tsx +277 -277
  48. package/packages/selector/src/client/decode.ts +57 -49
  49. package/packages/selector/src/client/index.ts +240 -149
  50. package/packages/selector/src/client/locales/de.ts +141 -0
  51. package/packages/selector/src/client/locales/es.ts +141 -0
  52. package/packages/selector/src/client/locales/fr.ts +141 -0
  53. package/packages/selector/src/client/locales/it.ts +141 -0
  54. package/packages/selector/src/client/locales/ja.ts +141 -0
  55. package/packages/selector/src/client/locales/ko.ts +141 -0
  56. package/packages/selector/src/client/locales/ru.ts +141 -0
  57. package/packages/selector/src/client/locales.ts +282 -196
  58. package/packages/selector/src/client/monitor-fab.ts +336 -0
  59. package/packages/selector/src/client/preset-options.ts +88 -88
  60. package/packages/selector/src/client/savings-card.tsx +150 -0
  61. package/packages/selector/src/client/settings-section.tsx +140 -124
  62. package/packages/selector/src/css-modules.d.ts +6 -6
  63. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -205
  64. package/packages/selector/src/estimator-catalog.ts +104 -104
  65. package/packages/selector/src/index.ts +673 -463
  66. package/packages/selector/src/invariant.ts +113 -113
  67. package/packages/selector/src/preset-overlay.ts +626 -626
  68. package/packages/selector/src/profiles.ts +431 -394
  69. package/packages/selector/src/pruner/content.ts +201 -201
  70. package/packages/selector/src/pruner/session.ts +94 -94
  71. package/packages/selector/src/pruner/state.ts +57 -50
  72. package/packages/selector/src/pruner/tuning.ts +23 -23
  73. package/packages/selector/src/pruner/types.ts +78 -78
  74. package/packages/selector/src/pruner.ts +2736 -2402
  75. package/packages/selector/src/runtime/adaptive-cost.ts +205 -205
  76. package/packages/selector/src/runtime/audit.ts +303 -286
  77. package/packages/selector/src/runtime/config.ts +756 -706
  78. package/packages/selector/src/runtime/custom-policy.ts +278 -278
  79. package/packages/selector/src/runtime/deepseek-official-pricing.ts +298 -298
  80. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +254 -254
  81. package/packages/selector/src/runtime/measurement.ts +436 -436
  82. package/packages/selector/src/runtime/monitor.ts +235 -0
  83. package/packages/selector/src/runtime/reducers.ts +1674 -1674
  84. package/packages/selector/src/runtime/retrieve.ts +479 -457
  85. package/packages/selector/src/runtime/savings.ts +337 -0
  86. package/packages/selector/src/runtime/session-events.ts +30 -30
  87. package/packages/selector/src/runtime/summary-command.ts +127 -0
  88. package/packages/selector/src/runtime/tail-trim.ts +166 -166
  89. package/packages/selector/src/runtime/token-count.ts +72 -72
  90. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -188
  91. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -149
  92. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -419
  93. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -200
  94. package/packages/selector/src/runtime/tokenpilot/dedup.ts +81 -81
  95. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -151
  96. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  97. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  98. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  99. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  100. package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -128
  101. package/packages/selector/src/runtime/tokenpilot/read-state.ts +98 -98
  102. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -303
  103. package/packages/selector/src/runtime/toolclass.ts +103 -103
  104. package/packages/selector/src/runtime/types.ts +365 -346
  105. package/packages/selector/src/runtime/value.ts +48 -48
  106. package/packages/selector/tests/advisor-report.host.spec.ts +223 -223
  107. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -213
  108. package/packages/selector/tests/built/client-artifact.spec.ts +59 -59
  109. package/packages/selector/tests/cache-prefix-audit.spec.ts +123 -123
  110. package/packages/selector/tests/code-skeleton.client.spec.ts +91 -90
  111. package/packages/selector/tests/custom-contract.client.spec.ts +205 -204
  112. package/packages/selector/tests/estimator-catalog.spec.ts +70 -70
  113. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -252
  114. package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -188
  115. package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -206
  116. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  117. package/packages/selector/tests/preset-options-write.client.spec.ts +207 -206
  118. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -201
  119. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -246
  120. package/packages/selector/tests/profiles.client.spec.tsx +436 -434
  121. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -78
  122. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +167 -167
  123. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -232
  124. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -272
  125. package/packages/selector/tests/runtime/advisor.spec.ts +226 -226
  126. package/packages/selector/tests/runtime/audit.spec.ts +275 -274
  127. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -523
  128. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -30
  129. package/packages/selector/tests/runtime/code-skeleton.spec.ts +152 -152
  130. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +186 -186
  131. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -122
  132. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +122 -122
  133. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -96
  134. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +273 -273
  135. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +106 -106
  136. package/packages/selector/tests/runtime/fixtures/vision-golden.json +459 -459
  137. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -74
  138. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -212
  139. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  140. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  141. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -153
  142. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  143. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -133
  144. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2724
  145. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -33
  146. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  147. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -110
  148. package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
  149. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -241
  150. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  151. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -159
  152. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +53 -53
  153. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -217
  154. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +52 -52
  155. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -79
  156. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +76 -76
  157. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -116
  158. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +82 -82
  159. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -156
  160. package/packages/selector/tests/runtime/value.spec.ts +23 -23
  161. package/packages/selector/tests/settings-seat.client.spec.ts +130 -118
  162. package/packages/selector/tests/standing-generation.host.spec.ts +697 -697
  163. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -253
  164. package/packages/selector/tests/support/cache-prefix-audit.ts +105 -105
  165. package/packages/selector/tests/support/mock-adapter.ts +37 -37
  166. package/packages/selector/tests/support/ui-primitives.tsx +34 -34
  167. package/packages/selector/tsconfig.json +11 -11
  168. package/packages/selector/tsdown.client.config.ts +102 -102
  169. package/packages/selector/tsdown.config.ts +20 -20
  170. package/pnpm-workspace.yaml +66 -66
  171. package/scripts/capture-profile-baseline.mjs +42 -42
  172. package/scripts/generate-tokenizer-fixtures.py +81 -81
  173. package/scripts/generate-vision-fixtures.py +208 -208
  174. package/scripts/packed-components-smoke.mjs +732 -732
  175. package/scripts/packed-install-e2e.mjs +1273 -1273
  176. package/scripts/toolclass-corpus-replay.mjs +281 -281
  177. package/scripts/verify-release.mjs +318 -317
  178. package/tests/TEST_INVENTORY.md +41 -41
  179. package/tsconfig.base.json +18 -18
  180. package/tsconfig.json +7 -7
  181. package/tsconfig.tests.json +15 -15
  182. package/vitest.built.config.ts +9 -9
  183. package/vitest.config.ts +43 -43
@@ -1,394 +1,431 @@
1
- /** Public context-compression choices shared by the Host schema and browser selector. */
2
- export const COMPRESSION_PROFILES = [
3
- 'off',
4
- 'native',
5
- 'balanced',
6
- 'cache-strict',
7
- 'savings',
8
- 'adaptive',
9
- 'tokenpilot-inspired',
10
- 'custom',
11
- ] as const
12
-
13
- /** One supported context-compression profile. */
14
- export type CompressionProfile = typeof COMPRESSION_PROFILES[number]
15
-
16
- /** Single canonical unit stored by a version-1 browser Custom document. */
17
- export type CustomCompressionUnit = 'tokens' | 'context-percent'
18
-
19
- /** Whether Custom History may routinely rewrite an already-sent prefix. */
20
- export type CustomPrefixPolicy = 'preserve' | 'pressure-break'
21
-
22
- /** Browser representation of one independently enabled Fresh or Aggregate budget. */
23
- export interface CustomCompressionBudget {
24
- enabled: boolean
25
- trigger: number
26
- target: number
27
- }
28
-
29
- /** Legacy browser representation of the Custom History working set. */
30
- export interface LegacyCustomHistoryPolicy {
31
- enabled: boolean
32
- trigger: number
33
- keepRecentTurns: number
34
- keepRecent: number
35
- minReclaim: number
36
- }
37
-
38
- /** Browser representation of Custom History tool-call and token-tail protection. */
39
- export interface CustomHistoryPolicy {
40
- enabled: boolean
41
- trigger: number
42
- keepRecentToolCalls: number
43
- keepRecentTokens: number
44
- minReclaim: number
45
- }
46
-
47
- /** Browser representation of the Custom-only Experimental TailTrim gate. */
48
- export interface CustomTailTrimPolicy {
49
- enabled: boolean
50
- trigger: number
51
- }
52
-
53
- interface CustomCompressionPolicyCommon<HistoryPolicy> {
54
- unit: CustomCompressionUnit
55
- fresh: CustomCompressionBudget
56
- aggregate: CustomCompressionBudget
57
- history: HistoryPolicy
58
- prefixPolicy: CustomPrefixPolicy
59
- }
60
-
61
- /** Legacy public Custom document; accepted and normalized before editing. */
62
- export interface CustomCompressionPolicyV1 extends CustomCompressionPolicyCommon<LegacyCustomHistoryPolicy> {
63
- version: 1
64
- }
65
-
66
- /** Legacy Custom document with a default-disabled TailTrim stage. */
67
- export interface CustomCompressionPolicyV2 extends CustomCompressionPolicyCommon<LegacyCustomHistoryPolicy> {
68
- version: 2
69
- tailTrim: CustomTailTrimPolicy
70
- }
71
-
72
- /** Public Custom document with tool-call working-set protection. */
73
- export interface CustomCompressionPolicyV3 extends CustomCompressionPolicyCommon<CustomHistoryPolicy> {
74
- version: 3
75
- tailTrim: CustomTailTrimPolicy
76
- }
77
-
78
- /** Exact public Custom document accepted by the Host and browser boundary. */
79
- export type CustomCompressionPolicy = CustomCompressionPolicyV1 | CustomCompressionPolicyV2 | CustomCompressionPolicyV3
80
-
81
- /** Browser-safe mirror of the Host's Balanced-equivalent Custom default. */
82
- export const DEFAULT_CUSTOM_COMPRESSION_POLICY: CustomCompressionPolicyV3 = {
83
- version: 3,
84
- unit: 'tokens',
85
- fresh: { enabled: true, trigger: 8_192, target: 3_072 },
86
- aggregate: { enabled: true, trigger: 32_768, target: 12_288 },
87
- history: {
88
- enabled: true,
89
- trigger: 500_000,
90
- keepRecentToolCalls: 10,
91
- keepRecentTokens: 64_000,
92
- minReclaim: 96_000,
93
- },
94
- prefixPolicy: 'pressure-break',
95
- tailTrim: { enabled: false, trigger: 700_000 },
96
- }
97
-
98
- /** User-tunable Auto Compact coordination preferences. */
99
- export interface AutoCompactSettings {
100
- thresholdPercent: number
101
- }
102
-
103
- /**
104
- * Orthogonal code-skeleton reducer gate, mirrored browser-safe from the
105
- * runtime: independent of every profile, default off.
106
- */
107
- export interface CodeSkeletonSettings {
108
- enabled: boolean
109
- }
110
-
111
- /**
112
- * Decode the persisted codeSkeleton section with exactly the runtime schema's
113
- * strictness: absent means the lossless off default; present values must be a
114
- * plain object carrying only a boolean `enabled`. Anything else is invalid,
115
- * never silently coerced.
116
- */
117
- export function decodeCodeSkeletonSettings(value: unknown): CodeSkeletonSettings | undefined {
118
- if (value === undefined) return { enabled: false }
119
- if (!isPlainRecord(value)) return undefined
120
- const keys = Object.keys(value)
121
- if (keys.length !== 1 || keys[0] !== 'enabled') return undefined
122
- const enabled = (value as Record<string, unknown>).enabled
123
- return typeof enabled === 'boolean' ? { enabled } : undefined
124
- }
125
-
126
- /** Browser-safe mirror of the runtime presetOptions section. */
127
- export interface PresetOptionsSettings {
128
- readonly dedupeToolResults?: boolean
129
- readonly summaryLocator?: boolean
130
- readonly prefixStabilizer?: boolean
131
- readonly readState?: boolean
132
- readonly estimatorMode?: '' | 'host' | 'direct'
133
- readonly estimatorProvider?: string
134
- readonly estimatorModel?: string
135
- readonly estimatorBaseUrl?: string
136
- readonly estimatorApiKey?: string
137
- readonly estimatorTimeoutMs?: number
138
- /** Advisory advisor channel; `''` (the default) keeps the advisor off. */
139
- readonly advisorMode?: '' | 'host' | 'direct'
140
- readonly advisorTimeoutMs?: number
141
- readonly advisorRefreshTurns?: number
142
- readonly advisorScoreThreshold?: number
143
- readonly advisorSampleLimit?: number
144
- readonly advisorMinTokens?: number
145
- }
146
-
147
- /**
148
- * Browser mirror of the runtime presetOptions section: absent inherits the
149
- * preset defaults (decodes to `undefined`); present values must be a plain
150
- * object carrying only the known keys with valid types.
151
- */
152
- export function decodePresetOptionsSettings(value: unknown): PresetOptionsSettings | undefined {
153
- if (value === undefined) return undefined
154
- if (!isPlainRecord(value)) return undefined
155
- const allowed = new Set([
156
- 'dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState', 'estimatorMode',
157
- 'estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey', 'estimatorTimeoutMs',
158
- // Legacy keys of the retired review gate: still ACCEPTED so an existing
159
- // settings document keeps decoding (rejecting them would report the whole
160
- // card unreadable), and ignored — nothing reads them any more.
161
- 'reviewMode', 'reviewTimeoutTurns', 'cacheHitDiscountAlpha', 'reviewHighImpactTokens',
162
- 'advisorMode', 'advisorTimeoutMs', 'advisorRefreshTurns', 'advisorScoreThreshold', 'advisorSampleLimit',
163
- 'advisorMinTokens',
164
- ])
165
- if (Object.keys(value).some(key => !allowed.has(key))) return undefined
166
- for (const key of ['dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState'] as const) {
167
- const entry = value[key]
168
- if (entry !== undefined && typeof entry !== 'boolean') return undefined
169
- }
170
- const estimatorMode = value.estimatorMode
171
- if (estimatorMode !== undefined && estimatorMode !== '' && estimatorMode !== 'host' && estimatorMode !== 'direct') {
172
- return undefined
173
- }
174
- const advisorMode = value.advisorMode
175
- if (advisorMode !== undefined && advisorMode !== '' && advisorMode !== 'host' && advisorMode !== 'direct') {
176
- return undefined
177
- }
178
- for (const key of ['estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey'] as const) {
179
- const entry = value[key]
180
- if (entry !== undefined && typeof entry !== 'string') return undefined
181
- }
182
- const estimatorTimeoutMs = value.estimatorTimeoutMs
183
- if (estimatorTimeoutMs !== undefined
184
- && (typeof estimatorTimeoutMs !== 'number' || !Number.isSafeInteger(estimatorTimeoutMs)
185
- || estimatorTimeoutMs < 100 || estimatorTimeoutMs > 60_000)) {
186
- return undefined
187
- }
188
- const advisorTimeoutMs = value.advisorTimeoutMs
189
- if (advisorTimeoutMs !== undefined
190
- && (typeof advisorTimeoutMs !== 'number' || !Number.isSafeInteger(advisorTimeoutMs)
191
- || advisorTimeoutMs < 100 || advisorTimeoutMs > 60_000)) {
192
- return undefined
193
- }
194
- const advisorRefreshTurns = value.advisorRefreshTurns
195
- if (advisorRefreshTurns !== undefined
196
- && (typeof advisorRefreshTurns !== 'number' || !Number.isSafeInteger(advisorRefreshTurns)
197
- || advisorRefreshTurns < 1)) {
198
- return undefined
199
- }
200
- const advisorScoreThreshold = value.advisorScoreThreshold
201
- if (advisorScoreThreshold !== undefined
202
- && (typeof advisorScoreThreshold !== 'number' || !Number.isFinite(advisorScoreThreshold)
203
- || advisorScoreThreshold <= 0 || advisorScoreThreshold >= 1)) {
204
- return undefined
205
- }
206
- const advisorSampleLimit = value.advisorSampleLimit
207
- if (advisorSampleLimit !== undefined
208
- && (typeof advisorSampleLimit !== 'number' || !Number.isSafeInteger(advisorSampleLimit)
209
- || advisorSampleLimit < 1 || advisorSampleLimit > 64)) {
210
- return undefined
211
- }
212
- const advisorMinTokens = value.advisorMinTokens
213
- if (advisorMinTokens !== undefined
214
- && (typeof advisorMinTokens !== 'number' || !Number.isSafeInteger(advisorMinTokens) || advisorMinTokens < 1)) {
215
- return undefined
216
- }
217
- const decoded: {
218
- -readonly [K in keyof PresetOptionsSettings]: PresetOptionsSettings[K]
219
- } = {}
220
- if (value.dedupeToolResults !== undefined) decoded.dedupeToolResults = value.dedupeToolResults as boolean
221
- if (value.summaryLocator !== undefined) decoded.summaryLocator = value.summaryLocator as boolean
222
- if (value.prefixStabilizer !== undefined) decoded.prefixStabilizer = value.prefixStabilizer as boolean
223
- if (value.readState !== undefined) decoded.readState = value.readState as boolean
224
- if (estimatorMode !== undefined) decoded.estimatorMode = estimatorMode as '' | 'host' | 'direct'
225
- if (value.estimatorProvider !== undefined) decoded.estimatorProvider = value.estimatorProvider as string
226
- if (value.estimatorModel !== undefined) decoded.estimatorModel = value.estimatorModel as string
227
- if (value.estimatorBaseUrl !== undefined) decoded.estimatorBaseUrl = value.estimatorBaseUrl as string
228
- if (value.estimatorApiKey !== undefined) decoded.estimatorApiKey = value.estimatorApiKey as string
229
- if (estimatorTimeoutMs !== undefined) decoded.estimatorTimeoutMs = estimatorTimeoutMs as number
230
- if (advisorMode !== undefined) decoded.advisorMode = advisorMode as '' | 'host' | 'direct'
231
- if (advisorTimeoutMs !== undefined) decoded.advisorTimeoutMs = advisorTimeoutMs as number
232
- if (advisorRefreshTurns !== undefined) decoded.advisorRefreshTurns = advisorRefreshTurns as number
233
- if (advisorScoreThreshold !== undefined) decoded.advisorScoreThreshold = advisorScoreThreshold as number
234
- if (advisorSampleLimit !== undefined) decoded.advisorSampleLimit = advisorSampleLimit as number
235
- if (advisorMinTokens !== undefined) decoded.advisorMinTokens = advisorMinTokens as number
236
- return decoded
237
- }
238
-
239
- /**
240
- * The one threshold contract shared by the UI, the persisted settings, and the
241
- * runtime resolver; mirrored browser-safe from the runtime package.
242
- */
243
- export const AUTO_COMPACT_THRESHOLD_LIMITS = Object.freeze({
244
- min: 50,
245
- max: 90,
246
- step: 1,
247
- default: 80,
248
- } as const)
249
-
250
- /** Narrow one unknown value to a valid Auto Compact threshold percent. */
251
- export function isValidAutoCompactThresholdPercent(value: unknown): value is number {
252
- return typeof value === 'number'
253
- && Number.isSafeInteger(value)
254
- && value >= AUTO_COMPACT_THRESHOLD_LIMITS.min
255
- && value <= AUTO_COMPACT_THRESHOLD_LIMITS.max
256
- }
257
-
258
- /** Accept JSON-object records while rejecting class instances and exotic prototypes. */
259
- export function isPlainRecord(value: unknown): value is Record<string, unknown> {
260
- if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
261
- const prototype = Object.getPrototypeOf(value) as object | null
262
- return prototype === Object.prototype || prototype === null
263
- }
264
-
265
- /**
266
- * Decode the persisted autoCompact section with exactly the runtime schema's
267
- * strictness: absent means the 80% default; present values must be a plain
268
- * object carrying only a valid `thresholdPercent`. Anything else is invalid,
269
- * never silently coerced.
270
- */
271
- export function decodeAutoCompactSettings(value: unknown): AutoCompactSettings | undefined {
272
- if (value === undefined) return { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default }
273
- if (!isPlainRecord(value)) return undefined
274
- const keys = Object.keys(value)
275
- if (keys.length !== 1 || keys[0] !== 'thresholdPercent') return undefined
276
- const thresholdPercent = (value as Record<string, unknown>).thresholdPercent
277
- return isValidAutoCompactThresholdPercent(thresholdPercent)
278
- ? { thresholdPercent }
279
- : undefined
280
- }
281
-
282
- /** Durable settings section owned by this package. */
283
- export interface ContextCompressionSettings {
284
- /** Default profile captured when each Session first reaches the pruner. */
285
- profile: CompressionProfile
286
- /** Complete canonical policy captured with `profile` when the runtime first observes a Session. */
287
- custom: CustomCompressionPolicy
288
- /** Auto Compact trigger captured with `profile` when the runtime first observes a Session. */
289
- autoCompact: AutoCompactSettings
290
- /** Code-skeleton reducer gate captured independently of `profile`. */
291
- codeSkeleton: CodeSkeletonSettings
292
- /** Optional tokenpilot-inspired sub-capability overrides (presence-validated only). */
293
- presetOptions?: PresetOptionsSettings
294
- }
295
-
296
- /**
297
- * Narrow an unknown settings value to a complete supported Custom policy.
298
- * @param value - Candidate settings value received from the Host or edited locally.
299
- * @returns Whether the value is a relation-valid Custom policy.
300
- */
301
- export function isCustomCompressionPolicy(value: unknown): value is CustomCompressionPolicy {
302
- if (!hasExactKeys(
303
- value,
304
- value !== null && typeof value === 'object' && 'version' in value && value.version === 1
305
- ? ['version', 'unit', 'fresh', 'aggregate', 'history', 'prefixPolicy']
306
- : ['version', 'unit', 'fresh', 'aggregate', 'history', 'prefixPolicy', 'tailTrim'],
307
- )) return false
308
- if ((value.version !== 1 && value.version !== 2 && value.version !== 3)
309
- || (value.unit !== 'tokens' && value.unit !== 'context-percent')) return false
310
- if (value.prefixPolicy !== 'preserve' && value.prefixPolicy !== 'pressure-break') return false
311
- if (!isBudget(value.fresh) || !isBudget(value.aggregate)) return false
312
- const modernHistory = value.version === 3
313
- if (!hasExactKeys(
314
- value.history,
315
- modernHistory
316
- ? ['enabled', 'trigger', 'keepRecentToolCalls', 'keepRecentTokens', 'minReclaim']
317
- : ['enabled', 'trigger', 'keepRecentTurns', 'keepRecent', 'minReclaim'],
318
- )) return false
319
- if (typeof value.history.enabled !== 'boolean'
320
- || typeof value.history.trigger !== 'number'
321
- || typeof value.history.minReclaim !== 'number') return false
322
- const recent = modernHistory
323
- ? value.history.keepRecentTokens
324
- : value.history.keepRecent
325
- const calls = modernHistory ? value.history.keepRecentToolCalls : value.history.keepRecentTurns
326
- if (typeof recent !== 'number'
327
- || typeof calls !== 'number'
328
- || !Number.isSafeInteger(calls)
329
- || calls < 0) return false
330
- let tailTrimTrigger: number | undefined
331
- if (value.version !== 1) {
332
- const tailTrim = value.tailTrim
333
- if (!hasExactKeys(tailTrim, ['enabled', 'trigger'])
334
- || typeof tailTrim.enabled !== 'boolean'
335
- || typeof tailTrim.trigger !== 'number') return false
336
- tailTrimTrigger = tailTrim.trigger
337
- }
338
- const measured = [
339
- value.fresh.trigger, value.fresh.target,
340
- value.aggregate.trigger, value.aggregate.target,
341
- value.history.trigger, recent, value.history.minReclaim,
342
- ...tailTrimTrigger === undefined ? [] : [tailTrimTrigger],
343
- ]
344
- if (!measured.every(entry => typeof entry === 'number' && Number.isFinite(entry))) return false
345
- if (value.fresh.trigger <= 0 || value.fresh.target <= 0
346
- || value.aggregate.trigger <= 0 || value.aggregate.target <= 0
347
- || value.history.trigger <= 0 || recent < 0
348
- || value.history.minReclaim <= 0
349
- || (tailTrimTrigger !== undefined && tailTrimTrigger <= 0)) return false
350
- if (value.unit === 'tokens' && !measured.every(Number.isSafeInteger)) return false
351
- if (value.unit === 'context-percent' && !measured.every(entry => entry <= 100)) return false
352
- return value.fresh.target < value.fresh.trigger
353
- && value.aggregate.target < value.aggregate.trigger
354
- && value.history.minReclaim <= value.history.trigger
355
- }
356
-
357
- function isBudget(value: unknown): value is CustomCompressionBudget {
358
- return hasExactKeys(value, ['enabled', 'trigger', 'target'])
359
- && typeof value.enabled === 'boolean'
360
- && typeof value.trigger === 'number'
361
- && typeof value.target === 'number'
362
- }
363
-
364
- /**
365
- * Canonicalize one validated Custom document to version 3, mirroring the
366
- * runtime's `canonicalizeCustomPolicy` exactly so the browser and runtime
367
- * boundaries hand the SAME complete document to the UI and the policy
368
- * resolver: legacy v1/v2 History working sets upgrade to the 10-call default,
369
- * and a v1 document gains the default-disabled TailTrim stage.
370
- */
371
- export function canonicalizeCustomPolicy(policy: CustomCompressionPolicy): CustomCompressionPolicyV3 {
372
- if (policy.version === 3) return structuredClone(policy)
373
- return {
374
- version: 3,
375
- unit: policy.unit,
376
- fresh: structuredClone(policy.fresh),
377
- aggregate: structuredClone(policy.aggregate),
378
- history: {
379
- enabled: policy.history.enabled,
380
- trigger: policy.history.trigger,
381
- keepRecentToolCalls: 10,
382
- keepRecentTokens: policy.history.keepRecent,
383
- minReclaim: policy.history.minReclaim,
384
- },
385
- prefixPolicy: policy.prefixPolicy,
386
- tailTrim: policy.version === 1 ? { enabled: false, trigger: 700_000 } : structuredClone(policy.tailTrim),
387
- }
388
- }
389
-
390
- function hasExactKeys(value: unknown, expected: readonly string[]): value is Record<string, unknown> {
391
- if (!isPlainRecord(value)) return false
392
- const keys = Object.keys(value)
393
- return keys.length === expected.length && keys.every(key => expected.includes(key))
394
- }
1
+ /** Public context-compression choices shared by the Host schema and browser selector. */
2
+ export const COMPRESSION_PROFILES = [
3
+ 'off',
4
+ 'native',
5
+ 'balanced',
6
+ 'cache-strict',
7
+ 'savings',
8
+ 'adaptive',
9
+ 'tokenpilot-inspired',
10
+ 'custom',
11
+ ] as const
12
+
13
+ /** One supported context-compression profile. */
14
+ export type CompressionProfile = typeof COMPRESSION_PROFILES[number]
15
+
16
+ /** Single canonical unit stored by a version-1 browser Custom document. */
17
+ export type CustomCompressionUnit = 'tokens' | 'context-percent'
18
+
19
+ /** Whether Custom History may routinely rewrite an already-sent prefix. */
20
+ export type CustomPrefixPolicy = 'preserve' | 'pressure-break'
21
+
22
+ /** Browser representation of one independently enabled Fresh or Aggregate budget. */
23
+ export interface CustomCompressionBudget {
24
+ enabled: boolean
25
+ trigger: number
26
+ target: number
27
+ }
28
+
29
+ /** Legacy browser representation of the Custom History working set. */
30
+ export interface LegacyCustomHistoryPolicy {
31
+ enabled: boolean
32
+ trigger: number
33
+ keepRecentTurns: number
34
+ keepRecent: number
35
+ minReclaim: number
36
+ }
37
+
38
+ /** Browser representation of Custom History tool-call and token-tail protection. */
39
+ export interface CustomHistoryPolicy {
40
+ enabled: boolean
41
+ trigger: number
42
+ keepRecentToolCalls: number
43
+ keepRecentTokens: number
44
+ minReclaim: number
45
+ }
46
+
47
+ /** Browser representation of the Custom-only Experimental TailTrim gate. */
48
+ export interface CustomTailTrimPolicy {
49
+ enabled: boolean
50
+ trigger: number
51
+ }
52
+
53
+ interface CustomCompressionPolicyCommon<HistoryPolicy> {
54
+ unit: CustomCompressionUnit
55
+ fresh: CustomCompressionBudget
56
+ aggregate: CustomCompressionBudget
57
+ history: HistoryPolicy
58
+ prefixPolicy: CustomPrefixPolicy
59
+ }
60
+
61
+ /** Legacy public Custom document; accepted and normalized before editing. */
62
+ export interface CustomCompressionPolicyV1 extends CustomCompressionPolicyCommon<LegacyCustomHistoryPolicy> {
63
+ version: 1
64
+ }
65
+
66
+ /** Legacy Custom document with a default-disabled TailTrim stage. */
67
+ export interface CustomCompressionPolicyV2 extends CustomCompressionPolicyCommon<LegacyCustomHistoryPolicy> {
68
+ version: 2
69
+ tailTrim: CustomTailTrimPolicy
70
+ }
71
+
72
+ /** Public Custom document with tool-call working-set protection. */
73
+ export interface CustomCompressionPolicyV3 extends CustomCompressionPolicyCommon<CustomHistoryPolicy> {
74
+ version: 3
75
+ tailTrim: CustomTailTrimPolicy
76
+ }
77
+
78
+ /** Exact public Custom document accepted by the Host and browser boundary. */
79
+ export type CustomCompressionPolicy = CustomCompressionPolicyV1 | CustomCompressionPolicyV2 | CustomCompressionPolicyV3
80
+
81
+ /** Browser-safe mirror of the Host's Balanced-equivalent Custom default. */
82
+ export const DEFAULT_CUSTOM_COMPRESSION_POLICY: CustomCompressionPolicyV3 = {
83
+ version: 3,
84
+ unit: 'tokens',
85
+ fresh: { enabled: true, trigger: 8_192, target: 3_072 },
86
+ aggregate: { enabled: true, trigger: 32_768, target: 12_288 },
87
+ history: {
88
+ enabled: true,
89
+ trigger: 500_000,
90
+ keepRecentToolCalls: 10,
91
+ keepRecentTokens: 64_000,
92
+ minReclaim: 96_000,
93
+ },
94
+ prefixPolicy: 'pressure-break',
95
+ tailTrim: { enabled: false, trigger: 700_000 },
96
+ }
97
+
98
+ /** User-tunable Auto Compact coordination preferences. */
99
+ export interface AutoCompactSettings {
100
+ thresholdPercent: number
101
+ }
102
+
103
+ /**
104
+ * Orthogonal code-skeleton reducer gate, mirrored browser-safe from the
105
+ * runtime: independent of every profile, default off.
106
+ */
107
+ export interface CodeSkeletonSettings {
108
+ enabled: boolean
109
+ }
110
+
111
+ /**
112
+ * Orthogonal turn-tail intent-summary gate, mirrored browser-safe from the
113
+ * runtime: independent of every profile, default off.
114
+ */
115
+ export interface IntentSummarySettings {
116
+ enabled: boolean
117
+ }
118
+
119
+ /** Floating compression-monitor panel (FAB); visibility switch. */
120
+ export interface MonitorPanelSettings {
121
+ enabled: boolean
122
+ }
123
+
124
+ /**
125
+ * Decode the persisted codeSkeleton section with exactly the runtime schema's
126
+ * strictness: absent means the lossless off default; present values must be a
127
+ * plain object carrying only a boolean `enabled`. Anything else is invalid,
128
+ * never silently coerced.
129
+ */
130
+ export function decodeCodeSkeletonSettings(value: unknown): CodeSkeletonSettings | undefined {
131
+ if (value === undefined) return { enabled: false }
132
+ if (!isPlainRecord(value)) return undefined
133
+ const keys = Object.keys(value)
134
+ if (keys.length !== 1 || keys[0] !== 'enabled') return undefined
135
+ const enabled = (value as Record<string, unknown>).enabled
136
+ return typeof enabled === 'boolean' ? { enabled } : undefined
137
+ }
138
+
139
+ /** Browser-safe mirror of the runtime intentSummary section (absent inherits off). */
140
+ export function decodeIntentSummarySettings(value: unknown): IntentSummarySettings | undefined {
141
+ if (value === undefined) return { enabled: false }
142
+ if (!isPlainRecord(value)) return undefined
143
+ const keys = Object.keys(value)
144
+ if (keys.length !== 1 || keys[0] !== 'enabled') return undefined
145
+ const enabled = (value as Record<string, unknown>).enabled
146
+ return typeof enabled === 'boolean' ? { enabled } : undefined
147
+ }
148
+
149
+ /** Browser-safe mirror of the runtime monitorPanel section (absent inherits hidden). */
150
+ export function decodeMonitorPanelSettings(value: unknown): MonitorPanelSettings | undefined {
151
+ if (value === undefined) return { enabled: false }
152
+ if (!isPlainRecord(value)) return undefined
153
+ const keys = Object.keys(value)
154
+ if (keys.length !== 1 || keys[0] !== 'enabled') return undefined
155
+ const enabled = (value as Record<string, unknown>).enabled
156
+ return typeof enabled === 'boolean' ? { enabled } : undefined
157
+ }
158
+
159
+ /** Browser-safe mirror of the runtime presetOptions section. */
160
+ export interface PresetOptionsSettings {
161
+ readonly dedupeToolResults?: boolean
162
+ readonly summaryLocator?: boolean
163
+ readonly prefixStabilizer?: boolean
164
+ readonly readState?: boolean
165
+ readonly estimatorMode?: '' | 'host' | 'direct'
166
+ readonly estimatorProvider?: string
167
+ readonly estimatorModel?: string
168
+ readonly estimatorBaseUrl?: string
169
+ readonly estimatorApiKey?: string
170
+ readonly estimatorTimeoutMs?: number
171
+ /** Advisory advisor channel; `''` (the default) keeps the advisor off. */
172
+ readonly advisorMode?: '' | 'host' | 'direct'
173
+ readonly advisorTimeoutMs?: number
174
+ readonly advisorRefreshTurns?: number
175
+ readonly advisorScoreThreshold?: number
176
+ readonly advisorSampleLimit?: number
177
+ readonly advisorMinTokens?: number
178
+ }
179
+
180
+ /**
181
+ * Browser mirror of the runtime presetOptions section: absent inherits the
182
+ * preset defaults (decodes to `undefined`); present values must be a plain
183
+ * object carrying only the known keys with valid types.
184
+ */
185
+ export function decodePresetOptionsSettings(value: unknown): PresetOptionsSettings | undefined {
186
+ if (value === undefined) return undefined
187
+ if (!isPlainRecord(value)) return undefined
188
+ const allowed = new Set([
189
+ 'dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState', 'estimatorMode',
190
+ 'estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey', 'estimatorTimeoutMs',
191
+ // Legacy keys of the retired review gate: still ACCEPTED so an existing
192
+ // settings document keeps decoding (rejecting them would report the whole
193
+ // card unreadable), and ignored — nothing reads them any more.
194
+ 'reviewMode', 'reviewTimeoutTurns', 'cacheHitDiscountAlpha', 'reviewHighImpactTokens',
195
+ 'advisorMode', 'advisorTimeoutMs', 'advisorRefreshTurns', 'advisorScoreThreshold', 'advisorSampleLimit',
196
+ 'advisorMinTokens',
197
+ ])
198
+ if (Object.keys(value).some(key => !allowed.has(key))) return undefined
199
+ for (const key of ['dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState'] as const) {
200
+ const entry = value[key]
201
+ if (entry !== undefined && typeof entry !== 'boolean') return undefined
202
+ }
203
+ const estimatorMode = value.estimatorMode
204
+ if (estimatorMode !== undefined && estimatorMode !== '' && estimatorMode !== 'host' && estimatorMode !== 'direct') {
205
+ return undefined
206
+ }
207
+ const advisorMode = value.advisorMode
208
+ if (advisorMode !== undefined && advisorMode !== '' && advisorMode !== 'host' && advisorMode !== 'direct') {
209
+ return undefined
210
+ }
211
+ for (const key of ['estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey'] as const) {
212
+ const entry = value[key]
213
+ if (entry !== undefined && typeof entry !== 'string') return undefined
214
+ }
215
+ const estimatorTimeoutMs = value.estimatorTimeoutMs
216
+ if (estimatorTimeoutMs !== undefined
217
+ && (typeof estimatorTimeoutMs !== 'number' || !Number.isSafeInteger(estimatorTimeoutMs)
218
+ || estimatorTimeoutMs < 100 || estimatorTimeoutMs > 60_000)) {
219
+ return undefined
220
+ }
221
+ const advisorTimeoutMs = value.advisorTimeoutMs
222
+ if (advisorTimeoutMs !== undefined
223
+ && (typeof advisorTimeoutMs !== 'number' || !Number.isSafeInteger(advisorTimeoutMs)
224
+ || advisorTimeoutMs < 100 || advisorTimeoutMs > 60_000)) {
225
+ return undefined
226
+ }
227
+ const advisorRefreshTurns = value.advisorRefreshTurns
228
+ if (advisorRefreshTurns !== undefined
229
+ && (typeof advisorRefreshTurns !== 'number' || !Number.isSafeInteger(advisorRefreshTurns)
230
+ || advisorRefreshTurns < 1)) {
231
+ return undefined
232
+ }
233
+ const advisorScoreThreshold = value.advisorScoreThreshold
234
+ if (advisorScoreThreshold !== undefined
235
+ && (typeof advisorScoreThreshold !== 'number' || !Number.isFinite(advisorScoreThreshold)
236
+ || advisorScoreThreshold <= 0 || advisorScoreThreshold >= 1)) {
237
+ return undefined
238
+ }
239
+ const advisorSampleLimit = value.advisorSampleLimit
240
+ if (advisorSampleLimit !== undefined
241
+ && (typeof advisorSampleLimit !== 'number' || !Number.isSafeInteger(advisorSampleLimit)
242
+ || advisorSampleLimit < 1 || advisorSampleLimit > 64)) {
243
+ return undefined
244
+ }
245
+ const advisorMinTokens = value.advisorMinTokens
246
+ if (advisorMinTokens !== undefined
247
+ && (typeof advisorMinTokens !== 'number' || !Number.isSafeInteger(advisorMinTokens) || advisorMinTokens < 1)) {
248
+ return undefined
249
+ }
250
+ const decoded: {
251
+ -readonly [K in keyof PresetOptionsSettings]: PresetOptionsSettings[K]
252
+ } = {}
253
+ if (value.dedupeToolResults !== undefined) decoded.dedupeToolResults = value.dedupeToolResults as boolean
254
+ if (value.summaryLocator !== undefined) decoded.summaryLocator = value.summaryLocator as boolean
255
+ if (value.prefixStabilizer !== undefined) decoded.prefixStabilizer = value.prefixStabilizer as boolean
256
+ if (value.readState !== undefined) decoded.readState = value.readState as boolean
257
+ if (estimatorMode !== undefined) decoded.estimatorMode = estimatorMode as '' | 'host' | 'direct'
258
+ if (value.estimatorProvider !== undefined) decoded.estimatorProvider = value.estimatorProvider as string
259
+ if (value.estimatorModel !== undefined) decoded.estimatorModel = value.estimatorModel as string
260
+ if (value.estimatorBaseUrl !== undefined) decoded.estimatorBaseUrl = value.estimatorBaseUrl as string
261
+ if (value.estimatorApiKey !== undefined) decoded.estimatorApiKey = value.estimatorApiKey as string
262
+ if (estimatorTimeoutMs !== undefined) decoded.estimatorTimeoutMs = estimatorTimeoutMs as number
263
+ if (advisorMode !== undefined) decoded.advisorMode = advisorMode as '' | 'host' | 'direct'
264
+ if (advisorTimeoutMs !== undefined) decoded.advisorTimeoutMs = advisorTimeoutMs as number
265
+ if (advisorRefreshTurns !== undefined) decoded.advisorRefreshTurns = advisorRefreshTurns as number
266
+ if (advisorScoreThreshold !== undefined) decoded.advisorScoreThreshold = advisorScoreThreshold as number
267
+ if (advisorSampleLimit !== undefined) decoded.advisorSampleLimit = advisorSampleLimit as number
268
+ if (advisorMinTokens !== undefined) decoded.advisorMinTokens = advisorMinTokens as number
269
+ return decoded
270
+ }
271
+
272
+ /**
273
+ * The one threshold contract shared by the UI, the persisted settings, and the
274
+ * runtime resolver; mirrored browser-safe from the runtime package.
275
+ */
276
+ export const AUTO_COMPACT_THRESHOLD_LIMITS = Object.freeze({
277
+ min: 50,
278
+ max: 90,
279
+ step: 1,
280
+ default: 80,
281
+ } as const)
282
+
283
+ /** Narrow one unknown value to a valid Auto Compact threshold percent. */
284
+ export function isValidAutoCompactThresholdPercent(value: unknown): value is number {
285
+ return typeof value === 'number'
286
+ && Number.isSafeInteger(value)
287
+ && value >= AUTO_COMPACT_THRESHOLD_LIMITS.min
288
+ && value <= AUTO_COMPACT_THRESHOLD_LIMITS.max
289
+ }
290
+
291
+ /** Accept JSON-object records while rejecting class instances and exotic prototypes. */
292
+ export function isPlainRecord(value: unknown): value is Record<string, unknown> {
293
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
294
+ const prototype = Object.getPrototypeOf(value) as object | null
295
+ return prototype === Object.prototype || prototype === null
296
+ }
297
+
298
+ /**
299
+ * Decode the persisted autoCompact section with exactly the runtime schema's
300
+ * strictness: absent means the 80% default; present values must be a plain
301
+ * object carrying only a valid `thresholdPercent`. Anything else is invalid,
302
+ * never silently coerced.
303
+ */
304
+ export function decodeAutoCompactSettings(value: unknown): AutoCompactSettings | undefined {
305
+ if (value === undefined) return { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default }
306
+ if (!isPlainRecord(value)) return undefined
307
+ const keys = Object.keys(value)
308
+ if (keys.length !== 1 || keys[0] !== 'thresholdPercent') return undefined
309
+ const thresholdPercent = (value as Record<string, unknown>).thresholdPercent
310
+ return isValidAutoCompactThresholdPercent(thresholdPercent)
311
+ ? { thresholdPercent }
312
+ : undefined
313
+ }
314
+
315
+ /** Durable settings section owned by this package. */
316
+ export interface ContextCompressionSettings {
317
+ /** Default profile captured when each Session first reaches the pruner. */
318
+ profile: CompressionProfile
319
+ /** Complete canonical policy captured with `profile` when the runtime first observes a Session. */
320
+ custom: CustomCompressionPolicy
321
+ /** Auto Compact trigger captured with `profile` when the runtime first observes a Session. */
322
+ autoCompact: AutoCompactSettings
323
+ /** Code-skeleton reducer gate captured independently of `profile`. */
324
+ codeSkeleton: CodeSkeletonSettings
325
+ /** Turn-tail intent-summary gate captured independently of `profile`. */
326
+ intentSummary: IntentSummarySettings
327
+ /** Floating compression-monitor panel (FAB); absent inherits hidden. */
328
+ monitorPanel?: MonitorPanelSettings
329
+ /** Optional tokenpilot-inspired sub-capability overrides (presence-validated only). */
330
+ presetOptions?: PresetOptionsSettings
331
+ }
332
+
333
+ /**
334
+ * Narrow an unknown settings value to a complete supported Custom policy.
335
+ * @param value - Candidate settings value received from the Host or edited locally.
336
+ * @returns Whether the value is a relation-valid Custom policy.
337
+ */
338
+ export function isCustomCompressionPolicy(value: unknown): value is CustomCompressionPolicy {
339
+ if (!hasExactKeys(
340
+ value,
341
+ value !== null && typeof value === 'object' && 'version' in value && value.version === 1
342
+ ? ['version', 'unit', 'fresh', 'aggregate', 'history', 'prefixPolicy']
343
+ : ['version', 'unit', 'fresh', 'aggregate', 'history', 'prefixPolicy', 'tailTrim'],
344
+ )) return false
345
+ if ((value.version !== 1 && value.version !== 2 && value.version !== 3)
346
+ || (value.unit !== 'tokens' && value.unit !== 'context-percent')) return false
347
+ if (value.prefixPolicy !== 'preserve' && value.prefixPolicy !== 'pressure-break') return false
348
+ if (!isBudget(value.fresh) || !isBudget(value.aggregate)) return false
349
+ const modernHistory = value.version === 3
350
+ if (!hasExactKeys(
351
+ value.history,
352
+ modernHistory
353
+ ? ['enabled', 'trigger', 'keepRecentToolCalls', 'keepRecentTokens', 'minReclaim']
354
+ : ['enabled', 'trigger', 'keepRecentTurns', 'keepRecent', 'minReclaim'],
355
+ )) return false
356
+ if (typeof value.history.enabled !== 'boolean'
357
+ || typeof value.history.trigger !== 'number'
358
+ || typeof value.history.minReclaim !== 'number') return false
359
+ const recent = modernHistory
360
+ ? value.history.keepRecentTokens
361
+ : value.history.keepRecent
362
+ const calls = modernHistory ? value.history.keepRecentToolCalls : value.history.keepRecentTurns
363
+ if (typeof recent !== 'number'
364
+ || typeof calls !== 'number'
365
+ || !Number.isSafeInteger(calls)
366
+ || calls < 0) return false
367
+ let tailTrimTrigger: number | undefined
368
+ if (value.version !== 1) {
369
+ const tailTrim = value.tailTrim
370
+ if (!hasExactKeys(tailTrim, ['enabled', 'trigger'])
371
+ || typeof tailTrim.enabled !== 'boolean'
372
+ || typeof tailTrim.trigger !== 'number') return false
373
+ tailTrimTrigger = tailTrim.trigger
374
+ }
375
+ const measured = [
376
+ value.fresh.trigger, value.fresh.target,
377
+ value.aggregate.trigger, value.aggregate.target,
378
+ value.history.trigger, recent, value.history.minReclaim,
379
+ ...tailTrimTrigger === undefined ? [] : [tailTrimTrigger],
380
+ ]
381
+ if (!measured.every(entry => typeof entry === 'number' && Number.isFinite(entry))) return false
382
+ if (value.fresh.trigger <= 0 || value.fresh.target <= 0
383
+ || value.aggregate.trigger <= 0 || value.aggregate.target <= 0
384
+ || value.history.trigger <= 0 || recent < 0
385
+ || value.history.minReclaim <= 0
386
+ || (tailTrimTrigger !== undefined && tailTrimTrigger <= 0)) return false
387
+ if (value.unit === 'tokens' && !measured.every(Number.isSafeInteger)) return false
388
+ if (value.unit === 'context-percent' && !measured.every(entry => entry <= 100)) return false
389
+ return value.fresh.target < value.fresh.trigger
390
+ && value.aggregate.target < value.aggregate.trigger
391
+ && value.history.minReclaim <= value.history.trigger
392
+ }
393
+
394
+ function isBudget(value: unknown): value is CustomCompressionBudget {
395
+ return hasExactKeys(value, ['enabled', 'trigger', 'target'])
396
+ && typeof value.enabled === 'boolean'
397
+ && typeof value.trigger === 'number'
398
+ && typeof value.target === 'number'
399
+ }
400
+
401
+ /**
402
+ * Canonicalize one validated Custom document to version 3, mirroring the
403
+ * runtime's `canonicalizeCustomPolicy` exactly so the browser and runtime
404
+ * boundaries hand the SAME complete document to the UI and the policy
405
+ * resolver: legacy v1/v2 History working sets upgrade to the 10-call default,
406
+ * and a v1 document gains the default-disabled TailTrim stage.
407
+ */
408
+ export function canonicalizeCustomPolicy(policy: CustomCompressionPolicy): CustomCompressionPolicyV3 {
409
+ if (policy.version === 3) return structuredClone(policy)
410
+ return {
411
+ version: 3,
412
+ unit: policy.unit,
413
+ fresh: structuredClone(policy.fresh),
414
+ aggregate: structuredClone(policy.aggregate),
415
+ history: {
416
+ enabled: policy.history.enabled,
417
+ trigger: policy.history.trigger,
418
+ keepRecentToolCalls: 10,
419
+ keepRecentTokens: policy.history.keepRecent,
420
+ minReclaim: policy.history.minReclaim,
421
+ },
422
+ prefixPolicy: policy.prefixPolicy,
423
+ tailTrim: policy.version === 1 ? { enabled: false, trigger: 700_000 } : structuredClone(policy.tailTrim),
424
+ }
425
+ }
426
+
427
+ function hasExactKeys(value: unknown, expected: readonly string[]): value is Record<string, unknown> {
428
+ if (!isPlainRecord(value)) return false
429
+ const keys = Object.keys(value)
430
+ return keys.length === expected.length && keys.every(key => expected.includes(key))
431
+ }