agent-loft 0.2.112 → 0.2.113

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.
@@ -0,0 +1,346 @@
1
+ // 读 dsh 的会话记录:$DSH_HOME/sessions/<按 cwd 编的目录>/<会话 id>/session.v4.jsonl.zstd。
2
+ //
3
+ // ACP 恢复会话时不回放历史,会话列表也不带标题和时间,只能读 dsh 落的盘。
4
+ // 文件是追加写的:每次 flush 追加一个 zstd frame。Node 的 zstdDecompressSync 只解第一个 frame,
5
+ // 所以自己按 frame 头切开再逐个解(splitFrames)。最后一个 frame 可能还在写,解不开就跳过。
6
+ //
7
+ // 每行一条事件,用到的几种:
8
+ // { type: "session", id, createdAt, cwd, origin?: "subagent", parentSession? } 第一行
9
+ // { type: "user/message", data: { content: [{ type: "text", text }], source: { kind: "user" | ... }, id } }
10
+ // { type: "assistant/message", data: { message: { content: [{ type: "text" | "reasoning" | "tool-call", ... }], id }, usage } }
11
+ // { type: "session/title", data: { title, source: { kind: "fallback" | "provider" } } }
12
+ // { type: "model/selection", data: { provider, model, reasoningEffort } }
13
+ // { type: "turn/start" | "turn/end", data: { turn } }
14
+ // 这是 dsh 的内部格式,认不出的事件一律跳过,别因为它升级了就整段读不出来。
15
+ import fs from "node:fs";
16
+ import path from "node:path";
17
+ import zlib from "node:zlib";
18
+ import { stripContext } from "../../core/expert-prompt.js";
19
+ import type { HistoryMessage, SessionSummary, TokenUsage } from "../../core/types.js";
20
+ import { splitAttachmentNote } from "../../core/uploads.js";
21
+ import { summarize } from "../claude/session.js";
22
+ import { TodoTracker } from "../claude/todos.js";
23
+ import { sessionsRoot } from "./sdk.js";
24
+ import { describeDshStep, todoName } from "./steps.js";
25
+
26
+ /** 会话 id 会拼进路径,先验形 */
27
+ export const SESSION_ID = /^[A-Za-z0-9_-]{8,80}$/;
28
+ const LOG_NAME = "session.v4.jsonl.zstd";
29
+
30
+ export type DshEvent = { type?: string; seq?: number; time?: number; data?: Record<string, unknown>; [k: string]: unknown };
31
+
32
+ // ---------- zstd frame ----------
33
+
34
+ const ZSTD_MAGIC = 0xfd2fb528;
35
+
36
+ /** 按 zstd 帧格式(RFC 8878)切出每个 frame;格式不对就停在那里 */
37
+ export function splitFrames(buf: Buffer): Buffer[] {
38
+ const frames: Buffer[] = [];
39
+ let pos = 0;
40
+ while (pos + 4 <= buf.length) {
41
+ const magic = buf.readUInt32LE(pos);
42
+ // 可跳过的帧:0x184D2A50 ~ 0x184D2A5F
43
+ if ((magic & 0xfffffff0) === 0x184d2a50) {
44
+ if (pos + 8 > buf.length) break;
45
+ pos += 8 + buf.readUInt32LE(pos + 4);
46
+ continue;
47
+ }
48
+ if (magic !== ZSTD_MAGIC) break;
49
+ const start = pos;
50
+ let p = pos + 4;
51
+ if (p >= buf.length) break;
52
+ const fhd = buf[p]!;
53
+ p += 1;
54
+ const fcsFlag = fhd >> 6;
55
+ const single = (fhd >> 5) & 1;
56
+ const checksum = (fhd >> 2) & 1;
57
+ const dictFlag = fhd & 3;
58
+ if (!single) p += 1;
59
+ p += [0, 1, 2, 4][dictFlag]!;
60
+ p += fcsFlag === 0 ? (single ? 1 : 0) : [0, 2, 4, 8][fcsFlag]!;
61
+ let last = false;
62
+ while (!last) {
63
+ if (p + 3 > buf.length) return frames;
64
+ const header = buf[p]! | (buf[p + 1]! << 8) | (buf[p + 2]! << 16);
65
+ p += 3;
66
+ last = (header & 1) === 1;
67
+ const type = (header >> 1) & 3;
68
+ const size = header >>> 3;
69
+ if (type === 3) return frames;
70
+ p += type === 1 ? 1 : size;
71
+ }
72
+ if (checksum) p += 4;
73
+ if (p > buf.length) break;
74
+ frames.push(buf.subarray(start, p));
75
+ pos = p;
76
+ }
77
+ return frames;
78
+ }
79
+
80
+ /** 解出整份记录的文本 */
81
+ export function decodeLog(buf: Buffer): string {
82
+ const parts: string[] = [];
83
+ for (const f of splitFrames(buf)) {
84
+ try {
85
+ parts.push(zlib.zstdDecompressSync(f).toString("utf8"));
86
+ } catch {
87
+ // 写到一半的 frame
88
+ }
89
+ }
90
+ return parts.join("");
91
+ }
92
+
93
+ export function readEvents(file: string): DshEvent[] {
94
+ const out: DshEvent[] = [];
95
+ for (const line of decodeLog(fs.readFileSync(file)).split("\n")) {
96
+ if (!line.trim()) continue;
97
+ try {
98
+ const r = JSON.parse(line) as unknown;
99
+ if (r && typeof r === "object") out.push(r as DshEvent);
100
+ } catch {
101
+ // 半行
102
+ }
103
+ }
104
+ return out;
105
+ }
106
+
107
+ // ---------- 找文件 ----------
108
+
109
+ /** 按会话 id 找记录文件。目录名是 dsh 按 cwd 编的,不去复刻规则,挨个目录找 */
110
+ export function sessionFile(id: string): string | undefined {
111
+ if (!SESSION_ID.test(id)) return undefined;
112
+ let dirs: string[];
113
+ try {
114
+ dirs = fs.readdirSync(sessionsRoot());
115
+ } catch {
116
+ return undefined;
117
+ }
118
+ for (const d of dirs) {
119
+ const file = path.join(sessionsRoot(), d, id, LOG_NAME);
120
+ if (fs.existsSync(file)) return file;
121
+ }
122
+ return undefined;
123
+ }
124
+
125
+ // ---------- 取字段 ----------
126
+
127
+ function textOf(content: unknown, type = "text"): string {
128
+ if (typeof content === "string") return content;
129
+ if (!Array.isArray(content)) return "";
130
+ return content
131
+ .map((c) => (c && typeof c === "object" && (c as { type?: string }).type === type && typeof (c as { text?: unknown }).text === "string" ? (c as { text: string }).text : ""))
132
+ .filter((t) => t.trim())
133
+ .join("\n");
134
+ }
135
+
136
+ function argsOf(raw: unknown): Record<string, unknown> {
137
+ if (raw && typeof raw === "object") return raw as Record<string, unknown>;
138
+ if (typeof raw !== "string") return {};
139
+ try {
140
+ const v = JSON.parse(raw) as unknown;
141
+ return v && typeof v === "object" ? (v as Record<string, unknown>) : {};
142
+ } catch {
143
+ return {};
144
+ }
145
+ }
146
+
147
+ function header(events: DshEvent[]): DshEvent | undefined {
148
+ return events[0]?.type === "session" ? events[0] : undefined;
149
+ }
150
+
151
+ /** 用户亲手发的消息(不是运行时上下文、子 agent 结果、时间提示这些塞进来的) */
152
+ function userText(e: DshEvent): string | undefined {
153
+ if (e.type !== "user/message") return undefined;
154
+ const d = e.data as { content?: unknown; source?: { kind?: string } } | undefined;
155
+ if (d?.source?.kind !== "user") return undefined;
156
+ return textOf(d.content);
157
+ }
158
+
159
+ function cleanTitle(raw: string): string | undefined {
160
+ const t = stripContext(raw).replace(/\s+/g, " ").trim();
161
+ if (!t) return undefined;
162
+ return t.length > 60 ? `${t.slice(0, 60)}…` : t;
163
+ }
164
+
165
+ /** 模型起的标题(最后一次为准);只有截首句的 fallback 时返回 undefined */
166
+ function titleIn(events: DshEvent[]): string | undefined {
167
+ for (let i = events.length - 1; i >= 0; i--) {
168
+ const e = events[i]!;
169
+ if (e.type !== "session/title") continue;
170
+ const d = e.data as { title?: unknown; source?: { kind?: string } } | undefined;
171
+ if (d?.source?.kind === "fallback") continue;
172
+ if (typeof d?.title === "string" && d.title.trim()) return cleanTitle(d.title);
173
+ }
174
+ return undefined;
175
+ }
176
+
177
+ function firstPrompt(events: DshEvent[]): string | undefined {
178
+ for (const e of events) {
179
+ const raw = userText(e);
180
+ if (raw === undefined) continue;
181
+ const t = splitAttachmentNote(stripContext(raw)).text;
182
+ if (t) return cleanTitle(t);
183
+ }
184
+ return undefined;
185
+ }
186
+
187
+ /** 最后用的模型服务商:ACP profile 只认它自己有适配器的(默认只有 deepseek-official),别的恢复不了 */
188
+ function lastProvider(events: DshEvent[]): string | undefined {
189
+ for (let i = events.length - 1; i >= 0; i--) {
190
+ const e = events[i]!;
191
+ if (e.type === "model/selection" && typeof e.data?.provider === "string") return e.data.provider;
192
+ }
193
+ return undefined;
194
+ }
195
+
196
+ export function sessionTitleOf(id: string): string | undefined {
197
+ const file = sessionFile(id);
198
+ return file ? titleIn(readEvents(file)) : undefined;
199
+ }
200
+
201
+ export function sessionCwd(id: string): string | undefined {
202
+ const file = sessionFile(id);
203
+ if (!file) return undefined;
204
+ const cwd = header(readEvents(file))?.cwd;
205
+ return typeof cwd === "string" ? cwd : undefined;
206
+ }
207
+
208
+ /**
209
+ * 最近的会话;cwd 给了就只要这个目录的。子 agent 的会话、没说过话的、
210
+ * 用了 ACP 认不了的服务商的(比如在 dsh web 里配的别家模型)不列
211
+ */
212
+ export function listSessionFiles(cwd: string | undefined, limit: number, providers?: Set<string>): SessionSummary[] {
213
+ let dirs: string[];
214
+ try {
215
+ dirs = fs.readdirSync(sessionsRoot());
216
+ } catch {
217
+ return [];
218
+ }
219
+ const files: { id: string; file: string; mtime: number }[] = [];
220
+ for (const d of dirs) {
221
+ let names: string[];
222
+ try {
223
+ names = fs.readdirSync(path.join(sessionsRoot(), d));
224
+ } catch {
225
+ continue;
226
+ }
227
+ for (const id of names) {
228
+ if (!SESSION_ID.test(id)) continue;
229
+ const file = path.join(sessionsRoot(), d, id, LOG_NAME);
230
+ try {
231
+ files.push({ id, file, mtime: fs.statSync(file).mtimeMs });
232
+ } catch {
233
+ // 不是会话目录
234
+ }
235
+ }
236
+ }
237
+ files.sort((a, b) => b.mtime - a.mtime);
238
+ const out: SessionSummary[] = [];
239
+ // 最多看 200 个,别为了凑数把整个目录读一遍
240
+ for (const f of files.slice(0, 200)) {
241
+ if (out.length >= limit) break;
242
+ let events: DshEvent[];
243
+ try {
244
+ events = readEvents(f.file);
245
+ } catch {
246
+ continue;
247
+ }
248
+ const h = header(events);
249
+ if (!h || h.origin === "subagent") continue;
250
+ const at = typeof h.cwd === "string" ? h.cwd : undefined;
251
+ if (cwd && at && path.resolve(at) !== path.resolve(cwd)) continue;
252
+ const provider = lastProvider(events);
253
+ if (providers && provider && !providers.has(provider)) continue;
254
+ const prompt = firstPrompt(events);
255
+ if (!prompt) continue;
256
+ out.push({ id: f.id, title: titleIn(events) ?? prompt, ...(at ? { cwd: at } : {}), updatedAt: f.mtime });
257
+ }
258
+ return out;
259
+ }
260
+
261
+ /**
262
+ * 整理成「一问一答」:用户一条,助手把这一轮的文字拼成一条,工具调用挂成过程摘要。
263
+ * 和 Claude 的 readHistory 一个口径(见 claude/driver.ts)。
264
+ */
265
+ export function readHistoryEvents(events: DshEvent[]): HistoryMessage[] {
266
+ const out: HistoryMessage[] = [];
267
+ let assistant: HistoryMessage | null = null;
268
+ const todos = new TodoTracker();
269
+ const flush = () => {
270
+ if (assistant && (assistant.text.trim() || assistant.steps?.length)) out.push(assistant);
271
+ assistant = null;
272
+ };
273
+ for (const e of events) {
274
+ const raw = userText(e);
275
+ if (raw !== undefined) {
276
+ const { text, attachments } = splitAttachmentNote(stripContext(raw));
277
+ flush();
278
+ if (!text && attachments.length === 0) continue;
279
+ const id = (e.data as { id?: unknown }).id;
280
+ out.push({
281
+ role: "user",
282
+ text,
283
+ ...(typeof id === "string" ? { anchor: id } : {}),
284
+ ...(attachments.length ? { attachments } : {}),
285
+ ...(typeof e.time === "number" ? { ts: e.time } : {}),
286
+ });
287
+ continue;
288
+ }
289
+ if (e.type === "assistant/message") {
290
+ const msg = (e.data as { message?: { content?: unknown; id?: unknown } } | undefined)?.message;
291
+ if (!msg) continue;
292
+ assistant ??= { role: "assistant", text: "", steps: [] };
293
+ if (typeof msg.id === "string") assistant.anchor = msg.id;
294
+ if (typeof e.time === "number") assistant.ts = e.time;
295
+ const blocks = Array.isArray(msg.content) ? (msg.content as Record<string, unknown>[]) : [];
296
+ for (const b of blocks) {
297
+ if (b.type === "reasoning" && typeof b.text === "string" && b.text.trim()) {
298
+ assistant.steps!.push(`💭 ${summarize(b.text)}`);
299
+ } else if (b.type === "tool-call" && typeof b.name === "string") {
300
+ const input = argsOf(b.arguments);
301
+ const todo = todos.use(todoName(b.name), input, typeof b.id === "string" ? b.id : undefined);
302
+ if (todo?.changed) assistant.todos = todos.list;
303
+ assistant.steps!.push(todo ? todo.step : `🔧 ${describeDshStep(b.name, input)}`);
304
+ }
305
+ }
306
+ const text = textOf(blocks);
307
+ if (text.trim()) assistant.text += (assistant.text ? "\n\n" : "") + text;
308
+ continue;
309
+ }
310
+ if (e.type === "turn/end") flush();
311
+ }
312
+ flush();
313
+ return out;
314
+ }
315
+
316
+ export function readHistoryFile(id: string): HistoryMessage[] {
317
+ const file = sessionFile(id);
318
+ return file ? readHistoryEvents(readEvents(file)) : [];
319
+ }
320
+
321
+ /**
322
+ * 最近一轮(最后一个 turn/start 之后)的 token 用量。ACP 只报上下文占用,不报每一轮花了多少,
323
+ * 这一轮结束后从记录里加出来。inputTokens 是没命中缓存的部分(实测 input + cacheRead + output = total)
324
+ */
325
+ export function lastTurnUsage(events: DshEvent[]): TokenUsage | undefined {
326
+ let start = -1;
327
+ for (let i = events.length - 1; i >= 0; i--) {
328
+ if (events[i]!.type === "turn/start") {
329
+ start = i;
330
+ break;
331
+ }
332
+ }
333
+ if (start < 0) return undefined;
334
+ const u: TokenUsage = { input: 0, cacheRead: 0, cacheWrite: 0, output: 0 };
335
+ for (const e of events.slice(start)) {
336
+ if (e.type !== "assistant/message") continue;
337
+ const usage = (e.data as { usage?: Record<string, unknown> } | undefined)?.usage;
338
+ if (!usage) continue;
339
+ const n = (k: string) => (typeof usage[k] === "number" ? (usage[k] as number) : 0);
340
+ u.input += n("inputTokens");
341
+ u.cacheRead += n("cacheReadTokens");
342
+ u.cacheWrite += n("cacheWriteTokens");
343
+ u.output += n("outputTokens");
344
+ }
345
+ return u.input + u.cacheRead + u.cacheWrite + u.output > 0 ? u : undefined;
346
+ }
@@ -0,0 +1,191 @@
1
+ // DeepSeek Harness(dsh,@deepseek-ai/dsh):怎么拉起、数据在哪、模型 id 怎么换算。
2
+ //
3
+ // dsh 是全局装的 npm 命令(npm i -g @deepseek-ai/dsh),不随 agent-loft 安装。数据都在 DSH_HOME(默认 ~/.dsh):
4
+ // .credentials.yaml 凭据(DEEPSEEK_API_KEY 等,dsh web 里填的)
5
+ // sessions/<目录编码>/<会话 id>/session.v4.jsonl.zstd 会话记录(见 history.ts)
6
+ // profiles/acp/ ACP profile,第一次用时 dsh 自己从模板建
7
+ //
8
+ // 每个会话一个 `dsh --profile acp` 进程。按会话不同的东西都在启动时给:
9
+ // DSH_PERMISSION_MODE 沙箱档位(read-only / workspace-write / danger-full-access),见 modeOf
10
+ // --patch <文件> 追加的系统提示(system-prompt.personaSuffix)、成员不加载机器技能
11
+ import crypto from "node:crypto";
12
+ import fs from "node:fs";
13
+ import os from "node:os";
14
+ import path from "node:path";
15
+ import { agentEnvironment } from "../../core/agent-env.js";
16
+ import { config } from "../../core/config.js";
17
+ import type { PermissionLevel } from "../../core/permission.js";
18
+ import type { ModelInfo } from "../../core/types.js";
19
+ import { dataDir } from "../../home.js";
20
+ import { AcpConnection, flatOptions, initialize, type AcpSpawn, type ConfigOption } from "./acp.js";
21
+
22
+ export function dshHome(): string {
23
+ const c = config().agents.dsh;
24
+ return c.home || process.env.DSH_HOME || path.join(os.homedir(), ".dsh");
25
+ }
26
+
27
+ export function sessionsRoot(): string {
28
+ return path.join(dshHome(), "sessions");
29
+ }
30
+
31
+ /** 级别 → dsh 的权限预设。不给 = dsh 默认(工作区可写,越界才问) */
32
+ export function modeOf(level: PermissionLevel | undefined, plan?: boolean): "read-only" | "workspace-write" | "danger-full-access" {
33
+ if (plan || level === "ask") return "read-only";
34
+ if (level === "full") return "danger-full-access";
35
+ return "workspace-write";
36
+ }
37
+
38
+ /** 每个进程的 --patch 文件放这里,进程退了就删 */
39
+ const PATCH_DIR = path.join(dataDir, "dsh");
40
+
41
+ export type LaunchSpec = {
42
+ cwd: string;
43
+ mode: ReturnType<typeof modeOf>;
44
+ /** 追加在 dsh 系统提示后面 */
45
+ append?: string;
46
+ /** 成员:不加载机器上的技能 */
47
+ noMachineSkills?: boolean;
48
+ env?: Record<string, string>;
49
+ };
50
+
51
+ /** 生成启动参数;返回的 cleanup 删掉临时 patch 文件 */
52
+ export function launchSpec(spec: LaunchSpec): { spawn: AcpSpawn; cleanup: () => void } {
53
+ const c = config().agents.dsh;
54
+ const args = ["--profile", "acp"];
55
+ if (c.patch) args.push("--patch", c.patch);
56
+ // YAML 是 JSON 的超集,直接写 JSON,免得自己转义
57
+ const entries: object[] = [];
58
+ if (spec.append) {
59
+ // personaSuffix 是模板,{{model}} 这类会被替换:拆开花括号
60
+ const suffix = spec.append.replace(/\{\{/g, "{ {").replace(/\}\}/g, "} }");
61
+ entries.push({ id: "system-prompt", config: { personaPrefix: "You are a coding agent powered by the {{model}} model.", personaSuffix: suffix } });
62
+ }
63
+ if (spec.noMachineSkills) entries.push({ id: "skill-filesystem", disabled: true });
64
+ let file: string | undefined;
65
+ if (entries.length) {
66
+ fs.mkdirSync(PATCH_DIR, { recursive: true, mode: 0o700 });
67
+ file = path.join(PATCH_DIR, `patch-${process.pid}-${crypto.randomBytes(6).toString("hex")}.yml`);
68
+ fs.writeFileSync(file, JSON.stringify(entries, null, 2), { mode: 0o600 });
69
+ args.push("--patch", file);
70
+ }
71
+ const env: NodeJS.ProcessEnv = {
72
+ ...agentEnvironment(process.env),
73
+ ...(spec.env ?? {}),
74
+ DSH_PERMISSION_MODE: spec.mode,
75
+ ...(c.home ? { DSH_HOME: c.home } : {}),
76
+ };
77
+ return {
78
+ spawn: { command: c.path || "dsh", args, cwd: spec.cwd, env },
79
+ cleanup: () => {
80
+ if (file) fs.rmSync(file, { force: true });
81
+ },
82
+ };
83
+ }
84
+
85
+ /** 上次异常退出留下的 patch 文件 */
86
+ export function sweepPatches(): void {
87
+ try {
88
+ for (const n of fs.readdirSync(PATCH_DIR)) if (n.startsWith("patch-")) fs.rmSync(path.join(PATCH_DIR, n), { force: true });
89
+ } catch {
90
+ // 目录还没有
91
+ }
92
+ }
93
+
94
+ // ---------- 模型 ----------
95
+
96
+ /** ACP 的模型选项值是 JSON 数组字符串 ["provider","model"];agent-loft 里用 provider/model */
97
+ export function modelIdOf(value: string): string | undefined {
98
+ try {
99
+ const v = JSON.parse(value) as unknown;
100
+ if (Array.isArray(v) && typeof v[0] === "string" && typeof v[1] === "string") return `${v[0]}/${v[1]}`;
101
+ } catch {
102
+ // 不是数组
103
+ }
104
+ return undefined;
105
+ }
106
+
107
+ export function modelValueOf(id: string): string {
108
+ const i = id.indexOf("/");
109
+ // 只写了模型名:按官方 DeepSeek 算
110
+ return i < 0 ? JSON.stringify(["deepseek-official", id]) : JSON.stringify([id.slice(0, i), id.slice(i + 1)]);
111
+ }
112
+
113
+ /** 从 session/new 返回的配置选项里读出模型列表 */
114
+ export function modelsOf(opts: ConfigOption[]): ModelInfo[] {
115
+ const model = opts.find((o) => o.id === "model");
116
+ const effort = opts.find((o) => o.id === "reasoning_effort");
117
+ const efforts = flatOptions(effort).map((o) => o.value);
118
+ const out: ModelInfo[] = [];
119
+ for (const o of flatOptions(model)) {
120
+ const id = modelIdOf(o.value);
121
+ if (!id) continue;
122
+ out.push({
123
+ id,
124
+ label: o.name || id,
125
+ ...(o.description ? { description: o.description } : {}),
126
+ ...(efforts.length ? { efforts } : {}),
127
+ ...(o.value === model?.currentValue ? { isDefault: true } : {}),
128
+ });
129
+ }
130
+ return out;
131
+ }
132
+
133
+ /** 当前选中的模型 / 思考程度 */
134
+ export function runtimeOf(opts: ConfigOption[]): { model?: string; effort?: string } {
135
+ const model = opts.find((o) => o.id === "model")?.currentValue;
136
+ const effort = opts.find((o) => o.id === "reasoning_effort")?.currentValue;
137
+ const id = model ? modelIdOf(model) : undefined;
138
+ return { ...(id ? { model: id } : {}), ...(effort ? { effort } : {}) };
139
+ }
140
+
141
+ // ---------- 一次性的探测进程 ----------
142
+
143
+ /** 探测用的工作目录:建出来的会话事后删掉,不进会话列表 */
144
+ const PROBE_CWD = path.join(os.tmpdir(), "agent-loft-dsh-probe");
145
+
146
+ /**
147
+ * 拉一个临时进程、建一个临时会话,交给 fn 用完就关、连会话记录一起删。
148
+ * 模型列表、后台整理记忆都走这里(ACP 没有不建会话就能问的接口)
149
+ */
150
+ export async function withProbe<T>(
151
+ fn: (conn: AcpConnection, sessionId: string, options: ConfigOption[]) => Promise<T>,
152
+ launch: Partial<LaunchSpec> = {},
153
+ ): Promise<T> {
154
+ fs.mkdirSync(PROBE_CWD, { recursive: true });
155
+ const { spawn, cleanup } = launchSpec({ cwd: PROBE_CWD, mode: "read-only", ...launch });
156
+ const conn = new AcpConnection(spawn);
157
+ let sessionId: string | undefined;
158
+ try {
159
+ await initialize(conn);
160
+ const res = await conn.request<{ sessionId: string; configOptions?: ConfigOption[] }>("session/new", { cwd: PROBE_CWD, mcpServers: [] });
161
+ sessionId = res.sessionId;
162
+ return await fn(conn, sessionId, res.configOptions ?? []);
163
+ } finally {
164
+ if (sessionId) await conn.request("session/close", { sessionId }).catch(() => {});
165
+ await conn.shutdown(3000).catch(() => {});
166
+ cleanup();
167
+ if (sessionId) removeSession(sessionId);
168
+ }
169
+ }
170
+
171
+ /** 删掉一条会话的记录目录(只给探测用的临时会话用) */
172
+ function removeSession(id: string): void {
173
+ if (!/^[A-Za-z0-9_-]{8,80}$/.test(id)) return;
174
+ let dirs: string[] = [];
175
+ try {
176
+ dirs = fs.readdirSync(sessionsRoot());
177
+ } catch {
178
+ return;
179
+ }
180
+ for (const d of dirs) {
181
+ const dir = path.join(sessionsRoot(), d, id);
182
+ if (!fs.existsSync(dir)) continue;
183
+ fs.rmSync(dir, { recursive: true, force: true });
184
+ // 探测目录下没别的会话了:目录也删掉
185
+ try {
186
+ fs.rmdirSync(path.join(sessionsRoot(), d));
187
+ } catch {
188
+ // 不空
189
+ }
190
+ }
191
+ }