dsh-context-compression-improved 0.2.3 → 0.2.4

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 (52) hide show
  1. package/.github/workflows/ci.yml +39 -39
  2. package/CHANGELOG.md +137 -135
  3. package/README.md +112 -112
  4. package/package.json +142 -142
  5. package/packages/selector/README.md +31 -31
  6. package/packages/selector/README.zh.md +31 -31
  7. package/packages/selector/dsh.plugin.json +16 -16
  8. package/packages/selector/lib/client.d.ts +228 -228
  9. package/packages/selector/lib/client.js +1462 -1462
  10. package/packages/selector/lib/config.js +856 -842
  11. package/packages/selector/lib/index.d.ts +37 -37
  12. package/packages/selector/lib/index.js +693 -645
  13. package/packages/selector/lib/invariant.js +70 -70
  14. package/packages/selector/lib/pruner.d.ts +728 -683
  15. package/packages/selector/lib/pruner.js +4765 -3807
  16. package/packages/selector/lib/style.css +46 -46
  17. package/packages/selector/lib/tail-trim.js +136 -136
  18. package/packages/selector/package.json +9 -1
  19. package/packages/selector/src/client/index.ts +111 -111
  20. package/packages/selector/src/preset-overlay.ts +60 -1
  21. package/packages/selector/src/pruner/content.ts +18 -5
  22. package/packages/selector/src/pruner/types.ts +23 -5
  23. package/packages/selector/src/pruner.ts +164 -154
  24. package/packages/selector/src/runtime/adaptive-cost.ts +23 -12
  25. package/packages/selector/src/runtime/audit.ts +18 -2
  26. package/packages/selector/src/runtime/config.ts +30 -1
  27. package/packages/selector/src/runtime/measurement.ts +31 -2
  28. package/packages/selector/src/runtime/reducers.ts +1115 -97
  29. package/packages/selector/src/runtime/tokenpilot/dedup.ts +1 -1
  30. package/packages/selector/src/runtime/tokenpilot/locator.ts +1 -1
  31. package/packages/selector/src/runtime/tokenpilot/read-state.ts +23 -2
  32. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +275 -0
  33. package/packages/selector/src/runtime/toolclass.ts +103 -0
  34. package/packages/selector/src/runtime/types.ts +16 -0
  35. package/packages/selector/tests/preset-overlay.host.spec.ts +256 -243
  36. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +7 -7
  37. package/packages/selector/tests/runtime/audit.spec.ts +44 -1
  38. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -0
  39. package/packages/selector/tests/runtime/code-skeleton.spec.ts +14 -3
  40. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -0
  41. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -0
  42. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -0
  43. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -0
  44. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +198 -27
  45. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -0
  46. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -0
  47. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -0
  48. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -0
  49. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +24 -0
  50. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -0
  51. package/packages/selector/tests/standing-generation.host.spec.ts +642 -631
  52. package/scripts/toolclass-corpus-replay.mjs +273 -0
@@ -1,645 +1,693 @@
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 { 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
+ /**
122
+ * True for the filesystem errors a concurrent publish can raise on Windows:
123
+ * `MoveFileEx` reports a lost race — or a reader holding the destination open —
124
+ * as EPERM/EBUSY/EACCES, where POSIX `rename` simply replaces the destination.
125
+ */
126
+ function isPublishRace(error) {
127
+ const code = error?.code;
128
+ return code === "EPERM" || code === "EBUSY" || code === "EACCES" || code === "EEXIST";
129
+ }
130
+ const COMPRESSION_IDS = /* @__PURE__ */ new Set([
131
+ "compaction",
132
+ "compaction-basic",
133
+ "command-compact",
134
+ "tool-result-pruner"
135
+ ]);
136
+ const COMPRESSION_PACKAGES = /* @__PURE__ */ 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
+ * Resolve the three compression package entries once from this package.
146
+ * @returns Absolute entry paths for the canonical compression layer.
147
+ */
148
+ function resolveCompressionModulePaths() {
149
+ return {
150
+ compactionBasic: modulePath("@deepseek-ai/dsh-compaction-basic", import.meta.resolve("@deepseek-ai/dsh-compaction-basic")),
151
+ commandCompact: modulePath("@deepseek-ai/dsh-command-compact", import.meta.resolve("@deepseek-ai/dsh-command-compact")),
152
+ toolResultPruner: modulePath("dsh-context-compression-improved/pruner", import.meta.resolve("dsh-context-compression-improved/pruner"))
153
+ };
154
+ }
155
+ /** Convert one package resolution into the absolute path preset mounting accepts. */
156
+ function modulePath(specifier, resolved) {
157
+ if (!resolved.startsWith("file:")) throw new Error(`context-compression selector: ${specifier} resolved outside the filesystem (${resolved})`);
158
+ return fileURLToPath(resolved);
159
+ }
160
+ /** Generated composition storage owned by one decorator installation. */
161
+ var PresetOverlayStore = class {
162
+ options;
163
+ rootTask;
164
+ disposed = false;
165
+ metadataIo;
166
+ constructor(options) {
167
+ this.options = options;
168
+ this.metadataIo = options.metadataIo ?? DEFAULT_METADATA_IO;
169
+ const paths = Object.entries(options.modules);
170
+ for (const [name, path] of paths) if (!isAbsolute(path)) throw new TypeError(`context-compression selector: module path ${name} is not absolute: ${path}`);
171
+ }
172
+ /** Return a detached preset record whose path names the canonical overlay. */
173
+ async overlay(preset) {
174
+ if (this.disposed) throw new Error("context-compression selector: preset overlay is disposed");
175
+ if (preset.broken !== void 0) return preset;
176
+ const source = await readFile(preset.path, "utf8");
177
+ const rows = parseRows(source, preset.path);
178
+ const thresholdPercent = this.options.autoCompactThresholdPercent?.();
179
+ if (thresholdPercent !== void 0 && !Number.isFinite(thresholdPercent)) throw new Error(`context-compression selector: Auto Compact threshold percent must be finite, got ${String(thresholdPercent)}`);
180
+ const patched = applyEntryPatches(stripCompressionRows(rows), [{ insert: canonicalCompressionRows(this.options.modules, thresholdPercent) }], (message, ...args) => {
181
+ throw new Error(renderPatchWarning(message, args));
182
+ });
183
+ const rendered = dump(patched, {
184
+ schema: entryListSchema,
185
+ noRefs: true,
186
+ lineWidth: -1,
187
+ sortKeys: false
188
+ });
189
+ const identity = createHash("sha256").update(preset.id).update("\0").update(source).update("\0").update(JSON.stringify({
190
+ modules: this.options.modules,
191
+ autoCompactThresholdPercent: thresholdPercent ?? null
192
+ })).digest("hex").slice(0, 24);
193
+ const root = await this.root();
194
+ const path = join(root, `${preset.id}-${identity}.agent.cordis.yml`);
195
+ const staging = join(root, `${preset.id}-${identity}.${String(process.pid)}-${String(Math.random()).slice(2)}.tmp`);
196
+ try {
197
+ await writeFile(staging, rendered, {
198
+ encoding: "utf8",
199
+ mode: 384
200
+ });
201
+ await chmod(staging, 384);
202
+ await this.disambiguateStamp(staging, identity);
203
+ await this.publish(staging, path);
204
+ } catch (error) {
205
+ try {
206
+ await rm(staging, { force: true });
207
+ } catch {}
208
+ throw error;
209
+ }
210
+ return {
211
+ ...preset,
212
+ path
213
+ };
214
+ }
215
+ /** In-flight publish chains, one per destination path. */
216
+ publishChains = /* @__PURE__ */ new Map();
217
+ /**
218
+ * Publish one stamped staging file to its final path, serialized per path.
219
+ *
220
+ * POSIX `rename` replaces an existing destination atomically, so concurrent
221
+ * composers of one identity are naturally idempotent there. Windows
222
+ * `MoveFileEx` instead fails the loser of that race with EPERM/EBUSY, which
223
+ * surfaced as `standingKeyFor()` throwing during concurrent composition.
224
+ * Every composer of one identity writes identical bytes and re-derives the
225
+ * same deterministic identity stamp, so a destination that already observes
226
+ * this staging file's {mtimeMs, size} key IS the intended end state: confirm
227
+ * it and treat the lost race as success. Every other outcome still throws, so
228
+ * a silently reused generation stays forbidden, and the caller still removes
229
+ * the staging file when this rejects.
230
+ */
231
+ publish(staging, path) {
232
+ const tracked = (this.publishChains.get(path) ?? Promise.resolve()).catch(() => void 0).then(async () => {
233
+ try {
234
+ await rename(staging, path);
235
+ return;
236
+ } catch (error) {
237
+ if (!isPublishRace(error)) throw error;
238
+ try {
239
+ const intended = await this.metadataIo.read(staging);
240
+ const published = await this.metadataIo.read(path);
241
+ if (published.size === intended.size && Math.abs(published.mtimeMs - intended.mtimeMs) < 2) {
242
+ await rm(staging, { force: true });
243
+ return;
244
+ }
245
+ } catch {}
246
+ throw error;
247
+ }
248
+ }).finally(() => {
249
+ if (this.publishChains.get(path) === tracked) this.publishChains.delete(path);
250
+ });
251
+ this.publishChains.set(path, tracked);
252
+ return tracked;
253
+ }
254
+ /** Observed {mtimeMs,size} keys published by this store, per identity. */
255
+ standingKeys = /* @__PURE__ */ new Map();
256
+ /**
257
+ * Ensure an unpublished staging file's observed {mtimeMs, size} is not
258
+ * shared with a different identity. Escalation rewrites the mtime from later
259
+ * hash windows before atomic publication, and fails loudly if no window
260
+ * separates them (better a loud error than a silently reused generation).
261
+ */
262
+ async disambiguateStamp(path, identity) {
263
+ for (let window = 0; window < 3; window += 1) {
264
+ const stamp = new Date(standingStampMsAtWindow(identity, window));
265
+ await this.metadataIo.setTimes(path, stamp);
266
+ const observed = await this.metadataIo.read(path);
267
+ const key = `${String(observed.mtimeMs)}:${String(observed.size)}`;
268
+ const owner = this.standingKeys.get(key);
269
+ if (owner === void 0 || owner === identity) {
270
+ this.standingKeys.set(key, identity);
271
+ return;
272
+ }
273
+ }
274
+ throw new Error(`context-compression selector: standing stamp collision for identity ${identity} across all hash windows`);
275
+ }
276
+ /** Remove all generated files without touching any source preset. */
277
+ async dispose() {
278
+ if (this.disposed) return;
279
+ this.disposed = true;
280
+ if (this.rootTask === void 0) return;
281
+ const root = await this.rootTask;
282
+ await rm(root, {
283
+ recursive: true,
284
+ force: true
285
+ });
286
+ }
287
+ /** Lazily create the one owner-only directory for this installation. */
288
+ async root() {
289
+ if (this.rootTask === void 0) {
290
+ const parent = this.options.tempParent ?? tmpdir();
291
+ this.rootTask = mkdtemp(join(parent, "dsh-context-compression-presets-")).then(async (root) => {
292
+ await chmod(root, 448);
293
+ return root;
294
+ });
295
+ }
296
+ return await this.rootTask;
297
+ }
298
+ };
299
+ /** Parse one native preset with exactly the Loader's YAML dialect. */
300
+ function parseRows(source, path) {
301
+ const parsed = load(source, { schema: entryListSchema });
302
+ if (!Array.isArray(parsed)) throw new TypeError(`context-compression selector: preset ${path} is not a top-level entry list`);
303
+ return parsed;
304
+ }
305
+ /** Remove any prior compression implementation before adding the canonical one. */
306
+ function stripCompressionRows(rows) {
307
+ const kept = [];
308
+ for (const row of rows) {
309
+ if (COMPRESSION_IDS.has(row.id) || COMPRESSION_PACKAGES.has(row.name)) continue;
310
+ if (row.group === true && Array.isArray(row.config)) {
311
+ const nested = row.config;
312
+ kept.push({
313
+ ...row,
314
+ config: stripCompressionRows(nested)
315
+ });
316
+ } else kept.push(row);
317
+ }
318
+ return kept;
319
+ }
320
+ /**
321
+ * Complete, same-realm compression stack added to every applicable preset.
322
+ * When the Host settings expose an Auto Compact threshold, one read feeds both
323
+ * the compaction-basic `thresholdRatio` (beside the pinned first-release
324
+ * `retainRatio`) and the runtime deployment config, so plugin History and
325
+ * native Auto Compact share one watermark for this whole generation.
326
+ */
327
+ function canonicalCompressionRows(modules, thresholdPercent) {
328
+ return [{
329
+ id: "compaction",
330
+ name: "cordis:group",
331
+ group: true,
332
+ isolate: {
333
+ compaction: true,
334
+ toolResultPruner: true
335
+ },
336
+ config: [
337
+ {
338
+ id: "compaction-basic",
339
+ name: modules.compactionBasic,
340
+ ...thresholdPercent === void 0 ? {} : { config: {
341
+ thresholdRatio: thresholdPercent / 100,
342
+ retainRatio: .16
343
+ } }
344
+ },
345
+ {
346
+ id: "command-compact",
347
+ name: modules.commandCompact
348
+ },
349
+ {
350
+ id: "tool-result-pruner",
351
+ name: modules.toolResultPruner,
352
+ config: {
353
+ headChars: 4096,
354
+ tailChars: 1024,
355
+ ...thresholdPercent === void 0 ? {} : { autoCompactThresholdPercent: thresholdPercent }
356
+ }
357
+ }
358
+ ]
359
+ }];
360
+ }
361
+ /** Render include's printf-style warning without silently losing its target. */
362
+ function renderPatchWarning(message, args) {
363
+ let index = 0;
364
+ return `context-compression selector: ${message.replace(/%C/g, () => JSON.stringify(args[index++]))}`;
365
+ }
366
+ /**
367
+ * Cordis can hand two callers different traceable proxies for one service.
368
+ * Symbol properties forward to the shared target, unlike proxy identity.
369
+ */
370
+ const SHARED_DECORATION = Symbol.for("dsh-context-compression-improved/preset-overlay");
371
+ /** Object-identity keys keep test metadata policies from sharing one store. */
372
+ const METADATA_IO_KEYS = /* @__PURE__ */ new WeakMap();
373
+ let nextMetadataIoKey = 1;
374
+ function metadataIoKey(metadataIo) {
375
+ const existing = METADATA_IO_KEYS.get(metadataIo);
376
+ if (existing !== void 0) return existing;
377
+ const key = nextMetadataIoKey;
378
+ nextMetadataIoKey += 1;
379
+ METADATA_IO_KEYS.set(metadataIo, key);
380
+ return key;
381
+ }
382
+ /**
383
+ * Reversibly decorate native AgentPresets composition calls.
384
+ *
385
+ * Duplicate Host rows share one physical decoration. This matters while an
386
+ * installation migrates from a Harness-bundled selector row to the standalone
387
+ * Bundle: either row can unload first without double-compressing or disposing
388
+ * the generated files still used by the other.
389
+ * @param presets Native AgentPresets service to decorate during composition.
390
+ * @param options Canonical module paths, exclusions, and optional test directory.
391
+ * @returns A reference-counted handle that restores the native service on final disposal.
392
+ */
393
+ function decorateAgentPresets(presets, options) {
394
+ const optionsKey = overlayOptionsKey(options);
395
+ const carrier = presets;
396
+ let shared = carrier[SHARED_DECORATION];
397
+ if (shared === void 0) {
398
+ shared = {
399
+ optionsKey,
400
+ references: 0,
401
+ installation: installAgentPresetsDecoration(presets, options)
402
+ };
403
+ Object.defineProperty(carrier, SHARED_DECORATION, {
404
+ configurable: true,
405
+ enumerable: false,
406
+ writable: false,
407
+ value: shared
408
+ });
409
+ } else if (shared.optionsKey !== optionsKey) throw new Error("context-compression selector: AgentPresets already has a different compression overlay");
410
+ const lease = shared;
411
+ lease.references += 1;
412
+ let disposed = false;
413
+ return { async dispose() {
414
+ if (disposed) return;
415
+ disposed = true;
416
+ lease.references -= 1;
417
+ if (lease.references !== 0) return;
418
+ if (carrier[SHARED_DECORATION] === lease) Reflect.deleteProperty(carrier, SHARED_DECORATION);
419
+ await lease.installation.dispose();
420
+ } };
421
+ }
422
+ /** Stable equality for two rows asking to share one physical overlay. */
423
+ function overlayOptionsKey(options) {
424
+ return JSON.stringify({
425
+ modules: options.modules,
426
+ excludedPresetIds: [...options.excludedPresetIds ?? ["minimal"]].sort(),
427
+ tempParent: options.tempParent,
428
+ metadataIo: metadataIoKey(options.metadataIo ?? DEFAULT_METADATA_IO)
429
+ });
430
+ }
431
+ /**
432
+ * Install the one physical method decoration leased by public callers.
433
+ *
434
+ * Direct resolution and authoring stay source-preserving. AsyncLocalStorage
435
+ * scopes the overlay to the async call tree of mount/recompose/standingKeyFor,
436
+ * so an unrelated resolve racing the mount cannot inherit its generated path.
437
+ */
438
+ function installAgentPresetsDecoration(presets, options) {
439
+ const excluded = new Set(options.excludedPresetIds ?? ["minimal"]);
440
+ const operations = new AsyncLocalStorage();
441
+ const store = new PresetOverlayStore(options);
442
+ const snapshots = snapshotMethods(presets);
443
+ const resolveSnapshot = snapshotFor(snapshots, "resolve");
444
+ const resolveWrapped = async (id) => {
445
+ const preset = await Reflect.apply(resolveSnapshot.original, presets, [id]);
446
+ if (operations.getStore()?.composing !== true || excluded.has(preset.id)) return preset;
447
+ return await store.overlay(preset);
448
+ };
449
+ installMethod(presets, resolveSnapshot, resolveWrapped);
450
+ for (const method of [
451
+ "mount",
452
+ "recompose",
453
+ "standingKeyFor"
454
+ ]) {
455
+ const snapshot = snapshotFor(snapshots, method);
456
+ const wrapped = (...args) => operations.run({ composing: true }, () => Reflect.apply(snapshot.original, presets, args));
457
+ installMethod(presets, snapshot, wrapped);
458
+ }
459
+ let disposed = false;
460
+ return { async dispose() {
461
+ if (disposed) return;
462
+ disposed = true;
463
+ for (const snapshot of [...snapshots].reverse()) restoreMethod(presets, snapshot);
464
+ await store.dispose();
465
+ } };
466
+ }
467
+ /** Capture callable methods and whether each was inherited or owned. */
468
+ function snapshotMethods(presets) {
469
+ return [
470
+ "resolve",
471
+ "mount",
472
+ "recompose",
473
+ "standingKeyFor"
474
+ ].map((name) => {
475
+ const original = presets[name];
476
+ if (typeof original !== "function") throw new TypeError(`context-compression selector: AgentPresets.${name} is unavailable`);
477
+ return {
478
+ name,
479
+ own: Object.getOwnPropertyDescriptor(presets, name),
480
+ original
481
+ };
482
+ });
483
+ }
484
+ /** Return the captured method or fail loudly if the snapshot set is corrupt. */
485
+ function snapshotFor(snapshots, name) {
486
+ const snapshot = snapshots.find((candidate) => candidate.name === name);
487
+ if (snapshot === void 0) throw new Error(`context-compression selector: missing method snapshot for ${name}`);
488
+ return snapshot;
489
+ }
490
+ /** Install one own method while retaining its identity for safe disposal. */
491
+ function installMethod(presets, snapshot, wrapped) {
492
+ snapshot.wrapped = wrapped;
493
+ Object.defineProperty(presets, snapshot.name, {
494
+ configurable: true,
495
+ writable: true,
496
+ value: wrapped
497
+ });
498
+ }
499
+ /** Restore the captured own/prototype state after the final shared lease. */
500
+ function restoreMethod(presets, snapshot) {
501
+ if (snapshot.own === void 0) Reflect.deleteProperty(presets, snapshot.name);
502
+ else Object.defineProperty(presets, snapshot.name, snapshot.own);
503
+ }
504
+ //#endregion
505
+ //#region src/index.ts
506
+ const ESTIMATOR_CATALOG_ROUTES = ["/endpoint/dsh-context-compression-improved/estimator-catalog", "/api/dsh-context-compression-improved/estimator-catalog"];
507
+ /**
508
+ * The one service the catalog route actually needs. `llm` and
509
+ * `agentDefaultModel` are payload enrichment the handler resolves per request,
510
+ * never reasons to withhold the route.
511
+ */
512
+ const ESTIMATOR_CATALOG_ROUTE_DEPS = ["webServer"];
513
+ function asWebServer(value) {
514
+ if (typeof value?.register !== "function") return void 0;
515
+ return value;
516
+ }
517
+ /**
518
+ * Serve `GET /api/dsh-context-compression-improved/estimator-catalog` — the
519
+ * settings card's host-route dropdowns (live provider/model groups from the DSH
520
+ * `llm` service plus the effective selection). This lives on the top-level
521
+ * plugin context, NOT inside the isolated toolResultPruner service.
522
+ *
523
+ * (The isolation reason this placement was originally justified with — "a route
524
+ * registered there can never reach `webServer` across the isolation boundary" —
525
+ * is **unverified**: no `@deepseek-ai` package calls `.isolate(`, so there is no
526
+ * boundary to cross here. Top-level placement is still the right choice, for a
527
+ * reason that needs no framework rule: the route is host-wide, not
528
+ * per-pruner-instance. Don't promote the isolation wording into a rule.)
529
+ *
530
+ * The route gates on `webServer` **alone**. `llm` and `agentDefaultModel` only
531
+ * enrich the response and are resolved per request, so listing them here would
532
+ * let an estimator-side service the handler never needs keep the route
533
+ * unregistered. That failure is silent by construction — an unsatisfied
534
+ * `ctx.inject` callback never runs, so the plugin simply has no HTTP API and
535
+ * every request falls through to the host 404.
536
+ *
537
+ * Two channels cover the two arrival orders: a direct lookup catches a
538
+ * `webServer` that is already active when the plugin loads, and `ctx.inject`
539
+ * catches one that activates later. Both funnel into a single guarded
540
+ * registration, because a late-arriving service must not re-register a
541
+ * `(kind, path)` the host treats as a composition-contract violation.
542
+ */
543
+ function registerEstimatorCatalogRoute(ctx) {
544
+ const readService = (name) => {
545
+ try {
546
+ return ctx.get(name);
547
+ } catch {
548
+ return;
549
+ }
550
+ };
551
+ const log = (level, message, ...args) => {
552
+ console[level](message, ...args);
553
+ };
554
+ let registered = false;
555
+ const register = (webServer, channel) => {
556
+ if (registered) return;
557
+ const handler = (_req, res) => {
558
+ const resTyped = res;
559
+ if (typeof resTyped?.writeHead !== "function" || typeof resTyped?.end !== "function") return;
560
+ const llm = readService("llm");
561
+ const defaults = readService("agentDefaultModel");
562
+ buildEstimatorCatalog({
563
+ ...llm === void 0 ? {} : { llm },
564
+ ...typeof defaults?.currentSelection === "function" ? { currentSelection: () => defaults.currentSelection?.() } : {}
565
+ }).then((catalog) => {
566
+ resTyped.writeHead(200, {
567
+ "content-type": "application/json; charset=utf-8",
568
+ "cache-control": "no-cache"
569
+ });
570
+ resTyped.end(JSON.stringify({
571
+ ok: true,
572
+ ...catalog
573
+ }));
574
+ }, (error) => {
575
+ resTyped.writeHead(500, { "content-type": "application/json; charset=utf-8" });
576
+ resTyped.end(JSON.stringify({
577
+ ok: false,
578
+ error: String(error?.message ?? error)
579
+ }));
580
+ });
581
+ };
582
+ try {
583
+ const disposers = ESTIMATOR_CATALOG_ROUTES.map((path) => webServer.register({
584
+ kind: "exact",
585
+ path,
586
+ handler
587
+ })).filter((off) => typeof off === "function");
588
+ registered = true;
589
+ ctx.effect(() => () => {
590
+ for (const off of disposers) off();
591
+ }, "contextCompressionSelector.estimator-catalog route");
592
+ log("info", "context-compression estimator catalog route registered (%s): %s", channel, ESTIMATOR_CATALOG_ROUTES.join(", "));
593
+ } catch (error) {
594
+ log("warn", "context-compression estimator catalog route registration failed (%s): %o", channel, error);
595
+ }
596
+ };
597
+ const active = asWebServer(readService("webServer"));
598
+ if (active !== void 0) {
599
+ register(active, "direct");
600
+ if (registered) return;
601
+ }
602
+ ctx.inject([...ESTIMATOR_CATALOG_ROUTE_DEPS], (injected) => {
603
+ const webServer = asWebServer(injected.webServer);
604
+ if (webServer === void 0) {
605
+ log("warn", "context-compression webServer exposes no register() — estimator catalog route not registered");
606
+ return;
607
+ }
608
+ register(webServer, "inject");
609
+ });
610
+ log("warn", "context-compression webServer not active yet — estimator catalog route pending: %s", ESTIMATOR_CATALOG_ROUTES.join(", "));
611
+ }
612
+ const CONTEXT_COMPRESSION_NAMESPACE = CONTEXT_COMPRESSION_SETTINGS_NAMESPACE;
613
+ /** Symbol properties reach the shared service target through Cordis proxies. */
614
+ const SHARED_SETTINGS = Symbol.for("dsh-context-compression-improved/settings-registration");
615
+ /** Loader validation for the standalone Bundle opt-in. */
616
+ const Config = z.object({
617
+ presetOverlay: z.boolean().default(false),
618
+ estimatorCatalogRoute: z.boolean().default(false)
619
+ });
620
+ /** Register the persisted default read by the currently mounted root pruner. */
621
+ function apply(ctx, config = {}) {
622
+ try {
623
+ ctx.inject(["settings"], (settingsCtx) => {
624
+ acquireSettingsRegistration(settingsCtx);
625
+ });
626
+ if (config.estimatorCatalogRoute === true) registerEstimatorCatalogRoute(ctx);
627
+ if (config.presetOverlay !== true) return;
628
+ ctx.inject(["agentPresets"], (presetsCtx) => {
629
+ const installation = decorateAgentPresets(presetsCtx.agentPresets, {
630
+ modules: resolveCompressionModulePaths(),
631
+ excludedPresetIds: ["minimal"],
632
+ autoCompactThresholdPercent: () => resolveAutoCompactThresholdPercent(presetsCtx)
633
+ });
634
+ presetsCtx.effect(() => () => installation.dispose(), "contextCompressionSelector.agentPresets()");
635
+ });
636
+ } catch (error) {
637
+ console.error("context-compression apply() failed:", error);
638
+ throw error;
639
+ }
640
+ }
641
+ /**
642
+ * Read the current Auto Compact threshold ratio at composition time. Settings
643
+ * values are revalidated here, and any unreadable value falls back to the 80%
644
+ * default rather than blocking preset composition.
645
+ */
646
+ function resolveAutoCompactThresholdPercent(presetsCtx) {
647
+ const raw = presetsCtx.get("settings")?.get(CONTEXT_COMPRESSION_NAMESPACE);
648
+ try {
649
+ return ContextCompressionSettingsSchema(structuredClone(raw)).autoCompact.thresholdPercent;
650
+ } catch {
651
+ return 80;
652
+ }
653
+ }
654
+ /**
655
+ * Lease one native settings registration across duplicate Host rows.
656
+ *
657
+ * The lease effect is intentionally registered before settings.register().
658
+ * Cordis disposes effects in reverse order, so the native registration first
659
+ * releases the namespace; this disposer can then transfer it to another live
660
+ * owner without a duplicate-registration window.
661
+ */
662
+ function acquireSettingsRegistration(ctx) {
663
+ const settings = ctx.settings;
664
+ const owner = { settings };
665
+ let shared = settings[SHARED_SETTINGS];
666
+ if (shared === void 0) {
667
+ shared = {
668
+ owners: /* @__PURE__ */ new Set(),
669
+ registrationOwner: owner,
670
+ scope: void 0
671
+ };
672
+ Object.defineProperty(settings, SHARED_SETTINGS, {
673
+ configurable: true,
674
+ enumerable: false,
675
+ writable: false,
676
+ value: shared
677
+ });
678
+ }
679
+ shared.owners.add(owner);
680
+ const state = shared;
681
+ ctx.effect(() => () => {
682
+ state.owners.delete(owner);
683
+ if (state.registrationOwner === owner && state.owners.size > 0) {
684
+ const next = state.owners.values().next().value;
685
+ state.registrationOwner = next;
686
+ state.scope = next.settings.register(CONTEXT_COMPRESSION_NAMESPACE, ContextCompressionSettingsSchema);
687
+ }
688
+ if (state.owners.size === 0 && settings[SHARED_SETTINGS] === state) Reflect.deleteProperty(settings, SHARED_SETTINGS);
689
+ }, "contextCompressionSelector.settingsLease()");
690
+ if (state.owners.size === 1) state.scope = settings.register(CONTEXT_COMPRESSION_NAMESPACE, ContextCompressionSettingsSchema);
691
+ }
692
+ //#endregion
693
+ export { Config, apply };