dsh-context-compression-improved 0.7.0-beta.1 → 0.7.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 (83) hide show
  1. package/.github/workflows/ci.yml +39 -39
  2. package/CHANGELOG.ja.md +217 -220
  3. package/CHANGELOG.ko.md +211 -214
  4. package/CHANGELOG.md +401 -376
  5. package/CHANGELOG.zh.md +196 -199
  6. package/README.md +97 -97
  7. package/README.zh.md +86 -86
  8. package/package.json +1 -1
  9. package/packages/selector/dsh.plugin.json +1 -1
  10. package/packages/selector/lib/client.d.ts +44 -0
  11. package/packages/selector/lib/client.js +1733 -6
  12. package/packages/selector/lib/{intent-gate.js → config.js} +799 -136
  13. package/packages/selector/lib/index.d.ts +13 -1
  14. package/packages/selector/lib/index.js +204 -3
  15. package/packages/selector/lib/profiles.d.ts +6 -0
  16. package/packages/selector/lib/pruner.d.ts +6 -0
  17. package/packages/selector/lib/pruner.js +90 -258
  18. package/packages/selector/lib/style.css +88 -46
  19. package/packages/selector/src/client/CompressionProfileControls.tsx +293 -226
  20. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  21. package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -83
  22. package/packages/selector/src/client/decode.ts +57 -53
  23. package/packages/selector/src/client/index.ts +307 -213
  24. package/packages/selector/src/client/locales/de.ts +141 -0
  25. package/packages/selector/src/client/locales/es.ts +141 -0
  26. package/packages/selector/src/client/locales/fr.ts +141 -0
  27. package/packages/selector/src/client/locales/it.ts +141 -0
  28. package/packages/selector/src/client/locales/ja.ts +141 -0
  29. package/packages/selector/src/client/locales/ko.ts +141 -0
  30. package/packages/selector/src/client/locales/ru.ts +141 -0
  31. package/packages/selector/src/client/locales.ts +282 -196
  32. package/packages/selector/src/client/monitor-fab.ts +336 -0
  33. package/packages/selector/src/client/savings-card.tsx +150 -0
  34. package/packages/selector/src/client/settings-section.tsx +140 -124
  35. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -205
  36. package/packages/selector/src/index.ts +207 -5
  37. package/packages/selector/src/preset-overlay.ts +629 -629
  38. package/packages/selector/src/profiles.ts +431 -414
  39. package/packages/selector/src/pruner/content.ts +198 -198
  40. package/packages/selector/src/pruner/state.ts +57 -57
  41. package/packages/selector/src/pruner.ts +2759 -2665
  42. package/packages/selector/src/runtime/audit.ts +303 -303
  43. package/packages/selector/src/runtime/config.ts +756 -731
  44. package/packages/selector/src/runtime/monitor.ts +235 -0
  45. package/packages/selector/src/runtime/reducers.ts +1674 -1674
  46. package/packages/selector/src/runtime/retrieve.ts +479 -457
  47. package/packages/selector/src/runtime/savings.ts +337 -0
  48. package/packages/selector/src/runtime/summary-command.ts +133 -133
  49. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -233
  50. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -204
  51. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -53
  52. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -65
  53. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -125
  54. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -37
  55. package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -128
  56. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +306 -306
  57. package/packages/selector/src/runtime/types.ts +365 -358
  58. package/packages/selector/tests/built/client-artifact.spec.ts +61 -61
  59. package/packages/selector/tests/code-skeleton.client.spec.ts +2 -2
  60. package/packages/selector/tests/custom-contract.client.spec.ts +2 -2
  61. package/packages/selector/tests/estimator-channel.client.spec.tsx +2 -0
  62. package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -188
  63. package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -15
  64. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -41
  65. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -647
  66. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -78
  67. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -234
  68. package/packages/selector/tests/host-preset-overlay.host.spec.ts +203 -203
  69. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  70. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -523
  71. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -122
  72. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -62
  73. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -156
  74. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  75. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  76. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -154
  77. package/packages/selector/tests/settings-seat.client.spec.ts +177 -165
  78. package/scripts/packed-components-smoke.mjs +734 -734
  79. package/scripts/packed-install-e2e.mjs +1 -1
  80. package/scripts/verify-release.mjs +1 -1
  81. package/tests/TEST_INVENTORY.md +41 -41
  82. package/tsconfig.tests.json +17 -17
  83. package/vitest.config.ts +57 -57
@@ -1,629 +1,629 @@
1
- /** Plugin-owned, reversible compression overlays for native agent presets. */
2
-
3
- import { AsyncLocalStorage } from 'node:async_hooks'
4
- import { createHash } from 'node:crypto'
5
- import { chmod, mkdtemp, readFile, rename, rm, stat, utimes, writeFile } from 'node:fs/promises'
6
- import { tmpdir } from 'node:os'
7
- import { isAbsolute, join } from 'node:path'
8
- import { fileURLToPath } from 'node:url'
9
- import { applyEntryPatches, entryListSchema } from '@deepseek-ai/cordis-plugin-include'
10
- import type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader'
11
- import type { AgentPreset } from '@deepseek-ai/dsh-agent-presets'
12
- import { dump, load } from 'js-yaml'
13
-
14
- /** Absolute runtime entry points used by the generated compression stack. */
15
- export interface CompressionModulePaths {
16
- /** Exact aggregate/history compaction implementation shipped with the Bundle. */
17
- readonly compactionBasic: string
18
- /** Exact manual compact command shipped with the Bundle. */
19
- readonly commandCompact: string
20
- /** Exact enhanced tool-result pruner shipped with the Bundle. */
21
- readonly toolResultPruner: string
22
- }
23
-
24
- /** The public native methods the decorator uses without reaching into core internals. */
25
- export interface OverlayableAgentPresets {
26
- /** Resolve a source preset for discovery and authoring. */
27
- resolve(id?: string): Promise<AgentPreset>
28
- /** Compose an agent from a preset. */
29
- mount(agentCtx: unknown, id?: string): Promise<AgentPreset>
30
- /** Move a blank agent to a different preset. */
31
- recompose(agentCtx: unknown, id: string): Promise<AgentPreset>
32
- /** Ensure a standing preset composition for cold readers. */
33
- standingKeyFor(id?: string): Promise<unknown>
34
- }
35
-
36
- /** Configuration for one reversible decoration. */
37
- export interface PresetOverlayOptions {
38
- /** Absolute module entry points written into the generated composition. */
39
- readonly modules: CompressionModulePaths
40
- /** Preset ids that deliberately retain their native composition. */
41
- readonly excludedPresetIds?: readonly string[]
42
- /**
43
- * Reads the Auto Compact threshold percent (50�?0) to freeze into newly
44
- * generated compositions �?once per composition, into BOTH the
45
- * compaction-basic `thresholdRatio` and the runtime deployment config, so
46
- * one generation can never split Auto Compact and micro compact across two
47
- * thresholds. Returning `undefined` keeps both defaults untouched.
48
- */
49
- readonly autoCompactThresholdPercent?: () => number | undefined
50
- /** Test seam for locating the owner-only generated directory. */
51
- readonly tempParent?: string
52
- /**
53
- * Metadata boundary used to prepare and observe the native standing key.
54
- * Production uses the real filesystem; tests may model coarser mtime
55
- * resolution without replacing identity generation.
56
- */
57
- readonly metadataIo?: PresetOverlayMetadataIo
58
- }
59
-
60
- /** Minimal filesystem metadata surface that determines AgentPresets identity. */
61
- export interface PresetOverlayMetadataIo {
62
- /** Persist one deterministic atime/mtime stamp on an unpublished staging file. */
63
- setTimes(path: string, stamp: Date): Promise<void>
64
- /** Read exactly the fields consumed by AgentPresets' standing key. */
65
- read(path: string): Promise<Readonly<{ mtimeMs: number, size: number }>>
66
- }
67
-
68
- /** Handle returned by {@link decorateAgentPresets}. */
69
- export interface PresetOverlayInstallation {
70
- /** Restore native methods and remove every generated composition. */
71
- dispose(): Promise<void>
72
- }
73
-
74
- /**
75
- * Fixed base for deterministic standing mtimes. The stamp is derived from the
76
- * FULL content identity (source + modules + threshold), not from the write
77
- * clock: identical identities always republish to the same stamp (no
78
- * generation flapping).
79
- *
80
- * The seconds component carries an 8-hex identity window directly. Most
81
- * identities therefore separate even when a filesystem truncates mtimes to
82
- * whole seconds; identities that share that 32-bit window deliberately collide
83
- * first, are detected from the staging file's observed {mtimeMs, size}, and
84
- * escalate to later hash windows before publication. The prefix keeps the
85
- * latest possible stamp around year 2162, inside the nanosecond range every
86
- * supported filesystem can store; the next 3 hex digits set sub-second
87
- * milliseconds on filesystems that preserve them.
88
- */
89
- const STANDING_MTIME_EPOCH_SECONDS = Math.floor(Date.UTC(2026, 0, 1) / 1000)
90
- const STANDING_MTIME_WINDOW_HEX = 11
91
-
92
- const DEFAULT_METADATA_IO: PresetOverlayMetadataIo = Object.freeze({
93
- async setTimes(path: string, stamp: Date): Promise<void> {
94
- await utimes(path, stamp, stamp)
95
- },
96
- async read(path: string): Promise<Readonly<{ mtimeMs: number, size: number }>> {
97
- const observed = await stat(path)
98
- return { mtimeMs: observed.mtimeMs, size: observed.size }
99
- },
100
- })
101
-
102
- /**
103
- * Deterministic standing stamp for one full generation identity, read from
104
- * hash window `windowIndex` (0 = identity prefix). Exported for the
105
- * collision-fixture tests; production code uses {@link standingStampMs}.
106
- */
107
- export function standingStampMsAtWindow(identity: string, windowIndex: number): number {
108
- const start = windowIndex * STANDING_MTIME_WINDOW_HEX
109
- const seconds = STANDING_MTIME_EPOCH_SECONDS + parseInt(identity.slice(start, start + 8).padEnd(8, '0'), 16)
110
- const subSecond = parseInt(identity.slice(start + 8, start + STANDING_MTIME_WINDOW_HEX).padEnd(3, '0'), 16) % 1000
111
- return seconds * 1000 + subSecond
112
- }
113
-
114
- /** Deterministic standing stamp for one full generation identity. */
115
- export function standingStampMs(identity: string): number {
116
- return standingStampMsAtWindow(identity, 0)
117
- }
118
-
119
- /**
120
- * True for the filesystem errors a concurrent publish can raise on Windows:
121
- * `MoveFileEx` reports a lost race — or a reader holding the destination open —
122
- * as EPERM/EBUSY/EACCES, where POSIX `rename` simply replaces the destination.
123
- */
124
- function isPublishRace(error: unknown): boolean {
125
- const code = (error as { code?: unknown } | null)?.code
126
- return code === 'EPERM' || code === 'EBUSY' || code === 'EACCES' || code === 'EEXIST'
127
- }
128
-
129
- const COMPRESSION_IDS = new Set([
130
- 'compaction',
131
- 'compaction-basic',
132
- 'command-compact',
133
- 'tool-result-pruner',
134
- ])
135
-
136
- const COMPRESSION_PACKAGES = new Set([
137
- '@deepseek-ai/dsh-compaction-basic',
138
- '@deepseek-ai/dsh-command-compact',
139
- '@deepseek-ai/dsh-compaction-tool-result-pruner',
140
- 'dsh-context-compression-improved-runtime',
141
- 'dsh-context-compression-improved',
142
- 'dsh-context-compression-improved/pruner',
143
- ])
144
-
145
- /**
146
- * Resolve the three compression package entries once from this package.
147
- * @returns Absolute entry paths for the canonical compression layer.
148
- */
149
- export function resolveCompressionModulePaths(): CompressionModulePaths {
150
- return {
151
- compactionBasic: modulePath(
152
- '@deepseek-ai/dsh-compaction-basic', import.meta.resolve('@deepseek-ai/dsh-compaction-basic')),
153
- commandCompact: modulePath(
154
- '@deepseek-ai/dsh-command-compact', import.meta.resolve('@deepseek-ai/dsh-command-compact')),
155
- toolResultPruner: modulePath(
156
- 'dsh-context-compression-improved/pruner', import.meta.resolve('dsh-context-compression-improved/pruner')),
157
- }
158
- }
159
-
160
- /** Convert one package resolution into the absolute path preset mounting accepts. */
161
- function modulePath(specifier: string, resolved: string): string {
162
- if (!resolved.startsWith('file:')) {
163
- throw new Error(`context-compression selector: ${specifier} resolved outside the filesystem (${resolved})`)
164
- }
165
- return fileURLToPath(resolved)
166
- }
167
-
168
- /** One operation's permission to see generated presets through resolve(). */
169
- interface CompositionOperation {
170
- readonly composing: true
171
- }
172
-
173
- /** Generated composition storage owned by one decorator installation. */
174
- class PresetOverlayStore {
175
- private rootTask: Promise<string> | undefined
176
- private disposed = false
177
- private readonly metadataIo: PresetOverlayMetadataIo
178
-
179
- constructor(private readonly options: PresetOverlayOptions) {
180
- this.metadataIo = options.metadataIo ?? DEFAULT_METADATA_IO
181
- const paths = Object.entries(options.modules) as [keyof CompressionModulePaths, string][]
182
- for (const [name, path] of paths) {
183
- if (!isAbsolute(path)) {
184
- throw new TypeError(`context-compression selector: module path ${name} is not absolute: ${path}`)
185
- }
186
- }
187
- }
188
-
189
- /** Return a detached preset record whose path names the canonical overlay. */
190
- async overlay(preset: AgentPreset): Promise<AgentPreset> {
191
- if (this.disposed) throw new Error('context-compression selector: preset overlay is disposed')
192
- if (preset.broken !== undefined) return preset
193
- const source = await readFile(preset.path, 'utf8')
194
- const rows = parseRows(source, preset.path)
195
- const thresholdPercent = this.options.autoCompactThresholdPercent?.()
196
- if (thresholdPercent !== undefined && !Number.isFinite(thresholdPercent)) {
197
- // JSON.stringify maps NaN to null (colliding identities) and the YAML
198
- // dump would serialize it as `.nan`; refuse instead.
199
- throw new Error(`context-compression selector: Auto Compact threshold percent must be finite, got ${String(thresholdPercent)}`)
200
- }
201
- const patched = applyEntryPatches(
202
- stripCompressionRows(rows),
203
- [{ insert: canonicalCompressionRows(this.options.modules, thresholdPercent) }],
204
- (message: string, ...args: unknown[]) => {
205
- throw new Error(renderPatchWarning(message, args))
206
- },
207
- )
208
- const rendered = dump(patched, {
209
- schema: entryListSchema,
210
- noRefs: true,
211
- lineWidth: -1,
212
- sortKeys: false,
213
- })
214
- // The percent joins the content identity by value, not by rendered
215
- // length, so an equal-length change (70 -> 80) still produces a new file.
216
- const identity = createHash('sha256')
217
- .update(preset.id).update('\0')
218
- .update(source).update('\0')
219
- .update(JSON.stringify({ modules: this.options.modules, autoCompactThresholdPercent: thresholdPercent ?? null }))
220
- .digest('hex')
221
- .slice(0, 24)
222
- const root = await this.root()
223
- const path = join(root, `${preset.id}-${identity}.agent.cordis.yml`)
224
- // Publish through a unique temporary file whose content, permissions, and
225
- // DETERMINISTIC identity stamp are all complete before the atomic rename:
226
- // once the final path exists it is fully metadata'd, so a concurrent
227
- // composer (or AgentPresets' standing-key reader) can never observe a
228
- // wall-clock mtime on a published composition.
229
- const staging = join(root, `${preset.id}-${identity}.${String(process.pid)}-${String(Math.random()).slice(2)}.tmp`)
230
- try {
231
- await writeFile(staging, rendered, { encoding: 'utf8', mode: 0o600 })
232
- await chmod(staging, 0o600)
233
- // Reserve and verify the FINAL observed standing key while the file is
234
- // still private. No reader can observe a colliding {mtimeMs,size}
235
- // between rename and a later corrective utimes call.
236
- await this.disambiguateStamp(staging, identity)
237
- await this.publish(staging, path)
238
- } catch (error) {
239
- // A failed publish must not leak its staging file into the store; the
240
- // cleanup must never mask the original failure either.
241
- try {
242
- await rm(staging, { force: true })
243
- } catch {
244
- // intentional: the publish error below is the actionable one
245
- }
246
- throw error
247
- }
248
- return { ...preset, path }
249
- }
250
-
251
- /** In-flight publish chains, one per destination path. */
252
- private readonly publishChains = new Map<string, Promise<void>>()
253
-
254
- /**
255
- * Publish one stamped staging file to its final path, serialized per path.
256
- *
257
- * POSIX `rename` replaces an existing destination atomically, so concurrent
258
- * composers of one identity are naturally idempotent there. Windows
259
- * `MoveFileEx` instead fails the loser of that race with EPERM/EBUSY, which
260
- * surfaced as `standingKeyFor()` throwing during concurrent composition.
261
- * Every composer of one identity writes identical bytes and re-derives the
262
- * same deterministic identity stamp, so a destination that already observes
263
- * this staging file's {mtimeMs, size} key IS the intended end state: confirm
264
- * it and treat the lost race as success. Every other outcome still throws, so
265
- * a silently reused generation stays forbidden, and the caller still removes
266
- * the staging file when this rejects.
267
- */
268
- private publish(staging: string, path: string): Promise<void> {
269
- const previous = this.publishChains.get(path) ?? Promise.resolve()
270
- const queued = previous.catch(() => undefined).then(async () => {
271
- try {
272
- await rename(staging, path)
273
- return
274
- } catch (error) {
275
- if (!isPublishRace(error)) throw error
276
- try {
277
- const intended = await this.metadataIo.read(staging)
278
- const published = await this.metadataIo.read(path)
279
- // Sub-second precision survives a wrapped seconds field, but NTFS
280
- // rounds it to 100ns, so compare the standing key within that
281
- // rounding rather than by exact float equality.
282
- if (published.size === intended.size
283
- && Math.abs(published.mtimeMs - intended.mtimeMs) < 2) {
284
- await rm(staging, { force: true })
285
- return
286
- }
287
- } catch {
288
- // The destination is unreadable: report the original publish failure.
289
- }
290
- throw error
291
- }
292
- })
293
- const tracked = queued.finally(() => {
294
- if (this.publishChains.get(path) === tracked) this.publishChains.delete(path)
295
- })
296
- this.publishChains.set(path, tracked)
297
- return tracked
298
- }
299
-
300
- /** Observed {mtimeMs,size} keys published by this store, per identity. */
301
- private readonly standingKeys = new Map<string, string>()
302
-
303
- /**
304
- * Ensure an unpublished staging file's observed {mtimeMs, size} is not
305
- * shared with a different identity. Escalation rewrites the mtime from later
306
- * hash windows before atomic publication, and fails loudly if no window
307
- * separates them (better a loud error than a silently reused generation).
308
- */
309
- private async disambiguateStamp(path: string, identity: string): Promise<void> {
310
- for (let window = 0; window < 3; window += 1) {
311
- const stamp = new Date(standingStampMsAtWindow(identity, window))
312
- await this.metadataIo.setTimes(path, stamp)
313
- // The native key uses the on-disk byte size, not the UTF-16 length of
314
- // the rendered string.
315
- const observed = await this.metadataIo.read(path)
316
- const key = `${String(observed.mtimeMs)}:${String(observed.size)}`
317
- const owner = this.standingKeys.get(key)
318
- if (owner === undefined || owner === identity) {
319
- this.standingKeys.set(key, identity)
320
- return
321
- }
322
- }
323
- throw new Error(`context-compression selector: standing stamp collision for identity ${identity} across all hash windows`)
324
- }
325
-
326
- /** Remove all generated files without touching any source preset. */
327
- async dispose(): Promise<void> {
328
- if (this.disposed) return
329
- this.disposed = true
330
- if (this.rootTask === undefined) return
331
- const root = await this.rootTask
332
- await rm(root, { recursive: true, force: true })
333
- }
334
-
335
- /** Lazily create the one owner-only directory for this installation. */
336
- private async root(): Promise<string> {
337
- if (this.rootTask === undefined) {
338
- const parent = this.options.tempParent ?? tmpdir()
339
- this.rootTask = mkdtemp(join(parent, 'dsh-context-compression-presets-'))
340
- .then(async (root) => {
341
- await chmod(root, 0o700)
342
- return root
343
- })
344
- }
345
- return await this.rootTask
346
- }
347
- }
348
-
349
- /** Parse one native preset with exactly the Loader's YAML dialect. */
350
- function parseRows(source: string, path: string): EntryOptions[] {
351
- const parsed = load(source, { schema: entryListSchema })
352
- if (!Array.isArray(parsed)) {
353
- throw new TypeError(`context-compression selector: preset ${path} is not a top-level entry list`)
354
- }
355
- return parsed as EntryOptions[]
356
- }
357
-
358
- /** Remove any prior compression implementation before adding the canonical one. */
359
- function stripCompressionRows(rows: EntryOptions[]): EntryOptions[] {
360
- const kept: EntryOptions[] = []
361
- for (const row of rows) {
362
- if (COMPRESSION_IDS.has(row.id) || COMPRESSION_PACKAGES.has(row.name)) continue
363
- if (row.group === true && Array.isArray(row.config)) {
364
- const nested = row.config as unknown as EntryOptions[]
365
- kept.push({ ...row, config: stripCompressionRows(nested) })
366
- } else {
367
- kept.push(row)
368
- }
369
- }
370
- return kept
371
- }
372
-
373
- /**
374
- * Complete, same-realm compression stack added to every applicable preset.
375
- * When the Host settings expose an Auto Compact threshold, one read feeds both
376
- * the compaction-basic `thresholdRatio` (beside the pinned first-release
377
- * `retainRatio`) and the runtime deployment config, so plugin History and
378
- * native Auto Compact share one watermark for this whole generation.
379
- */
380
- function canonicalCompressionRows(
381
- modules: CompressionModulePaths,
382
- thresholdPercent?: number,
383
- ): EntryOptions[] {
384
- return [
385
- {
386
- id: 'compaction',
387
- name: 'cordis:group',
388
- group: true,
389
- isolate: {
390
- compaction: true,
391
- toolResultPruner: true,
392
- },
393
- config: [
394
- {
395
- id: 'compaction-basic',
396
- name: modules.compactionBasic,
397
- ...(thresholdPercent === undefined ? {} : {
398
- config: {
399
- thresholdRatio: thresholdPercent / 100,
400
- retainRatio: 0.16,
401
- },
402
- }),
403
- },
404
- {
405
- id: 'command-compact',
406
- name: modules.commandCompact,
407
- },
408
- {
409
- id: 'tool-result-pruner',
410
- name: modules.toolResultPruner,
411
- config: {
412
- headChars: 4096,
413
- tailChars: 1024,
414
- ...(thresholdPercent === undefined ? {} : { autoCompactThresholdPercent: thresholdPercent }),
415
- },
416
- },
417
- ],
418
- },
419
- ]
420
- }
421
-
422
- /** Render include's printf-style warning without silently losing its target. */
423
- function renderPatchWarning(message: string, args: readonly unknown[]): string {
424
- let index = 0
425
- return `context-compression selector: ${message.replace(/%C/g, () => JSON.stringify(args[index++]))}`
426
- }
427
-
428
- /** Method names whose native execution is allowed to resolve an overlay. */
429
- type CompositionMethod = 'mount' | 'recompose' | 'standingKeyFor'
430
-
431
- /** Restore one method to exactly the own/prototype state it had before decoration. */
432
- interface MethodSnapshot {
433
- readonly name: 'resolve' | CompositionMethod
434
- readonly own: PropertyDescriptor | undefined
435
- readonly original: (...args: never[]) => unknown
436
- wrapped?: (...args: never[]) => unknown
437
- }
438
-
439
- /** One physical decoration shared by every duplicate Host row. */
440
- interface SharedDecoration {
441
- /** Canonical options prevent two rows from silently requesting different stacks. */
442
- readonly optionsKey: string
443
- /** Number of live plugin fibers leasing this decoration. */
444
- references: number
445
- /** Physical method wrappers and generated-directory owner. */
446
- readonly installation: PresetOverlayInstallation
447
- }
448
-
449
- /**
450
- * Cordis can hand two callers different traceable proxies for one service.
451
- * Symbol properties forward to the shared target, unlike proxy identity.
452
- */
453
- const SHARED_DECORATION = Symbol.for(
454
- 'dsh-context-compression-improved/preset-overlay',
455
- )
456
-
457
- /** Object-identity keys keep test metadata policies from sharing one store. */
458
- const METADATA_IO_KEYS = new WeakMap<object, number>()
459
- let nextMetadataIoKey = 1
460
-
461
- function metadataIoKey(metadataIo: PresetOverlayMetadataIo): number {
462
- const existing = METADATA_IO_KEYS.get(metadataIo)
463
- if (existing !== undefined) return existing
464
- const key = nextMetadataIoKey
465
- nextMetadataIoKey += 1
466
- METADATA_IO_KEYS.set(metadataIo, key)
467
- return key
468
- }
469
-
470
- /**
471
- * Reversibly decorate native AgentPresets composition calls.
472
- *
473
- * Duplicate Host rows share one physical decoration. This matters while an
474
- * installation migrates from a Harness-bundled selector row to the standalone
475
- * Bundle: either row can unload first without double-compressing or disposing
476
- * the generated files still used by the other.
477
- * @param presets Native AgentPresets service to decorate during composition.
478
- * @param options Canonical module paths, exclusions, and optional test directory.
479
- * @returns A reference-counted handle that restores the native service on final disposal.
480
- */
481
- export function decorateAgentPresets(
482
- presets: OverlayableAgentPresets,
483
- options: PresetOverlayOptions,
484
- ): PresetOverlayInstallation {
485
- const optionsKey = overlayOptionsKey(options)
486
- const carrier = presets as OverlayableAgentPresets & { [SHARED_DECORATION]?: SharedDecoration }
487
- let shared = carrier[SHARED_DECORATION]
488
- if (shared === undefined) {
489
- shared = {
490
- optionsKey,
491
- references: 0,
492
- installation: installAgentPresetsDecoration(presets, options),
493
- }
494
- Object.defineProperty(carrier, SHARED_DECORATION, {
495
- configurable: true,
496
- enumerable: false,
497
- writable: false,
498
- value: shared,
499
- })
500
- } else if (shared.optionsKey !== optionsKey) {
501
- throw new Error('context-compression selector: AgentPresets already has a different compression overlay')
502
- }
503
- const lease = shared
504
- lease.references += 1
505
-
506
- let disposed = false
507
- return {
508
- async dispose(): Promise<void> {
509
- if (disposed) return
510
- disposed = true
511
- lease.references -= 1
512
- if (lease.references !== 0) return
513
- if (carrier[SHARED_DECORATION] === lease) {
514
- Reflect.deleteProperty(carrier, SHARED_DECORATION)
515
- }
516
- await lease.installation.dispose()
517
- },
518
- }
519
- }
520
-
521
- /** Stable equality for two rows asking to share one physical overlay. */
522
- function overlayOptionsKey(options: PresetOverlayOptions): string {
523
- return JSON.stringify({
524
- modules: options.modules,
525
- excludedPresetIds: [...(options.excludedPresetIds ?? ['minimal'])].sort(),
526
- tempParent: options.tempParent,
527
- metadataIo: metadataIoKey(options.metadataIo ?? DEFAULT_METADATA_IO),
528
- })
529
- }
530
-
531
- /**
532
- * Install the one physical method decoration leased by public callers.
533
- *
534
- * Direct resolution and authoring stay source-preserving. AsyncLocalStorage
535
- * scopes the overlay to the async call tree of mount/recompose/standingKeyFor,
536
- * so an unrelated resolve racing the mount cannot inherit its generated path.
537
- */
538
- function installAgentPresetsDecoration(
539
- presets: OverlayableAgentPresets,
540
- options: PresetOverlayOptions,
541
- ): PresetOverlayInstallation {
542
- const excluded = new Set(options.excludedPresetIds ?? ['minimal'])
543
- const operations = new AsyncLocalStorage<CompositionOperation>()
544
- const store = new PresetOverlayStore(options)
545
- const snapshots = snapshotMethods(presets)
546
- const resolveSnapshot = snapshotFor(snapshots, 'resolve')
547
-
548
- const resolveWrapped = async (id?: string): Promise<AgentPreset> => {
549
- const preset = await Reflect.apply(resolveSnapshot.original, presets, [id]) as AgentPreset
550
- if (operations.getStore()?.composing !== true || excluded.has(preset.id)) return preset
551
- return await store.overlay(preset)
552
- }
553
- installMethod(presets, resolveSnapshot, resolveWrapped)
554
-
555
- for (const method of ['mount', 'recompose', 'standingKeyFor'] as const) {
556
- const snapshot = snapshotFor(snapshots, method)
557
- const wrapped = (...args: unknown[]): unknown => operations.run(
558
- { composing: true },
559
- (): unknown => Reflect.apply(snapshot.original, presets, args) as unknown,
560
- )
561
- installMethod(presets, snapshot, wrapped)
562
- }
563
-
564
- let disposed = false
565
- return {
566
- async dispose(): Promise<void> {
567
- if (disposed) return
568
- disposed = true
569
- for (const snapshot of [...snapshots].reverse()) restoreMethod(presets, snapshot)
570
- await store.dispose()
571
- },
572
- }
573
- }
574
-
575
- /** Capture callable methods and whether each was inherited or owned. */
576
- function snapshotMethods(presets: OverlayableAgentPresets): MethodSnapshot[] {
577
- return (['resolve', 'mount', 'recompose', 'standingKeyFor'] as const).map((name) => {
578
- // Capture is detached by design: every apply/restore site re-binds via
579
- // Reflect.apply(..., presets, args), so this read never escapes its `this`.
580
- // eslint-disable-next-line @typescript-eslint/unbound-method
581
- const original = presets[name]
582
- if (typeof original !== 'function') {
583
- throw new TypeError(`context-compression selector: AgentPresets.${name} is unavailable`)
584
- }
585
- return {
586
- name,
587
- own: Object.getOwnPropertyDescriptor(presets, name),
588
- original,
589
- }
590
- })
591
- }
592
-
593
- /** Return the captured method or fail loudly if the snapshot set is corrupt. */
594
- function snapshotFor(
595
- snapshots: readonly MethodSnapshot[],
596
- name: MethodSnapshot['name'],
597
- ): MethodSnapshot {
598
- const snapshot = snapshots.find(candidate => candidate.name === name)
599
- if (snapshot === undefined) {
600
- throw new Error(`context-compression selector: missing method snapshot for ${name}`)
601
- }
602
- return snapshot
603
- }
604
-
605
- /** Install one own method while retaining its identity for safe disposal. */
606
- function installMethod(
607
- presets: OverlayableAgentPresets,
608
- snapshot: MethodSnapshot,
609
- wrapped: (...args: never[]) => unknown,
610
- ): void {
611
- snapshot.wrapped = wrapped
612
- Object.defineProperty(presets, snapshot.name, {
613
- configurable: true,
614
- writable: true,
615
- value: wrapped,
616
- })
617
- }
618
-
619
- /** Restore the captured own/prototype state after the final shared lease. */
620
- function restoreMethod(presets: OverlayableAgentPresets, snapshot: MethodSnapshot): void {
621
- // Cordis' traceable service proxy rebinds a method on every read, so function
622
- // identity cannot prove ownership here. The shared reference count is the
623
- // ownership guard: this path runs only after the final decorator lease ends.
624
- if (snapshot.own === undefined) {
625
- Reflect.deleteProperty(presets, snapshot.name)
626
- } else {
627
- Object.defineProperty(presets, snapshot.name, snapshot.own)
628
- }
629
- }
1
+ /** Plugin-owned, reversible compression overlays for native agent presets. */
2
+
3
+ import { AsyncLocalStorage } from 'node:async_hooks'
4
+ import { createHash } from 'node:crypto'
5
+ import { chmod, mkdtemp, readFile, rename, rm, stat, utimes, writeFile } from 'node:fs/promises'
6
+ import { tmpdir } from 'node:os'
7
+ import { isAbsolute, join } from 'node:path'
8
+ import { fileURLToPath } from 'node:url'
9
+ import { applyEntryPatches, entryListSchema } from '@deepseek-ai/cordis-plugin-include'
10
+ import type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader'
11
+ import type { AgentPreset } from '@deepseek-ai/dsh-agent-presets'
12
+ import { dump, load } from 'js-yaml'
13
+
14
+ /** Absolute runtime entry points used by the generated compression stack. */
15
+ export interface CompressionModulePaths {
16
+ /** Exact aggregate/history compaction implementation shipped with the Bundle. */
17
+ readonly compactionBasic: string
18
+ /** Exact manual compact command shipped with the Bundle. */
19
+ readonly commandCompact: string
20
+ /** Exact enhanced tool-result pruner shipped with the Bundle. */
21
+ readonly toolResultPruner: string
22
+ }
23
+
24
+ /** The public native methods the decorator uses without reaching into core internals. */
25
+ export interface OverlayableAgentPresets {
26
+ /** Resolve a source preset for discovery and authoring. */
27
+ resolve(id?: string): Promise<AgentPreset>
28
+ /** Compose an agent from a preset. */
29
+ mount(agentCtx: unknown, id?: string): Promise<AgentPreset>
30
+ /** Move a blank agent to a different preset. */
31
+ recompose(agentCtx: unknown, id: string): Promise<AgentPreset>
32
+ /** Ensure a standing preset composition for cold readers. */
33
+ standingKeyFor(id?: string): Promise<unknown>
34
+ }
35
+
36
+ /** Configuration for one reversible decoration. */
37
+ export interface PresetOverlayOptions {
38
+ /** Absolute module entry points written into the generated composition. */
39
+ readonly modules: CompressionModulePaths
40
+ /** Preset ids that deliberately retain their native composition. */
41
+ readonly excludedPresetIds?: readonly string[]
42
+ /**
43
+ * Reads the Auto Compact threshold percent (50�?0) to freeze into newly
44
+ * generated compositions �?once per composition, into BOTH the
45
+ * compaction-basic `thresholdRatio` and the runtime deployment config, so
46
+ * one generation can never split Auto Compact and micro compact across two
47
+ * thresholds. Returning `undefined` keeps both defaults untouched.
48
+ */
49
+ readonly autoCompactThresholdPercent?: () => number | undefined
50
+ /** Test seam for locating the owner-only generated directory. */
51
+ readonly tempParent?: string
52
+ /**
53
+ * Metadata boundary used to prepare and observe the native standing key.
54
+ * Production uses the real filesystem; tests may model coarser mtime
55
+ * resolution without replacing identity generation.
56
+ */
57
+ readonly metadataIo?: PresetOverlayMetadataIo
58
+ }
59
+
60
+ /** Minimal filesystem metadata surface that determines AgentPresets identity. */
61
+ export interface PresetOverlayMetadataIo {
62
+ /** Persist one deterministic atime/mtime stamp on an unpublished staging file. */
63
+ setTimes(path: string, stamp: Date): Promise<void>
64
+ /** Read exactly the fields consumed by AgentPresets' standing key. */
65
+ read(path: string): Promise<Readonly<{ mtimeMs: number, size: number }>>
66
+ }
67
+
68
+ /** Handle returned by {@link decorateAgentPresets}. */
69
+ export interface PresetOverlayInstallation {
70
+ /** Restore native methods and remove every generated composition. */
71
+ dispose(): Promise<void>
72
+ }
73
+
74
+ /**
75
+ * Fixed base for deterministic standing mtimes. The stamp is derived from the
76
+ * FULL content identity (source + modules + threshold), not from the write
77
+ * clock: identical identities always republish to the same stamp (no
78
+ * generation flapping).
79
+ *
80
+ * The seconds component carries an 8-hex identity window directly. Most
81
+ * identities therefore separate even when a filesystem truncates mtimes to
82
+ * whole seconds; identities that share that 32-bit window deliberately collide
83
+ * first, are detected from the staging file's observed {mtimeMs, size}, and
84
+ * escalate to later hash windows before publication. The prefix keeps the
85
+ * latest possible stamp around year 2162, inside the nanosecond range every
86
+ * supported filesystem can store; the next 3 hex digits set sub-second
87
+ * milliseconds on filesystems that preserve them.
88
+ */
89
+ const STANDING_MTIME_EPOCH_SECONDS = Math.floor(Date.UTC(2026, 0, 1) / 1000)
90
+ const STANDING_MTIME_WINDOW_HEX = 11
91
+
92
+ const DEFAULT_METADATA_IO: PresetOverlayMetadataIo = Object.freeze({
93
+ async setTimes(path: string, stamp: Date): Promise<void> {
94
+ await utimes(path, stamp, stamp)
95
+ },
96
+ async read(path: string): Promise<Readonly<{ mtimeMs: number, size: number }>> {
97
+ const observed = await stat(path)
98
+ return { mtimeMs: observed.mtimeMs, size: observed.size }
99
+ },
100
+ })
101
+
102
+ /**
103
+ * Deterministic standing stamp for one full generation identity, read from
104
+ * hash window `windowIndex` (0 = identity prefix). Exported for the
105
+ * collision-fixture tests; production code uses {@link standingStampMs}.
106
+ */
107
+ export function standingStampMsAtWindow(identity: string, windowIndex: number): number {
108
+ const start = windowIndex * STANDING_MTIME_WINDOW_HEX
109
+ const seconds = STANDING_MTIME_EPOCH_SECONDS + parseInt(identity.slice(start, start + 8).padEnd(8, '0'), 16)
110
+ const subSecond = parseInt(identity.slice(start + 8, start + STANDING_MTIME_WINDOW_HEX).padEnd(3, '0'), 16) % 1000
111
+ return seconds * 1000 + subSecond
112
+ }
113
+
114
+ /** Deterministic standing stamp for one full generation identity. */
115
+ export function standingStampMs(identity: string): number {
116
+ return standingStampMsAtWindow(identity, 0)
117
+ }
118
+
119
+ /**
120
+ * True for the filesystem errors a concurrent publish can raise on Windows:
121
+ * `MoveFileEx` reports a lost race — or a reader holding the destination open —
122
+ * as EPERM/EBUSY/EACCES, where POSIX `rename` simply replaces the destination.
123
+ */
124
+ function isPublishRace(error: unknown): boolean {
125
+ const code = (error as { code?: unknown } | null)?.code
126
+ return code === 'EPERM' || code === 'EBUSY' || code === 'EACCES' || code === 'EEXIST'
127
+ }
128
+
129
+ const COMPRESSION_IDS = new Set([
130
+ 'compaction',
131
+ 'compaction-basic',
132
+ 'command-compact',
133
+ 'tool-result-pruner',
134
+ ])
135
+
136
+ const COMPRESSION_PACKAGES = new Set([
137
+ '@deepseek-ai/dsh-compaction-basic',
138
+ '@deepseek-ai/dsh-command-compact',
139
+ '@deepseek-ai/dsh-compaction-tool-result-pruner',
140
+ 'dsh-context-compression-improved-runtime',
141
+ 'dsh-context-compression-improved',
142
+ 'dsh-context-compression-improved/pruner',
143
+ ])
144
+
145
+ /**
146
+ * Resolve the three compression package entries once from this package.
147
+ * @returns Absolute entry paths for the canonical compression layer.
148
+ */
149
+ export function resolveCompressionModulePaths(): CompressionModulePaths {
150
+ return {
151
+ compactionBasic: modulePath(
152
+ '@deepseek-ai/dsh-compaction-basic', import.meta.resolve('@deepseek-ai/dsh-compaction-basic')),
153
+ commandCompact: modulePath(
154
+ '@deepseek-ai/dsh-command-compact', import.meta.resolve('@deepseek-ai/dsh-command-compact')),
155
+ toolResultPruner: modulePath(
156
+ 'dsh-context-compression-improved/pruner', import.meta.resolve('dsh-context-compression-improved/pruner')),
157
+ }
158
+ }
159
+
160
+ /** Convert one package resolution into the absolute path preset mounting accepts. */
161
+ function modulePath(specifier: string, resolved: string): string {
162
+ if (!resolved.startsWith('file:')) {
163
+ throw new Error(`context-compression selector: ${specifier} resolved outside the filesystem (${resolved})`)
164
+ }
165
+ return fileURLToPath(resolved)
166
+ }
167
+
168
+ /** One operation's permission to see generated presets through resolve(). */
169
+ interface CompositionOperation {
170
+ readonly composing: true
171
+ }
172
+
173
+ /** Generated composition storage owned by one decorator installation. */
174
+ class PresetOverlayStore {
175
+ private rootTask: Promise<string> | undefined
176
+ private disposed = false
177
+ private readonly metadataIo: PresetOverlayMetadataIo
178
+
179
+ constructor(private readonly options: PresetOverlayOptions) {
180
+ this.metadataIo = options.metadataIo ?? DEFAULT_METADATA_IO
181
+ const paths = Object.entries(options.modules) as [keyof CompressionModulePaths, string][]
182
+ for (const [name, path] of paths) {
183
+ if (!isAbsolute(path)) {
184
+ throw new TypeError(`context-compression selector: module path ${name} is not absolute: ${path}`)
185
+ }
186
+ }
187
+ }
188
+
189
+ /** Return a detached preset record whose path names the canonical overlay. */
190
+ async overlay(preset: AgentPreset): Promise<AgentPreset> {
191
+ if (this.disposed) throw new Error('context-compression selector: preset overlay is disposed')
192
+ if (preset.broken !== undefined) return preset
193
+ const source = await readFile(preset.path, 'utf8')
194
+ const rows = parseRows(source, preset.path)
195
+ const thresholdPercent = this.options.autoCompactThresholdPercent?.()
196
+ if (thresholdPercent !== undefined && !Number.isFinite(thresholdPercent)) {
197
+ // JSON.stringify maps NaN to null (colliding identities) and the YAML
198
+ // dump would serialize it as `.nan`; refuse instead.
199
+ throw new Error(`context-compression selector: Auto Compact threshold percent must be finite, got ${String(thresholdPercent)}`)
200
+ }
201
+ const patched = applyEntryPatches(
202
+ stripCompressionRows(rows),
203
+ [{ insert: canonicalCompressionRows(this.options.modules, thresholdPercent) }],
204
+ (message: string, ...args: unknown[]) => {
205
+ throw new Error(renderPatchWarning(message, args))
206
+ },
207
+ )
208
+ const rendered = dump(patched, {
209
+ schema: entryListSchema,
210
+ noRefs: true,
211
+ lineWidth: -1,
212
+ sortKeys: false,
213
+ })
214
+ // The percent joins the content identity by value, not by rendered
215
+ // length, so an equal-length change (70 -> 80) still produces a new file.
216
+ const identity = createHash('sha256')
217
+ .update(preset.id).update('\0')
218
+ .update(source).update('\0')
219
+ .update(JSON.stringify({ modules: this.options.modules, autoCompactThresholdPercent: thresholdPercent ?? null }))
220
+ .digest('hex')
221
+ .slice(0, 24)
222
+ const root = await this.root()
223
+ const path = join(root, `${preset.id}-${identity}.agent.cordis.yml`)
224
+ // Publish through a unique temporary file whose content, permissions, and
225
+ // DETERMINISTIC identity stamp are all complete before the atomic rename:
226
+ // once the final path exists it is fully metadata'd, so a concurrent
227
+ // composer (or AgentPresets' standing-key reader) can never observe a
228
+ // wall-clock mtime on a published composition.
229
+ const staging = join(root, `${preset.id}-${identity}.${String(process.pid)}-${String(Math.random()).slice(2)}.tmp`)
230
+ try {
231
+ await writeFile(staging, rendered, { encoding: 'utf8', mode: 0o600 })
232
+ await chmod(staging, 0o600)
233
+ // Reserve and verify the FINAL observed standing key while the file is
234
+ // still private. No reader can observe a colliding {mtimeMs,size}
235
+ // between rename and a later corrective utimes call.
236
+ await this.disambiguateStamp(staging, identity)
237
+ await this.publish(staging, path)
238
+ } catch (error) {
239
+ // A failed publish must not leak its staging file into the store; the
240
+ // cleanup must never mask the original failure either.
241
+ try {
242
+ await rm(staging, { force: true })
243
+ } catch {
244
+ // intentional: the publish error below is the actionable one
245
+ }
246
+ throw error
247
+ }
248
+ return { ...preset, path }
249
+ }
250
+
251
+ /** In-flight publish chains, one per destination path. */
252
+ private readonly publishChains = new Map<string, Promise<void>>()
253
+
254
+ /**
255
+ * Publish one stamped staging file to its final path, serialized per path.
256
+ *
257
+ * POSIX `rename` replaces an existing destination atomically, so concurrent
258
+ * composers of one identity are naturally idempotent there. Windows
259
+ * `MoveFileEx` instead fails the loser of that race with EPERM/EBUSY, which
260
+ * surfaced as `standingKeyFor()` throwing during concurrent composition.
261
+ * Every composer of one identity writes identical bytes and re-derives the
262
+ * same deterministic identity stamp, so a destination that already observes
263
+ * this staging file's {mtimeMs, size} key IS the intended end state: confirm
264
+ * it and treat the lost race as success. Every other outcome still throws, so
265
+ * a silently reused generation stays forbidden, and the caller still removes
266
+ * the staging file when this rejects.
267
+ */
268
+ private publish(staging: string, path: string): Promise<void> {
269
+ const previous = this.publishChains.get(path) ?? Promise.resolve()
270
+ const queued = previous.catch(() => undefined).then(async () => {
271
+ try {
272
+ await rename(staging, path)
273
+ return
274
+ } catch (error) {
275
+ if (!isPublishRace(error)) throw error
276
+ try {
277
+ const intended = await this.metadataIo.read(staging)
278
+ const published = await this.metadataIo.read(path)
279
+ // Sub-second precision survives a wrapped seconds field, but NTFS
280
+ // rounds it to 100ns, so compare the standing key within that
281
+ // rounding rather than by exact float equality.
282
+ if (published.size === intended.size
283
+ && Math.abs(published.mtimeMs - intended.mtimeMs) < 2) {
284
+ await rm(staging, { force: true })
285
+ return
286
+ }
287
+ } catch {
288
+ // The destination is unreadable: report the original publish failure.
289
+ }
290
+ throw error
291
+ }
292
+ })
293
+ const tracked = queued.finally(() => {
294
+ if (this.publishChains.get(path) === tracked) this.publishChains.delete(path)
295
+ })
296
+ this.publishChains.set(path, tracked)
297
+ return tracked
298
+ }
299
+
300
+ /** Observed {mtimeMs,size} keys published by this store, per identity. */
301
+ private readonly standingKeys = new Map<string, string>()
302
+
303
+ /**
304
+ * Ensure an unpublished staging file's observed {mtimeMs, size} is not
305
+ * shared with a different identity. Escalation rewrites the mtime from later
306
+ * hash windows before atomic publication, and fails loudly if no window
307
+ * separates them (better a loud error than a silently reused generation).
308
+ */
309
+ private async disambiguateStamp(path: string, identity: string): Promise<void> {
310
+ for (let window = 0; window < 3; window += 1) {
311
+ const stamp = new Date(standingStampMsAtWindow(identity, window))
312
+ await this.metadataIo.setTimes(path, stamp)
313
+ // The native key uses the on-disk byte size, not the UTF-16 length of
314
+ // the rendered string.
315
+ const observed = await this.metadataIo.read(path)
316
+ const key = `${String(observed.mtimeMs)}:${String(observed.size)}`
317
+ const owner = this.standingKeys.get(key)
318
+ if (owner === undefined || owner === identity) {
319
+ this.standingKeys.set(key, identity)
320
+ return
321
+ }
322
+ }
323
+ throw new Error(`context-compression selector: standing stamp collision for identity ${identity} across all hash windows`)
324
+ }
325
+
326
+ /** Remove all generated files without touching any source preset. */
327
+ async dispose(): Promise<void> {
328
+ if (this.disposed) return
329
+ this.disposed = true
330
+ if (this.rootTask === undefined) return
331
+ const root = await this.rootTask
332
+ await rm(root, { recursive: true, force: true })
333
+ }
334
+
335
+ /** Lazily create the one owner-only directory for this installation. */
336
+ private async root(): Promise<string> {
337
+ if (this.rootTask === undefined) {
338
+ const parent = this.options.tempParent ?? tmpdir()
339
+ this.rootTask = mkdtemp(join(parent, 'dsh-context-compression-presets-'))
340
+ .then(async (root) => {
341
+ await chmod(root, 0o700)
342
+ return root
343
+ })
344
+ }
345
+ return await this.rootTask
346
+ }
347
+ }
348
+
349
+ /** Parse one native preset with exactly the Loader's YAML dialect. */
350
+ function parseRows(source: string, path: string): EntryOptions[] {
351
+ const parsed = load(source, { schema: entryListSchema })
352
+ if (!Array.isArray(parsed)) {
353
+ throw new TypeError(`context-compression selector: preset ${path} is not a top-level entry list`)
354
+ }
355
+ return parsed as EntryOptions[]
356
+ }
357
+
358
+ /** Remove any prior compression implementation before adding the canonical one. */
359
+ function stripCompressionRows(rows: EntryOptions[]): EntryOptions[] {
360
+ const kept: EntryOptions[] = []
361
+ for (const row of rows) {
362
+ if (COMPRESSION_IDS.has(row.id) || COMPRESSION_PACKAGES.has(row.name)) continue
363
+ if (row.group === true && Array.isArray(row.config)) {
364
+ const nested = row.config as unknown as EntryOptions[]
365
+ kept.push({ ...row, config: stripCompressionRows(nested) })
366
+ } else {
367
+ kept.push(row)
368
+ }
369
+ }
370
+ return kept
371
+ }
372
+
373
+ /**
374
+ * Complete, same-realm compression stack added to every applicable preset.
375
+ * When the Host settings expose an Auto Compact threshold, one read feeds both
376
+ * the compaction-basic `thresholdRatio` (beside the pinned first-release
377
+ * `retainRatio`) and the runtime deployment config, so plugin History and
378
+ * native Auto Compact share one watermark for this whole generation.
379
+ */
380
+ function canonicalCompressionRows(
381
+ modules: CompressionModulePaths,
382
+ thresholdPercent?: number,
383
+ ): EntryOptions[] {
384
+ return [
385
+ {
386
+ id: 'compaction',
387
+ name: 'cordis:group',
388
+ group: true,
389
+ isolate: {
390
+ compaction: true,
391
+ toolResultPruner: true,
392
+ },
393
+ config: [
394
+ {
395
+ id: 'compaction-basic',
396
+ name: modules.compactionBasic,
397
+ ...(thresholdPercent === undefined ? {} : {
398
+ config: {
399
+ thresholdRatio: thresholdPercent / 100,
400
+ retainRatio: 0.16,
401
+ },
402
+ }),
403
+ },
404
+ {
405
+ id: 'command-compact',
406
+ name: modules.commandCompact,
407
+ },
408
+ {
409
+ id: 'tool-result-pruner',
410
+ name: modules.toolResultPruner,
411
+ config: {
412
+ headChars: 4096,
413
+ tailChars: 1024,
414
+ ...(thresholdPercent === undefined ? {} : { autoCompactThresholdPercent: thresholdPercent }),
415
+ },
416
+ },
417
+ ],
418
+ },
419
+ ]
420
+ }
421
+
422
+ /** Render include's printf-style warning without silently losing its target. */
423
+ function renderPatchWarning(message: string, args: readonly unknown[]): string {
424
+ let index = 0
425
+ return `context-compression selector: ${message.replace(/%C/g, () => JSON.stringify(args[index++]))}`
426
+ }
427
+
428
+ /** Method names whose native execution is allowed to resolve an overlay. */
429
+ type CompositionMethod = 'mount' | 'recompose' | 'standingKeyFor'
430
+
431
+ /** Restore one method to exactly the own/prototype state it had before decoration. */
432
+ interface MethodSnapshot {
433
+ readonly name: 'resolve' | CompositionMethod
434
+ readonly own: PropertyDescriptor | undefined
435
+ readonly original: (...args: never[]) => unknown
436
+ wrapped?: (...args: never[]) => unknown
437
+ }
438
+
439
+ /** One physical decoration shared by every duplicate Host row. */
440
+ interface SharedDecoration {
441
+ /** Canonical options prevent two rows from silently requesting different stacks. */
442
+ readonly optionsKey: string
443
+ /** Number of live plugin fibers leasing this decoration. */
444
+ references: number
445
+ /** Physical method wrappers and generated-directory owner. */
446
+ readonly installation: PresetOverlayInstallation
447
+ }
448
+
449
+ /**
450
+ * Cordis can hand two callers different traceable proxies for one service.
451
+ * Symbol properties forward to the shared target, unlike proxy identity.
452
+ */
453
+ const SHARED_DECORATION = Symbol.for(
454
+ 'dsh-context-compression-improved/preset-overlay',
455
+ )
456
+
457
+ /** Object-identity keys keep test metadata policies from sharing one store. */
458
+ const METADATA_IO_KEYS = new WeakMap<object, number>()
459
+ let nextMetadataIoKey = 1
460
+
461
+ function metadataIoKey(metadataIo: PresetOverlayMetadataIo): number {
462
+ const existing = METADATA_IO_KEYS.get(metadataIo)
463
+ if (existing !== undefined) return existing
464
+ const key = nextMetadataIoKey
465
+ nextMetadataIoKey += 1
466
+ METADATA_IO_KEYS.set(metadataIo, key)
467
+ return key
468
+ }
469
+
470
+ /**
471
+ * Reversibly decorate native AgentPresets composition calls.
472
+ *
473
+ * Duplicate Host rows share one physical decoration. This matters while an
474
+ * installation migrates from a Harness-bundled selector row to the standalone
475
+ * Bundle: either row can unload first without double-compressing or disposing
476
+ * the generated files still used by the other.
477
+ * @param presets Native AgentPresets service to decorate during composition.
478
+ * @param options Canonical module paths, exclusions, and optional test directory.
479
+ * @returns A reference-counted handle that restores the native service on final disposal.
480
+ */
481
+ export function decorateAgentPresets(
482
+ presets: OverlayableAgentPresets,
483
+ options: PresetOverlayOptions,
484
+ ): PresetOverlayInstallation {
485
+ const optionsKey = overlayOptionsKey(options)
486
+ const carrier = presets as OverlayableAgentPresets & { [SHARED_DECORATION]?: SharedDecoration }
487
+ let shared = carrier[SHARED_DECORATION]
488
+ if (shared === undefined) {
489
+ shared = {
490
+ optionsKey,
491
+ references: 0,
492
+ installation: installAgentPresetsDecoration(presets, options),
493
+ }
494
+ Object.defineProperty(carrier, SHARED_DECORATION, {
495
+ configurable: true,
496
+ enumerable: false,
497
+ writable: false,
498
+ value: shared,
499
+ })
500
+ } else if (shared.optionsKey !== optionsKey) {
501
+ throw new Error('context-compression selector: AgentPresets already has a different compression overlay')
502
+ }
503
+ const lease = shared
504
+ lease.references += 1
505
+
506
+ let disposed = false
507
+ return {
508
+ async dispose(): Promise<void> {
509
+ if (disposed) return
510
+ disposed = true
511
+ lease.references -= 1
512
+ if (lease.references !== 0) return
513
+ if (carrier[SHARED_DECORATION] === lease) {
514
+ Reflect.deleteProperty(carrier, SHARED_DECORATION)
515
+ }
516
+ await lease.installation.dispose()
517
+ },
518
+ }
519
+ }
520
+
521
+ /** Stable equality for two rows asking to share one physical overlay. */
522
+ function overlayOptionsKey(options: PresetOverlayOptions): string {
523
+ return JSON.stringify({
524
+ modules: options.modules,
525
+ excludedPresetIds: [...(options.excludedPresetIds ?? ['minimal'])].sort(),
526
+ tempParent: options.tempParent,
527
+ metadataIo: metadataIoKey(options.metadataIo ?? DEFAULT_METADATA_IO),
528
+ })
529
+ }
530
+
531
+ /**
532
+ * Install the one physical method decoration leased by public callers.
533
+ *
534
+ * Direct resolution and authoring stay source-preserving. AsyncLocalStorage
535
+ * scopes the overlay to the async call tree of mount/recompose/standingKeyFor,
536
+ * so an unrelated resolve racing the mount cannot inherit its generated path.
537
+ */
538
+ function installAgentPresetsDecoration(
539
+ presets: OverlayableAgentPresets,
540
+ options: PresetOverlayOptions,
541
+ ): PresetOverlayInstallation {
542
+ const excluded = new Set(options.excludedPresetIds ?? ['minimal'])
543
+ const operations = new AsyncLocalStorage<CompositionOperation>()
544
+ const store = new PresetOverlayStore(options)
545
+ const snapshots = snapshotMethods(presets)
546
+ const resolveSnapshot = snapshotFor(snapshots, 'resolve')
547
+
548
+ const resolveWrapped = async (id?: string): Promise<AgentPreset> => {
549
+ const preset = await Reflect.apply(resolveSnapshot.original, presets, [id]) as AgentPreset
550
+ if (operations.getStore()?.composing !== true || excluded.has(preset.id)) return preset
551
+ return await store.overlay(preset)
552
+ }
553
+ installMethod(presets, resolveSnapshot, resolveWrapped)
554
+
555
+ for (const method of ['mount', 'recompose', 'standingKeyFor'] as const) {
556
+ const snapshot = snapshotFor(snapshots, method)
557
+ const wrapped = (...args: unknown[]): unknown => operations.run(
558
+ { composing: true },
559
+ (): unknown => Reflect.apply(snapshot.original, presets, args) as unknown,
560
+ )
561
+ installMethod(presets, snapshot, wrapped)
562
+ }
563
+
564
+ let disposed = false
565
+ return {
566
+ async dispose(): Promise<void> {
567
+ if (disposed) return
568
+ disposed = true
569
+ for (const snapshot of [...snapshots].reverse()) restoreMethod(presets, snapshot)
570
+ await store.dispose()
571
+ },
572
+ }
573
+ }
574
+
575
+ /** Capture callable methods and whether each was inherited or owned. */
576
+ function snapshotMethods(presets: OverlayableAgentPresets): MethodSnapshot[] {
577
+ return (['resolve', 'mount', 'recompose', 'standingKeyFor'] as const).map((name) => {
578
+ // Capture is detached by design: every apply/restore site re-binds via
579
+ // Reflect.apply(..., presets, args), so this read never escapes its `this`.
580
+ // eslint-disable-next-line @typescript-eslint/unbound-method
581
+ const original = presets[name]
582
+ if (typeof original !== 'function') {
583
+ throw new TypeError(`context-compression selector: AgentPresets.${name} is unavailable`)
584
+ }
585
+ return {
586
+ name,
587
+ own: Object.getOwnPropertyDescriptor(presets, name),
588
+ original,
589
+ }
590
+ })
591
+ }
592
+
593
+ /** Return the captured method or fail loudly if the snapshot set is corrupt. */
594
+ function snapshotFor(
595
+ snapshots: readonly MethodSnapshot[],
596
+ name: MethodSnapshot['name'],
597
+ ): MethodSnapshot {
598
+ const snapshot = snapshots.find(candidate => candidate.name === name)
599
+ if (snapshot === undefined) {
600
+ throw new Error(`context-compression selector: missing method snapshot for ${name}`)
601
+ }
602
+ return snapshot
603
+ }
604
+
605
+ /** Install one own method while retaining its identity for safe disposal. */
606
+ function installMethod(
607
+ presets: OverlayableAgentPresets,
608
+ snapshot: MethodSnapshot,
609
+ wrapped: (...args: never[]) => unknown,
610
+ ): void {
611
+ snapshot.wrapped = wrapped
612
+ Object.defineProperty(presets, snapshot.name, {
613
+ configurable: true,
614
+ writable: true,
615
+ value: wrapped,
616
+ })
617
+ }
618
+
619
+ /** Restore the captured own/prototype state after the final shared lease. */
620
+ function restoreMethod(presets: OverlayableAgentPresets, snapshot: MethodSnapshot): void {
621
+ // Cordis' traceable service proxy rebinds a method on every read, so function
622
+ // identity cannot prove ownership here. The shared reference count is the
623
+ // ownership guard: this path runs only after the final decorator lease ends.
624
+ if (snapshot.own === undefined) {
625
+ Reflect.deleteProperty(presets, snapshot.name)
626
+ } else {
627
+ Object.defineProperty(presets, snapshot.name, snapshot.own)
628
+ }
629
+ }