dsh-context-compression-improved 0.2.3 → 0.2.5

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 (149) hide show
  1. package/.gitattributes +2 -1
  2. package/.githooks/pre-push +37 -0
  3. package/.github/workflows/ci.yml +39 -39
  4. package/CHANGELOG.ja.md +169 -39
  5. package/CHANGELOG.ko.md +167 -39
  6. package/CHANGELOG.md +333 -135
  7. package/CHANGELOG.zh.md +152 -39
  8. package/CONTRIBUTING.md +22 -22
  9. package/README.ja.md +85 -104
  10. package/README.ko.md +85 -103
  11. package/README.md +94 -112
  12. package/README.zh.md +85 -101
  13. package/THIRD_PARTY_NOTICES.md +14 -14
  14. package/docs/compat-0.1.5-report.md +77 -0
  15. package/docs/installation.ja.md +78 -76
  16. package/docs/installation.ko.md +78 -76
  17. package/docs/installation.md +103 -76
  18. package/docs/installation.zh.md +100 -76
  19. package/docs/repair-log.md +657 -582
  20. package/eslint.config.js +30 -30
  21. package/package.json +163 -142
  22. package/packages/selector/README.md +26 -31
  23. package/packages/selector/README.zh.md +24 -31
  24. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -38
  25. package/packages/selector/cordis.patch.yml +27 -19
  26. package/packages/selector/dsh.plugin.json +2 -2
  27. package/packages/selector/lib/client.d.ts +320 -228
  28. package/packages/selector/lib/client.js +3254 -1462
  29. package/packages/selector/lib/config.js +1713 -842
  30. package/packages/selector/lib/index.d.ts +46 -38
  31. package/packages/selector/lib/index.js +1099 -645
  32. package/packages/selector/lib/invariant.js +70 -70
  33. package/packages/selector/lib/pruner.d.ts +904 -684
  34. package/packages/selector/lib/pruner.js +5800 -3807
  35. package/packages/selector/lib/style.css +88 -46
  36. package/packages/selector/lib/tail-trim.js +145 -136
  37. package/packages/selector/package.json +18 -19
  38. package/packages/selector/screenshots.json +3 -6
  39. package/packages/selector/src/client/CompressionProfileControls.tsx +293 -229
  40. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  41. package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -79
  42. package/packages/selector/src/client/EstimatorControls.tsx +277 -281
  43. package/packages/selector/src/client/decode.ts +57 -49
  44. package/packages/selector/src/client/index.ts +249 -111
  45. package/packages/selector/src/client/locales/de.ts +141 -0
  46. package/packages/selector/src/client/locales/es.ts +141 -0
  47. package/packages/selector/src/client/locales/fr.ts +141 -0
  48. package/packages/selector/src/client/locales/it.ts +141 -0
  49. package/packages/selector/src/client/locales/ja.ts +141 -0
  50. package/packages/selector/src/client/locales/ko.ts +141 -0
  51. package/packages/selector/src/client/locales/ru.ts +141 -0
  52. package/packages/selector/src/client/locales.ts +282 -198
  53. package/packages/selector/src/client/monitor-fab.ts +336 -0
  54. package/packages/selector/src/client/preset-options.ts +88 -70
  55. package/packages/selector/src/client/savings-card.tsx +150 -0
  56. package/packages/selector/src/client/settings-section.tsx +140 -126
  57. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -210
  58. package/packages/selector/src/index.ts +671 -327
  59. package/packages/selector/src/invariant.ts +113 -113
  60. package/packages/selector/src/preset-overlay.ts +60 -1
  61. package/packages/selector/src/profiles.ts +431 -342
  62. package/packages/selector/src/pruner/content.ts +18 -5
  63. package/packages/selector/src/pruner/state.ts +57 -43
  64. package/packages/selector/src/pruner/types.ts +23 -5
  65. package/packages/selector/src/pruner.ts +2736 -2144
  66. package/packages/selector/src/runtime/adaptive-cost.ts +23 -12
  67. package/packages/selector/src/runtime/audit.ts +303 -215
  68. package/packages/selector/src/runtime/config.ts +756 -613
  69. package/packages/selector/src/runtime/measurement.ts +436 -403
  70. package/packages/selector/src/runtime/monitor.ts +235 -0
  71. package/packages/selector/src/runtime/reducers.ts +1115 -97
  72. package/packages/selector/src/runtime/retrieve.ts +479 -457
  73. package/packages/selector/src/runtime/savings.ts +337 -0
  74. package/packages/selector/src/runtime/session-events.ts +30 -17
  75. package/packages/selector/src/runtime/summary-command.ts +127 -0
  76. package/packages/selector/src/runtime/tail-trim.ts +166 -166
  77. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
  78. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
  79. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
  80. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
  81. package/packages/selector/src/runtime/tokenpilot/dedup.ts +1 -1
  82. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -183
  83. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  84. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  85. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  86. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  87. package/packages/selector/src/runtime/tokenpilot/locator.ts +1 -1
  88. package/packages/selector/src/runtime/tokenpilot/read-state.ts +23 -2
  89. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -0
  90. package/packages/selector/src/runtime/toolclass.ts +103 -0
  91. package/packages/selector/src/runtime/types.ts +365 -309
  92. package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
  93. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -226
  94. package/packages/selector/tests/built/client-artifact.spec.ts +59 -51
  95. package/packages/selector/tests/code-skeleton.client.spec.ts +91 -88
  96. package/packages/selector/tests/custom-contract.client.spec.ts +205 -202
  97. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -247
  98. package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -176
  99. package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -204
  100. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  101. package/packages/selector/tests/preset-options-write.client.spec.ts +207 -181
  102. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -196
  103. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -243
  104. package/packages/selector/tests/profiles.client.spec.tsx +436 -434
  105. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -33
  106. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +7 -7
  107. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -0
  108. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
  109. package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
  110. package/packages/selector/tests/runtime/audit.spec.ts +275 -129
  111. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -0
  112. package/packages/selector/tests/runtime/code-skeleton.spec.ts +14 -3
  113. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
  114. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -0
  115. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -0
  116. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  117. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  118. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -0
  119. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  120. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -0
  121. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2531
  122. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -0
  123. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  124. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -0
  125. package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
  126. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -0
  127. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  128. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -0
  129. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
  130. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -56
  131. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -100
  132. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +24 -0
  133. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -0
  134. package/packages/selector/tests/settings-seat.client.spec.ts +130 -0
  135. package/packages/selector/tests/standing-generation.host.spec.ts +697 -631
  136. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -250
  137. package/pnpm-workspace.yaml +66 -19
  138. package/scripts/capture-profile-baseline.mjs +42 -0
  139. package/scripts/generate-tokenizer-fixtures.py +81 -81
  140. package/scripts/generate-vision-fixtures.py +208 -208
  141. package/scripts/{packed-components-smoke.ts → packed-components-smoke.mjs} +732 -713
  142. package/scripts/{packed-install-e2e.ts → packed-install-e2e.mjs} +1273 -1072
  143. package/scripts/toolclass-corpus-replay.mjs +281 -0
  144. package/scripts/{verify-release.ts → verify-release.mjs} +318 -300
  145. package/tests/TEST_INVENTORY.md +41 -42
  146. package/scripts/capture-profile-baseline.ts +0 -80
  147. package/tsconfig.scripts.json +0 -13
  148. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-profiles.jpg +0 -0
  149. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-settings.png +0 -0
@@ -1,645 +1,1099 @@
1
- import { n as CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, r as ContextCompressionSettingsSchema } from "./config.js";
2
- import z from "@deepseek-ai/schemastery";
3
- import "@deepseek-ai/dsh-settings";
4
- import { AsyncLocalStorage } from "node:async_hooks";
5
- import { createHash } from "node:crypto";
6
- import { chmod, mkdtemp, readFile, rename, rm, stat, utimes, writeFile } from "node:fs/promises";
7
- import { tmpdir } from "node:os";
8
- import { isAbsolute, join } from "node:path";
9
- import { fileURLToPath } from "node:url";
10
- import { applyEntryPatches, entryListSchema } from "@deepseek-ai/cordis-plugin-include";
11
- import { dump, load } from "js-yaml";
12
- //#region src/estimator-catalog.ts
13
- function str(value) {
14
- return typeof value === "string" ? value : "";
15
- }
16
- /** Resolve the effective host model route (override → session default). */
17
- function resolveHostRoute(deps) {
18
- const overrideProvider = str(deps.overrideProvider);
19
- const overrideModel = str(deps.overrideModel);
20
- const selected = deps.currentSelection?.();
21
- const selectedProvider = str(selected?.provider);
22
- const selectedModel = str(selected?.model);
23
- const provider = overrideProvider !== "" ? overrideProvider : selectedProvider;
24
- const model = overrideModel !== "" ? overrideModel : selectedModel;
25
- if (provider === "" || model === "") return void 0;
26
- return {
27
- provider,
28
- model
29
- };
30
- }
31
- /** Build the catalog projection. Never throws. */
32
- async function buildEstimatorCatalog(deps) {
33
- if (deps.llm?.listProviders === void 0) {
34
- const selection = resolveHostRoute(deps);
35
- return selection === void 0 ? { providers: [] } : {
36
- providers: [],
37
- selection
38
- };
39
- }
40
- const selection = resolveHostRoute(deps);
41
- const raw = deps.llm.listProviders();
42
- return {
43
- providers: await Promise.all(raw.map(async (p) => {
44
- let models = [];
45
- let error;
46
- try {
47
- models = (await deps.llm?.listModels?.(p.id) ?? []).map((m) => ({
48
- id: m.id,
49
- name: m.name
50
- }));
51
- } catch (e) {
52
- error = String(e?.message ?? e);
53
- }
54
- if (models.length === 0) try {
55
- const entry = deps.llm?.listConfigurableProviders?.().find((c) => c.provider === p.id);
56
- if (entry !== void 0 && deps.llm?.discoverModels !== void 0) {
57
- const discovered = await deps.llm.discoverModels(entry.settingsNs, { provider: p.id });
58
- if (discovered.length > 0) {
59
- models = discovered.map((m) => ({
60
- id: m.id,
61
- name: m.name ?? m.id
62
- }));
63
- error = void 0;
64
- }
65
- }
66
- } catch {}
67
- if (models.length === 0 && error === void 0) error = "no models advertised";
68
- return {
69
- id: p.id,
70
- name: p.name,
71
- models,
72
- ...error === void 0 ? {} : { error }
73
- };
74
- })),
75
- ...selection === void 0 ? {} : { selection }
76
- };
77
- }
78
- //#endregion
79
- //#region src/preset-overlay.ts
80
- /** Plugin-owned, reversible compression overlays for native agent presets. */
81
- /**
82
- * Fixed base for deterministic standing mtimes. The stamp is derived from the
83
- * FULL content identity (source + modules + threshold), not from the write
84
- * clock: identical identities always republish to the same stamp (no
85
- * generation flapping).
86
- *
87
- * The seconds component carries an 8-hex identity window directly. Most
88
- * identities therefore separate even when a filesystem truncates mtimes to
89
- * whole seconds; identities that share that 32-bit window deliberately collide
90
- * first, are detected from the staging file's observed {mtimeMs, size}, and
91
- * escalate to later hash windows before publication. The prefix keeps the
92
- * latest possible stamp around year 2162, inside the nanosecond range every
93
- * supported filesystem can store; the next 3 hex digits set sub-second
94
- * milliseconds on filesystems that preserve them.
95
- */
96
- const STANDING_MTIME_EPOCH_SECONDS = Math.floor(Date.UTC(2026, 0, 1) / 1e3);
97
- const STANDING_MTIME_WINDOW_HEX = 11;
98
- const DEFAULT_METADATA_IO = Object.freeze({
99
- async setTimes(path, stamp) {
100
- await utimes(path, stamp, stamp);
101
- },
102
- async read(path) {
103
- const observed = await stat(path);
104
- return {
105
- mtimeMs: observed.mtimeMs,
106
- size: observed.size
107
- };
108
- }
109
- });
110
- /**
111
- * Deterministic standing stamp for one full generation identity, read from
112
- * hash window `windowIndex` (0 = identity prefix). Exported for the
113
- * collision-fixture tests; production code uses {@link standingStampMs}.
114
- */
115
- function standingStampMsAtWindow(identity, windowIndex) {
116
- const start = windowIndex * STANDING_MTIME_WINDOW_HEX;
117
- const seconds = STANDING_MTIME_EPOCH_SECONDS + parseInt(identity.slice(start, start + 8).padEnd(8, "0"), 16);
118
- const subSecond = parseInt(identity.slice(start + 8, start + STANDING_MTIME_WINDOW_HEX).padEnd(3, "0"), 16) % 1e3;
119
- return seconds * 1e3 + subSecond;
120
- }
121
- const COMPRESSION_IDS = /* @__PURE__ */ new Set([
122
- "compaction",
123
- "compaction-basic",
124
- "command-compact",
125
- "tool-result-pruner"
126
- ]);
127
- const COMPRESSION_PACKAGES = /* @__PURE__ */ new Set([
128
- "@deepseek-ai/dsh-compaction-basic",
129
- "@deepseek-ai/dsh-command-compact",
130
- "@deepseek-ai/dsh-compaction-tool-result-pruner",
131
- "dsh-context-compression-improved-runtime",
132
- "dsh-context-compression-improved",
133
- "dsh-context-compression-improved/pruner"
134
- ]);
135
- /**
136
- * Resolve the three compression package entries once from this package.
137
- * @returns Absolute entry paths for the canonical compression layer.
138
- */
139
- function resolveCompressionModulePaths() {
140
- return {
141
- compactionBasic: modulePath("@deepseek-ai/dsh-compaction-basic", import.meta.resolve("@deepseek-ai/dsh-compaction-basic")),
142
- commandCompact: modulePath("@deepseek-ai/dsh-command-compact", import.meta.resolve("@deepseek-ai/dsh-command-compact")),
143
- toolResultPruner: modulePath("dsh-context-compression-improved/pruner", import.meta.resolve("dsh-context-compression-improved/pruner"))
144
- };
145
- }
146
- /** Convert one package resolution into the absolute path preset mounting accepts. */
147
- function modulePath(specifier, resolved) {
148
- if (!resolved.startsWith("file:")) throw new Error(`context-compression selector: ${specifier} resolved outside the filesystem (${resolved})`);
149
- return fileURLToPath(resolved);
150
- }
151
- /** Generated composition storage owned by one decorator installation. */
152
- var PresetOverlayStore = class {
153
- options;
154
- rootTask;
155
- disposed = false;
156
- metadataIo;
157
- constructor(options) {
158
- this.options = options;
159
- this.metadataIo = options.metadataIo ?? DEFAULT_METADATA_IO;
160
- const paths = Object.entries(options.modules);
161
- for (const [name, path] of paths) if (!isAbsolute(path)) throw new TypeError(`context-compression selector: module path ${name} is not absolute: ${path}`);
162
- }
163
- /** Return a detached preset record whose path names the canonical overlay. */
164
- async overlay(preset) {
165
- if (this.disposed) throw new Error("context-compression selector: preset overlay is disposed");
166
- if (preset.broken !== void 0) return preset;
167
- const source = await readFile(preset.path, "utf8");
168
- const rows = parseRows(source, preset.path);
169
- const thresholdPercent = this.options.autoCompactThresholdPercent?.();
170
- if (thresholdPercent !== void 0 && !Number.isFinite(thresholdPercent)) throw new Error(`context-compression selector: Auto Compact threshold percent must be finite, got ${String(thresholdPercent)}`);
171
- const patched = applyEntryPatches(stripCompressionRows(rows), [{ insert: canonicalCompressionRows(this.options.modules, thresholdPercent) }], (message, ...args) => {
172
- throw new Error(renderPatchWarning(message, args));
173
- });
174
- const rendered = dump(patched, {
175
- schema: entryListSchema,
176
- noRefs: true,
177
- lineWidth: -1,
178
- sortKeys: false
179
- });
180
- const identity = createHash("sha256").update(preset.id).update("\0").update(source).update("\0").update(JSON.stringify({
181
- modules: this.options.modules,
182
- autoCompactThresholdPercent: thresholdPercent ?? null
183
- })).digest("hex").slice(0, 24);
184
- const root = await this.root();
185
- const path = join(root, `${preset.id}-${identity}.agent.cordis.yml`);
186
- const staging = join(root, `${preset.id}-${identity}.${String(process.pid)}-${String(Math.random()).slice(2)}.tmp`);
187
- try {
188
- await writeFile(staging, rendered, {
189
- encoding: "utf8",
190
- mode: 384
191
- });
192
- await chmod(staging, 384);
193
- await this.disambiguateStamp(staging, identity);
194
- await rename(staging, path);
195
- } catch (error) {
196
- try {
197
- await rm(staging, { force: true });
198
- } catch {}
199
- throw error;
200
- }
201
- return {
202
- ...preset,
203
- path
204
- };
205
- }
206
- /** Observed {mtimeMs,size} keys published by this store, per identity. */
207
- standingKeys = /* @__PURE__ */ new Map();
208
- /**
209
- * Ensure an unpublished staging file's observed {mtimeMs, size} is not
210
- * shared with a different identity. Escalation rewrites the mtime from later
211
- * hash windows before atomic publication, and fails loudly if no window
212
- * separates them (better a loud error than a silently reused generation).
213
- */
214
- async disambiguateStamp(path, identity) {
215
- for (let window = 0; window < 3; window += 1) {
216
- const stamp = new Date(standingStampMsAtWindow(identity, window));
217
- await this.metadataIo.setTimes(path, stamp);
218
- const observed = await this.metadataIo.read(path);
219
- const key = `${String(observed.mtimeMs)}:${String(observed.size)}`;
220
- const owner = this.standingKeys.get(key);
221
- if (owner === void 0 || owner === identity) {
222
- this.standingKeys.set(key, identity);
223
- return;
224
- }
225
- }
226
- throw new Error(`context-compression selector: standing stamp collision for identity ${identity} across all hash windows`);
227
- }
228
- /** Remove all generated files without touching any source preset. */
229
- async dispose() {
230
- if (this.disposed) return;
231
- this.disposed = true;
232
- if (this.rootTask === void 0) return;
233
- const root = await this.rootTask;
234
- await rm(root, {
235
- recursive: true,
236
- force: true
237
- });
238
- }
239
- /** Lazily create the one owner-only directory for this installation. */
240
- async root() {
241
- if (this.rootTask === void 0) {
242
- const parent = this.options.tempParent ?? tmpdir();
243
- this.rootTask = mkdtemp(join(parent, "dsh-context-compression-presets-")).then(async (root) => {
244
- await chmod(root, 448);
245
- return root;
246
- });
247
- }
248
- return await this.rootTask;
249
- }
250
- };
251
- /** Parse one native preset with exactly the Loader's YAML dialect. */
252
- function parseRows(source, path) {
253
- const parsed = load(source, { schema: entryListSchema });
254
- if (!Array.isArray(parsed)) throw new TypeError(`context-compression selector: preset ${path} is not a top-level entry list`);
255
- return parsed;
256
- }
257
- /** Remove any prior compression implementation before adding the canonical one. */
258
- function stripCompressionRows(rows) {
259
- const kept = [];
260
- for (const row of rows) {
261
- if (COMPRESSION_IDS.has(row.id) || COMPRESSION_PACKAGES.has(row.name)) continue;
262
- if (row.group === true && Array.isArray(row.config)) {
263
- const nested = row.config;
264
- kept.push({
265
- ...row,
266
- config: stripCompressionRows(nested)
267
- });
268
- } else kept.push(row);
269
- }
270
- return kept;
271
- }
272
- /**
273
- * Complete, same-realm compression stack added to every applicable preset.
274
- * When the Host settings expose an Auto Compact threshold, one read feeds both
275
- * the compaction-basic `thresholdRatio` (beside the pinned first-release
276
- * `retainRatio`) and the runtime deployment config, so plugin History and
277
- * native Auto Compact share one watermark for this whole generation.
278
- */
279
- function canonicalCompressionRows(modules, thresholdPercent) {
280
- return [{
281
- id: "compaction",
282
- name: "cordis:group",
283
- group: true,
284
- isolate: {
285
- compaction: true,
286
- toolResultPruner: true
287
- },
288
- config: [
289
- {
290
- id: "compaction-basic",
291
- name: modules.compactionBasic,
292
- ...thresholdPercent === void 0 ? {} : { config: {
293
- thresholdRatio: thresholdPercent / 100,
294
- retainRatio: .16
295
- } }
296
- },
297
- {
298
- id: "command-compact",
299
- name: modules.commandCompact
300
- },
301
- {
302
- id: "tool-result-pruner",
303
- name: modules.toolResultPruner,
304
- config: {
305
- headChars: 4096,
306
- tailChars: 1024,
307
- ...thresholdPercent === void 0 ? {} : { autoCompactThresholdPercent: thresholdPercent }
308
- }
309
- }
310
- ]
311
- }];
312
- }
313
- /** Render include's printf-style warning without silently losing its target. */
314
- function renderPatchWarning(message, args) {
315
- let index = 0;
316
- return `context-compression selector: ${message.replace(/%C/g, () => JSON.stringify(args[index++]))}`;
317
- }
318
- /**
319
- * Cordis can hand two callers different traceable proxies for one service.
320
- * Symbol properties forward to the shared target, unlike proxy identity.
321
- */
322
- const SHARED_DECORATION = Symbol.for("dsh-context-compression-improved/preset-overlay");
323
- /** Object-identity keys keep test metadata policies from sharing one store. */
324
- const METADATA_IO_KEYS = /* @__PURE__ */ new WeakMap();
325
- let nextMetadataIoKey = 1;
326
- function metadataIoKey(metadataIo) {
327
- const existing = METADATA_IO_KEYS.get(metadataIo);
328
- if (existing !== void 0) return existing;
329
- const key = nextMetadataIoKey;
330
- nextMetadataIoKey += 1;
331
- METADATA_IO_KEYS.set(metadataIo, key);
332
- return key;
333
- }
334
- /**
335
- * Reversibly decorate native AgentPresets composition calls.
336
- *
337
- * Duplicate Host rows share one physical decoration. This matters while an
338
- * installation migrates from a Harness-bundled selector row to the standalone
339
- * Bundle: either row can unload first without double-compressing or disposing
340
- * the generated files still used by the other.
341
- * @param presets Native AgentPresets service to decorate during composition.
342
- * @param options Canonical module paths, exclusions, and optional test directory.
343
- * @returns A reference-counted handle that restores the native service on final disposal.
344
- */
345
- function decorateAgentPresets(presets, options) {
346
- const optionsKey = overlayOptionsKey(options);
347
- const carrier = presets;
348
- let shared = carrier[SHARED_DECORATION];
349
- if (shared === void 0) {
350
- shared = {
351
- optionsKey,
352
- references: 0,
353
- installation: installAgentPresetsDecoration(presets, options)
354
- };
355
- Object.defineProperty(carrier, SHARED_DECORATION, {
356
- configurable: true,
357
- enumerable: false,
358
- writable: false,
359
- value: shared
360
- });
361
- } else if (shared.optionsKey !== optionsKey) throw new Error("context-compression selector: AgentPresets already has a different compression overlay");
362
- const lease = shared;
363
- lease.references += 1;
364
- let disposed = false;
365
- return { async dispose() {
366
- if (disposed) return;
367
- disposed = true;
368
- lease.references -= 1;
369
- if (lease.references !== 0) return;
370
- if (carrier[SHARED_DECORATION] === lease) Reflect.deleteProperty(carrier, SHARED_DECORATION);
371
- await lease.installation.dispose();
372
- } };
373
- }
374
- /** Stable equality for two rows asking to share one physical overlay. */
375
- function overlayOptionsKey(options) {
376
- return JSON.stringify({
377
- modules: options.modules,
378
- excludedPresetIds: [...options.excludedPresetIds ?? ["minimal"]].sort(),
379
- tempParent: options.tempParent,
380
- metadataIo: metadataIoKey(options.metadataIo ?? DEFAULT_METADATA_IO)
381
- });
382
- }
383
- /**
384
- * Install the one physical method decoration leased by public callers.
385
- *
386
- * Direct resolution and authoring stay source-preserving. AsyncLocalStorage
387
- * scopes the overlay to the async call tree of mount/recompose/standingKeyFor,
388
- * so an unrelated resolve racing the mount cannot inherit its generated path.
389
- */
390
- function installAgentPresetsDecoration(presets, options) {
391
- const excluded = new Set(options.excludedPresetIds ?? ["minimal"]);
392
- const operations = new AsyncLocalStorage();
393
- const store = new PresetOverlayStore(options);
394
- const snapshots = snapshotMethods(presets);
395
- const resolveSnapshot = snapshotFor(snapshots, "resolve");
396
- const resolveWrapped = async (id) => {
397
- const preset = await Reflect.apply(resolveSnapshot.original, presets, [id]);
398
- if (operations.getStore()?.composing !== true || excluded.has(preset.id)) return preset;
399
- return await store.overlay(preset);
400
- };
401
- installMethod(presets, resolveSnapshot, resolveWrapped);
402
- for (const method of [
403
- "mount",
404
- "recompose",
405
- "standingKeyFor"
406
- ]) {
407
- const snapshot = snapshotFor(snapshots, method);
408
- const wrapped = (...args) => operations.run({ composing: true }, () => Reflect.apply(snapshot.original, presets, args));
409
- installMethod(presets, snapshot, wrapped);
410
- }
411
- let disposed = false;
412
- return { async dispose() {
413
- if (disposed) return;
414
- disposed = true;
415
- for (const snapshot of [...snapshots].reverse()) restoreMethod(presets, snapshot);
416
- await store.dispose();
417
- } };
418
- }
419
- /** Capture callable methods and whether each was inherited or owned. */
420
- function snapshotMethods(presets) {
421
- return [
422
- "resolve",
423
- "mount",
424
- "recompose",
425
- "standingKeyFor"
426
- ].map((name) => {
427
- const original = presets[name];
428
- if (typeof original !== "function") throw new TypeError(`context-compression selector: AgentPresets.${name} is unavailable`);
429
- return {
430
- name,
431
- own: Object.getOwnPropertyDescriptor(presets, name),
432
- original
433
- };
434
- });
435
- }
436
- /** Return the captured method or fail loudly if the snapshot set is corrupt. */
437
- function snapshotFor(snapshots, name) {
438
- const snapshot = snapshots.find((candidate) => candidate.name === name);
439
- if (snapshot === void 0) throw new Error(`context-compression selector: missing method snapshot for ${name}`);
440
- return snapshot;
441
- }
442
- /** Install one own method while retaining its identity for safe disposal. */
443
- function installMethod(presets, snapshot, wrapped) {
444
- snapshot.wrapped = wrapped;
445
- Object.defineProperty(presets, snapshot.name, {
446
- configurable: true,
447
- writable: true,
448
- value: wrapped
449
- });
450
- }
451
- /** Restore the captured own/prototype state after the final shared lease. */
452
- function restoreMethod(presets, snapshot) {
453
- if (snapshot.own === void 0) Reflect.deleteProperty(presets, snapshot.name);
454
- else Object.defineProperty(presets, snapshot.name, snapshot.own);
455
- }
456
- //#endregion
457
- //#region src/index.ts
458
- const ESTIMATOR_CATALOG_ROUTES = ["/endpoint/dsh-context-compression-improved/estimator-catalog", "/api/dsh-context-compression-improved/estimator-catalog"];
459
- /**
460
- * The one service the catalog route actually needs. `llm` and
461
- * `agentDefaultModel` are payload enrichment the handler resolves per request,
462
- * never reasons to withhold the route.
463
- */
464
- const ESTIMATOR_CATALOG_ROUTE_DEPS = ["webServer"];
465
- function asWebServer(value) {
466
- if (typeof value?.register !== "function") return void 0;
467
- return value;
468
- }
469
- /**
470
- * Serve `GET /api/dsh-context-compression-improved/estimator-catalog` — the
471
- * settings card's host-route dropdowns (live provider/model groups from the DSH
472
- * `llm` service plus the effective selection). This lives on the top-level
473
- * plugin context, NOT inside the isolated toolResultPruner service.
474
- *
475
- * (The isolation reason this placement was originally justified with — "a route
476
- * registered there can never reach `webServer` across the isolation boundary" —
477
- * is **unverified**: no `@deepseek-ai` package calls `.isolate(`, so there is no
478
- * boundary to cross here. Top-level placement is still the right choice, for a
479
- * reason that needs no framework rule: the route is host-wide, not
480
- * per-pruner-instance. Don't promote the isolation wording into a rule.)
481
- *
482
- * The route gates on `webServer` **alone**. `llm` and `agentDefaultModel` only
483
- * enrich the response and are resolved per request, so listing them here would
484
- * let an estimator-side service the handler never needs keep the route
485
- * unregistered. That failure is silent by construction — an unsatisfied
486
- * `ctx.inject` callback never runs, so the plugin simply has no HTTP API and
487
- * every request falls through to the host 404.
488
- *
489
- * Two channels cover the two arrival orders: a direct lookup catches a
490
- * `webServer` that is already active when the plugin loads, and `ctx.inject`
491
- * catches one that activates later. Both funnel into a single guarded
492
- * registration, because a late-arriving service must not re-register a
493
- * `(kind, path)` the host treats as a composition-contract violation.
494
- */
495
- function registerEstimatorCatalogRoute(ctx) {
496
- const readService = (name) => {
497
- try {
498
- return ctx.get(name);
499
- } catch {
500
- return;
501
- }
502
- };
503
- const log = (level, message, ...args) => {
504
- console[level](message, ...args);
505
- };
506
- let registered = false;
507
- const register = (webServer, channel) => {
508
- if (registered) return;
509
- const handler = (_req, res) => {
510
- const resTyped = res;
511
- if (typeof resTyped?.writeHead !== "function" || typeof resTyped?.end !== "function") return;
512
- const llm = readService("llm");
513
- const defaults = readService("agentDefaultModel");
514
- buildEstimatorCatalog({
515
- ...llm === void 0 ? {} : { llm },
516
- ...typeof defaults?.currentSelection === "function" ? { currentSelection: () => defaults.currentSelection?.() } : {}
517
- }).then((catalog) => {
518
- resTyped.writeHead(200, {
519
- "content-type": "application/json; charset=utf-8",
520
- "cache-control": "no-cache"
521
- });
522
- resTyped.end(JSON.stringify({
523
- ok: true,
524
- ...catalog
525
- }));
526
- }, (error) => {
527
- resTyped.writeHead(500, { "content-type": "application/json; charset=utf-8" });
528
- resTyped.end(JSON.stringify({
529
- ok: false,
530
- error: String(error?.message ?? error)
531
- }));
532
- });
533
- };
534
- try {
535
- const disposers = ESTIMATOR_CATALOG_ROUTES.map((path) => webServer.register({
536
- kind: "exact",
537
- path,
538
- handler
539
- })).filter((off) => typeof off === "function");
540
- registered = true;
541
- ctx.effect(() => () => {
542
- for (const off of disposers) off();
543
- }, "contextCompressionSelector.estimator-catalog route");
544
- log("info", "context-compression estimator catalog route registered (%s): %s", channel, ESTIMATOR_CATALOG_ROUTES.join(", "));
545
- } catch (error) {
546
- log("warn", "context-compression estimator catalog route registration failed (%s): %o", channel, error);
547
- }
548
- };
549
- const active = asWebServer(readService("webServer"));
550
- if (active !== void 0) {
551
- register(active, "direct");
552
- if (registered) return;
553
- }
554
- ctx.inject([...ESTIMATOR_CATALOG_ROUTE_DEPS], (injected) => {
555
- const webServer = asWebServer(injected.webServer);
556
- if (webServer === void 0) {
557
- log("warn", "context-compression webServer exposes no register() — estimator catalog route not registered");
558
- return;
559
- }
560
- register(webServer, "inject");
561
- });
562
- log("warn", "context-compression webServer not active yet — estimator catalog route pending: %s", ESTIMATOR_CATALOG_ROUTES.join(", "));
563
- }
564
- const CONTEXT_COMPRESSION_NAMESPACE = CONTEXT_COMPRESSION_SETTINGS_NAMESPACE;
565
- /** Symbol properties reach the shared service target through Cordis proxies. */
566
- const SHARED_SETTINGS = Symbol.for("dsh-context-compression-improved/settings-registration");
567
- /** Loader validation for the standalone Bundle opt-in. */
568
- const Config = z.object({
569
- presetOverlay: z.boolean().default(false),
570
- estimatorCatalogRoute: z.boolean().default(false)
571
- });
572
- /** Register the persisted default read by the currently mounted root pruner. */
573
- function apply(ctx, config = {}) {
574
- try {
575
- ctx.inject(["settings"], (settingsCtx) => {
576
- acquireSettingsRegistration(settingsCtx);
577
- });
578
- if (config.estimatorCatalogRoute === true) registerEstimatorCatalogRoute(ctx);
579
- if (config.presetOverlay !== true) return;
580
- ctx.inject(["agentPresets"], (presetsCtx) => {
581
- const installation = decorateAgentPresets(presetsCtx.agentPresets, {
582
- modules: resolveCompressionModulePaths(),
583
- excludedPresetIds: ["minimal"],
584
- autoCompactThresholdPercent: () => resolveAutoCompactThresholdPercent(presetsCtx)
585
- });
586
- presetsCtx.effect(() => () => installation.dispose(), "contextCompressionSelector.agentPresets()");
587
- });
588
- } catch (error) {
589
- console.error("context-compression apply() failed:", error);
590
- throw error;
591
- }
592
- }
593
- /**
594
- * Read the current Auto Compact threshold ratio at composition time. Settings
595
- * values are revalidated here, and any unreadable value falls back to the 80%
596
- * default rather than blocking preset composition.
597
- */
598
- function resolveAutoCompactThresholdPercent(presetsCtx) {
599
- const raw = presetsCtx.get("settings")?.get(CONTEXT_COMPRESSION_NAMESPACE);
600
- try {
601
- return ContextCompressionSettingsSchema(structuredClone(raw)).autoCompact.thresholdPercent;
602
- } catch {
603
- return 80;
604
- }
605
- }
606
- /**
607
- * Lease one native settings registration across duplicate Host rows.
608
- *
609
- * The lease effect is intentionally registered before settings.register().
610
- * Cordis disposes effects in reverse order, so the native registration first
611
- * releases the namespace; this disposer can then transfer it to another live
612
- * owner without a duplicate-registration window.
613
- */
614
- function acquireSettingsRegistration(ctx) {
615
- const settings = ctx.settings;
616
- const owner = { settings };
617
- let shared = settings[SHARED_SETTINGS];
618
- if (shared === void 0) {
619
- shared = {
620
- owners: /* @__PURE__ */ new Set(),
621
- registrationOwner: owner,
622
- scope: void 0
623
- };
624
- Object.defineProperty(settings, SHARED_SETTINGS, {
625
- configurable: true,
626
- enumerable: false,
627
- writable: false,
628
- value: shared
629
- });
630
- }
631
- shared.owners.add(owner);
632
- const state = shared;
633
- ctx.effect(() => () => {
634
- state.owners.delete(owner);
635
- if (state.registrationOwner === owner && state.owners.size > 0) {
636
- const next = state.owners.values().next().value;
637
- state.registrationOwner = next;
638
- state.scope = next.settings.register(CONTEXT_COMPRESSION_NAMESPACE, ContextCompressionSettingsSchema);
639
- }
640
- if (state.owners.size === 0 && settings[SHARED_SETTINGS] === state) Reflect.deleteProperty(settings, SHARED_SETTINGS);
641
- }, "contextCompressionSelector.settingsLease()");
642
- if (state.owners.size === 1) state.scope = settings.register(CONTEXT_COMPRESSION_NAMESPACE, ContextCompressionSettingsSchema);
643
- }
644
- //#endregion
645
- export { Config, apply };
1
+ import { A as getObservedIntentEnabled, C as isSessionOverrideAction, E as INTENT_GATE_GROWTH_TOKENS, H as getSavingsLedger, L as setSummaryOverride, O as getAdvisorState, S as estimateSavingsPricing, T as INTENT_GATE_FLOOR_FRACTION, b as applySessionOverride, j as getSummaryOverride, k as getLastIntentFold, n as CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, r as ContextCompressionSettingsSchema, x as buildMonitorSnapshot } from "./config.js";
2
+ import z from "@deepseek-ai/schemastery";
3
+ import "@deepseek-ai/dsh-settings";
4
+ import { createHash } from "node:crypto";
5
+ import { AsyncLocalStorage } from "node:async_hooks";
6
+ import { chmod, mkdtemp, readFile, rename, rm, stat, utimes, writeFile } from "node:fs/promises";
7
+ import { tmpdir } from "node:os";
8
+ import { isAbsolute, join } from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+ import { applyEntryPatches, entryListSchema } from "@deepseek-ai/cordis-plugin-include";
11
+ import { dump, load } from "js-yaml";
12
+ //#region src/estimator-catalog.ts
13
+ function str(value) {
14
+ return typeof value === "string" ? value : "";
15
+ }
16
+ /** Resolve the effective host model route (override → session default). */
17
+ function resolveHostRoute(deps) {
18
+ const overrideProvider = str(deps.overrideProvider);
19
+ const overrideModel = str(deps.overrideModel);
20
+ const selected = deps.currentSelection?.();
21
+ const selectedProvider = str(selected?.provider);
22
+ const selectedModel = str(selected?.model);
23
+ const provider = overrideProvider !== "" ? overrideProvider : selectedProvider;
24
+ const model = overrideModel !== "" ? overrideModel : selectedModel;
25
+ if (provider === "" || model === "") return void 0;
26
+ return {
27
+ provider,
28
+ model
29
+ };
30
+ }
31
+ /** Build the catalog projection. Never throws. */
32
+ async function buildEstimatorCatalog(deps) {
33
+ if (deps.llm?.listProviders === void 0) {
34
+ const selection = resolveHostRoute(deps);
35
+ return selection === void 0 ? { providers: [] } : {
36
+ providers: [],
37
+ selection
38
+ };
39
+ }
40
+ const selection = resolveHostRoute(deps);
41
+ const raw = deps.llm.listProviders();
42
+ return {
43
+ providers: await Promise.all(raw.map(async (p) => {
44
+ let models = [];
45
+ let error;
46
+ try {
47
+ models = (await deps.llm?.listModels?.(p.id) ?? []).map((m) => ({
48
+ id: m.id,
49
+ name: m.name
50
+ }));
51
+ } catch (e) {
52
+ error = String(e?.message ?? e);
53
+ }
54
+ if (models.length === 0) try {
55
+ const entry = deps.llm?.listConfigurableProviders?.().find((c) => c.provider === p.id);
56
+ if (entry !== void 0 && deps.llm?.discoverModels !== void 0) {
57
+ const discovered = await deps.llm.discoverModels(entry.settingsNs, { provider: p.id });
58
+ if (discovered.length > 0) {
59
+ models = discovered.map((m) => ({
60
+ id: m.id,
61
+ name: m.name ?? m.id
62
+ }));
63
+ error = void 0;
64
+ }
65
+ }
66
+ } catch {}
67
+ if (models.length === 0 && error === void 0) error = "no models advertised";
68
+ return {
69
+ id: p.id,
70
+ name: p.name,
71
+ models,
72
+ ...error === void 0 ? {} : { error }
73
+ };
74
+ })),
75
+ ...selection === void 0 ? {} : { selection }
76
+ };
77
+ }
78
+ //#endregion
79
+ //#region src/runtime/summary-command.ts
80
+ const SUMMARY_COMMAND_NAME = "ctx-summary";
81
+ const USAGE = "Usage: /ctx-summary off|on|status";
82
+ /** Parse the raw argument string; `undefined` = unrecognized (usage error). */
83
+ function parseSummaryCommandArgs(rawInput) {
84
+ const token = rawInput.trim().toLowerCase();
85
+ if (token === "off" || token === "on" || token === "status") return token;
86
+ }
87
+ function describeFold(sessionId) {
88
+ const fold = getLastIntentFold(sessionId);
89
+ if (fold === void 0) return "none";
90
+ return `turn ${fold.turn}, seq ${fold.startSeq}..${fold.endSeq}`;
91
+ }
92
+ /** Human-facing status line; observability only, never a decision input. */
93
+ function formatSummaryStatus(sessionId) {
94
+ const override = getSummaryOverride(sessionId);
95
+ const enabled = getObservedIntentEnabled(sessionId);
96
+ const enabledText = enabled === void 0 ? "unknown (gate not evaluated yet)" : enabled ? "yes" : "no";
97
+ return [
98
+ `ctx-summary status:`,
99
+ ` override: ${override ?? "default (settings-driven)"}`,
100
+ ` intentSummary enabled (settings): ${enabledText}`,
101
+ ` gate: floor >${Math.round(INTENT_GATE_FLOOR_FRACTION * 100)}% of window AND growth >${INTENT_GATE_GROWTH_TOKENS} tokens since last fold`,
102
+ ` last fold: ${describeFold(sessionId)}`
103
+ ].join("\n");
104
+ }
105
+ /** Resolve the invoking agent's session id (`''` when the host exposes none). */
106
+ function sessionIdOf(agent) {
107
+ const session = agent?.session;
108
+ if (session === void 0 || session.id === void 0 || session.id === null) return "";
109
+ return String(session.id);
110
+ }
111
+ /** Best-effort `CommandDefinitionId` brand; `undefined` on stripped hosts (registered without it). */
112
+ async function loadCommandDefinitionId() {
113
+ try {
114
+ return (await import("@deepseek-ai/dsh-commands")).CommandDefinitionId;
115
+ } catch {
116
+ return;
117
+ }
118
+ }
119
+ /**
120
+ * Mount `/ctx-summary` for every composed human-command adapter. Never
121
+ * throws: the command is a convenience surface, and a host without the
122
+ * commands service (or with an incompatible registry shape) simply runs
123
+ * without it.
124
+ */
125
+ function registerSummaryCommand(ctx) {
126
+ ctx.inject(["commands"], (injected) => {
127
+ const commands = injected.commands;
128
+ if (commands === void 0 || typeof commands.register !== "function") return;
129
+ (async () => {
130
+ try {
131
+ const definitionId = await loadCommandDefinitionId();
132
+ await commands.register({
133
+ name: SUMMARY_COMMAND_NAME,
134
+ description: "Turn-tail intent summary: temporarily disable/resume or inspect status",
135
+ ...definitionId === void 0 ? {} : { definitionId: definitionId("dsh-context-compression-improved/ctx-summary") },
136
+ handler: async (invocation) => {
137
+ const args = parseSummaryCommandArgs(typeof invocation.rawInput === "string" ? invocation.rawInput : "");
138
+ if (args === void 0) return {
139
+ kind: "error",
140
+ text: USAGE
141
+ };
142
+ const sessionId = sessionIdOf(invocation.agent);
143
+ if (args === "status") {
144
+ if (sessionId === "") return {
145
+ kind: "error",
146
+ text: "ctx-summary: no session is attached to this invocation"
147
+ };
148
+ return {
149
+ kind: "success",
150
+ text: formatSummaryStatus(sessionId)
151
+ };
152
+ }
153
+ if (sessionId === "") return {
154
+ kind: "error",
155
+ text: "ctx-summary: no session is attached to this invocation"
156
+ };
157
+ setSummaryOverride(sessionId, args);
158
+ return {
159
+ kind: "success",
160
+ text: args === "off" ? "ctx-summary: turn-tail intent summary paused for this session (until process restart or `/ctx-summary on`)" : "ctx-summary: turn-tail intent summary resumed for this session (numeric gates still apply)"
161
+ };
162
+ }
163
+ });
164
+ } catch {}
165
+ })();
166
+ });
167
+ }
168
+ //#endregion
169
+ //#region src/preset-overlay.ts
170
+ /** Plugin-owned, reversible compression overlays for native agent presets. */
171
+ /**
172
+ * Fixed base for deterministic standing mtimes. The stamp is derived from the
173
+ * FULL content identity (source + modules + threshold), not from the write
174
+ * clock: identical identities always republish to the same stamp (no
175
+ * generation flapping).
176
+ *
177
+ * The seconds component carries an 8-hex identity window directly. Most
178
+ * identities therefore separate even when a filesystem truncates mtimes to
179
+ * whole seconds; identities that share that 32-bit window deliberately collide
180
+ * first, are detected from the staging file's observed {mtimeMs, size}, and
181
+ * escalate to later hash windows before publication. The prefix keeps the
182
+ * latest possible stamp around year 2162, inside the nanosecond range every
183
+ * supported filesystem can store; the next 3 hex digits set sub-second
184
+ * milliseconds on filesystems that preserve them.
185
+ */
186
+ const STANDING_MTIME_EPOCH_SECONDS = Math.floor(Date.UTC(2026, 0, 1) / 1e3);
187
+ const STANDING_MTIME_WINDOW_HEX = 11;
188
+ const DEFAULT_METADATA_IO = Object.freeze({
189
+ async setTimes(path, stamp) {
190
+ await utimes(path, stamp, stamp);
191
+ },
192
+ async read(path) {
193
+ const observed = await stat(path);
194
+ return {
195
+ mtimeMs: observed.mtimeMs,
196
+ size: observed.size
197
+ };
198
+ }
199
+ });
200
+ /**
201
+ * Deterministic standing stamp for one full generation identity, read from
202
+ * hash window `windowIndex` (0 = identity prefix). Exported for the
203
+ * collision-fixture tests; production code uses {@link standingStampMs}.
204
+ */
205
+ function standingStampMsAtWindow(identity, windowIndex) {
206
+ const start = windowIndex * STANDING_MTIME_WINDOW_HEX;
207
+ const seconds = STANDING_MTIME_EPOCH_SECONDS + parseInt(identity.slice(start, start + 8).padEnd(8, "0"), 16);
208
+ const subSecond = parseInt(identity.slice(start + 8, start + STANDING_MTIME_WINDOW_HEX).padEnd(3, "0"), 16) % 1e3;
209
+ return seconds * 1e3 + subSecond;
210
+ }
211
+ /**
212
+ * True for the filesystem errors a concurrent publish can raise on Windows:
213
+ * `MoveFileEx` reports a lost race — or a reader holding the destination open —
214
+ * as EPERM/EBUSY/EACCES, where POSIX `rename` simply replaces the destination.
215
+ */
216
+ function isPublishRace(error) {
217
+ const code = error?.code;
218
+ return code === "EPERM" || code === "EBUSY" || code === "EACCES" || code === "EEXIST";
219
+ }
220
+ const COMPRESSION_IDS = /* @__PURE__ */ new Set([
221
+ "compaction",
222
+ "compaction-basic",
223
+ "command-compact",
224
+ "tool-result-pruner"
225
+ ]);
226
+ const COMPRESSION_PACKAGES = /* @__PURE__ */ new Set([
227
+ "@deepseek-ai/dsh-compaction-basic",
228
+ "@deepseek-ai/dsh-command-compact",
229
+ "@deepseek-ai/dsh-compaction-tool-result-pruner",
230
+ "dsh-context-compression-improved-runtime",
231
+ "dsh-context-compression-improved",
232
+ "dsh-context-compression-improved/pruner"
233
+ ]);
234
+ /**
235
+ * Resolve the three compression package entries once from this package.
236
+ * @returns Absolute entry paths for the canonical compression layer.
237
+ */
238
+ function resolveCompressionModulePaths() {
239
+ return {
240
+ compactionBasic: modulePath("@deepseek-ai/dsh-compaction-basic", import.meta.resolve("@deepseek-ai/dsh-compaction-basic")),
241
+ commandCompact: modulePath("@deepseek-ai/dsh-command-compact", import.meta.resolve("@deepseek-ai/dsh-command-compact")),
242
+ toolResultPruner: modulePath("dsh-context-compression-improved/pruner", import.meta.resolve("dsh-context-compression-improved/pruner"))
243
+ };
244
+ }
245
+ /** Convert one package resolution into the absolute path preset mounting accepts. */
246
+ function modulePath(specifier, resolved) {
247
+ if (!resolved.startsWith("file:")) throw new Error(`context-compression selector: ${specifier} resolved outside the filesystem (${resolved})`);
248
+ return fileURLToPath(resolved);
249
+ }
250
+ /** Generated composition storage owned by one decorator installation. */
251
+ var PresetOverlayStore = class {
252
+ options;
253
+ rootTask;
254
+ disposed = false;
255
+ metadataIo;
256
+ constructor(options) {
257
+ this.options = options;
258
+ this.metadataIo = options.metadataIo ?? DEFAULT_METADATA_IO;
259
+ const paths = Object.entries(options.modules);
260
+ for (const [name, path] of paths) if (!isAbsolute(path)) throw new TypeError(`context-compression selector: module path ${name} is not absolute: ${path}`);
261
+ }
262
+ /** Return a detached preset record whose path names the canonical overlay. */
263
+ async overlay(preset) {
264
+ if (this.disposed) throw new Error("context-compression selector: preset overlay is disposed");
265
+ if (preset.broken !== void 0) return preset;
266
+ const source = await readFile(preset.path, "utf8");
267
+ const rows = parseRows(source, preset.path);
268
+ const thresholdPercent = this.options.autoCompactThresholdPercent?.();
269
+ if (thresholdPercent !== void 0 && !Number.isFinite(thresholdPercent)) throw new Error(`context-compression selector: Auto Compact threshold percent must be finite, got ${String(thresholdPercent)}`);
270
+ const patched = applyEntryPatches(stripCompressionRows(rows), [{ insert: canonicalCompressionRows(this.options.modules, thresholdPercent) }], (message, ...args) => {
271
+ throw new Error(renderPatchWarning(message, args));
272
+ });
273
+ const rendered = dump(patched, {
274
+ schema: entryListSchema,
275
+ noRefs: true,
276
+ lineWidth: -1,
277
+ sortKeys: false
278
+ });
279
+ const identity = createHash("sha256").update(preset.id).update("\0").update(source).update("\0").update(JSON.stringify({
280
+ modules: this.options.modules,
281
+ autoCompactThresholdPercent: thresholdPercent ?? null
282
+ })).digest("hex").slice(0, 24);
283
+ const root = await this.root();
284
+ const path = join(root, `${preset.id}-${identity}.agent.cordis.yml`);
285
+ const staging = join(root, `${preset.id}-${identity}.${String(process.pid)}-${String(Math.random()).slice(2)}.tmp`);
286
+ try {
287
+ await writeFile(staging, rendered, {
288
+ encoding: "utf8",
289
+ mode: 384
290
+ });
291
+ await chmod(staging, 384);
292
+ await this.disambiguateStamp(staging, identity);
293
+ await this.publish(staging, path);
294
+ } catch (error) {
295
+ try {
296
+ await rm(staging, { force: true });
297
+ } catch {}
298
+ throw error;
299
+ }
300
+ return {
301
+ ...preset,
302
+ path
303
+ };
304
+ }
305
+ /** In-flight publish chains, one per destination path. */
306
+ publishChains = /* @__PURE__ */ new Map();
307
+ /**
308
+ * Publish one stamped staging file to its final path, serialized per path.
309
+ *
310
+ * POSIX `rename` replaces an existing destination atomically, so concurrent
311
+ * composers of one identity are naturally idempotent there. Windows
312
+ * `MoveFileEx` instead fails the loser of that race with EPERM/EBUSY, which
313
+ * surfaced as `standingKeyFor()` throwing during concurrent composition.
314
+ * Every composer of one identity writes identical bytes and re-derives the
315
+ * same deterministic identity stamp, so a destination that already observes
316
+ * this staging file's {mtimeMs, size} key IS the intended end state: confirm
317
+ * it and treat the lost race as success. Every other outcome still throws, so
318
+ * a silently reused generation stays forbidden, and the caller still removes
319
+ * the staging file when this rejects.
320
+ */
321
+ publish(staging, path) {
322
+ const tracked = (this.publishChains.get(path) ?? Promise.resolve()).catch(() => void 0).then(async () => {
323
+ try {
324
+ await rename(staging, path);
325
+ return;
326
+ } catch (error) {
327
+ if (!isPublishRace(error)) throw error;
328
+ try {
329
+ const intended = await this.metadataIo.read(staging);
330
+ const published = await this.metadataIo.read(path);
331
+ if (published.size === intended.size && Math.abs(published.mtimeMs - intended.mtimeMs) < 2) {
332
+ await rm(staging, { force: true });
333
+ return;
334
+ }
335
+ } catch {}
336
+ throw error;
337
+ }
338
+ }).finally(() => {
339
+ if (this.publishChains.get(path) === tracked) this.publishChains.delete(path);
340
+ });
341
+ this.publishChains.set(path, tracked);
342
+ return tracked;
343
+ }
344
+ /** Observed {mtimeMs,size} keys published by this store, per identity. */
345
+ standingKeys = /* @__PURE__ */ new Map();
346
+ /**
347
+ * Ensure an unpublished staging file's observed {mtimeMs, size} is not
348
+ * shared with a different identity. Escalation rewrites the mtime from later
349
+ * hash windows before atomic publication, and fails loudly if no window
350
+ * separates them (better a loud error than a silently reused generation).
351
+ */
352
+ async disambiguateStamp(path, identity) {
353
+ for (let window = 0; window < 3; window += 1) {
354
+ const stamp = new Date(standingStampMsAtWindow(identity, window));
355
+ await this.metadataIo.setTimes(path, stamp);
356
+ const observed = await this.metadataIo.read(path);
357
+ const key = `${String(observed.mtimeMs)}:${String(observed.size)}`;
358
+ const owner = this.standingKeys.get(key);
359
+ if (owner === void 0 || owner === identity) {
360
+ this.standingKeys.set(key, identity);
361
+ return;
362
+ }
363
+ }
364
+ throw new Error(`context-compression selector: standing stamp collision for identity ${identity} across all hash windows`);
365
+ }
366
+ /** Remove all generated files without touching any source preset. */
367
+ async dispose() {
368
+ if (this.disposed) return;
369
+ this.disposed = true;
370
+ if (this.rootTask === void 0) return;
371
+ const root = await this.rootTask;
372
+ await rm(root, {
373
+ recursive: true,
374
+ force: true
375
+ });
376
+ }
377
+ /** Lazily create the one owner-only directory for this installation. */
378
+ async root() {
379
+ if (this.rootTask === void 0) {
380
+ const parent = this.options.tempParent ?? tmpdir();
381
+ this.rootTask = mkdtemp(join(parent, "dsh-context-compression-presets-")).then(async (root) => {
382
+ await chmod(root, 448);
383
+ return root;
384
+ });
385
+ }
386
+ return await this.rootTask;
387
+ }
388
+ };
389
+ /** Parse one native preset with exactly the Loader's YAML dialect. */
390
+ function parseRows(source, path) {
391
+ const parsed = load(source, { schema: entryListSchema });
392
+ if (!Array.isArray(parsed)) throw new TypeError(`context-compression selector: preset ${path} is not a top-level entry list`);
393
+ return parsed;
394
+ }
395
+ /** Remove any prior compression implementation before adding the canonical one. */
396
+ function stripCompressionRows(rows) {
397
+ const kept = [];
398
+ for (const row of rows) {
399
+ if (COMPRESSION_IDS.has(row.id) || COMPRESSION_PACKAGES.has(row.name)) continue;
400
+ if (row.group === true && Array.isArray(row.config)) {
401
+ const nested = row.config;
402
+ kept.push({
403
+ ...row,
404
+ config: stripCompressionRows(nested)
405
+ });
406
+ } else kept.push(row);
407
+ }
408
+ return kept;
409
+ }
410
+ /**
411
+ * Complete, same-realm compression stack added to every applicable preset.
412
+ * When the Host settings expose an Auto Compact threshold, one read feeds both
413
+ * the compaction-basic `thresholdRatio` (beside the pinned first-release
414
+ * `retainRatio`) and the runtime deployment config, so plugin History and
415
+ * native Auto Compact share one watermark for this whole generation.
416
+ */
417
+ function canonicalCompressionRows(modules, thresholdPercent) {
418
+ return [{
419
+ id: "compaction",
420
+ name: "cordis:group",
421
+ group: true,
422
+ isolate: {
423
+ compaction: true,
424
+ toolResultPruner: true
425
+ },
426
+ config: [
427
+ {
428
+ id: "compaction-basic",
429
+ name: modules.compactionBasic,
430
+ ...thresholdPercent === void 0 ? {} : { config: {
431
+ thresholdRatio: thresholdPercent / 100,
432
+ retainRatio: .16
433
+ } }
434
+ },
435
+ {
436
+ id: "command-compact",
437
+ name: modules.commandCompact
438
+ },
439
+ {
440
+ id: "tool-result-pruner",
441
+ name: modules.toolResultPruner,
442
+ config: {
443
+ headChars: 4096,
444
+ tailChars: 1024,
445
+ ...thresholdPercent === void 0 ? {} : { autoCompactThresholdPercent: thresholdPercent }
446
+ }
447
+ }
448
+ ]
449
+ }];
450
+ }
451
+ /** Render include's printf-style warning without silently losing its target. */
452
+ function renderPatchWarning(message, args) {
453
+ let index = 0;
454
+ return `context-compression selector: ${message.replace(/%C/g, () => JSON.stringify(args[index++]))}`;
455
+ }
456
+ /**
457
+ * Cordis can hand two callers different traceable proxies for one service.
458
+ * Symbol properties forward to the shared target, unlike proxy identity.
459
+ */
460
+ const SHARED_DECORATION = Symbol.for("dsh-context-compression-improved/preset-overlay");
461
+ /** Object-identity keys keep test metadata policies from sharing one store. */
462
+ const METADATA_IO_KEYS = /* @__PURE__ */ new WeakMap();
463
+ let nextMetadataIoKey = 1;
464
+ function metadataIoKey(metadataIo) {
465
+ const existing = METADATA_IO_KEYS.get(metadataIo);
466
+ if (existing !== void 0) return existing;
467
+ const key = nextMetadataIoKey;
468
+ nextMetadataIoKey += 1;
469
+ METADATA_IO_KEYS.set(metadataIo, key);
470
+ return key;
471
+ }
472
+ /**
473
+ * Reversibly decorate native AgentPresets composition calls.
474
+ *
475
+ * Duplicate Host rows share one physical decoration. This matters while an
476
+ * installation migrates from a Harness-bundled selector row to the standalone
477
+ * Bundle: either row can unload first without double-compressing or disposing
478
+ * the generated files still used by the other.
479
+ * @param presets Native AgentPresets service to decorate during composition.
480
+ * @param options Canonical module paths, exclusions, and optional test directory.
481
+ * @returns A reference-counted handle that restores the native service on final disposal.
482
+ */
483
+ function decorateAgentPresets(presets, options) {
484
+ const optionsKey = overlayOptionsKey(options);
485
+ const carrier = presets;
486
+ let shared = carrier[SHARED_DECORATION];
487
+ if (shared === void 0) {
488
+ shared = {
489
+ optionsKey,
490
+ references: 0,
491
+ installation: installAgentPresetsDecoration(presets, options)
492
+ };
493
+ Object.defineProperty(carrier, SHARED_DECORATION, {
494
+ configurable: true,
495
+ enumerable: false,
496
+ writable: false,
497
+ value: shared
498
+ });
499
+ } else if (shared.optionsKey !== optionsKey) throw new Error("context-compression selector: AgentPresets already has a different compression overlay");
500
+ const lease = shared;
501
+ lease.references += 1;
502
+ let disposed = false;
503
+ return { async dispose() {
504
+ if (disposed) return;
505
+ disposed = true;
506
+ lease.references -= 1;
507
+ if (lease.references !== 0) return;
508
+ if (carrier[SHARED_DECORATION] === lease) Reflect.deleteProperty(carrier, SHARED_DECORATION);
509
+ await lease.installation.dispose();
510
+ } };
511
+ }
512
+ /** Stable equality for two rows asking to share one physical overlay. */
513
+ function overlayOptionsKey(options) {
514
+ return JSON.stringify({
515
+ modules: options.modules,
516
+ excludedPresetIds: [...options.excludedPresetIds ?? ["minimal"]].sort(),
517
+ tempParent: options.tempParent,
518
+ metadataIo: metadataIoKey(options.metadataIo ?? DEFAULT_METADATA_IO)
519
+ });
520
+ }
521
+ /**
522
+ * Install the one physical method decoration leased by public callers.
523
+ *
524
+ * Direct resolution and authoring stay source-preserving. AsyncLocalStorage
525
+ * scopes the overlay to the async call tree of mount/recompose/standingKeyFor,
526
+ * so an unrelated resolve racing the mount cannot inherit its generated path.
527
+ */
528
+ function installAgentPresetsDecoration(presets, options) {
529
+ const excluded = new Set(options.excludedPresetIds ?? ["minimal"]);
530
+ const operations = new AsyncLocalStorage();
531
+ const store = new PresetOverlayStore(options);
532
+ const snapshots = snapshotMethods(presets);
533
+ const resolveSnapshot = snapshotFor(snapshots, "resolve");
534
+ const resolveWrapped = async (id) => {
535
+ const preset = await Reflect.apply(resolveSnapshot.original, presets, [id]);
536
+ if (operations.getStore()?.composing !== true || excluded.has(preset.id)) return preset;
537
+ return await store.overlay(preset);
538
+ };
539
+ installMethod(presets, resolveSnapshot, resolveWrapped);
540
+ for (const method of [
541
+ "mount",
542
+ "recompose",
543
+ "standingKeyFor"
544
+ ]) {
545
+ const snapshot = snapshotFor(snapshots, method);
546
+ const wrapped = (...args) => operations.run({ composing: true }, () => Reflect.apply(snapshot.original, presets, args));
547
+ installMethod(presets, snapshot, wrapped);
548
+ }
549
+ let disposed = false;
550
+ return { async dispose() {
551
+ if (disposed) return;
552
+ disposed = true;
553
+ for (const snapshot of [...snapshots].reverse()) restoreMethod(presets, snapshot);
554
+ await store.dispose();
555
+ } };
556
+ }
557
+ /** Capture callable methods and whether each was inherited or owned. */
558
+ function snapshotMethods(presets) {
559
+ return [
560
+ "resolve",
561
+ "mount",
562
+ "recompose",
563
+ "standingKeyFor"
564
+ ].map((name) => {
565
+ const original = presets[name];
566
+ if (typeof original !== "function") throw new TypeError(`context-compression selector: AgentPresets.${name} is unavailable`);
567
+ return {
568
+ name,
569
+ own: Object.getOwnPropertyDescriptor(presets, name),
570
+ original
571
+ };
572
+ });
573
+ }
574
+ /** Return the captured method or fail loudly if the snapshot set is corrupt. */
575
+ function snapshotFor(snapshots, name) {
576
+ const snapshot = snapshots.find((candidate) => candidate.name === name);
577
+ if (snapshot === void 0) throw new Error(`context-compression selector: missing method snapshot for ${name}`);
578
+ return snapshot;
579
+ }
580
+ /** Install one own method while retaining its identity for safe disposal. */
581
+ function installMethod(presets, snapshot, wrapped) {
582
+ snapshot.wrapped = wrapped;
583
+ Object.defineProperty(presets, snapshot.name, {
584
+ configurable: true,
585
+ writable: true,
586
+ value: wrapped
587
+ });
588
+ }
589
+ /** Restore the captured own/prototype state after the final shared lease. */
590
+ function restoreMethod(presets, snapshot) {
591
+ if (snapshot.own === void 0) Reflect.deleteProperty(presets, snapshot.name);
592
+ else Object.defineProperty(presets, snapshot.name, snapshot.own);
593
+ }
594
+ //#endregion
595
+ //#region src/index.ts
596
+ const CONTEXT_COMPRESSION_NAMESPACE = CONTEXT_COMPRESSION_SETTINGS_NAMESPACE;
597
+ const ESTIMATOR_CATALOG_ROUTES = ["/endpoint/dsh-context-compression-improved/estimator-catalog", "/api/dsh-context-compression-improved/estimator-catalog"];
598
+ const ADVISOR_REPORT_ROUTES = ["/endpoint/dsh-context-compression-improved/advisor-report", "/api/dsh-context-compression-improved/advisor-report"];
599
+ const SAVINGS_ROUTES = ["/endpoint/dsh-context-compression-improved/savings", "/api/dsh-context-compression-improved/savings"];
600
+ const MONITOR_ROUTES = ["/endpoint/dsh-context-compression-improved/monitor", "/api/dsh-context-compression-improved/monitor"];
601
+ function sessionFor(readService, sessionId) {
602
+ const agents = readService("agents");
603
+ return typeof agents?.get === "function" ? agents.get(sessionId)?.session : void 0;
604
+ }
605
+ function jsonResponse(res, status, body) {
606
+ const resTyped = res;
607
+ resTyped.writeHead(status, {
608
+ "content-type": "application/json; charset=utf-8",
609
+ "cache-control": "no-cache"
610
+ });
611
+ resTyped.end(JSON.stringify(body));
612
+ }
613
+ /**
614
+ * Serve the advisory advisor's read-only report route (same registration
615
+ * skeleton as the estimator-catalog route):
616
+ *
617
+ * `GET .../advisor-report?sessionId=…` → the session's prefix-decay figure,
618
+ * the todolist-bound task summary, and the score distribution. Content-free
619
+ * by construction: task semantics are LLM-derived summaries, never message
620
+ * text, and no score reason or candidate preview is ever returned.
621
+ * Unknown session → 404; no agents service → 503. A session whose advisor
622
+ * never ran reports nulls and empty arrays, not an error.
623
+ */
624
+ function registerAdvisorReportRoute(ctx) {
625
+ const readService = (name) => {
626
+ try {
627
+ return ctx.get(name);
628
+ } catch {
629
+ return;
630
+ }
631
+ };
632
+ const log = (level, message, ...args) => {
633
+ console[level](message, ...args);
634
+ };
635
+ const getHandler = (req, res) => {
636
+ if (typeof readService("agents")?.get !== "function") {
637
+ jsonResponse(res, 503, {
638
+ ok: false,
639
+ error: "advisor report unavailable"
640
+ });
641
+ return;
642
+ }
643
+ let sessionId = "";
644
+ try {
645
+ sessionId = new URL(String(req.url ?? ""), "http://localhost").searchParams.get("sessionId") ?? "";
646
+ } catch {}
647
+ if (sessionId === "") {
648
+ jsonResponse(res, 400, {
649
+ ok: false,
650
+ error: "sessionId is required"
651
+ });
652
+ return;
653
+ }
654
+ const session = sessionFor(readService, sessionId);
655
+ if (session === void 0) {
656
+ jsonResponse(res, 404, {
657
+ ok: false,
658
+ error: "unknown session"
659
+ });
660
+ return;
661
+ }
662
+ const state = getAdvisorState(session);
663
+ jsonResponse(res, 200, {
664
+ ok: true,
665
+ sessionId,
666
+ advisor: {
667
+ summary: state.summary ?? null,
668
+ decay: state.lastDecay?.decay ?? null,
669
+ weightedChars: state.lastDecay?.weightedChars ?? null,
670
+ decayTurn: state.lastDecay?.turn ?? null,
671
+ scores: [...state.scores].map(([seq, entry]) => ({
672
+ seq,
673
+ score: entry.score,
674
+ turn: entry.turn
675
+ })),
676
+ lowRelevanceSeqs: [...state.recertified.keys()],
677
+ lastAdvice: state.lastAdvice === void 0 ? null : {
678
+ band: state.lastAdvice.band,
679
+ turn: state.lastAdvice.turn,
680
+ itemSeqs: state.lastAdvice.itemSeqs,
681
+ recoveredTokens: state.lastAdvice.recoveredTokens,
682
+ penaltyTokens: state.lastAdvice.penaltyTokens,
683
+ paybackTurns: state.lastAdvice.paybackTurns ?? null
684
+ }
685
+ }
686
+ });
687
+ };
688
+ const register = (webServer) => {
689
+ const disposers = [...ADVISOR_REPORT_ROUTES].map((path) => ({
690
+ path,
691
+ handler: getHandler
692
+ })).map((entry) => webServer.register({
693
+ kind: "exact",
694
+ path: entry.path,
695
+ handler: entry.handler
696
+ })).filter((off) => typeof off === "function");
697
+ ctx.effect(() => () => {
698
+ for (const off of disposers) off();
699
+ }, "contextCompressionSelector.advisor report route");
700
+ log("info", "context-compression advisor report route registered: %s", ADVISOR_REPORT_ROUTES.join(", "));
701
+ };
702
+ const active = asWebServer(readService("webServer"));
703
+ if (active !== void 0) {
704
+ register(active);
705
+ return;
706
+ }
707
+ ctx.inject(["webServer"], (injected) => {
708
+ const webServer = asWebServer(injected.webServer);
709
+ if (webServer === void 0) {
710
+ log("warn", "context-compression webServer exposes no register() — advisor report route not registered");
711
+ return;
712
+ }
713
+ register(webServer);
714
+ });
715
+ log("warn", "context-compression webServer not active yet — advisor report route pending: %s", ADVISOR_REPORT_ROUTES.join(", "));
716
+ }
717
+ /**
718
+ * The one service the catalog route actually needs. `llm` and
719
+ * `agentDefaultModel` are payload enrichment the handler resolves per request,
720
+ * never reasons to withhold the route.
721
+ */
722
+ const ESTIMATOR_CATALOG_ROUTE_DEPS = ["webServer"];
723
+ /** The estimator-side service the catalog handler enriches its response with. */
724
+ function asWebServer(value) {
725
+ if (typeof value !== "object" || value === null) return void 0;
726
+ return typeof value.register === "function" ? value : void 0;
727
+ }
728
+ /**
729
+ * Serve `GET /api/dsh-context-compression-improved/estimator-catalog` — the
730
+ * settings card's host-route dropdowns (live provider/model groups from the DSH
731
+ * `llm` service plus the effective selection). Best effort: without the
732
+ * `webServer` service the plugin keeps working, only the HTTP API is missing.
733
+ *
734
+ * The route gates on `webServer` **alone**. `llm` and `agentDefaultModel` only
735
+ * enrich the response and are resolved per request, so listing them here would
736
+ * let an estimator-side service the handler never needs keep the route
737
+ * unregistered. That failure is silent by construction — an unsatisfied
738
+ * `ctx.inject` callback never runs, so the plugin simply has no HTTP API and
739
+ * every request falls through to the host 404.
740
+ *
741
+ * Two channels cover the two arrival orders: a direct lookup catches a
742
+ * `webServer` that is already active when the plugin loads, and `ctx.inject`
743
+ * catches one that activates later. Both funnel into a single guarded
744
+ * registration, because a late-arriving service must not re-register a
745
+ * `(kind, path)` the host treats as a composition-contract violation.
746
+ */
747
+ function registerEstimatorCatalogRoute(ctx) {
748
+ const readService = (name) => {
749
+ try {
750
+ return ctx.get(name);
751
+ } catch {
752
+ return;
753
+ }
754
+ };
755
+ const log = (level, message, ...args) => {
756
+ console[level](message, ...args);
757
+ };
758
+ let registered = false;
759
+ const register = (webServer, channel) => {
760
+ if (registered) return;
761
+ const handler = (_req, res) => {
762
+ const resTyped = res;
763
+ if (typeof resTyped?.writeHead !== "function" || typeof resTyped?.end !== "function") return;
764
+ const llm = readService("llm");
765
+ const defaults = readService("agentDefaultModel");
766
+ buildEstimatorCatalog({
767
+ ...llm === void 0 ? {} : { llm },
768
+ ...typeof defaults?.currentSelection === "function" ? { currentSelection: () => defaults.currentSelection?.() } : {}
769
+ }).then((catalog) => {
770
+ resTyped.writeHead(200, {
771
+ "content-type": "application/json; charset=utf-8",
772
+ "cache-control": "no-cache"
773
+ });
774
+ resTyped.end(JSON.stringify({
775
+ ok: true,
776
+ ...catalog
777
+ }));
778
+ }, (error) => {
779
+ resTyped.writeHead(500, { "content-type": "application/json; charset=utf-8" });
780
+ resTyped.end(JSON.stringify({
781
+ ok: false,
782
+ error: String(error?.message ?? error)
783
+ }));
784
+ });
785
+ };
786
+ try {
787
+ const disposers = ESTIMATOR_CATALOG_ROUTES.map((path) => webServer.register({
788
+ kind: "exact",
789
+ path,
790
+ handler
791
+ })).filter((off) => typeof off === "function");
792
+ registered = true;
793
+ ctx.effect(() => () => {
794
+ for (const off of disposers) off();
795
+ }, "contextCompressionSelector.estimator-catalog route");
796
+ log("info", "context-compression estimator catalog route registered (%s): %s", channel, ESTIMATOR_CATALOG_ROUTES.join(", "));
797
+ } catch (error) {
798
+ log("warn", "context-compression estimator catalog route registration failed (%s): %o", channel, error);
799
+ }
800
+ };
801
+ const active = asWebServer(readService("webServer"));
802
+ if (active !== void 0) {
803
+ register(active, "direct");
804
+ if (registered) return;
805
+ }
806
+ ctx.inject([...ESTIMATOR_CATALOG_ROUTE_DEPS], (injected) => {
807
+ const webServer = asWebServer(injected.webServer);
808
+ if (webServer === void 0) {
809
+ log("warn", "context-compression webServer exposes no register() — estimator catalog route not registered");
810
+ return;
811
+ }
812
+ register(webServer, "inject");
813
+ });
814
+ log("warn", "context-compression webServer not active yet — estimator catalog route pending: %s", ESTIMATOR_CATALOG_ROUTES.join(", "));
815
+ }
816
+ /**
817
+ * Read-only savings snapshot route (`GET .../savings?sessionId=…`): gross saved,
818
+ * offsets (negative savings — compressed content later re-read in full), and net,
819
+ * with exact-tokenizer and chars/4 bases reported separately and never merged.
820
+ * Registration mirrors the estimator-catalog route (webServer gate alone, dual
821
+ * channels for both service arrival orders, single guarded registration).
822
+ */
823
+ function registerSavingsRoute(ctx) {
824
+ const readService = (name) => {
825
+ try {
826
+ return ctx.get(name);
827
+ } catch {
828
+ return;
829
+ }
830
+ };
831
+ const log = (level, message, ...args) => {
832
+ console[level](message, ...args);
833
+ };
834
+ let registered = false;
835
+ const register = (webServer, channel) => {
836
+ if (registered) return;
837
+ const handler = (req, res) => {
838
+ const resTyped = res;
839
+ if (typeof resTyped?.writeHead !== "function" || typeof resTyped?.end !== "function") return;
840
+ let sessionId;
841
+ try {
842
+ const raw = new URL(String(req?.url ?? "/"), "http://localhost").searchParams.get("sessionId");
843
+ if (typeof raw === "string" && raw.length > 0 && raw.length <= 512) sessionId = raw;
844
+ } catch {}
845
+ const snapshot = getSavingsLedger().snapshot(sessionId);
846
+ const pricing = estimateSavingsPricing(readService, snapshot);
847
+ resTyped.writeHead(200, {
848
+ "content-type": "application/json; charset=utf-8",
849
+ "cache-control": "no-cache"
850
+ });
851
+ resTyped.end(JSON.stringify({
852
+ ok: true,
853
+ ...snapshot,
854
+ ...pricing === void 0 ? {} : { pricing }
855
+ }));
856
+ };
857
+ try {
858
+ const disposers = SAVINGS_ROUTES.map((path) => webServer.register({
859
+ kind: "exact",
860
+ path,
861
+ handler
862
+ })).filter((off) => typeof off === "function");
863
+ registered = true;
864
+ ctx.effect(() => () => {
865
+ for (const off of disposers) off();
866
+ }, "contextCompressionSelector.savings route");
867
+ log("info", "context-compression savings route registered (%s): %s", channel, SAVINGS_ROUTES.join(", "));
868
+ } catch (error) {
869
+ log("warn", "context-compression savings route registration failed (%s): %o", channel, error);
870
+ }
871
+ };
872
+ const active = asWebServer(readService("webServer"));
873
+ if (active !== void 0) {
874
+ register(active, "direct");
875
+ if (registered) return;
876
+ }
877
+ ctx.inject(["webServer"], (injected) => {
878
+ const webServer = asWebServer(injected.webServer);
879
+ if (webServer === void 0) {
880
+ log("warn", "context-compression webServer exposes no register() — savings route not registered");
881
+ return;
882
+ }
883
+ register(webServer, "inject");
884
+ });
885
+ }
886
+ /**
887
+ * Floating-panel monitor route (`GET|POST .../monitor?sessionId=…`):
888
+ * - GET → the monitor snapshot (savings aggregate + intent control block +
889
+ * pricing) — the payload shape the panel polls;
890
+ * - POST → session override action (`{"action":"on"|"off"|"clear"}`),
891
+ * driving the exact state machine `/ctx-summary` drives.
892
+ * Registration mirrors the savings route (webServer gate alone, dual channels,
893
+ * single guarded registration); the handler branches on `req.method` because
894
+ * the registration surface is method-agnostic.
895
+ */
896
+ /** Exported for the runtime monitor spec; the entry owns all webServer wiring. */
897
+ function registerMonitorRoute(ctx) {
898
+ const readService = (name) => {
899
+ try {
900
+ return ctx.get(name);
901
+ } catch {
902
+ return;
903
+ }
904
+ };
905
+ const log = (level, message, ...args) => {
906
+ console[level](message, ...args);
907
+ };
908
+ let registered = false;
909
+ const register = (webServer, channel) => {
910
+ if (registered) return;
911
+ const handler = (req, res) => {
912
+ const resTyped = res;
913
+ if (typeof resTyped?.writeHead !== "function" || typeof resTyped?.end !== "function") return;
914
+ let sessionId;
915
+ try {
916
+ const raw = new URL(String(req?.url ?? "/"), "http://localhost").searchParams.get("sessionId");
917
+ if (typeof raw === "string" && raw.length > 0 && raw.length <= 512) sessionId = raw;
918
+ } catch {}
919
+ if (String(req?.method ?? "GET").toUpperCase() === "POST") {
920
+ const chunks = [];
921
+ let size = 0;
922
+ let done = false;
923
+ const respond = (status, body) => {
924
+ if (done) return;
925
+ done = true;
926
+ resTyped.writeHead(status, {
927
+ "content-type": "application/json; charset=utf-8",
928
+ "cache-control": "no-cache"
929
+ });
930
+ resTyped.end(JSON.stringify(body));
931
+ };
932
+ const reqTyped = req;
933
+ if (typeof reqTyped?.on !== "function") {
934
+ respond(400, {
935
+ ok: false,
936
+ error: "unreadable request body"
937
+ });
938
+ return;
939
+ }
940
+ reqTyped.on("data", (chunk) => {
941
+ size += chunk?.length ?? 0;
942
+ if (size <= 4096) chunks.push(Buffer.from(chunk ?? /* @__PURE__ */ new Uint8Array()));
943
+ });
944
+ reqTyped.on("end", () => {
945
+ let action;
946
+ try {
947
+ action = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}").action;
948
+ } catch {
949
+ respond(400, {
950
+ ok: false,
951
+ error: "monitor override action must be JSON"
952
+ });
953
+ return;
954
+ }
955
+ if (!isSessionOverrideAction(action)) {
956
+ respond(400, {
957
+ ok: false,
958
+ error: "monitor override action must be \"on\" | \"off\" | \"clear\""
959
+ });
960
+ return;
961
+ }
962
+ const { override } = applySessionOverride(sessionId ?? "", action);
963
+ respond(200, {
964
+ ok: true,
965
+ override: override ?? null,
966
+ sessionScope: sessionId ?? null
967
+ });
968
+ });
969
+ return;
970
+ }
971
+ const snapshot = buildMonitorSnapshot(sessionId);
972
+ const pricing = estimateSavingsPricing(readService, snapshot);
973
+ resTyped.writeHead(200, {
974
+ "content-type": "application/json; charset=utf-8",
975
+ "cache-control": "no-cache"
976
+ });
977
+ resTyped.end(JSON.stringify({
978
+ ok: true,
979
+ ...snapshot,
980
+ ...pricing === void 0 ? {} : { pricing }
981
+ }));
982
+ };
983
+ try {
984
+ const disposers = MONITOR_ROUTES.map((path) => webServer.register({
985
+ kind: "exact",
986
+ path,
987
+ handler
988
+ })).filter((off) => typeof off === "function");
989
+ registered = true;
990
+ ctx.effect(() => () => {
991
+ for (const off of disposers) off();
992
+ }, "contextCompressionSelector.monitor route");
993
+ log("info", "context-compression monitor route registered (%s): %s", channel, MONITOR_ROUTES.join(", "));
994
+ } catch (error) {
995
+ log("warn", "context-compression monitor route registration failed (%s): %o", channel, error);
996
+ }
997
+ };
998
+ const active = asWebServer(readService("webServer"));
999
+ if (active !== void 0) {
1000
+ register(active, "direct");
1001
+ if (registered) return;
1002
+ }
1003
+ ctx.inject(["webServer"], (injected) => {
1004
+ const webServer = asWebServer(injected.webServer);
1005
+ if (webServer === void 0) {
1006
+ log("warn", "context-compression webServer exposes no register() — monitor route not registered");
1007
+ return;
1008
+ }
1009
+ register(webServer, "inject");
1010
+ });
1011
+ }
1012
+ /** Symbol properties reach the shared service target through Cordis proxies. */
1013
+ const SHARED_SETTINGS = Symbol.for("dsh-context-compression-improved/settings-registration");
1014
+ /** Loader validation for the standalone Bundle opt-in. */
1015
+ const Config = z.object({
1016
+ presetOverlay: z.boolean().default(false),
1017
+ estimatorCatalogRoute: z.boolean().default(false),
1018
+ advisorReportRoute: z.boolean().default(false)
1019
+ });
1020
+ /** Register the persisted default read by the currently mounted root pruner. */
1021
+ function apply(ctx, config = {}) {
1022
+ try {
1023
+ ctx.inject(["settings"], (settingsCtx) => {
1024
+ acquireSettingsRegistration(settingsCtx);
1025
+ });
1026
+ if (config.estimatorCatalogRoute === true) registerEstimatorCatalogRoute(ctx);
1027
+ registerSavingsRoute(ctx);
1028
+ registerMonitorRoute(ctx);
1029
+ if (config.advisorReportRoute === true) registerAdvisorReportRoute(ctx);
1030
+ registerSummaryCommand(ctx);
1031
+ if (config.presetOverlay !== true) return;
1032
+ ctx.inject(["agentPresets"], (presetsCtx) => {
1033
+ const installation = decorateAgentPresets(presetsCtx.agentPresets, {
1034
+ modules: resolveCompressionModulePaths(),
1035
+ excludedPresetIds: ["minimal"],
1036
+ autoCompactThresholdPercent: () => resolveAutoCompactThresholdPercent(presetsCtx)
1037
+ });
1038
+ presetsCtx.effect(() => () => installation.dispose(), "contextCompressionSelector.agentPresets()");
1039
+ });
1040
+ } catch (error) {
1041
+ console.error("context-compression selector apply failed: %o", error);
1042
+ throw error;
1043
+ }
1044
+ }
1045
+ /**
1046
+ * Read the current Auto Compact threshold ratio at composition time. Settings
1047
+ * values are revalidated here, and any unreadable value falls back to the 80%
1048
+ * default rather than blocking preset composition.
1049
+ */
1050
+ function resolveAutoCompactThresholdPercent(presetsCtx) {
1051
+ const raw = presetsCtx.get("settings")?.get(CONTEXT_COMPRESSION_NAMESPACE);
1052
+ try {
1053
+ const threshold = structuredClone(raw)?.autoCompact;
1054
+ const value = typeof threshold?.thresholdPercent === "number" ? threshold.thresholdPercent : 80;
1055
+ return Number.isFinite(value) && value >= 50 && value <= 90 ? value : 80;
1056
+ } catch {
1057
+ return 80;
1058
+ }
1059
+ }
1060
+ /**
1061
+ * Lease one native settings registration across duplicate Host rows.
1062
+ *
1063
+ * The lease effect is intentionally registered before settings.register().
1064
+ * Cordis disposes effects in reverse order, so the native registration first
1065
+ * releases the namespace; this disposer can then transfer it to another live
1066
+ * owner without a duplicate-registration window.
1067
+ */
1068
+ function acquireSettingsRegistration(ctx) {
1069
+ const settings = ctx.settings;
1070
+ const owner = { settings };
1071
+ let shared = settings[SHARED_SETTINGS];
1072
+ if (shared === void 0) {
1073
+ shared = {
1074
+ owners: /* @__PURE__ */ new Set(),
1075
+ registrationOwner: owner,
1076
+ scope: void 0
1077
+ };
1078
+ Object.defineProperty(settings, SHARED_SETTINGS, {
1079
+ configurable: true,
1080
+ enumerable: false,
1081
+ writable: false,
1082
+ value: shared
1083
+ });
1084
+ }
1085
+ shared.owners.add(owner);
1086
+ const state = shared;
1087
+ ctx.effect(() => () => {
1088
+ state.owners.delete(owner);
1089
+ if (state.registrationOwner === owner && state.owners.size > 0) {
1090
+ const next = state.owners.values().next().value;
1091
+ state.registrationOwner = next;
1092
+ state.scope = next.settings.register(CONTEXT_COMPRESSION_NAMESPACE, ContextCompressionSettingsSchema);
1093
+ }
1094
+ if (state.owners.size === 0 && settings[SHARED_SETTINGS] === state) Reflect.deleteProperty(settings, SHARED_SETTINGS);
1095
+ }, "contextCompressionSelector.settingsLease()");
1096
+ if (state.owners.size === 1) state.scope = settings.register(CONTEXT_COMPRESSION_NAMESPACE, ContextCompressionSettingsSchema);
1097
+ }
1098
+ //#endregion
1099
+ export { Config, apply, registerMonitorRoute };