dsh-compaction-adaptive 0.0.0-stage → 0.1.3

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.
package/lib/policy.js ADDED
@@ -0,0 +1,315 @@
1
+ /**
2
+ * Pure adaptive budgeting for the adaptive compaction backend.
3
+ *
4
+ * Nothing here touches a Context, a Session, or the LLM seam: the whole policy
5
+ * decision is a function of (window, reserved output, measured growth). That
6
+ * keeps the interesting arithmetic testable with a plain Node process, while
7
+ * `lib/index.js` owns the durable compaction protocol it reuses from
8
+ * `@deepseek-ai/dsh-compaction-basic`.
9
+ *
10
+ * @module dsh-compaction-adaptive/policy
11
+ */
12
+
13
+ /** Strategy profiles: how much working room the policy tries to keep. */
14
+ export const PROFILES = Object.freeze({
15
+ economy: Object.freeze({ turnsAhead: 0.6, tailScale: 0.6, headroomScale: 0.9, tailMaxScale: 0.8 }),
16
+ balanced: Object.freeze({ turnsAhead: 1, tailScale: 1, headroomScale: 1, tailMaxScale: 1 }),
17
+ quality: Object.freeze({ turnsAhead: 1.75, tailScale: 1.4, headroomScale: 1.15, tailMaxScale: 1.25 }),
18
+ })
19
+
20
+ /** Scalar configuration keys consumed by this module (the rest belongs to the base backend). */
21
+ export const ADAPTIVE_KEYS = Object.freeze([
22
+ 'mode',
23
+ 'profile',
24
+ 'turnsAhead',
25
+ 'growthAlpha',
26
+ 'floorRatio',
27
+ 'ceilRatio',
28
+ 'headroomMinRatio',
29
+ 'headroomMaxRatio',
30
+ 'minHeadroomTokens',
31
+ 'tailRatio',
32
+ 'tailMinTokens',
33
+ 'tailMaxRatio',
34
+ 'keepTurns',
35
+ 'cooldownSteps',
36
+ 'thrashMargin',
37
+ 'minGrowthTokens',
38
+ 'verbose',
39
+ ])
40
+
41
+ const DEFAULTS = Object.freeze({
42
+ mode: 'adaptive',
43
+ profile: 'balanced',
44
+ turnsAhead: 3,
45
+ growthAlpha: 0.35,
46
+ floorRatio: 0.35,
47
+ ceilRatio: 0.9,
48
+ headroomMinRatio: 0.06,
49
+ headroomMaxRatio: 0.4,
50
+ minHeadroomTokens: 0,
51
+ tailRatio: 0.1,
52
+ tailMinTokens: 4096,
53
+ tailMaxRatio: 0.22,
54
+ keepTurns: 1,
55
+ cooldownSteps: 1,
56
+ thrashMargin: 1.15,
57
+ minGrowthTokens: 0,
58
+ verbose: false,
59
+ })
60
+
61
+ /** Supported `mode` values. */
62
+ export const MODES = Object.freeze(['adaptive', 'fixed'])
63
+
64
+ function fail(message) {
65
+ throw new Error(`dsh-compaction-adaptive: ${message}`)
66
+ }
67
+
68
+ function assertNumber(name, value, { min, max, integer = false } = {}) {
69
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
70
+ fail(`${name} (${String(value)}) must be a finite number`)
71
+ }
72
+ if (integer && !Number.isInteger(value)) fail(`${name} (${value}) must be an integer`)
73
+ if (min !== undefined && value < min) fail(`${name} (${value}) must be >= ${min}`)
74
+ if (max !== undefined && value > max) fail(`${name} (${value}) must be <= ${max}`)
75
+ }
76
+
77
+ function clamp(value, low, high) {
78
+ return Math.min(Math.max(value, low), high)
79
+ }
80
+
81
+ /**
82
+ * Validate the adaptive half of the plugin configuration.
83
+ *
84
+ * @param {Record<string, unknown>} [raw] - raw plugin configuration.
85
+ * @returns {Readonly<Record<string, any>>} resolved adaptive configuration.
86
+ */
87
+ export function resolveAdaptiveConfig(raw = {}) {
88
+ const config = { ...DEFAULTS }
89
+ for (const key of ADAPTIVE_KEYS) {
90
+ if (raw[key] !== undefined) config[key] = raw[key]
91
+ }
92
+
93
+ if (!MODES.includes(config.mode)) {
94
+ fail(`mode (${String(config.mode)}) must be one of ${MODES.join(', ')}`)
95
+ }
96
+ if (!Object.hasOwn(PROFILES, config.profile)) {
97
+ fail(`profile (${String(config.profile)}) must be one of ${Object.keys(PROFILES).join(', ')}`)
98
+ }
99
+ assertNumber('turnsAhead', config.turnsAhead, { min: 0.25, max: 50 })
100
+ assertNumber('growthAlpha', config.growthAlpha, { min: 0.01, max: 1 })
101
+ assertNumber('floorRatio', config.floorRatio, { min: 0.05, max: 1 })
102
+ assertNumber('ceilRatio', config.ceilRatio, { min: 0.05, max: 1 })
103
+ assertNumber('headroomMinRatio', config.headroomMinRatio, { min: 0, max: 1 })
104
+ assertNumber('headroomMaxRatio', config.headroomMaxRatio, { min: 0.01, max: 1 })
105
+ assertNumber('minHeadroomTokens', config.minHeadroomTokens, { min: 0, integer: true })
106
+ assertNumber('tailRatio', config.tailRatio, { min: 0, max: 1 })
107
+ assertNumber('tailMinTokens', config.tailMinTokens, { min: 0, integer: true })
108
+ assertNumber('tailMaxRatio', config.tailMaxRatio, { min: 0.01, max: 1 })
109
+ assertNumber('keepTurns', config.keepTurns, { min: 0, max: 20 })
110
+ assertNumber('cooldownSteps', config.cooldownSteps, { min: 0, max: 20, integer: true })
111
+ assertNumber('thrashMargin', config.thrashMargin, { min: 1, max: 3 })
112
+ assertNumber('minGrowthTokens', config.minGrowthTokens, { min: 0, integer: true })
113
+ if (typeof config.verbose !== 'boolean') fail('verbose must be a boolean')
114
+ if (config.floorRatio > config.ceilRatio) {
115
+ fail(`floorRatio (${config.floorRatio}) must not exceed ceilRatio (${config.ceilRatio})`)
116
+ }
117
+ if (config.headroomMinRatio > config.headroomMaxRatio) {
118
+ fail(`headroomMinRatio (${config.headroomMinRatio}) must not exceed headroomMaxRatio (${config.headroomMaxRatio})`)
119
+ }
120
+ return Object.freeze(config)
121
+ }
122
+
123
+ /**
124
+ * Fold one measured step delta into the session's growth estimate.
125
+ *
126
+ * A non-positive delta means the surface shrank (a compaction landed, or the
127
+ * turn consumed a pruned tool output); it re-baselines without polluting the
128
+ * estimate, because the useful signal is how fast the session grows, not the
129
+ * size of a summary.
130
+ *
131
+ * @param {number} previous - current estimate in tokens.
132
+ * @param {number} delta - measured tokens added since the previous observation.
133
+ * @param {number} alpha - exponential weight of the newest sample in (0, 1].
134
+ * @returns {number} the updated estimate.
135
+ */
136
+ export function nextGrowth(previous, delta, alpha) {
137
+ if (!Number.isFinite(delta) || delta <= 0) return previous
138
+ if (!Number.isFinite(previous) || previous <= 0) return delta
139
+ return alpha * delta + (1 - alpha) * previous
140
+ }
141
+
142
+ /**
143
+ * Validate one route's partial adaptive overrides.
144
+ *
145
+ * Routes exist for cost, not for overflow: a route whose prefill is expensive
146
+ * wants a lower ceiling even when the window is large. A partial override only
147
+ * has to be self-consistent; it is merged over the service defaults at planning
148
+ * time, so omitted keys keep adapting globally.
149
+ *
150
+ * @param {Record<string, unknown>} raw - one `routes` entry.
151
+ * @param {number} index - entry position, used in diagnostics.
152
+ * @returns {Readonly<Record<string, any>>} the validated partial override.
153
+ */
154
+ export function resolveRouteOverride(raw, index = 0) {
155
+ const name = `routes[${index}]`
156
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) fail(`${name} must be an object`)
157
+ for (const key of Object.keys(raw)) {
158
+ if (!ADAPTIVE_KEYS.includes(key) && key !== 'provider' && key !== 'model') {
159
+ fail(`${name}: unknown key "${key}"`)
160
+ }
161
+ }
162
+ if (typeof raw.provider !== 'string' || raw.provider.length === 0) fail(`${name}.provider must be a non-empty string`)
163
+ if (typeof raw.model !== 'string' || raw.model.length === 0) fail(`${name}.model must be a non-empty string`)
164
+
165
+ /** @type {Record<string, any>} */
166
+ const override = {}
167
+ for (const key of ADAPTIVE_KEYS) {
168
+ if (raw[key] !== undefined) override[key] = raw[key]
169
+ }
170
+ // Validate each supplied key on its own: a route may lower only the ceiling,
171
+ // and the floor/ceiling relation is settled by `mergeAdaptive` against the
172
+ // service defaults it will actually merge with.
173
+ if (override.mode !== undefined && !MODES.includes(override.mode)) {
174
+ fail(`${name}.mode (${String(override.mode)}) must be one of ${MODES.join(', ')}`)
175
+ }
176
+ if (override.profile !== undefined && !Object.hasOwn(PROFILES, override.profile)) {
177
+ fail(`${name}.profile (${String(override.profile)}) must be one of ${Object.keys(PROFILES).join(', ')}`)
178
+ }
179
+ if (override.turnsAhead !== undefined) assertNumber(`${name}.turnsAhead`, override.turnsAhead, { min: 0.25, max: 50 })
180
+ if (override.growthAlpha !== undefined) assertNumber(`${name}.growthAlpha`, override.growthAlpha, { min: 0.01, max: 1 })
181
+ if (override.floorRatio !== undefined) assertNumber(`${name}.floorRatio`, override.floorRatio, { min: 0.05, max: 1 })
182
+ if (override.ceilRatio !== undefined) assertNumber(`${name}.ceilRatio`, override.ceilRatio, { min: 0.05, max: 1 })
183
+ if (override.headroomMinRatio !== undefined) assertNumber(`${name}.headroomMinRatio`, override.headroomMinRatio, { min: 0, max: 1 })
184
+ if (override.headroomMaxRatio !== undefined) assertNumber(`${name}.headroomMaxRatio`, override.headroomMaxRatio, { min: 0.01, max: 1 })
185
+ if (override.minHeadroomTokens !== undefined) assertNumber(`${name}.minHeadroomTokens`, override.minHeadroomTokens, { min: 0, integer: true })
186
+ if (override.tailRatio !== undefined) assertNumber(`${name}.tailRatio`, override.tailRatio, { min: 0, max: 1 })
187
+ if (override.tailMinTokens !== undefined) assertNumber(`${name}.tailMinTokens`, override.tailMinTokens, { min: 0, integer: true })
188
+ if (override.tailMaxRatio !== undefined) assertNumber(`${name}.tailMaxRatio`, override.tailMaxRatio, { min: 0.01, max: 1 })
189
+ if (override.keepTurns !== undefined) assertNumber(`${name}.keepTurns`, override.keepTurns, { min: 0, max: 20 })
190
+ if (override.cooldownSteps !== undefined) assertNumber(`${name}.cooldownSteps`, override.cooldownSteps, { min: 0, max: 20, integer: true })
191
+ if (override.thrashMargin !== undefined) assertNumber(`${name}.thrashMargin`, override.thrashMargin, { min: 1, max: 3 })
192
+ if (override.minGrowthTokens !== undefined) assertNumber(`${name}.minGrowthTokens`, override.minGrowthTokens, { min: 0, integer: true })
193
+ if (override.verbose !== undefined && typeof override.verbose !== 'boolean') fail(`${name}.verbose must be a boolean`)
194
+ return Object.freeze(override)
195
+ }
196
+
197
+ /**
198
+ * Merge one route's partial overrides over the service defaults and settle the
199
+ * cross-field relations the pure planner relies on.
200
+ * @param {Readonly<Record<string, any>>} base - resolved service defaults.
201
+ * @param {Readonly<Record<string, any>> | undefined} override - partial route override.
202
+ * @returns {Record<string, any>} effective settings.
203
+ */
204
+ export function mergeAdaptive(base, override) {
205
+ if (override === undefined) return base
206
+ const merged = { ...base, ...override }
207
+ if (merged.floorRatio > merged.ceilRatio) merged.floorRatio = merged.ceilRatio
208
+ if (merged.headroomMinRatio > merged.headroomMaxRatio) {
209
+ merged.headroomMinRatio = merged.headroomMaxRatio
210
+ }
211
+ return merged
212
+ }
213
+
214
+ /**
215
+ * Build the exact-route override table.
216
+ * @param {readonly unknown[] | undefined} list - configured `routes` entries.
217
+ * @returns {ReadonlyMap<string, Readonly<Record<string, any>>>} overrides keyed by `provider\\u0000model`.
218
+ */
219
+ export function resolveRoutes(list) {
220
+ const table = new Map()
221
+ if (list === undefined) return table
222
+ if (!Array.isArray(list)) fail('routes must be an array')
223
+ for (const [index, raw] of list.entries()) {
224
+ const override = resolveRouteOverride(raw, index)
225
+ const key = `${raw.provider}\u0000${raw.model}`
226
+ if (table.has(key)) fail(`routes: duplicate entry for ${raw.provider}/${raw.model}`)
227
+ table.set(key, override)
228
+ }
229
+ return table
230
+ }
231
+
232
+ /** Key used by the route override table. */
233
+ export function routeKey(provider, model) {
234
+ return `${provider}\u0000${model}`
235
+ }
236
+
237
+ /**
238
+ * Choose the pressure threshold and retained tail for one routed model.
239
+ *
240
+ * The threshold is expressed twice, exactly as the base backend expects it:
241
+ * as a window fraction (`thresholdRatio`) and as the absolute headroom it
242
+ * leaves below the message budget (`headroomTokens`), so both `min()` terms
243
+ * agree on one token budget.
244
+ *
245
+ * @param {object} input - planning input.
246
+ * @param {number} input.contextWindow - adapter-declared window in tokens.
247
+ * @param {number} input.reservedTokens - output tokens the routed request reserves.
248
+ * @param {number} input.growthTokens - per-turn growth estimate in tokens.
249
+ * @param {Readonly<Record<string, any>>} input.adaptive - resolved adaptive configuration.
250
+ * @param {string} [input.profile] - profile name; defaults to the configured one.
251
+ * @param {boolean} [input.force] - overflow recovery: keep the smallest tail.
252
+ * @returns {null | {contextWindow: number, messageBudget: number, growthTokens: number, thresholdTokens: number, thresholdRatio: number, headroomTokens: number, retainTokens: number}} the plan, or `null` when the route has no usable budget.
253
+ */
254
+ export function planPolicy(input) {
255
+ const window = input.contextWindow
256
+ const reserved = Math.max(0, input.reservedTokens ?? 0)
257
+ if (!Number.isInteger(window) || window <= 0) return null
258
+ const budget = window - reserved
259
+ if (budget <= 1024) return null
260
+
261
+ const adaptive = input.adaptive
262
+ const preset = PROFILES[input.profile ?? adaptive.profile] ?? PROFILES.balanced
263
+ const floorToken = Math.max(1024, Math.ceil(window * adaptive.floorRatio))
264
+ const ceilToken = Math.max(floorToken, Math.floor(window * adaptive.ceilRatio))
265
+ const ceiling = Math.max(1, Math.min(ceilToken, budget - 1024))
266
+ const floorBound = Math.min(floorToken, ceiling)
267
+
268
+ const growth = clamp(
269
+ Number.isFinite(input.growthTokens) ? Math.max(0, input.growthTokens) : 0,
270
+ 0,
271
+ budget / 2,
272
+ )
273
+ const headroomFloor = Math.max(window * adaptive.headroomMinRatio * preset.headroomScale, adaptive.minHeadroomTokens)
274
+ const headroomCeil = Math.max(headroomFloor, Math.min(window * adaptive.headroomMaxRatio, budget - 1024))
275
+ const headroom = clamp(growth * adaptive.turnsAhead * preset.turnsAhead, headroomFloor, headroomCeil)
276
+
277
+ let thresholdTokens = Math.floor(budget - headroom)
278
+ if (input.force) thresholdTokens = ceiling
279
+ thresholdTokens = clamp(thresholdTokens, floorBound, ceiling)
280
+ if (thresholdTokens < 1) return null
281
+
282
+ const thresholdRatio = thresholdTokens / window
283
+ const headroomTokens = Math.max(0, Math.floor(budget - thresholdTokens))
284
+
285
+ const tailFloor = Math.max(
286
+ 1,
287
+ Math.min(adaptive.tailMinTokens, Math.floor(thresholdTokens * 0.5)),
288
+ )
289
+ const tailCeil = Math.max(
290
+ tailFloor,
291
+ Math.floor(Math.min(budget * adaptive.tailMaxRatio * preset.tailMaxScale, thresholdTokens * 0.6)),
292
+ )
293
+ const wantedTail = input.force
294
+ ? 0
295
+ : Math.max(growth * adaptive.keepTurns, budget * adaptive.tailRatio * preset.tailScale)
296
+ const retainTokens = Math.floor(clamp(wantedTail, tailFloor, tailCeil))
297
+
298
+ return {
299
+ contextWindow: window,
300
+ messageBudget: budget,
301
+ growthTokens: Math.round(growth),
302
+ thresholdTokens,
303
+ thresholdRatio,
304
+ headroomTokens,
305
+ retainTokens,
306
+ }
307
+ }
308
+
309
+ /** Human-readable one-line plan summary used by the plugin's logging. */
310
+ export function describePlan(plan, target) {
311
+ const pct = (plan.thresholdTokens / plan.contextWindow) * 100
312
+ return `${target} window=${plan.contextWindow} budget=${plan.messageBudget} `
313
+ + `growth=${plan.growthTokens} threshold=${plan.thresholdTokens} (${pct.toFixed(1)}%) `
314
+ + `tail=${plan.retainTokens}`
315
+ }
package/locale/en.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "Adaptive context compaction",
4
+ "description": "Condenses long sessions before they overflow, deriving each model's trigger point and retained tail from its context window and this session's measured growth instead of fixed ratios, and splitting an oversized summary request into parts it can actually ship.",
5
+ "detail": "docs/DETAIL.md"
6
+ }
7
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "自适应上下文压缩",
4
+ "description": "在会话溢出前按需压缩历史:触发阈值与保留尾窗根据当前模型的上下文窗口和本会话实测的增长速度自动推算,不再依赖固定比例;单次摘要请求过大时自动分块再合并。",
5
+ "detail": "docs/DETAIL.md"
6
+ }
7
+ }
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "dsh-compaction-adaptive",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.3",
4
+ "private": false,
5
+ "description": "Adaptive context compaction for DeepSeek Harness: derives each model's pressure threshold and retained tail from its context window and the session's measured growth.",
6
+ "icon": "icon.svg",
7
+ "type": "module",
8
+ "main": "lib/index.js",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/ArtomYuan/dsh-compaction-adaptive.git"
12
+ },
13
+ "homepage": "https://github.com/ArtomYuan/dsh-compaction-adaptive#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/ArtomYuan/dsh-compaction-adaptive/issues"
16
+ },
17
+ "publishConfig": {
18
+ "access": "public"
19
+ },
20
+ "exports": {
21
+ ".": "./lib/index.js",
22
+ "./policy": "./lib/policy.js",
23
+ "./chunking": "./lib/chunking.js",
24
+ "./locale/*.json": "./locale/*.json",
25
+ "./icon": "./icon.svg",
26
+ "./package.json": "./package.json"
27
+ },
28
+ "files": [
29
+ "lib",
30
+ "locale",
31
+ "docs",
32
+ "icon.svg",
33
+ "cordis.patch.yml",
34
+ "README.md"
35
+ ],
36
+ "engines": {
37
+ "dsh": ">=0.2.2-rc.1"
38
+ },
39
+ "dsh": {
40
+ "bundle": {
41
+ "patch": "./cordis.patch.yml"
42
+ }
43
+ },
44
+ "keywords": [
45
+ "deepseek-harness",
46
+ "dsh",
47
+ "cordis",
48
+ "plugin",
49
+ "compaction",
50
+ "context"
51
+ ],
52
+ "license": "MIT"
53
+ }