dsh-auto-compaction 0.1.2 → 0.2.0

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/lib/index.js CHANGED
@@ -1,386 +1,284 @@
1
1
  /**
2
- * dsh-handoff-compaction
2
+ * dsh-auto-compaction — node half (bundle).
3
3
  *
4
- * Idle-time handoff compaction for deepseek-harness.
4
+ * Registers no service (so it can be mounted alongside the engine without any
5
+ * risk of a duplicate `ctx.compaction`). Its only job is to mirror its own
6
+ * configuration into the sidecar file the engine reads on every decision:
5
7
  *
6
- * At a configurable share of the model window (default 90%) this backend waits
7
- * for the agent to go idle, then asks the routed model — replaying the current
8
- * conversation as the prompt prefix so the provider's cache is reused — for a
9
- * handoff checkpoint, and replaces the whole compactable surface with that one
10
- * message. The next user turn therefore starts from system prompt + tools +
11
- * handoff text, and nothing else.
8
+ * %USERPROFILE%\.dsh-handoff-compaction\settings.json
12
9
  *
13
- * It subclasses the stock basic backend so selection, tool-pair balance,
14
- * durable compaction markers, flushes and the idle admission reservation are
15
- * the proven implementation; only the trigger point, the summarization
16
- * template and the idle gate differ.
10
+ * Writing on every (re)load is what makes a settings save take effect live:
11
+ * DSH reloads this plugin, this function runs, the engine picks the file up at
12
+ * its next idle check.
17
13
  */
18
14
  import z from "@deepseek-ai/schemastery";
19
- import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
15
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
16
+ import { createRequire } from "node:module";
20
17
  import { homedir } from "node:os";
21
- import { join } from "node:path";
22
- import { BlockAssembler, LlmError, contentHasImage } from "@deepseek-ai/dsh-llm";
23
- import BasicCompactionEngine from "@deepseek-ai/dsh-compaction-basic";
24
- import { decideTrigger, shouldAttempt } from "./plan.js";
18
+ import { dirname, join } from "node:path";
19
+ import { execFile, spawn } from "node:child_process";
25
20
 
26
- const LOG = "[handoff]";
21
+ export const name = "dsh-auto-compaction";
22
+ export const inject = [];
27
23
 
28
- const SETTINGS_DIR = join(homedir(), ".dsh-handoff-compaction");
29
- // Test harnesses point this at a missing file so the live sidecar cannot leak
30
- // into a case that expects the configured ratio.
31
- const SETTINGS_FILE = process.env.DSH_HANDOFF_SETTINGS_FILE ?? join(SETTINGS_DIR, "settings.json");
32
- const DEFAULT_TEMPLATE_FILE = join(SETTINGS_DIR, "template.md");
24
+ export const Config = z.object({
25
+ enabled: z.boolean().default(true),
26
+ thresholdRatio: z.number().default(90),
27
+ scopePreset: z.boolean().default(false),
28
+ presets: z.string().default("lightweight-local"),
29
+ templateFile: z.string().default(""),
30
+ openTemplate: z.string().default(""),
31
+ displayStyle: z.string().default("orbit"),
32
+ });
33
+
34
+ const DIR = join(homedir(), ".dsh-handoff-compaction");
35
+ const SETTINGS_FILE = join(DIR, "settings.json");
36
+ const TEMPLATE_FILE = join(DIR, "template.md");
37
+ const UI_LOG = join(DIR, "ui.log");
38
+ const STATUS_DIR = process.env.DSH_HANDOFF_STATUS_DIR || join(DIR, "status");
39
+ const STATUS_SESSION_ID = /^[A-Za-z0-9_-]{1,128}$/;
33
40
 
34
41
  /**
35
- * Live settings written by the companion UI package (dsh-handoff-compaction-ui).
36
- * Read fresh on every decision, cached by mtime so a turn never blocks on disk.
42
+ * Read the engine's per-session status sidecar without importing the engine
43
+ * package: DSH's host module fallback cannot resolve a linked package from the
44
+ * UI package's real path, and a top-level import here blocks startup.
37
45
  */
38
- let settingsCache = { mtimeMs: -1, value: undefined };
39
- function readSettings() {
46
+ function readStatus(sessionId) {
47
+ if (typeof sessionId !== "string" || !STATUS_SESSION_ID.test(sessionId)) return undefined;
40
48
  try {
41
- const stat = statSync(SETTINGS_FILE);
42
- if (stat.mtimeMs === settingsCache.mtimeMs) return settingsCache.value;
43
- const parsed = JSON.parse(readFileSync(SETTINGS_FILE, "utf8"));
44
- settingsCache = { mtimeMs: stat.mtimeMs, value: parsed && typeof parsed === "object" ? parsed : undefined };
45
- return settingsCache.value;
49
+ const parsed = JSON.parse(readFileSync(join(STATUS_DIR, sessionId + ".json"), "utf8"));
50
+ return parsed && typeof parsed === "object" ? parsed : undefined;
46
51
  } catch {
47
52
  return undefined;
48
53
  }
49
54
  }
55
+ const requireFromUi = createRequire(import.meta.url);
56
+
57
+ function trace(message) {
58
+ try { mkdirSync(DIR, { recursive: true }); appendFileSync(UI_LOG, new Date().toISOString() + " " + message + String.fromCharCode(10), "utf8"); } catch { /* ignore */ }
59
+ }
60
+
61
+ let lastOpenRequest = "";
62
+
63
+ const DISPLAY_STYLES = new Set(["orbit", "strip", "ring", "topbar"]);
64
+
65
+ function normalizeDisplayStyle(value) {
66
+ return typeof value === "string" && DISPLAY_STYLES.has(value) ? value : "orbit";
67
+ }
50
68
 
51
- function templatePathFrom(configured) {
52
- if (typeof configured === "string" && configured.trim().length > 0) return configured.trim();
53
- const env = process.env.DSH_HANDOFF_TEMPLATE;
54
- if (typeof env === "string" && env.trim().length > 0) return env.trim();
55
- return DEFAULT_TEMPLATE_FILE;
69
+ function normalize(config) {
70
+ const raw = Number(config.thresholdRatio ?? 90);
71
+ const pct = Number.isFinite(raw) ? Math.max(1, Math.min(100, raw)) : 90;
72
+ return {
73
+ enabled: config.enabled !== false,
74
+ thresholdRatio: pct / 100,
75
+ scope: config.scopePreset === true ? "preset" : "global",
76
+ presets: String(config.presets ?? "")
77
+ .split(/[,,\s]+/)
78
+ .map((part) => part.trim())
79
+ .filter((part) => part.length > 0),
80
+ templateFile: String(config.templateFile ?? "").trim(),
81
+ displayStyle: normalizeDisplayStyle(config.displayStyle),
82
+ };
56
83
  }
57
84
 
58
- /** Read the handoff template, falling back to the built-in text. */
59
- function readTemplate(filePath, autoCreate) {
85
+ function writeSettings(ctx, settings) {
60
86
  try {
61
- if (!existsSync(filePath)) {
62
- if (!autoCreate) return { text: undefined, source: "builtin (file missing)" };
63
- mkdirSync(join(filePath, ".."), { recursive: true });
64
- writeFileSync(filePath, BUILTIN_INSTRUCTION + "\n", "utf8");
65
- return { text: BUILTIN_INSTRUCTION, source: "builtin (written to " + filePath + ")" };
66
- }
67
- const text = readFileSync(filePath, "utf8").replace(/^\uFEFF/, "");
68
- if (text.trim().length < 20) return { text: undefined, source: "builtin (file empty)" };
69
- return { text, source: filePath };
87
+ mkdirSync(DIR, { recursive: true });
88
+ writeFileSync(SETTINGS_FILE, JSON.stringify(settings, null, 2) + "\n", "utf8");
89
+ ctx.logger?.info?.(`[handoff-ui] settings -> ${SETTINGS_FILE} (${JSON.stringify(settings)})`);
70
90
  } catch (error) {
71
- return { text: undefined, source: `builtin (read failed: ${error instanceof Error ? error.message : String(error)})` };
91
+ ctx.logger?.warn?.(`[handoff-ui] settings write failed: ${error instanceof Error ? error.message : String(error)}`);
72
92
  }
73
93
  }
74
94
 
95
+ function launch(ctx, label, command, args) {
96
+ try {
97
+ const child = spawn(command, args, { detached: true, stdio: "ignore", windowsHide: false });
98
+ child.on("error", (error) => {
99
+ trace("spawn error " + label + " (" + command + "): " + (error instanceof Error ? error.message : String(error)));
100
+ ctx.logger?.warn?.(`[handoff-ui] ${label} failed: ${error instanceof Error ? error.message : String(error)}`);
101
+ });
102
+ child.on("spawn", () => trace("spawned " + label + " (" + command + ")"));
103
+ child.unref();
104
+ return true;
105
+ } catch (error) {
106
+ trace("spawn threw " + label + ": " + (error instanceof Error ? error.message : String(error)));
107
+ return false;
108
+ }
109
+ }
75
110
 
76
- const BUILTIN_INSTRUCTION = [
77
- "你现在要为本会话写一份交接文档:我会用它替换掉上面的全部对话记录,然后由你在一个空白的上下文里继续同一件事。写漏的东西将永久丢失。",
78
- "",
79
- "只输出 Markdown,严格按下面小节顺序,每节用短横线要点,不许省略任何小节;没有内容写「(无)」。",
80
- "",
81
- "## 用户目标与原始要求",
82
- "- 用户最初想做什么、之后怎么改过口;关键原话逐字引用",
83
- "",
84
- "## 当前任务状态",
85
- "- 在做什么、进行到哪一步、哪些已完成、哪些没完成",
86
- "",
87
- "## 涉及的文件与代码",
88
- "- 精确路径:为什么重要、改了什么、还有哪里没改",
89
- "",
90
- "## 已验证的事实与命令",
91
- "- 跑过的命令、测试结果、报错原文、环境约束(版本、端口、路径)",
92
- "",
93
- "## 关键决策与被放弃的方案",
94
- "- 选了什么、为什么;试过但放弃的方案及放弃原因",
95
- "",
96
- "## 待办与下一步",
97
- "- 用户明确要求但尚未完成的项;紧接着要执行的第一步",
98
- "",
99
- "## 风险与注意事项",
100
- "- 容易踩的坑、用户的偏好与禁忌",
101
- "",
102
- "规则:",
103
- "- 保留精确的路径、命令、错误串、标识符、数值、函数签名;不要概括成\"修改了相关文件\"这类废话。",
104
- "- 如果对话里有用户粘贴的长文档或上一轮交接文档(例如包在 <compacted-summary> 标记里的那份),不要原样照抄:保留仍然生效的硬约束(路径、命令、版本、验收标准)并逐字引用其关键句,其余概括;过时的内容删掉,最终只输出一份同样结构的文档。",
105
- "- 如果用户的早期消息给出了一份磁盘上的工程交接文档的绝对路径,必须逐字保留该路径并注明\"需要时重新读取该文件\";不要把它的内容当成必须在本文档里复述的东西。",
106
- "- 不要提到这份交接文档本身,也不要说上下文被压缩或摘要。",
107
- "- 只输出文档正文,不要调用任何工具。",
108
- "",
109
- "写入时还要记住下面两条,它们会被交给后续的你执行:",
110
- "- 更早的对话消息不会留在你的上下文里,也没有任何工具或磁盘检索能把它们找回来。不要去搜索会话文件、日志或历史记录还原旧对话;文档里没写的,就当作不知道,直接说不知道。",
111
- "- 用户问起\"之前说过什么\"时,以本文档为准;文档没有逐字保留的内容(例如旧回答的原文),直接说明已经被压缩掉,不要编造,也不要为了找它去翻文件。",
112
- ].join("\n");
111
+ async function handleOpen(ctx, request, target) {
112
+ const trimmed = String(request ?? "").trim();
113
+ if (trimmed === "" || trimmed === lastOpenRequest) return { ok: true, value: { skipped: true } };
114
+ lastOpenRequest = trimmed;
115
+ const mode = trimmed.startsWith("folder") ? "folder" : "file";
116
+ const root = process.env.SystemRoot || "C:\\Windows";
117
+ const explorerPath = join(root, "explorer.exe");
118
+ const explorer = existsSync(explorerPath) ? explorerPath : "explorer.exe";
113
119
 
114
- function finishError(finish) {
115
- switch (finish.kind) {
116
- case "error":
117
- case "aborted":
118
- return new LlmError(finish.failure.message, finish.failure.code, finish.failure);
119
- case "max-tokens": {
120
- const error = new Error("handoff summary truncated at the token cap (incomplete checkpoint)");
121
- error.code = "MAX_TOKENS";
122
- return error;
123
- }
124
- default:
125
- return undefined;
120
+ trace("open requested mode=" + mode + " target=" + target + " explorer=" + explorer);
121
+ if (!existsSync(target)) {
122
+ const message = "file not found: " + target;
123
+ trace("open failed: " + message);
124
+ return { ok: false, error: { code: "auto-compaction/open-missing", message } };
126
125
  }
127
- }
128
126
 
129
- export default class HandoffCompaction extends BasicCompactionEngine {
130
- static inject = ["llm", "tokenMeter", "sessions"];
127
+ // Launch through the existing Explorer shell. DSH's host runs plugin
128
+ // children in a job object; cmd/PowerShell descendants are killed with the
129
+ // request, while Explorer hands the file to the shell and exits.
130
+ const args = mode === "folder" ? ["/select," + target] : [target];
131
+ const ok = launch(ctx, mode + "/explorer", explorer, args);
132
+ return ok
133
+ ? { ok: true, value: { mode, target, opener: "explorer" } }
134
+ : { ok: false, error: { code: "auto-compaction/open-failed", message: "explorer failed to start" } };
135
+ }
131
136
 
132
- static Config = z.object({
133
- thresholdRatio: z.number(),
134
- headroomTokens: z.number(),
135
- retainRatio: z.number(),
136
- retainTokens: z.number(),
137
- summarizationProvider: z.string(),
138
- summarizationModel: z.string(),
139
- maxTokens: z.number(),
140
- compactionRetries: z.number(),
141
- maxOverflowRetries: z.number(),
142
- contextWindowOverride: z.number(),
143
- reservedCompletionTokensOverride: z.number(),
144
- idleDelayMs: z.number(),
145
- minIntervalMs: z.number(),
146
- minTokenGrowth: z.number(),
147
- timeoutMs: z.number(),
148
- dryRun: z.boolean(),
149
- handoffInstruction: z.string(),
150
- traceFile: z.string(),
151
- traceConsole: z.boolean(),
152
- templateFile: z.string(),
153
- presetId: z.string(),
154
- autoCreateTemplate: z.boolean(),
155
- });
137
+ function scopeScriptPath() {
138
+ try {
139
+ const entry = requireFromUi.resolve("dsh-auto-compaction-engine");
140
+ return join(dirname(entry), "..", "scripts", "preset-scope.mjs");
141
+ } catch {
142
+ return join(homedir(), ".dsh-local-pkgs", "dsh-auto-compaction-engine", "scripts", "preset-scope.mjs");
143
+ }
144
+ }
156
145
 
157
- constructor(ctx, config = {}) {
158
- const {
159
- contextWindowOverride,
160
- reservedCompletionTokensOverride,
161
- idleDelayMs,
162
- minIntervalMs,
163
- minTokenGrowth,
164
- timeoutMs,
165
- dryRun,
166
- handoffInstruction,
167
- traceFile,
168
- traceConsole,
169
- templateFile,
170
- presetId,
171
- autoCreateTemplate,
172
- ...base
173
- } = config;
174
- // auto:false keeps the stock between-step pressure trigger out of the way;
175
- // this backend decides on idle instead.
176
- super(ctx, { ...base, auto: false });
177
- this.handoff = {
178
- instruction: typeof handoffInstruction === "string" && handoffInstruction.trim().length > 0 ? handoffInstruction : undefined,
179
- contextWindowOverride: contextWindowOverride ?? 0,
180
- reservedOverride: reservedCompletionTokensOverride ?? -1,
181
- idleDelayMs: idleDelayMs ?? 1_500,
182
- minIntervalMs: minIntervalMs ?? 60_000,
183
- minTokenGrowth: minTokenGrowth ?? 2_048,
184
- timeoutMs: timeoutMs ?? 600_000,
185
- dryRun: dryRun ?? false,
186
- templateFile: templatePathFrom(templateFile ?? readSettings()?.templateFile),
187
- presetId: typeof presetId === "string" ? presetId : "",
188
- autoCreateTemplate: autoCreateTemplate !== false,
189
- };
190
- this.handoff.traceFile = typeof traceFile === "string" ? traceFile : "";
191
- this.handoff.traceConsole = traceConsole === true;
192
- // Materialise the template so the settings card can point at a real file.
193
- try { readTemplate(this.handoff.templateFile, this.handoff.autoCreateTemplate); } catch { /* never block construction */ }
194
- this.attempts = new WeakMap();
195
- this.running = new WeakSet();
196
- this.timers = new WeakMap();
197
- this.agents = new WeakMap();
198
- ctx.on("agent/status", ({ agent, status }) => {
199
- if (agent?.session) this.agents.set(agent.session, agent);
200
- if (status === "idle") this.scheduleCheck(agent, "agent/status idle");
201
- });
202
- // A finished turn is the gap the user described; agent/status is not the only
203
- // place DSH reports it, so both paths are wired.
204
- ctx.on("session/event", (session, event) => {
205
- if (event?.type !== "turn/end") return;
206
- const owner = this.agents.get(session);
207
- if (owner !== undefined) this.scheduleCheck(owner, "turn/end");
146
+ function execSwitchOnce(command, env, script) {
147
+ return new Promise((resolve, reject) => {
148
+ execFile(command, [script, "enable"], { timeout: 6000, windowsHide: true, env }, (error, stdout, stderr) => {
149
+ if (error) {
150
+ error.stdout = stdout;
151
+ error.stderr = stderr;
152
+ reject(error);
153
+ return;
154
+ }
155
+ resolve({ stdout, stderr });
208
156
  });
209
- this.log(`ready (threshold ${this.describeThreshold()}, dryRun=${this.handoff.dryRun}, trace=${this.handoff.traceFile || (this.handoff.traceConsole ? "console" : "off")})`);
210
- }
157
+ });
158
+ }
211
159
 
212
- describeThreshold() {
213
- return `${Math.round((this.config.thresholdRatio ?? 0.9) * 100)}%`;
160
+ /**
161
+ * Apply the current settings sidecar to the preset/profile YAML. `node` is the
162
+ * normal path; the Electron binary with ELECTRON_RUN_AS_NODE is the fallback
163
+ * when the host has no node on PATH.
164
+ */
165
+ async function applyScopeSwitch() {
166
+ const script = scopeScriptPath();
167
+ if (!existsSync(script)) {
168
+ const message = "preset-scope.mjs not found: " + script;
169
+ trace("scope switch failed: " + message);
170
+ return { ok: false, message };
214
171
  }
215
-
216
- log(message, level = "info") {
217
- const line = `${new Date().toISOString()} ${LOG} ${message}`;
218
- if (this.handoff?.traceConsole === true) {
219
- try { console.error(line); } catch { /* trace must never break the turn */ }
220
- }
221
- const file = this.handoff?.traceFile;
222
- if (typeof file === "string" && file.length > 0) {
223
- try { appendFileSync(file, line + "\n"); } catch { /* trace must never break the turn */ }
172
+ const explicit = process.env.DSH_NODE;
173
+ const attempts = typeof explicit === "string" && explicit.trim().length > 0
174
+ ? [{ command: explicit.trim(), env: process.env }]
175
+ : [
176
+ { command: "node", env: process.env },
177
+ { command: process.execPath, env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" } },
178
+ ];
179
+ let lastError;
180
+ for (const attempt of attempts) {
181
+ try {
182
+ const result = await execSwitchOnce(attempt.command, attempt.env, script);
183
+ const output = `${result.stdout ?? ""}${result.stderr ?? ""}`.trim();
184
+ trace("scope switch ok" + (output ? " | " + output : ""));
185
+ return { ok: true, output };
186
+ } catch (error) {
187
+ lastError = error;
188
+ if (error?.code !== "ENOENT") break;
224
189
  }
225
- const write = this.ctx.logger?.[level] ?? this.ctx.logger?.info;
226
- if (typeof write === "function") write.call(this.ctx.logger, `${LOG} ${message}`);
227
190
  }
191
+ const output = `${lastError?.stdout ?? ""}${lastError?.stderr ?? ""}`.trim();
192
+ const message = (lastError?.message ?? String(lastError)) + (output ? "\n" + output : "");
193
+ trace("scope switch failed: " + message);
194
+ return { ok: false, message };
195
+ }
228
196
 
229
- /** Debounce the idle signal so a turn that immediately resumes does not trigger work. */
230
- scheduleCheck(agent, why = "idle") {
231
- const previous = this.timers.get(agent);
232
- if (previous !== undefined) clearTimeout(previous);
233
- const timer = setTimeout(() => {
234
- this.timers.delete(agent);
235
- void this.checkAndHandoff(agent, why);
236
- }, this.handoff.idleDelayMs);
237
- if (typeof timer.unref === "function") timer.unref();
238
- this.timers.set(agent, timer);
239
- }
197
+ const CHANNEL = "/dsh-auto-compaction";
240
198
 
241
- routedTarget(agent) {
242
- const routed = agent.session?.requestHeader?.()?.config;
243
- if (routed?.provider && routed?.model) return { provider: routed.provider, model: routed.model };
244
- const options = agent.options ?? {};
245
- if (options.provider && options.model) return { provider: options.provider, model: options.model };
199
+ function readSettings() {
200
+ try {
201
+ const parsed = JSON.parse(readFileSync(SETTINGS_FILE, "utf8"));
202
+ return parsed && typeof parsed === "object" ? parsed : undefined;
203
+ } catch {
246
204
  return undefined;
247
205
  }
206
+ }
248
207
 
249
- async checkAndHandoff(agent, why = "idle") {
250
- if (this.running.has(agent)) return;
251
- try {
252
- const session = agent.session;
253
- if (!session) return;
254
- const measurement = this.ctx.tokenMeter.measure(session);
255
- const target = this.routedTarget(agent);
256
- if (target === undefined) return this.log(`${why}: no routed provider/model yet; skipping`);
257
-
258
- const info = await this.ctx.llm.resolveModelInfo(target.provider, target.model);
259
- const headerMaxTokens = session.requestHeader?.()?.config?.maxTokens;
260
- const reserved = this.handoff.reservedOverride >= 0
261
- ? this.handoff.reservedOverride
262
- : (headerMaxTokens ?? info.defaultMaxTokens ?? 0);
263
- const contextWindow = this.handoff.contextWindowOverride > 0
264
- ? this.handoff.contextWindowOverride
265
- : info.context?.contextWindow;
266
-
267
- const live = readSettings();
268
- const scope = live?.scope === "preset" ? "preset" : "global";
269
- const selectedPresets = Array.isArray(live?.presets) ? live.presets : [];
270
- if (scope === "preset" && this.handoff.presetId !== "" && !selectedPresets.includes(this.handoff.presetId)) {
271
- return this.log(`${why}: skipped by scope (preset "${this.handoff.presetId}" not selected)`);
272
- }
273
- const liveRatio = typeof live?.thresholdRatio === "number" && live.thresholdRatio > 0 && live.thresholdRatio <= 1
274
- ? live.thresholdRatio
275
- : undefined;
276
-
277
- const decision = decideTrigger({
278
- totalTokens: measurement.totalTokens,
279
- contextWindow,
280
- reservedCompletionTokens: reserved,
281
- headroomTokens: this.config.headroomTokens ?? 0,
282
- thresholdRatio: liveRatio ?? this.config.thresholdRatio ?? 0.9,
283
- });
284
- if (!decision.trigger) {
285
- return this.log(`${why}: ${measurement.totalTokens}/${decision.thresholdTokens ?? "?"} tokens${decision.ok === false ? ` (${decision.reason})` : ""}`);
286
- }
208
+ function sanitize(payload) {
209
+ const pct = Number(payload?.thresholdRatio);
210
+ const ratio = Number.isFinite(pct) ? Math.max(1, Math.min(100, pct)) : 90;
211
+ const presets = Array.isArray(payload?.presets)
212
+ ? payload.presets.filter((v) => typeof v === "string" && v.trim().length > 0)
213
+ : String(payload?.presets ?? "").split(/[,,s]+/).filter((v) => v.trim().length > 0);
214
+ return {
215
+ enabled: payload?.enabled !== false,
216
+ thresholdRatio: ratio / 100,
217
+ scope: payload?.scope === "preset" ? "preset" : "global",
218
+ presets,
219
+ templateFile: String(payload?.templateFile ?? "").trim(),
220
+ displayStyle: normalizeDisplayStyle(payload?.displayStyle),
221
+ };
222
+ }
287
223
 
288
- const last = this.attempts.get(agent);
289
- if (!shouldAttempt({
290
- now: Date.now(),
291
- last,
292
- tokens: measurement.totalTokens,
293
- thresholdTokens: decision.thresholdTokens,
294
- minIntervalMs: this.handoff.minIntervalMs,
295
- minTokenGrowth: this.handoff.minTokenGrowth,
296
- })) {
297
- return this.log(`over threshold (${measurement.totalTokens} >= ${decision.thresholdTokens}) but holding: retry gate`);
298
- }
224
+ export function apply(ctx, config = {}) {
225
+ const seeded = normalize(config);
226
+ if (readSettings() === undefined) writeSettings(ctx, seeded);
227
+ void handleOpen(ctx, config.openTemplate, seeded.templateFile || TEMPLATE_FILE).catch((error) => {
228
+ ctx.logger?.warn?.(`[handoff-ui] openTemplate failed: ${error instanceof Error ? error.message : String(error)}`);
229
+ });
299
230
 
300
- this.attempts.set(agent, { at: Date.now(), tokens: measurement.totalTokens });
301
- if (this.handoff.dryRun) {
302
- return this.log(`DRY-RUN: would hand off now (${measurement.totalTokens} >= ${decision.thresholdTokens} of an assumed ${contextWindow}-token window)`);
231
+ ctx.inject(["connection"], (scope) => {
232
+ try {
233
+ const connection = scope.root?.connection ?? scope.connection;
234
+ if (connection === undefined) {
235
+ ctx.logger?.warn?.("[handoff-ui] no connection service; settings RPC unavailable");
236
+ return;
303
237
  }
304
-
305
- this.running.add(agent);
306
- try {
307
- const result = await this.compactNow(agent, AbortSignal.timeout(this.handoff.timeoutMs));
308
- if (result === null || result === undefined) {
309
- this.log("idle: no compactable range; nothing replaced", "warn");
310
- return;
238
+ const dispose = connection.rpc.handle(CHANNEL, async (endpoint, payload) => {
239
+ try {
240
+ if (endpoint === "status") {
241
+ // A switched-off plugin leaves no live status behind; hide any
242
+ // sidecar left over from a compaction that ran before the switch.
243
+ if (readSettings()?.enabled === false) return { ok: true, value: null };
244
+ return { ok: true, value: readStatus(String(payload?.sessionId ?? "")) ?? null };
245
+ }
246
+ if (endpoint === "get") {
247
+ const stored = readSettings() ?? seeded;
248
+ return {
249
+ ok: true,
250
+ value: {
251
+ ...stored,
252
+ enabled: stored.enabled !== false,
253
+ displayStyle: normalizeDisplayStyle(stored.displayStyle),
254
+ defaultTemplate: TEMPLATE_FILE,
255
+ },
256
+ };
257
+ }
258
+ if (endpoint === "set") {
259
+ const next = sanitize(payload);
260
+ trace("set " + JSON.stringify(next));
261
+ writeSettings(ctx, next);
262
+ const applied = await applyScopeSwitch();
263
+ if (!applied.ok) {
264
+ return { ok: false, error: { code: "auto-compaction/switch-failed", message: applied.message }, value: next };
265
+ }
266
+ return { ok: true, value: { ...next, switchApplied: true, defaultTemplate: TEMPLATE_FILE } };
267
+ }
268
+ if (endpoint === "open") {
269
+ trace("open " + JSON.stringify(payload));
270
+ return await handleOpen(ctx, String(payload?.kind ?? "file") + ":" + Date.now(), String(payload?.path ?? "") || TEMPLATE_FILE);
271
+ }
272
+ return { ok: false, error: { code: "auto-compaction/bad-request", message: "unknown endpoint: " + String(endpoint) } };
273
+ } catch (error) {
274
+ return { ok: false, error: { code: "auto-compaction/failed", message: error instanceof Error ? error.message : String(error) } };
311
275
  }
312
- this.log(`committed: replaced ${result.shadowedSeqs.length} node(s) (~${result.shadowedTokenCount} tokens) with the handoff checkpoint`);
313
- } finally {
314
- this.running.delete(agent);
315
- }
276
+ });
277
+ scope.effect(() => dispose, "auto-compaction settings rpc");
278
+ trace("rpc ready on " + CHANNEL);
279
+ ctx.logger?.info?.("[handoff-ui] settings RPC ready on " + CHANNEL);
316
280
  } catch (error) {
317
- const message = error instanceof Error ? error.message : String(error);
318
- this.log(`failed: ${message}`, "warn");
281
+ ctx.logger?.warn?.("[handoff-ui] RPC registration failed: " + (error instanceof Error ? error.message : String(error)));
319
282
  }
320
- }
321
-
322
- /** Handoff template instead of the stock compaction instruction. */
323
- async summarize(input, agent, signal) {
324
- const latest = agent.session.requestHeader?.()?.config;
325
- const configured = this.config.summarizationProvider && this.config.summarizationModel
326
- ? { provider: this.config.summarizationProvider, model: this.config.summarizationModel }
327
- : undefined;
328
- const agentTarget = agent.options?.provider && agent.options?.model
329
- ? { provider: agent.options.provider, model: agent.options.model }
330
- : undefined;
331
- const target = configured ?? latest ?? agentTarget;
332
- if (target === undefined) throw new Error("no provider/model available for the handoff summary");
333
- // Replaying the prefix only reuses the provider cache when the auxiliary
334
- // request carries the same routing knobs as the routed one. Strata writes
335
- // the reasoning directive into the prefix, so a missing effort breaks the
336
- // cache a few thousand tokens in. Only inherit it when the summary target
337
- // is the same model that produced the latest request.
338
- const sameTarget = latest !== undefined && target.provider === latest.provider && target.model === latest.model;
339
- const reasoningEffort = sameTarget ? latest.reasoningEffort : undefined;
340
-
341
- const resolved = this.handoff.instruction === undefined
342
- ? readTemplate(this.handoff.templateFile, this.handoff.autoCreateTemplate)
343
- : { text: this.handoff.instruction, source: "config handoffInstruction" };
344
- const instruction = typeof resolved.text === "string" && resolved.text.trim().length > 0
345
- ? resolved.text
346
- : BUILTIN_INSTRUCTION;
347
- this.log(`template: ${resolved.source}${resolved.text === undefined ? " (fallback)" : ""}`);
348
-
349
- const assembler = new BlockAssembler();
350
- const messages = [
351
- ...input.messages,
352
- Object.freeze({ role: "user", content: [{ type: "text", text: instruction }] }),
353
- ];
354
- const options = {
355
- provider: target.provider,
356
- model: target.model,
357
- messages,
358
- toolHistory: agent.session.toolHistory(),
359
- ...(input.tools === undefined ? {} : { tools: [...input.tools] }),
360
- maxTokens: this.config.maxTokens,
361
- ...(reasoningEffort === undefined ? {} : { reasoningEffort }),
362
- sessionId: agent.session.id,
363
- purpose: "compaction",
364
- ...(signal === undefined ? {} : { signal }),
365
- };
366
-
367
- for await (const chunk of this.ctx.llm.stream(options)) assembler.push(chunk);
368
- const error = finishError(assembler.finish);
369
- if (error !== undefined) throw error;
370
-
371
- const rawOutput = assembler.blocks();
372
- if (contentHasImage(rawOutput)) throw new LlmError("handoff summary cannot contain image output", "UNSUPPORTED_CONTENT");
373
- const summary = rawOutput.filter((block) => block.type === "text");
374
- if (!summary.some((block) => block.text.trim().length > 0)) throw new Error("handoff summary produced no text content");
375
-
376
- return {
377
- summary,
378
- rawOutput,
379
- llmStreamCall: true,
380
- provider: target.provider,
381
- model: target.model,
382
- maxTokens: this.config.maxTokens,
383
- ...(assembler.usage === undefined ? {} : { usage: assembler.usage }),
384
- };
385
- }
283
+ });
386
284
  }