dsh-context-compression-improved 0.8.0-beta.3 → 0.8.0-beta.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/CHANGELOG.md +20 -0
- package/eslint.config.js +30 -30
- package/package.json +163 -163
- package/packages/selector/dsh.plugin.json +16 -16
- package/packages/selector/lib/client.d.ts +28 -0
- package/packages/selector/lib/client.js +631 -7
- package/packages/selector/lib/{advisor-state.js → config.js} +170 -65
- package/packages/selector/lib/index.d.ts +13 -1
- package/packages/selector/lib/index.js +306 -50
- package/packages/selector/lib/profiles.d.ts +15 -0
- package/packages/selector/lib/pruner.d.ts +65 -0
- package/packages/selector/lib/pruner.js +408 -5
- package/packages/selector/src/client/CompressionProfileControls.tsx +67 -0
- package/packages/selector/src/client/CompressionProfileSelector.tsx +2 -0
- package/packages/selector/src/client/decode.ts +57 -49
- package/packages/selector/src/client/index.ts +41 -0
- package/packages/selector/src/client/locales/de.ts +26 -0
- package/packages/selector/src/client/locales/es.ts +26 -0
- package/packages/selector/src/client/locales/fr.ts +26 -0
- package/packages/selector/src/client/locales/it.ts +26 -0
- package/packages/selector/src/client/locales/ja.ts +26 -0
- package/packages/selector/src/client/locales/ko.ts +26 -0
- package/packages/selector/src/client/locales/ru.ts +26 -0
- package/packages/selector/src/client/locales.ts +52 -0
- package/packages/selector/src/client/monitor-fab.ts +307 -0
- package/packages/selector/src/client/settings-section.tsx +16 -2
- package/packages/selector/src/index.ts +133 -60
- package/packages/selector/src/profiles.ts +431 -394
- package/packages/selector/src/pruner/state.ts +57 -50
- package/packages/selector/src/pruner.ts +241 -1
- package/packages/selector/src/runtime/audit.ts +303 -286
- package/packages/selector/src/runtime/config.ts +756 -706
- package/packages/selector/src/runtime/monitor.ts +149 -0
- package/packages/selector/src/runtime/summary-command.ts +127 -0
- package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -188
- package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -149
- 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/types.ts +365 -346
- package/packages/selector/tests/auto-compact.client.spec.tsx +214 -213
- package/packages/selector/tests/code-skeleton.client.spec.ts +94 -93
- package/packages/selector/tests/custom-contract.client.spec.ts +223 -222
- package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -252
- package/packages/selector/tests/estimator-route-registration.host.spec.ts +8 -6
- package/packages/selector/tests/monitor-fab.client.spec.ts +117 -0
- package/packages/selector/tests/preset-options-write.client.spec.ts +188 -187
- package/packages/selector/tests/profiles.client.spec.tsx +436 -434
- package/packages/selector/tests/runtime/audit.spec.ts +275 -274
- 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 +236 -0
- package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2734 -2731
- package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
- package/packages/selector/tests/settings-seat.client.spec.ts +1 -1
- package/scripts/packed-install-e2e.mjs +1 -1
- package/scripts/verify-release.mjs +2 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { D as priceOfficialDeepSeekUsage,
|
|
1
|
+
import { D as getSummaryOverride, E as getObservedIntentEnabled, I as priceOfficialDeepSeekUsage, N as setSummaryOverride, R as getSavingsLedger, S as INTENT_GATE_GROWTH_TOKENS, T as getLastIntentFold, a as DEFAULT_CONTEXT_COMPRESSION_SETTINGS, w as getAdvisorState, x as INTENT_GATE_FLOOR_FRACTION } from "./config.js";
|
|
2
2
|
import z from "@deepseek-ai/schemastery";
|
|
3
3
|
import { createHash } from "node:crypto";
|
|
4
4
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
@@ -75,6 +75,180 @@ async function buildEstimatorCatalog(deps) {
|
|
|
75
75
|
};
|
|
76
76
|
}
|
|
77
77
|
//#endregion
|
|
78
|
+
//#region src/runtime/monitor.ts
|
|
79
|
+
/**
|
|
80
|
+
* Savings snapshot plus the intent-summary control block. Ledger is
|
|
81
|
+
* injectable so tests seed a private instance instead of the process
|
|
82
|
+
* singleton.
|
|
83
|
+
*/
|
|
84
|
+
function buildMonitorSnapshot(sessionId, ledger = getSavingsLedger()) {
|
|
85
|
+
const override = getSummaryOverride(sessionId ?? "");
|
|
86
|
+
return {
|
|
87
|
+
...ledger.snapshot(sessionId),
|
|
88
|
+
intent: {
|
|
89
|
+
override,
|
|
90
|
+
observedEnabled: getObservedIntentEnabled(sessionId ?? ""),
|
|
91
|
+
gate: {
|
|
92
|
+
floorFraction: INTENT_GATE_FLOOR_FRACTION,
|
|
93
|
+
growthTokens: INTENT_GATE_GROWTH_TOKENS
|
|
94
|
+
},
|
|
95
|
+
lastFold: getLastIntentFold(sessionId ?? "")
|
|
96
|
+
},
|
|
97
|
+
sessionScope: sessionId ?? null
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
function isSessionOverrideAction(value) {
|
|
101
|
+
return value === "on" || value === "off" || value === "clear";
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Drive the `/ctx-summary` override state machine: `on`/`off` pin the
|
|
105
|
+
* session, `clear` returns it to settings-driven. The resulting override is
|
|
106
|
+
* handed back so the route can echo the post-action truth.
|
|
107
|
+
*/
|
|
108
|
+
function applySessionOverride(sessionId, action) {
|
|
109
|
+
setSummaryOverride(sessionId, action === "clear" ? void 0 : action);
|
|
110
|
+
return { override: getSummaryOverride(sessionId) };
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* 金额估算(monitor 口径的 token/金额估算,结合官方牌价):
|
|
114
|
+
* - actualCost:本进程累计真实 usage 的官方牌价(exact/range);
|
|
115
|
+
* - estimatedSavedCost:净节省(精确口径)按 cache-miss 输入价折算——
|
|
116
|
+
* 基线假设"这些 token 不压缩就要全价进上下文",标注估算。
|
|
117
|
+
* 仅官方 deepseek-official 路由可解;第三方/未知模型 fail-closed 为 undefined。
|
|
118
|
+
* (自入口迁入: savings 路由与 monitor 路由共享,避免 runtime → entry 回环。)
|
|
119
|
+
*/
|
|
120
|
+
function estimateSavingsPricing(readService, snapshot) {
|
|
121
|
+
if (snapshot.usage.requests === 0 && snapshot.net.exact === 0) return void 0;
|
|
122
|
+
const selection = readService("agentDefaultModel")?.currentSelection?.();
|
|
123
|
+
const provider = typeof selection?.provider === "string" ? selection.provider : "";
|
|
124
|
+
const modelId = typeof selection?.model === "string" ? selection.model : "";
|
|
125
|
+
if (provider !== "deepseek-official") return void 0;
|
|
126
|
+
const now = /* @__PURE__ */ new Date();
|
|
127
|
+
const startedAt = new Date(snapshot.startedAt);
|
|
128
|
+
const base = {
|
|
129
|
+
provider,
|
|
130
|
+
baseUrlClass: "official-public",
|
|
131
|
+
apiRoute: "chat-completions",
|
|
132
|
+
modelId,
|
|
133
|
+
currency: "USD",
|
|
134
|
+
startedAt,
|
|
135
|
+
completedAt: now.getTime() > startedAt.getTime() ? now : new Date(startedAt.getTime() + 1)
|
|
136
|
+
};
|
|
137
|
+
const actual = priceOfficialDeepSeekUsage({
|
|
138
|
+
...base,
|
|
139
|
+
usage: {
|
|
140
|
+
cacheReadTokens: Math.max(0, Math.round(snapshot.usage.cacheReadTokens)),
|
|
141
|
+
cacheMissTokens: Math.max(0, Math.round(snapshot.usage.inputTokens)),
|
|
142
|
+
outputTokens: Math.max(0, Math.round(snapshot.usage.outputTokens))
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
const saved = snapshot.net.exact > 0 ? priceOfficialDeepSeekUsage({
|
|
146
|
+
...base,
|
|
147
|
+
usage: {
|
|
148
|
+
cacheReadTokens: 0,
|
|
149
|
+
cacheMissTokens: Math.round(snapshot.net.exact),
|
|
150
|
+
outputTokens: 0
|
|
151
|
+
}
|
|
152
|
+
}) : void 0;
|
|
153
|
+
const decimalOf = (cost) => cost.kind === "exact" ? cost.decimal : cost.kind === "range" ? cost.minimum.decimal : void 0;
|
|
154
|
+
if (actual.kind === "unpriced" && (saved === void 0 || saved.kind === "unpriced")) return void 0;
|
|
155
|
+
return {
|
|
156
|
+
currency: "USD",
|
|
157
|
+
...actual.kind === "unpriced" ? {} : { actualCost: decimalOf(actual) },
|
|
158
|
+
...saved === void 0 || saved.kind === "unpriced" ? {} : { estimatedSavedCost: decimalOf(saved) }
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
//#endregion
|
|
162
|
+
//#region src/runtime/summary-command.ts
|
|
163
|
+
const SUMMARY_COMMAND_NAME = "ctx-summary";
|
|
164
|
+
const USAGE = "Usage: /ctx-summary off|on|status";
|
|
165
|
+
/** Parse the raw argument string; `undefined` = unrecognized (usage error). */
|
|
166
|
+
function parseSummaryCommandArgs(rawInput) {
|
|
167
|
+
const token = rawInput.trim().toLowerCase();
|
|
168
|
+
if (token === "off" || token === "on" || token === "status") return token;
|
|
169
|
+
}
|
|
170
|
+
function describeFold(sessionId) {
|
|
171
|
+
const fold = getLastIntentFold(sessionId);
|
|
172
|
+
if (fold === void 0) return "none";
|
|
173
|
+
return `turn ${fold.turn}, seq ${fold.startSeq}..${fold.endSeq}`;
|
|
174
|
+
}
|
|
175
|
+
/** Human-facing status line; observability only, never a decision input. */
|
|
176
|
+
function formatSummaryStatus(sessionId) {
|
|
177
|
+
const override = getSummaryOverride(sessionId);
|
|
178
|
+
const enabled = getObservedIntentEnabled(sessionId);
|
|
179
|
+
const enabledText = enabled === void 0 ? "unknown (gate not evaluated yet)" : enabled ? "yes" : "no";
|
|
180
|
+
return [
|
|
181
|
+
`ctx-summary status:`,
|
|
182
|
+
` override: ${override ?? "default (settings-driven)"}`,
|
|
183
|
+
` intentSummary enabled (settings): ${enabledText}`,
|
|
184
|
+
` gate: floor >${Math.round(INTENT_GATE_FLOOR_FRACTION * 100)}% of window AND growth >${INTENT_GATE_GROWTH_TOKENS} tokens since last fold`,
|
|
185
|
+
` last fold: ${describeFold(sessionId)}`
|
|
186
|
+
].join("\n");
|
|
187
|
+
}
|
|
188
|
+
/** Resolve the invoking agent's session id (`''` when the host exposes none). */
|
|
189
|
+
function sessionIdOf(agent) {
|
|
190
|
+
const session = agent?.session;
|
|
191
|
+
if (session === void 0 || session.id === void 0 || session.id === null) return "";
|
|
192
|
+
return String(session.id);
|
|
193
|
+
}
|
|
194
|
+
/** Best-effort `CommandDefinitionId` brand; `undefined` on stripped hosts (registered without it). */
|
|
195
|
+
async function loadCommandDefinitionId() {
|
|
196
|
+
try {
|
|
197
|
+
return (await import("@deepseek-ai/dsh-commands")).CommandDefinitionId;
|
|
198
|
+
} catch {
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Mount `/ctx-summary` for every composed human-command adapter. Never
|
|
204
|
+
* throws: the command is a convenience surface, and a host without the
|
|
205
|
+
* commands service (or with an incompatible registry shape) simply runs
|
|
206
|
+
* without it.
|
|
207
|
+
*/
|
|
208
|
+
function registerSummaryCommand(ctx) {
|
|
209
|
+
ctx.inject(["commands"], (injected) => {
|
|
210
|
+
const commands = injected.commands;
|
|
211
|
+
if (commands === void 0 || typeof commands.register !== "function") return;
|
|
212
|
+
(async () => {
|
|
213
|
+
try {
|
|
214
|
+
const definitionId = await loadCommandDefinitionId();
|
|
215
|
+
await commands.register({
|
|
216
|
+
name: SUMMARY_COMMAND_NAME,
|
|
217
|
+
description: "Turn-tail intent summary: temporarily disable/resume or inspect status",
|
|
218
|
+
...definitionId === void 0 ? {} : { definitionId: definitionId("dsh-context-compression-improved/ctx-summary") },
|
|
219
|
+
handler: async (invocation) => {
|
|
220
|
+
const args = parseSummaryCommandArgs(typeof invocation.rawInput === "string" ? invocation.rawInput : "");
|
|
221
|
+
if (args === void 0) return {
|
|
222
|
+
kind: "error",
|
|
223
|
+
text: USAGE
|
|
224
|
+
};
|
|
225
|
+
const sessionId = sessionIdOf(invocation.agent);
|
|
226
|
+
if (args === "status") {
|
|
227
|
+
if (sessionId === "") return {
|
|
228
|
+
kind: "error",
|
|
229
|
+
text: "ctx-summary: no session is attached to this invocation"
|
|
230
|
+
};
|
|
231
|
+
return {
|
|
232
|
+
kind: "success",
|
|
233
|
+
text: formatSummaryStatus(sessionId)
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
if (sessionId === "") return {
|
|
237
|
+
kind: "error",
|
|
238
|
+
text: "ctx-summary: no session is attached to this invocation"
|
|
239
|
+
};
|
|
240
|
+
setSummaryOverride(sessionId, args);
|
|
241
|
+
return {
|
|
242
|
+
kind: "success",
|
|
243
|
+
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)"
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
});
|
|
247
|
+
} catch {}
|
|
248
|
+
})();
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
//#endregion
|
|
78
252
|
//#region src/preset-overlay.ts
|
|
79
253
|
/** Plugin-owned, reversible compression overlays for native agent presets. */
|
|
80
254
|
/**
|
|
@@ -505,6 +679,7 @@ function restoreMethod(presets, snapshot) {
|
|
|
505
679
|
const ESTIMATOR_CATALOG_ROUTES = ["/endpoint/dsh-context-compression-improved/estimator-catalog", "/api/dsh-context-compression-improved/estimator-catalog"];
|
|
506
680
|
const ADVISOR_REPORT_ROUTES = ["/endpoint/dsh-context-compression-improved/advisor-report", "/api/dsh-context-compression-improved/advisor-report"];
|
|
507
681
|
const SAVINGS_ROUTES = ["/endpoint/dsh-context-compression-improved/savings", "/api/dsh-context-compression-improved/savings"];
|
|
682
|
+
const MONITOR_ROUTES = ["/endpoint/dsh-context-compression-improved/monitor", "/api/dsh-context-compression-improved/monitor"];
|
|
508
683
|
function sessionFor(readService, sessionId) {
|
|
509
684
|
const agents = readService("agents");
|
|
510
685
|
return typeof agents?.get === "function" ? agents.get(sessionId)?.session : void 0;
|
|
@@ -627,6 +802,7 @@ function registerAdvisorReportRoute(ctx) {
|
|
|
627
802
|
* never reasons to withhold the route.
|
|
628
803
|
*/
|
|
629
804
|
const ESTIMATOR_CATALOG_ROUTE_DEPS = ["webServer"];
|
|
805
|
+
/** The estimator-side service the catalog handler enriches its response with. */
|
|
630
806
|
function asWebServer(value) {
|
|
631
807
|
if (typeof value !== "object" || value === null) return void 0;
|
|
632
808
|
return typeof value.register === "function" ? value : void 0;
|
|
@@ -720,54 +896,6 @@ function registerEstimatorCatalogRoute(ctx) {
|
|
|
720
896
|
log("warn", "context-compression webServer not active yet — estimator catalog route pending: %s", ESTIMATOR_CATALOG_ROUTES.join(", "));
|
|
721
897
|
}
|
|
722
898
|
/**
|
|
723
|
-
* 金额估算(monitor 口径的 token/金额估算,结合官方牌价):
|
|
724
|
-
* - actualCost:本进程累计真实 usage 的官方牌价(exact/range);
|
|
725
|
-
* - estimatedSavedCost:净节省(精确口径)按 cache-miss 输入价折算——
|
|
726
|
-
* 基线假设"这些 token 不压缩就要全价进上下文",标注估算。
|
|
727
|
-
* 仅官方 deepseek-official 路由可解;第三方/未知模型 fail-closed 为 undefined。
|
|
728
|
-
*/
|
|
729
|
-
function estimateSavingsPricing(readService, snapshot) {
|
|
730
|
-
if (snapshot.usage.requests === 0 && snapshot.net.exact === 0) return void 0;
|
|
731
|
-
const selection = readService("agentDefaultModel")?.currentSelection?.();
|
|
732
|
-
const provider = typeof selection?.provider === "string" ? selection.provider : "";
|
|
733
|
-
const modelId = typeof selection?.model === "string" ? selection.model : "";
|
|
734
|
-
if (provider !== "deepseek-official") return void 0;
|
|
735
|
-
const now = /* @__PURE__ */ new Date();
|
|
736
|
-
const startedAt = new Date(snapshot.startedAt);
|
|
737
|
-
const base = {
|
|
738
|
-
provider,
|
|
739
|
-
baseUrlClass: "official-public",
|
|
740
|
-
apiRoute: "chat-completions",
|
|
741
|
-
modelId,
|
|
742
|
-
currency: "USD",
|
|
743
|
-
startedAt,
|
|
744
|
-
completedAt: now.getTime() > startedAt.getTime() ? now : new Date(startedAt.getTime() + 1)
|
|
745
|
-
};
|
|
746
|
-
const actual = priceOfficialDeepSeekUsage({
|
|
747
|
-
...base,
|
|
748
|
-
usage: {
|
|
749
|
-
cacheReadTokens: Math.max(0, Math.round(snapshot.usage.cacheReadTokens)),
|
|
750
|
-
cacheMissTokens: Math.max(0, Math.round(snapshot.usage.inputTokens)),
|
|
751
|
-
outputTokens: Math.max(0, Math.round(snapshot.usage.outputTokens))
|
|
752
|
-
}
|
|
753
|
-
});
|
|
754
|
-
const saved = snapshot.net.exact > 0 ? priceOfficialDeepSeekUsage({
|
|
755
|
-
...base,
|
|
756
|
-
usage: {
|
|
757
|
-
cacheReadTokens: 0,
|
|
758
|
-
cacheMissTokens: Math.round(snapshot.net.exact),
|
|
759
|
-
outputTokens: 0
|
|
760
|
-
}
|
|
761
|
-
}) : void 0;
|
|
762
|
-
const decimalOf = (cost) => cost.kind === "exact" ? cost.decimal : cost.kind === "range" ? cost.minimum.decimal : void 0;
|
|
763
|
-
if (actual.kind === "unpriced" && (saved === void 0 || saved.kind === "unpriced")) return void 0;
|
|
764
|
-
return {
|
|
765
|
-
currency: "USD",
|
|
766
|
-
...actual.kind === "unpriced" ? {} : { actualCost: decimalOf(actual) },
|
|
767
|
-
...saved === void 0 || saved.kind === "unpriced" ? {} : { estimatedSavedCost: decimalOf(saved) }
|
|
768
|
-
};
|
|
769
|
-
}
|
|
770
|
-
/**
|
|
771
899
|
* Read-only savings snapshot route (`GET .../savings?sessionId=…`): gross saved,
|
|
772
900
|
* offsets (negative savings — compressed content later re-read in full), and net,
|
|
773
901
|
* with exact-tokenizer and chars/4 bases reported separately and never merged.
|
|
@@ -838,6 +966,132 @@ function registerSavingsRoute(ctx) {
|
|
|
838
966
|
});
|
|
839
967
|
}
|
|
840
968
|
/**
|
|
969
|
+
* Floating-panel monitor route (`GET|POST .../monitor?sessionId=…`):
|
|
970
|
+
* - GET → the monitor snapshot (savings aggregate + intent control block +
|
|
971
|
+
* pricing) — the payload shape the panel polls;
|
|
972
|
+
* - POST → session override action (`{"action":"on"|"off"|"clear"}`),
|
|
973
|
+
* driving the exact state machine `/ctx-summary` drives.
|
|
974
|
+
* Registration mirrors the savings route (webServer gate alone, dual channels,
|
|
975
|
+
* single guarded registration); the handler branches on `req.method` because
|
|
976
|
+
* the registration surface is method-agnostic.
|
|
977
|
+
*/
|
|
978
|
+
/** Exported for the runtime monitor spec; the entry owns all webServer wiring. */
|
|
979
|
+
function registerMonitorRoute(ctx) {
|
|
980
|
+
const readService = (name) => {
|
|
981
|
+
try {
|
|
982
|
+
return ctx.get(name);
|
|
983
|
+
} catch {
|
|
984
|
+
return;
|
|
985
|
+
}
|
|
986
|
+
};
|
|
987
|
+
const log = (level, message, ...args) => {
|
|
988
|
+
console[level](message, ...args);
|
|
989
|
+
};
|
|
990
|
+
let registered = false;
|
|
991
|
+
const register = (webServer, channel) => {
|
|
992
|
+
if (registered) return;
|
|
993
|
+
const handler = (req, res) => {
|
|
994
|
+
const resTyped = res;
|
|
995
|
+
if (typeof resTyped?.writeHead !== "function" || typeof resTyped?.end !== "function") return;
|
|
996
|
+
let sessionId;
|
|
997
|
+
try {
|
|
998
|
+
const raw = new URL(String(req?.url ?? "/"), "http://localhost").searchParams.get("sessionId");
|
|
999
|
+
if (typeof raw === "string" && raw.length > 0 && raw.length <= 512) sessionId = raw;
|
|
1000
|
+
} catch {}
|
|
1001
|
+
if (String(req?.method ?? "GET").toUpperCase() === "POST") {
|
|
1002
|
+
const chunks = [];
|
|
1003
|
+
let size = 0;
|
|
1004
|
+
let done = false;
|
|
1005
|
+
const respond = (status, body) => {
|
|
1006
|
+
if (done) return;
|
|
1007
|
+
done = true;
|
|
1008
|
+
resTyped.writeHead(status, {
|
|
1009
|
+
"content-type": "application/json; charset=utf-8",
|
|
1010
|
+
"cache-control": "no-cache"
|
|
1011
|
+
});
|
|
1012
|
+
resTyped.end(JSON.stringify(body));
|
|
1013
|
+
};
|
|
1014
|
+
const reqTyped = req;
|
|
1015
|
+
if (typeof reqTyped?.on !== "function") {
|
|
1016
|
+
respond(400, {
|
|
1017
|
+
ok: false,
|
|
1018
|
+
error: "unreadable request body"
|
|
1019
|
+
});
|
|
1020
|
+
return;
|
|
1021
|
+
}
|
|
1022
|
+
reqTyped.on("data", (chunk) => {
|
|
1023
|
+
size += chunk?.length ?? 0;
|
|
1024
|
+
if (size <= 4096) chunks.push(Buffer.from(chunk ?? /* @__PURE__ */ new Uint8Array()));
|
|
1025
|
+
});
|
|
1026
|
+
reqTyped.on("end", () => {
|
|
1027
|
+
let action;
|
|
1028
|
+
try {
|
|
1029
|
+
action = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}").action;
|
|
1030
|
+
} catch {
|
|
1031
|
+
respond(400, {
|
|
1032
|
+
ok: false,
|
|
1033
|
+
error: "monitor override action must be JSON"
|
|
1034
|
+
});
|
|
1035
|
+
return;
|
|
1036
|
+
}
|
|
1037
|
+
if (!isSessionOverrideAction(action)) {
|
|
1038
|
+
respond(400, {
|
|
1039
|
+
ok: false,
|
|
1040
|
+
error: "monitor override action must be \"on\" | \"off\" | \"clear\""
|
|
1041
|
+
});
|
|
1042
|
+
return;
|
|
1043
|
+
}
|
|
1044
|
+
const { override } = applySessionOverride(sessionId ?? "", action);
|
|
1045
|
+
respond(200, {
|
|
1046
|
+
ok: true,
|
|
1047
|
+
override: override ?? null,
|
|
1048
|
+
sessionScope: sessionId ?? null
|
|
1049
|
+
});
|
|
1050
|
+
});
|
|
1051
|
+
return;
|
|
1052
|
+
}
|
|
1053
|
+
const snapshot = buildMonitorSnapshot(sessionId);
|
|
1054
|
+
const pricing = estimateSavingsPricing(readService, snapshot);
|
|
1055
|
+
resTyped.writeHead(200, {
|
|
1056
|
+
"content-type": "application/json; charset=utf-8",
|
|
1057
|
+
"cache-control": "no-cache"
|
|
1058
|
+
});
|
|
1059
|
+
resTyped.end(JSON.stringify({
|
|
1060
|
+
ok: true,
|
|
1061
|
+
...snapshot,
|
|
1062
|
+
...pricing === void 0 ? {} : { pricing }
|
|
1063
|
+
}));
|
|
1064
|
+
};
|
|
1065
|
+
try {
|
|
1066
|
+
const disposers = MONITOR_ROUTES.map((path) => webServer.register({
|
|
1067
|
+
kind: "exact",
|
|
1068
|
+
path,
|
|
1069
|
+
handler
|
|
1070
|
+
})).filter((off) => typeof off === "function");
|
|
1071
|
+
registered = true;
|
|
1072
|
+
ctx.effect(() => () => {
|
|
1073
|
+
for (const off of disposers) off();
|
|
1074
|
+
}, "contextCompressionSelector.monitor route");
|
|
1075
|
+
log("info", "context-compression monitor route registered (%s): %s", channel, MONITOR_ROUTES.join(", "));
|
|
1076
|
+
} catch (error) {
|
|
1077
|
+
log("warn", "context-compression monitor route registration failed (%s): %o", channel, error);
|
|
1078
|
+
}
|
|
1079
|
+
};
|
|
1080
|
+
const active = asWebServer(readService("webServer"));
|
|
1081
|
+
if (active !== void 0) {
|
|
1082
|
+
register(active, "direct");
|
|
1083
|
+
if (registered) return;
|
|
1084
|
+
}
|
|
1085
|
+
ctx.inject(["webServer"], (injected) => {
|
|
1086
|
+
const webServer = asWebServer(injected.webServer);
|
|
1087
|
+
if (webServer === void 0) {
|
|
1088
|
+
log("warn", "context-compression webServer exposes no register() — monitor route not registered");
|
|
1089
|
+
return;
|
|
1090
|
+
}
|
|
1091
|
+
register(webServer, "inject");
|
|
1092
|
+
});
|
|
1093
|
+
}
|
|
1094
|
+
/**
|
|
841
1095
|
* Resolve one possibly-volatile field: a live ref on 0.1.7+, a plain value
|
|
842
1096
|
* otherwise (0.1.7 hands `.volatile()` fields to `apply()` as live refs).
|
|
843
1097
|
*/
|
|
@@ -861,7 +1115,9 @@ function apply(ctx, config = {}) {
|
|
|
861
1115
|
try {
|
|
862
1116
|
if (config.estimatorCatalogRoute === true) registerEstimatorCatalogRoute(ctx);
|
|
863
1117
|
registerSavingsRoute(ctx);
|
|
1118
|
+
registerMonitorRoute(ctx);
|
|
864
1119
|
if (config.advisorReportRoute === true) registerAdvisorReportRoute(ctx);
|
|
1120
|
+
registerSummaryCommand(ctx);
|
|
865
1121
|
if (config.presetOverlay !== true) return;
|
|
866
1122
|
ctx.inject(["agentPresets"], (presetsCtx) => {
|
|
867
1123
|
const installation = decorateAgentPresets(presetsCtx.agentPresets, {
|
|
@@ -892,4 +1148,4 @@ function resolveAutoCompactThresholdPercent(config, presetsCtx) {
|
|
|
892
1148
|
}
|
|
893
1149
|
}
|
|
894
1150
|
//#endregion
|
|
895
|
-
export { Config, apply };
|
|
1151
|
+
export { Config, apply, registerMonitorRoute };
|
|
@@ -68,6 +68,17 @@ interface AutoCompactSettings {
|
|
|
68
68
|
interface CodeSkeletonSettings {
|
|
69
69
|
enabled: boolean;
|
|
70
70
|
}
|
|
71
|
+
/**
|
|
72
|
+
* Orthogonal turn-tail intent-summary gate, mirrored browser-safe from the
|
|
73
|
+
* runtime: independent of every profile, default off.
|
|
74
|
+
*/
|
|
75
|
+
interface IntentSummarySettings {
|
|
76
|
+
enabled: boolean;
|
|
77
|
+
}
|
|
78
|
+
/** Floating compression-monitor panel (FAB); visibility switch. */
|
|
79
|
+
interface MonitorPanelSettings {
|
|
80
|
+
enabled: boolean;
|
|
81
|
+
}
|
|
71
82
|
/** Browser-safe mirror of the runtime presetOptions section. */
|
|
72
83
|
interface PresetOptionsSettings {
|
|
73
84
|
readonly dedupeToolResults?: boolean;
|
|
@@ -98,6 +109,10 @@ interface ContextCompressionSettings {
|
|
|
98
109
|
autoCompact: AutoCompactSettings;
|
|
99
110
|
/** Code-skeleton reducer gate captured independently of `profile`. */
|
|
100
111
|
codeSkeleton: CodeSkeletonSettings;
|
|
112
|
+
/** Turn-tail intent-summary gate captured independently of `profile`. */
|
|
113
|
+
intentSummary: IntentSummarySettings;
|
|
114
|
+
/** Floating compression-monitor panel (FAB); absent inherits hidden. */
|
|
115
|
+
monitorPanel?: MonitorPanelSettings;
|
|
101
116
|
/** Optional tokenpilot-inspired sub-capability overrides (presence-validated only). */
|
|
102
117
|
presetOptions?: PresetOptionsSettings;
|
|
103
118
|
}
|
|
@@ -134,6 +134,19 @@ interface AutoCompactSettings {
|
|
|
134
134
|
interface CodeSkeletonSettings {
|
|
135
135
|
enabled: boolean;
|
|
136
136
|
}
|
|
137
|
+
/**
|
|
138
|
+
* Orthogonal turn-tail intent-summary gate. Independent of every profile:
|
|
139
|
+
* when enabled, the turn-boundary growth gate may fold consumed-increment
|
|
140
|
+
* tool results into an LLM-written intent block (skeleton + verbatim error
|
|
141
|
+
* lines are kept; the model only ever writes the summary segment).
|
|
142
|
+
*/
|
|
143
|
+
interface IntentSummarySettings {
|
|
144
|
+
enabled: boolean;
|
|
145
|
+
}
|
|
146
|
+
/** Floating compression-monitor panel (FAB); visibility switch. */
|
|
147
|
+
interface MonitorPanelSettings {
|
|
148
|
+
enabled: boolean;
|
|
149
|
+
}
|
|
137
150
|
/**
|
|
138
151
|
* Persisted sub-capability overrides for the `tokenpilot-inspired` preset.
|
|
139
152
|
* Absent fields inherit the preset defaults; the section is only meaningful
|
|
@@ -173,6 +186,10 @@ interface ContextCompressionSettings {
|
|
|
173
186
|
autoCompact: AutoCompactSettings;
|
|
174
187
|
/** Code-skeleton reducer gate snapped independently of `profile`. */
|
|
175
188
|
codeSkeleton: CodeSkeletonSettings;
|
|
189
|
+
/** Turn-tail intent-summary gate snapped independently of `profile`. */
|
|
190
|
+
intentSummary: IntentSummarySettings;
|
|
191
|
+
/** Floating compression-monitor panel (FAB); absent inherits hidden. */
|
|
192
|
+
monitorPanel?: MonitorPanelSettings;
|
|
176
193
|
/** Optional tokenpilot-inspired sub-capability overrides; absent inherits preset defaults. */
|
|
177
194
|
presetOptions?: PresetOptionsSettings;
|
|
178
195
|
}
|
|
@@ -397,6 +414,32 @@ interface EstimatorFailures {
|
|
|
397
414
|
cooldownUntil: number;
|
|
398
415
|
}
|
|
399
416
|
//#endregion
|
|
417
|
+
//#region src/runtime/tokenpilot/intent-input-mask.d.ts
|
|
418
|
+
type IntentRole = 'read-mask' | 'write-keep' | 'conservative';
|
|
419
|
+
//#endregion
|
|
420
|
+
//#region src/runtime/tokenpilot/intent-fold.d.ts
|
|
421
|
+
/** One staged fold awaiting the next pressure round. */
|
|
422
|
+
interface PendingIntentFold {
|
|
423
|
+
readonly createdAt: number;
|
|
424
|
+
readonly turn: number;
|
|
425
|
+
/** Inclusive seq span of the folded candidates. */
|
|
426
|
+
readonly startSeq: number;
|
|
427
|
+
readonly endSeq: number;
|
|
428
|
+
/** LLM-written summary segment (fail-open parsed, char-capped). */
|
|
429
|
+
readonly summary: string;
|
|
430
|
+
/** Verbatim error lines collected across the batch (never LLM-revoiced). */
|
|
431
|
+
readonly errorLines: readonly string[];
|
|
432
|
+
/** Per-candidate faces: read-mask single lines ride the block, keep-class lines prompt-only. */
|
|
433
|
+
readonly records: ReadonlyArray<{
|
|
434
|
+
readonly seq: number;
|
|
435
|
+
readonly role: IntentRole;
|
|
436
|
+
readonly toolName: string;
|
|
437
|
+
readonly line: string;
|
|
438
|
+
}>;
|
|
439
|
+
/** Characters consumed by the summary-writer call (credit accounting). */
|
|
440
|
+
readonly summaryCallChars: number;
|
|
441
|
+
}
|
|
442
|
+
//#endregion
|
|
400
443
|
//#region src/pruner/state.d.ts
|
|
401
444
|
/** Mutable per-session state bag used inside {@link ToolResultPruner}. */
|
|
402
445
|
interface PrunerState {
|
|
@@ -430,6 +473,12 @@ interface PrunerState {
|
|
|
430
473
|
readonly estimatorRemainingTurns: WeakMap<Session, number>;
|
|
431
474
|
/** Per-session advisor side channel, constructed once with the advisor overrides. */
|
|
432
475
|
readonly advisorChannels: WeakMap<Session, SideChannel>;
|
|
476
|
+
/** Staged intent fold awaiting the next pressure round (at most one per session). */
|
|
477
|
+
readonly pendingIntentFolds: WeakMap<Session, PendingIntentFold>;
|
|
478
|
+
/** Landed intent-fold seqs: fold-once, never reconsidered by any later stage. */
|
|
479
|
+
readonly intentFoldedSeqs: WeakMap<Session, Set<number>>;
|
|
480
|
+
/** Live-surface tokens when the last intent fold landed (growth-gate baseline). */
|
|
481
|
+
readonly intentBaselines: WeakMap<Session, number>;
|
|
433
482
|
}
|
|
434
483
|
//#endregion
|
|
435
484
|
//#region src/runtime/custom-policy.d.ts
|
|
@@ -759,6 +808,22 @@ declare class ToolResultPruner extends Service {
|
|
|
759
808
|
* reads, so the default configuration adds exactly zero behavior.
|
|
760
809
|
*/
|
|
761
810
|
private postflightAdvisorPass;
|
|
811
|
+
/**
|
|
812
|
+
* Fire-and-forget postflight: evaluate the growth gate, and only when it
|
|
813
|
+
* passes, select the consumed increment OUTSIDE the protected working set,
|
|
814
|
+
* mask it to semantic-role records, and spend ONE summary-writer call. The
|
|
815
|
+
* verdict stages as a pending fold that the NEXT pressure round lands via
|
|
816
|
+
* the ordinary plan/apply machinery — the synchronous decision path never
|
|
817
|
+
* waits on an LLM.
|
|
818
|
+
*/
|
|
819
|
+
private postflightIntentFoldPass;
|
|
820
|
+
/**
|
|
821
|
+
* Convert a staged pending fold into per-candidate planned replacements
|
|
822
|
+
* (reducer `intent-summary`). Fail-open: a candidate that would grow, is
|
|
823
|
+
* rich-content, or no longer exists keeps its original text. Returns
|
|
824
|
+
* `undefined` when there is nothing (or no longer anything) to fold.
|
|
825
|
+
*/
|
|
826
|
+
private applyPendingIntentFold;
|
|
762
827
|
/**
|
|
763
828
|
* Monotonic per-session turn clock for advisory records. Bumped by the agent
|
|
764
829
|
* loop payloads (`pre-step`); passes without a turn coordinate reuse the last
|