dsh-context-compression-improved 0.2.4 → 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.
- package/.gitattributes +2 -1
- package/.githooks/pre-push +37 -0
- package/.github/workflows/ci.yml +8 -8
- package/CHANGELOG.ja.md +169 -39
- package/CHANGELOG.ko.md +167 -39
- package/CHANGELOG.md +212 -16
- package/CHANGELOG.zh.md +152 -39
- package/CONTRIBUTING.md +22 -22
- package/README.ja.md +85 -104
- package/README.ko.md +85 -103
- package/README.md +1 -19
- package/README.zh.md +85 -101
- package/THIRD_PARTY_NOTICES.md +14 -14
- package/docs/compat-0.1.5-report.md +77 -0
- package/docs/installation.ja.md +78 -76
- package/docs/installation.ko.md +78 -76
- package/docs/installation.md +103 -76
- package/docs/installation.zh.md +100 -76
- package/docs/repair-log.md +657 -582
- package/eslint.config.js +30 -30
- package/package.json +75 -54
- package/packages/selector/README.md +7 -12
- package/packages/selector/README.zh.md +6 -13
- package/packages/selector/THIRD_PARTY_NOTICES.md +32 -38
- package/packages/selector/cordis.patch.yml +27 -19
- package/packages/selector/dsh.plugin.json +16 -16
- package/packages/selector/lib/client.d.ts +97 -5
- package/packages/selector/lib/client.js +1884 -92
- package/packages/selector/lib/config.js +863 -6
- package/packages/selector/lib/index.d.ts +29 -21
- package/packages/selector/lib/index.js +424 -18
- package/packages/selector/lib/invariant.js +4 -4
- package/packages/selector/lib/pruner.d.ts +179 -4
- package/packages/selector/lib/pruner.js +1406 -371
- package/packages/selector/lib/style.css +42 -0
- package/packages/selector/lib/tail-trim.js +13 -4
- package/packages/selector/package.json +18 -27
- package/packages/selector/screenshots.json +3 -6
- package/packages/selector/src/client/CompressionProfileControls.tsx +293 -229
- package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
- package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -79
- package/packages/selector/src/client/EstimatorControls.tsx +277 -281
- package/packages/selector/src/client/decode.ts +57 -49
- package/packages/selector/src/client/index.ts +200 -62
- package/packages/selector/src/client/locales/de.ts +141 -0
- package/packages/selector/src/client/locales/es.ts +141 -0
- package/packages/selector/src/client/locales/fr.ts +141 -0
- package/packages/selector/src/client/locales/it.ts +141 -0
- package/packages/selector/src/client/locales/ja.ts +141 -0
- package/packages/selector/src/client/locales/ko.ts +141 -0
- package/packages/selector/src/client/locales/ru.ts +141 -0
- package/packages/selector/src/client/locales.ts +282 -198
- package/packages/selector/src/client/monitor-fab.ts +336 -0
- package/packages/selector/src/client/preset-options.ts +88 -70
- package/packages/selector/src/client/savings-card.tsx +150 -0
- package/packages/selector/src/client/settings-section.tsx +140 -126
- package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -210
- package/packages/selector/src/index.ts +671 -327
- package/packages/selector/src/invariant.ts +113 -113
- package/packages/selector/src/profiles.ts +431 -342
- package/packages/selector/src/pruner/state.ts +57 -43
- package/packages/selector/src/pruner.ts +2736 -2154
- package/packages/selector/src/runtime/audit.ts +303 -231
- package/packages/selector/src/runtime/config.ts +756 -642
- package/packages/selector/src/runtime/measurement.ts +436 -432
- package/packages/selector/src/runtime/monitor.ts +235 -0
- package/packages/selector/src/runtime/retrieve.ts +479 -457
- package/packages/selector/src/runtime/savings.ts +337 -0
- package/packages/selector/src/runtime/session-events.ts +30 -17
- package/packages/selector/src/runtime/summary-command.ts +127 -0
- package/packages/selector/src/runtime/tail-trim.ts +166 -166
- package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
- package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
- package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
- package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
- package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -183
- package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
- package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
- package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
- package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
- package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -275
- package/packages/selector/src/runtime/types.ts +365 -325
- package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
- package/packages/selector/tests/auto-compact.client.spec.tsx +214 -226
- package/packages/selector/tests/built/client-artifact.spec.ts +59 -51
- package/packages/selector/tests/code-skeleton.client.spec.ts +91 -88
- package/packages/selector/tests/custom-contract.client.spec.ts +205 -202
- package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -247
- package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -176
- package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -204
- package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
- package/packages/selector/tests/preset-options-write.client.spec.ts +207 -181
- package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -196
- package/packages/selector/tests/preset-overlay.host.spec.ts +8 -18
- package/packages/selector/tests/profiles.client.spec.tsx +436 -434
- package/packages/selector/tests/public/package-contract.client.spec.ts +78 -33
- package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -0
- package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
- package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
- package/packages/selector/tests/runtime/audit.spec.ts +275 -172
- package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
- package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
- package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
- package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
- package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2702
- package/packages/selector/tests/runtime/savings.spec.ts +120 -0
- package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
- package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
- package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
- package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -56
- package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -100
- package/packages/selector/tests/settings-seat.client.spec.ts +130 -0
- package/packages/selector/tests/standing-generation.host.spec.ts +142 -87
- package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -250
- package/pnpm-workspace.yaml +66 -19
- package/scripts/capture-profile-baseline.mjs +42 -0
- package/scripts/generate-tokenizer-fixtures.py +81 -81
- package/scripts/generate-vision-fixtures.py +208 -208
- package/scripts/{packed-components-smoke.ts → packed-components-smoke.mjs} +732 -713
- package/scripts/{packed-install-e2e.ts → packed-install-e2e.mjs} +1273 -1072
- package/scripts/toolclass-corpus-replay.mjs +281 -273
- package/scripts/{verify-release.ts → verify-release.mjs} +318 -300
- package/tests/TEST_INVENTORY.md +41 -42
- package/scripts/capture-profile-baseline.ts +0 -80
- package/tsconfig.scripts.json +0 -13
- /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-profiles.jpg +0 -0
- /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-settings.png +0 -0
|
@@ -1,38 +1,46 @@
|
|
|
1
1
|
import z from "@deepseek-ai/schemastery";
|
|
2
2
|
import { Context } from "@deepseek-ai/cordis";
|
|
3
3
|
//#region src/index.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Floating-panel monitor route (`GET|POST .../monitor?sessionId=…`):
|
|
6
|
+
* - GET → the monitor snapshot (savings aggregate + intent control block +
|
|
7
|
+
* pricing) — the payload shape the panel polls;
|
|
8
|
+
* - POST → session override action (`{"action":"on"|"off"|"clear"}`),
|
|
9
|
+
* driving the exact state machine `/ctx-summary` drives.
|
|
10
|
+
* Registration mirrors the savings route (webServer gate alone, dual channels,
|
|
11
|
+
* single guarded registration); the handler branches on `req.method` because
|
|
12
|
+
* the registration surface is method-agnostic.
|
|
13
|
+
*/
|
|
14
|
+
/** Exported for the runtime monitor spec; the entry owns all webServer wiring. */
|
|
15
|
+
declare function registerMonitorRoute(ctx: Context): void;
|
|
4
16
|
/** Standalone Bundle behavior; the settings/UI owner remains safe when false. */
|
|
5
17
|
interface Config {
|
|
6
18
|
/** Add the canonical compression stack to every non-Minimal preset. */
|
|
7
19
|
presetOverlay?: boolean;
|
|
8
20
|
/**
|
|
9
|
-
*
|
|
10
|
-
* `inject: [webServer]`.
|
|
21
|
+
* Register the estimator-catalog HTTP route on this row.
|
|
11
22
|
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
* fiber is active (`state === 2`), never the caller's `inject` list. The one
|
|
20
|
-
* inject-gated path is the `ctx.webServer` **property** access, which this
|
|
21
|
-
* plugin never uses: `registerEstimatorCatalogRoute` uses `ctx.get` plus its
|
|
22
|
-
* own `ctx.inject(['webServer'], …)`.
|
|
23
|
-
*
|
|
24
|
-
* So the row-level `inject` is **not load-bearing**; it is kept as
|
|
25
|
-
* belt-and-braces so the route row stays inactive until `webServer` exists,
|
|
26
|
-
* and the flag keeps the route off standalone Bundle rows on profiles that
|
|
27
|
-
* have no web server. The internal two-channel registration is what actually
|
|
28
|
-
* covers both arrival orders. Do not cite this comment as a rule to the
|
|
29
|
-
* 0.1.5 replay — cite the host source.
|
|
23
|
+
* The standalone Bundle patch sets this on its own row (which declares
|
|
24
|
+
* `inject: [webServer]`), so profiles without a host web server never mount a
|
|
25
|
+
* row that could only announce a pending route. The row-level `inject` is
|
|
26
|
+
* belt-and-braces: `dsh-host-webserver.register` performs no authorization
|
|
27
|
+
* check and `ctx.get(name)` only asks whether the providing fiber is active,
|
|
28
|
+
* so the two-channel registration inside this function is what actually
|
|
29
|
+
* covers both arrival orders.
|
|
30
30
|
*/
|
|
31
31
|
estimatorCatalogRoute?: boolean;
|
|
32
|
+
/**
|
|
33
|
+
* Register the advisory advisor's read-only HTTP report route (decay
|
|
34
|
+
* figure, task summary, score distribution, last benefit-model advice).
|
|
35
|
+
* Same Bundle opt-in semantics as `estimatorCatalogRoute`; the advisor
|
|
36
|
+
* itself stays off until the user turns it on through the
|
|
37
|
+
* `presetOptions.advisor*` settings keys.
|
|
38
|
+
*/
|
|
39
|
+
advisorReportRoute?: boolean;
|
|
32
40
|
}
|
|
33
41
|
/** Loader validation for the standalone Bundle opt-in. */
|
|
34
42
|
declare const Config: z<Config>;
|
|
35
43
|
/** Register the persisted default read by the currently mounted root pruner. */
|
|
36
44
|
declare function apply(ctx: Context, config?: Config): void;
|
|
37
45
|
//#endregion
|
|
38
|
-
export { Config, apply };
|
|
46
|
+
export { Config, apply, registerMonitorRoute };
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { n as CONTEXT_COMPRESSION_SETTINGS_NAMESPACE, r as ContextCompressionSettingsSchema } from "./config.js";
|
|
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
2
|
import z from "@deepseek-ai/schemastery";
|
|
3
3
|
import "@deepseek-ai/dsh-settings";
|
|
4
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
5
4
|
import { createHash } from "node:crypto";
|
|
5
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
6
6
|
import { chmod, mkdtemp, readFile, rename, rm, stat, utimes, writeFile } from "node:fs/promises";
|
|
7
7
|
import { tmpdir } from "node:os";
|
|
8
8
|
import { isAbsolute, join } from "node:path";
|
|
@@ -76,6 +76,96 @@ async function buildEstimatorCatalog(deps) {
|
|
|
76
76
|
};
|
|
77
77
|
}
|
|
78
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
|
|
79
169
|
//#region src/preset-overlay.ts
|
|
80
170
|
/** Plugin-owned, reversible compression overlays for native agent presets. */
|
|
81
171
|
/**
|
|
@@ -503,29 +593,143 @@ function restoreMethod(presets, snapshot) {
|
|
|
503
593
|
}
|
|
504
594
|
//#endregion
|
|
505
595
|
//#region src/index.ts
|
|
596
|
+
const CONTEXT_COMPRESSION_NAMESPACE = CONTEXT_COMPRESSION_SETTINGS_NAMESPACE;
|
|
506
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
|
+
}
|
|
507
717
|
/**
|
|
508
718
|
* The one service the catalog route actually needs. `llm` and
|
|
509
719
|
* `agentDefaultModel` are payload enrichment the handler resolves per request,
|
|
510
720
|
* never reasons to withhold the route.
|
|
511
721
|
*/
|
|
512
722
|
const ESTIMATOR_CATALOG_ROUTE_DEPS = ["webServer"];
|
|
723
|
+
/** The estimator-side service the catalog handler enriches its response with. */
|
|
513
724
|
function asWebServer(value) {
|
|
514
|
-
if (typeof value
|
|
515
|
-
return value;
|
|
725
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
726
|
+
return typeof value.register === "function" ? value : void 0;
|
|
516
727
|
}
|
|
517
728
|
/**
|
|
518
729
|
* Serve `GET /api/dsh-context-compression-improved/estimator-catalog` — the
|
|
519
730
|
* settings card's host-route dropdowns (live provider/model groups from the DSH
|
|
520
|
-
* `llm` service plus the effective selection).
|
|
521
|
-
* plugin
|
|
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.)
|
|
731
|
+
* `llm` service plus the effective selection). Best effort: without the
|
|
732
|
+
* `webServer` service the plugin keeps working, only the HTTP API is missing.
|
|
529
733
|
*
|
|
530
734
|
* The route gates on `webServer` **alone**. `llm` and `agentDefaultModel` only
|
|
531
735
|
* enrich the response and are resolved per request, so listing them here would
|
|
@@ -609,13 +813,209 @@ function registerEstimatorCatalogRoute(ctx) {
|
|
|
609
813
|
});
|
|
610
814
|
log("warn", "context-compression webServer not active yet — estimator catalog route pending: %s", ESTIMATOR_CATALOG_ROUTES.join(", "));
|
|
611
815
|
}
|
|
612
|
-
|
|
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
|
+
}
|
|
613
1012
|
/** Symbol properties reach the shared service target through Cordis proxies. */
|
|
614
1013
|
const SHARED_SETTINGS = Symbol.for("dsh-context-compression-improved/settings-registration");
|
|
615
1014
|
/** Loader validation for the standalone Bundle opt-in. */
|
|
616
1015
|
const Config = z.object({
|
|
617
1016
|
presetOverlay: z.boolean().default(false),
|
|
618
|
-
estimatorCatalogRoute: z.boolean().default(false)
|
|
1017
|
+
estimatorCatalogRoute: z.boolean().default(false),
|
|
1018
|
+
advisorReportRoute: z.boolean().default(false)
|
|
619
1019
|
});
|
|
620
1020
|
/** Register the persisted default read by the currently mounted root pruner. */
|
|
621
1021
|
function apply(ctx, config = {}) {
|
|
@@ -624,6 +1024,10 @@ function apply(ctx, config = {}) {
|
|
|
624
1024
|
acquireSettingsRegistration(settingsCtx);
|
|
625
1025
|
});
|
|
626
1026
|
if (config.estimatorCatalogRoute === true) registerEstimatorCatalogRoute(ctx);
|
|
1027
|
+
registerSavingsRoute(ctx);
|
|
1028
|
+
registerMonitorRoute(ctx);
|
|
1029
|
+
if (config.advisorReportRoute === true) registerAdvisorReportRoute(ctx);
|
|
1030
|
+
registerSummaryCommand(ctx);
|
|
627
1031
|
if (config.presetOverlay !== true) return;
|
|
628
1032
|
ctx.inject(["agentPresets"], (presetsCtx) => {
|
|
629
1033
|
const installation = decorateAgentPresets(presetsCtx.agentPresets, {
|
|
@@ -634,7 +1038,7 @@ function apply(ctx, config = {}) {
|
|
|
634
1038
|
presetsCtx.effect(() => () => installation.dispose(), "contextCompressionSelector.agentPresets()");
|
|
635
1039
|
});
|
|
636
1040
|
} catch (error) {
|
|
637
|
-
console.error("context-compression apply
|
|
1041
|
+
console.error("context-compression selector apply failed: %o", error);
|
|
638
1042
|
throw error;
|
|
639
1043
|
}
|
|
640
1044
|
}
|
|
@@ -646,7 +1050,9 @@ function apply(ctx, config = {}) {
|
|
|
646
1050
|
function resolveAutoCompactThresholdPercent(presetsCtx) {
|
|
647
1051
|
const raw = presetsCtx.get("settings")?.get(CONTEXT_COMPRESSION_NAMESPACE);
|
|
648
1052
|
try {
|
|
649
|
-
|
|
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;
|
|
650
1056
|
} catch {
|
|
651
1057
|
return 80;
|
|
652
1058
|
}
|
|
@@ -690,4 +1096,4 @@ function acquireSettingsRegistration(ctx) {
|
|
|
690
1096
|
if (state.owners.size === 1) state.scope = settings.register(CONTEXT_COMPRESSION_NAMESPACE, ContextCompressionSettingsSchema);
|
|
691
1097
|
}
|
|
692
1098
|
//#endregion
|
|
693
|
-
export { Config, apply };
|
|
1099
|
+
export { Config, apply, registerMonitorRoute };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as validatePublishedTailTrim,
|
|
1
|
+
import { a as validatePublishedTailTrim, s as sessionEvents } from "./tail-trim.js";
|
|
2
2
|
//#region src/invariant.ts
|
|
3
3
|
const PACKAGE_NAME = "dsh-context-compression-improved-runtime";
|
|
4
4
|
/** Cordis companion plugin name. */
|
|
@@ -9,14 +9,14 @@ const inject = ["invariants"];
|
|
|
9
9
|
function resemblesCompanion(prune, event) {
|
|
10
10
|
if (event.type !== "tool/result" && event.type !== "user/message" || typeof event.surfaceOp !== "object") return false;
|
|
11
11
|
const sources = new Set(event.sourceEventSeqs ?? []);
|
|
12
|
-
return event.surfaceOp.
|
|
12
|
+
return event.surfaceOp.startSeq === prune.data.shadowedRange.start && event.surfaceOp.endSeq === prune.data.shadowedRange.end || prune.data.shadowedSeqs.some((seq) => sources.has(seq));
|
|
13
13
|
}
|
|
14
14
|
/** Validate one standard prune's immediately adjacent surface replacement. */
|
|
15
15
|
function validateCompanion(session, prune, event, fail) {
|
|
16
16
|
if (event.type !== "tool/result" && event.type !== "user/message" || typeof event.surfaceOp !== "object") fail(`compaction/prune at seq ${prune.seq} must be immediately followed by a replacement surface event`);
|
|
17
17
|
const { shadowedRange, shadowedSeqs } = prune.data;
|
|
18
|
-
if (shadowedSeqs.length === 0 || shadowedSeqs[0] !== shadowedRange.start || shadowedSeqs.at(-1) !== shadowedRange.end) fail(`compaction/prune at seq ${prune.seq} has a shadowed range inconsistent with shadowedSeqs`);
|
|
19
|
-
if (event.surfaceOp.
|
|
18
|
+
if (shadowedSeqs.length === 0 || shadowedSeqs[0] !== Number(shadowedRange.start) || shadowedSeqs.at(-1) !== Number(shadowedRange.end)) fail(`compaction/prune at seq ${prune.seq} has a shadowed range inconsistent with shadowedSeqs`);
|
|
19
|
+
if (event.surfaceOp.startSeq !== shadowedRange.start || event.surfaceOp.endSeq !== shadowedRange.end) fail(`replacement at seq ${event.seq} does not replace compaction/prune range ${shadowedRange.start}-${shadowedRange.end}`);
|
|
20
20
|
const sources = new Set(event.sourceEventSeqs ?? []);
|
|
21
21
|
const missing = shadowedSeqs.filter((seq) => !sources.has(seq));
|
|
22
22
|
if (missing.length > 0) fail(`replacement at seq ${event.seq} omits shadowed source seqs ${missing.join(", ")}`);
|