dsh-context-compression-improved 0.5.6 → 0.5.7

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 (162) 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 +314 -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 +164 -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.js +733 -0
  34. package/packages/selector/lib/style.css +46 -46
  35. package/packages/selector/package.json +114 -114
  36. package/packages/selector/screenshots.json +3 -3
  37. package/packages/selector/src/client/CompressionProfileControls.tsx +226 -226
  38. package/packages/selector/src/client/CompressionProfileSelector.module.css +170 -170
  39. package/packages/selector/src/client/CompressionProfileSelector.tsx +83 -83
  40. package/packages/selector/src/client/CustomPolicyEditor.tsx +216 -216
  41. package/packages/selector/src/client/EstimatorControls.tsx +277 -277
  42. package/packages/selector/src/client/decode.ts +49 -49
  43. package/packages/selector/src/client/index.ts +178 -149
  44. package/packages/selector/src/client/locales/de.ts +98 -0
  45. package/packages/selector/src/client/locales/es.ts +98 -0
  46. package/packages/selector/src/client/locales/fr.ts +98 -0
  47. package/packages/selector/src/client/locales/it.ts +98 -0
  48. package/packages/selector/src/client/locales/ja.ts +98 -0
  49. package/packages/selector/src/client/locales/ko.ts +98 -0
  50. package/packages/selector/src/client/locales/ru.ts +98 -0
  51. package/packages/selector/src/client/locales.ts +196 -196
  52. package/packages/selector/src/client/preset-options.ts +88 -88
  53. package/packages/selector/src/client/settings-section.tsx +124 -124
  54. package/packages/selector/src/css-modules.d.ts +6 -6
  55. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -205
  56. package/packages/selector/src/estimator-catalog.ts +104 -104
  57. package/packages/selector/src/index.ts +463 -463
  58. package/packages/selector/src/invariant.ts +113 -113
  59. package/packages/selector/src/preset-overlay.ts +626 -626
  60. package/packages/selector/src/profiles.ts +394 -394
  61. package/packages/selector/src/pruner/content.ts +201 -201
  62. package/packages/selector/src/pruner/session.ts +94 -94
  63. package/packages/selector/src/pruner/state.ts +50 -50
  64. package/packages/selector/src/pruner/tuning.ts +23 -23
  65. package/packages/selector/src/pruner/types.ts +78 -78
  66. package/packages/selector/src/pruner.ts +2402 -2402
  67. package/packages/selector/src/runtime/adaptive-cost.ts +205 -205
  68. package/packages/selector/src/runtime/audit.ts +286 -286
  69. package/packages/selector/src/runtime/config.ts +706 -706
  70. package/packages/selector/src/runtime/custom-policy.ts +278 -278
  71. package/packages/selector/src/runtime/deepseek-official-pricing.ts +298 -298
  72. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +254 -254
  73. package/packages/selector/src/runtime/measurement.ts +436 -436
  74. package/packages/selector/src/runtime/reducers.ts +1674 -1674
  75. package/packages/selector/src/runtime/retrieve.ts +457 -457
  76. package/packages/selector/src/runtime/session-events.ts +30 -30
  77. package/packages/selector/src/runtime/tail-trim.ts +166 -166
  78. package/packages/selector/src/runtime/token-count.ts +72 -72
  79. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +188 -188
  80. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +149 -149
  81. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -419
  82. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -200
  83. package/packages/selector/src/runtime/tokenpilot/dedup.ts +81 -81
  84. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -151
  85. package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -128
  86. package/packages/selector/src/runtime/tokenpilot/read-state.ts +98 -98
  87. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -303
  88. package/packages/selector/src/runtime/toolclass.ts +103 -103
  89. package/packages/selector/src/runtime/types.ts +346 -346
  90. package/packages/selector/src/runtime/value.ts +48 -48
  91. package/packages/selector/tests/advisor-report.host.spec.ts +223 -223
  92. package/packages/selector/tests/auto-compact.client.spec.tsx +213 -213
  93. package/packages/selector/tests/built/client-artifact.spec.ts +59 -59
  94. package/packages/selector/tests/cache-prefix-audit.spec.ts +123 -123
  95. package/packages/selector/tests/code-skeleton.client.spec.ts +90 -90
  96. package/packages/selector/tests/custom-contract.client.spec.ts +204 -204
  97. package/packages/selector/tests/estimator-catalog.spec.ts +70 -70
  98. package/packages/selector/tests/estimator-channel.client.spec.tsx +252 -252
  99. package/packages/selector/tests/estimator-route-registration.host.spec.ts +188 -188
  100. package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -206
  101. package/packages/selector/tests/preset-options-write.client.spec.ts +206 -206
  102. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -201
  103. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -246
  104. package/packages/selector/tests/profiles.client.spec.tsx +434 -434
  105. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -78
  106. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +167 -167
  107. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -232
  108. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -272
  109. package/packages/selector/tests/runtime/advisor.spec.ts +226 -226
  110. package/packages/selector/tests/runtime/audit.spec.ts +274 -274
  111. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -523
  112. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -30
  113. package/packages/selector/tests/runtime/code-skeleton.spec.ts +152 -152
  114. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +186 -186
  115. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -122
  116. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +122 -122
  117. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -96
  118. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +273 -273
  119. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +106 -106
  120. package/packages/selector/tests/runtime/fixtures/vision-golden.json +459 -459
  121. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -74
  122. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -212
  123. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -153
  124. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -133
  125. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2724
  126. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -33
  127. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -110
  128. package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
  129. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -241
  130. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -159
  131. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +53 -53
  132. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -217
  133. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +52 -52
  134. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -79
  135. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +76 -76
  136. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -116
  137. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +82 -82
  138. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -156
  139. package/packages/selector/tests/runtime/value.spec.ts +23 -23
  140. package/packages/selector/tests/settings-seat.client.spec.ts +118 -118
  141. package/packages/selector/tests/standing-generation.host.spec.ts +697 -697
  142. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -253
  143. package/packages/selector/tests/support/cache-prefix-audit.ts +105 -105
  144. package/packages/selector/tests/support/mock-adapter.ts +37 -37
  145. package/packages/selector/tests/support/ui-primitives.tsx +34 -34
  146. package/packages/selector/tsconfig.json +11 -11
  147. package/packages/selector/tsdown.client.config.ts +102 -102
  148. package/packages/selector/tsdown.config.ts +20 -20
  149. package/pnpm-workspace.yaml +66 -66
  150. package/scripts/capture-profile-baseline.mjs +42 -42
  151. package/scripts/generate-tokenizer-fixtures.py +81 -81
  152. package/scripts/generate-vision-fixtures.py +208 -208
  153. package/scripts/packed-components-smoke.mjs +732 -732
  154. package/scripts/packed-install-e2e.mjs +1273 -1273
  155. package/scripts/toolclass-corpus-replay.mjs +281 -281
  156. package/scripts/verify-release.mjs +317 -317
  157. package/tests/TEST_INVENTORY.md +41 -41
  158. package/tsconfig.base.json +18 -18
  159. package/tsconfig.json +7 -7
  160. package/tsconfig.tests.json +15 -15
  161. package/vitest.built.config.ts +9 -9
  162. package/vitest.config.ts +43 -43
@@ -1,626 +1,626 @@
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
- const original = presets[name]
579
- if (typeof original !== 'function') {
580
- throw new TypeError(`context-compression selector: AgentPresets.${name} is unavailable`)
581
- }
582
- return {
583
- name,
584
- own: Object.getOwnPropertyDescriptor(presets, name),
585
- original,
586
- }
587
- })
588
- }
589
-
590
- /** Return the captured method or fail loudly if the snapshot set is corrupt. */
591
- function snapshotFor(
592
- snapshots: readonly MethodSnapshot[],
593
- name: MethodSnapshot['name'],
594
- ): MethodSnapshot {
595
- const snapshot = snapshots.find(candidate => candidate.name === name)
596
- if (snapshot === undefined) {
597
- throw new Error(`context-compression selector: missing method snapshot for ${name}`)
598
- }
599
- return snapshot
600
- }
601
-
602
- /** Install one own method while retaining its identity for safe disposal. */
603
- function installMethod(
604
- presets: OverlayableAgentPresets,
605
- snapshot: MethodSnapshot,
606
- wrapped: (...args: never[]) => unknown,
607
- ): void {
608
- snapshot.wrapped = wrapped
609
- Object.defineProperty(presets, snapshot.name, {
610
- configurable: true,
611
- writable: true,
612
- value: wrapped,
613
- })
614
- }
615
-
616
- /** Restore the captured own/prototype state after the final shared lease. */
617
- function restoreMethod(presets: OverlayableAgentPresets, snapshot: MethodSnapshot): void {
618
- // Cordis' traceable service proxy rebinds a method on every read, so function
619
- // identity cannot prove ownership here. The shared reference count is the
620
- // ownership guard: this path runs only after the final decorator lease ends.
621
- if (snapshot.own === undefined) {
622
- Reflect.deleteProperty(presets, snapshot.name)
623
- } else {
624
- Object.defineProperty(presets, snapshot.name, snapshot.own)
625
- }
626
- }
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
+ const original = presets[name]
579
+ if (typeof original !== 'function') {
580
+ throw new TypeError(`context-compression selector: AgentPresets.${name} is unavailable`)
581
+ }
582
+ return {
583
+ name,
584
+ own: Object.getOwnPropertyDescriptor(presets, name),
585
+ original,
586
+ }
587
+ })
588
+ }
589
+
590
+ /** Return the captured method or fail loudly if the snapshot set is corrupt. */
591
+ function snapshotFor(
592
+ snapshots: readonly MethodSnapshot[],
593
+ name: MethodSnapshot['name'],
594
+ ): MethodSnapshot {
595
+ const snapshot = snapshots.find(candidate => candidate.name === name)
596
+ if (snapshot === undefined) {
597
+ throw new Error(`context-compression selector: missing method snapshot for ${name}`)
598
+ }
599
+ return snapshot
600
+ }
601
+
602
+ /** Install one own method while retaining its identity for safe disposal. */
603
+ function installMethod(
604
+ presets: OverlayableAgentPresets,
605
+ snapshot: MethodSnapshot,
606
+ wrapped: (...args: never[]) => unknown,
607
+ ): void {
608
+ snapshot.wrapped = wrapped
609
+ Object.defineProperty(presets, snapshot.name, {
610
+ configurable: true,
611
+ writable: true,
612
+ value: wrapped,
613
+ })
614
+ }
615
+
616
+ /** Restore the captured own/prototype state after the final shared lease. */
617
+ function restoreMethod(presets: OverlayableAgentPresets, snapshot: MethodSnapshot): void {
618
+ // Cordis' traceable service proxy rebinds a method on every read, so function
619
+ // identity cannot prove ownership here. The shared reference count is the
620
+ // ownership guard: this path runs only after the final decorator lease ends.
621
+ if (snapshot.own === undefined) {
622
+ Reflect.deleteProperty(presets, snapshot.name)
623
+ } else {
624
+ Object.defineProperty(presets, snapshot.name, snapshot.own)
625
+ }
626
+ }