zcode-pro 1.6.2 → 1.8.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.
@@ -0,0 +1,488 @@
1
+ #!/usr/bin/env node
2
+ // MCP stdio 单例桥(自 zcode-plugins 的 headroom/mcp/bridge.mjs 改造):同一台机器上
3
+ // 的多个 ZCode 运行时(主会话 + 子代理等)都按配置各自拉起一份 MCP 服务进程,serena
4
+ // 这类服务单份带一个语言服务器(JDTLS 一份 1-2G 内存),两份抢同一项目的工作区会一个
5
+ // 起不来、抢得凶还会把缓存写坏。本桥让首个实例兼任守护方(持有真正的服务进程),后续
6
+ // 实例经本地套接字复用同一个 MCP 会话:initialize 只发给服务一次(在途时后来者的握手
7
+ // 挂起、应答后扇出,再后来的直接用缓存应答),请求/应答经 id 重映射表路由回各自客户端
8
+ // (id 原值原样保留,类型不改;客户端的取消通知按在途请求改写 id 后转发),服务端通知
9
+ // 广播给所有客户端。全部客户端断开并空闲一段时间后,守护方结束服务进程并退出。套接字
10
+ // 机制不可用时自动退化为直接执行服务命令。
11
+ //
12
+ // 在原版之上加了四件事:
13
+ // 1. $CWD 令牌:服务命令参数里的 $CWD 替换为本进程工作目录(会话工作区),服务身份
14
+ // (套接字名哈希)因此按项目区分——同一项目多会话共用一份服务,不同项目各用各的;
15
+ // 2. 保温上限 2 份:新守护方就绪后清点其它守护方,只保留最近活跃的一个(合计两份),
16
+ // 其余发关闭指令优雅退出;死套接字残留顺手清掉;
17
+ // 3. 坏缓存自愈:守护方启动服务后盯 90 秒服务日志,出现语言服务器启动失败就按日志里
18
+ // 的工作区目录清掉损坏缓存并退出守护方(下个连接重新孵化、重建缓存);
19
+ // 4. 空闲存活时间默认 30 分钟(原版 2 分钟),serena 语言服务器冷启动贵,留长些。
20
+ //
21
+ // 用法: node mcp-bridge.mjs -- <服务命令> [参数...]
22
+ // 环境变量:
23
+ // MCP_BRIDGE_IDLE_MS 全部客户端断开后守护方存活时间(默认 1800000)
24
+ // MCP_BRIDGE_DEBUG 置 1 输出调试日志到 stderr
25
+ //
26
+ // 协议按 MCP stdio 传输层:一行一条 JSON 消息(NDJSON)。
27
+
28
+ import net from 'node:net';
29
+ import { spawn } from 'node:child_process';
30
+ import { createHash, randomBytes } from 'node:crypto';
31
+ import { chmodSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, utimesSync } from 'node:fs';
32
+ import { homedir, tmpdir } from 'node:os';
33
+ import path from 'node:path';
34
+
35
+ const dash = process.argv.indexOf('--');
36
+ if (dash < 0 || !process.argv[dash + 1]) {
37
+ console.error('[mcp-bridge] 用法: bridge.mjs -- <服务命令> [参数...]');
38
+ process.exit(2);
39
+ }
40
+ const serverArgv = process.argv.slice(dash + 1)
41
+ // $CWD 令牌换成会话工作区:服务身份(套接字哈希)按项目区分,同项目共用、异项目隔离
42
+ .map((a) => (a === '$CWD' ? process.cwd() : a));
43
+ const IDLE_MS = Number(process.env.MCP_BRIDGE_IDLE_MS) > 0 ? Number(process.env.MCP_BRIDGE_IDLE_MS) : 1800000;
44
+ const log = (...a) => { if (process.env.MCP_BRIDGE_DEBUG) console.error('[mcp-bridge]', ...a); };
45
+
46
+ // 套接字路径:同一服务命令(含参数)共用一个;Windows 用命名管道
47
+ const sockKey = createHash('sha1').update(JSON.stringify(serverArgv)).digest('hex').slice(0, 12);
48
+ // 目录不可信(同机他用户预占等)时为 false:不启用套接字,退化为直接执行服务命令
49
+ let sockDirOk = true;
50
+ const sockPath = process.platform === 'win32'
51
+ ? `\\\\.\\pipe\\zcode-mcp-bridge-${sockKey}`
52
+ : (() => {
53
+ const dir = path.join(tmpdir(), `zcode-mcp-bridge-${process.getuid()}`);
54
+ // 0700:守护方套接字无应用层鉴权,目录必须仅限本用户访问;
55
+ // mkdir 的 mode 只对新建生效,已存在(含前次宽松权限创建)的要补校正
56
+ try { mkdirSync(dir, { recursive: true, mode: 0o700 }); } catch (e) {
57
+ sockDirOk = false;
58
+ console.error('[mcp-bridge] 建套接字目录失败,不启用套接字:', e.message);
59
+ return '';
60
+ }
61
+ try { chmodSync(dir, 0o700); } catch (e) {
62
+ sockDirOk = false;
63
+ console.error('[mcp-bridge] 套接字目录改 0700 失败,不启用套接字:', e.message);
64
+ return '';
65
+ }
66
+ // 同机他用户可预占同名目录(mkdir 对已存在目录静默成功),把套接字放进他的地盘
67
+ // 劫持连接。逐项核对:真目录(lstat 下符号链接不算目录)、属主是自己、无组/其他位,
68
+ // 任一不满足就不启用套接字
69
+ try {
70
+ const st = lstatSync(dir);
71
+ if (!st.isDirectory() || st.uid !== process.getuid() || (st.mode & 0o077) !== 0) {
72
+ sockDirOk = false;
73
+ console.error('[mcp-bridge] 套接字目录属主/权限不对,不启用套接字:', dir);
74
+ return '';
75
+ }
76
+ } catch (e) {
77
+ sockDirOk = false;
78
+ console.error('[mcp-bridge] 套接字目录核对失败,不启用套接字:', e.message);
79
+ return '';
80
+ }
81
+ return path.join(dir, `${sockKey}.sock`);
82
+ })();
83
+
84
+ // 活跃时间戳:守护方把套接字文件 mtime 刷成最近一次收发消息的时间,供保温上限踢除
85
+ // 时按“最久没用”排序(Windows 命名管道没法写 mtime,跳过,靠空闲自退兜底)
86
+ let lastSockTouch = 0;
87
+ function touchSock() {
88
+ if (process.platform === 'win32' || !sockPath) return;
89
+ const now = Date.now();
90
+ if (now - lastSockTouch < 5000) return;
91
+ lastSockTouch = now;
92
+ try { utimesSync(sockPath, now / 1000, now / 1000); } catch { /* ignore */ }
93
+ }
94
+
95
+ const isRequest = (m) => m && m.method !== undefined && m.id !== undefined && m.id !== null;
96
+ const isNotification = (m) => m && m.method !== undefined && (m.id === undefined || m.id === null);
97
+ const isResponse = (m) => m && (m.result !== undefined || m.error !== undefined) && m.id !== undefined;
98
+
99
+ // 按行拆流(TCP 是字节流,消息可能跨块/粘包),cb 收到完整一行
100
+ function onLines(sock, cb) {
101
+ let buf = '';
102
+ sock.setEncoding('utf8');
103
+ sock.on('data', (chunk) => {
104
+ buf += chunk;
105
+ let idx;
106
+ while ((idx = buf.indexOf('\n')) >= 0) {
107
+ const line = buf.slice(0, idx);
108
+ buf = buf.slice(idx + 1);
109
+ if (line.trim()) cb(line);
110
+ }
111
+ });
112
+ }
113
+
114
+ // =====================================================================
115
+ // 客户端:把本进程 stdio 桥接到守护方套接字;守护方消失则退出,
116
+ // 由宿主(ZCode)按 MCP 连接失败自行处理。
117
+ // =====================================================================
118
+ function runClient() {
119
+ // 12 位十六进制(48bit):短 id 并发客户端会碰撞——守护方按 id 路由应答,
120
+ // 碰撞时连接互相覆盖、应答串线
121
+ const clientId = randomBytes(6).toString('hex');
122
+ const sock = net.connect(sockPath);
123
+ const send = (line) => { try { sock.write(JSON.stringify({ c: clientId, d: line }) + '\n'); } catch { /* ignore */ } };
124
+ const stop = () => { try { sock.destroy(); } catch { /* ignore */ } process.exit(1); };
125
+
126
+ sock.on('connect', () => log(`client ${clientId} 已连接`));
127
+ sock.on('close', stop);
128
+ sock.on('error', stop);
129
+ onLines(sock, (line) => {
130
+ try {
131
+ const env = JSON.parse(line);
132
+ // '*' 为守护方广播;d 是已序列化的服务端消息原文,直接透传给宿主
133
+ if (env && typeof env.d === 'string' && (env.c === clientId || env.c === '*')) {
134
+ process.stdout.write(env.d + '\n');
135
+ }
136
+ } catch { log('守护方消息解析失败'); }
137
+ });
138
+
139
+ onLines(process.stdin, send);
140
+ process.stdin.on('end', () => { try { sock.end(); } catch { /* ignore */ } process.exit(0); });
141
+ process.stdin.on('close', () => { try { sock.end(); } catch { /* ignore */ } });
142
+ }
143
+
144
+ // =====================================================================
145
+ // 守护方:监听套接字,持有真正的服务进程,服务多个客户端
146
+ // =====================================================================
147
+ function createDaemon() {
148
+ const clients = new Map(); // clientId -> socket
149
+ let server = null;
150
+ let serverDead = false;
151
+ let initResult = null; // 首个 initialize 的结果缓存(后来客户端直接复用)
152
+ let initInFlight = false; // 首个 initialize 已发出、应答未回(期间的握手挂起等扇出)
153
+ const initWaiters = []; // 等首个 initialize 应答的后来客户端 [{ client, id }]
154
+ let sawInitNotified = false; // initialized 通知只向服务放行一份
155
+ const pending = new Map(); // 发往服务的请求 id -> { client, id, init? }
156
+ const serverReqs = new Set(); // 服务端主动发起、尚无应答的请求 id(首个应答生效)
157
+ let seq = 0;
158
+ let idleTimer = null;
159
+ let closing = false;
160
+ let ownsSock = false; // 是否取得监听权(决定退出时能否清理套接字文件)
161
+
162
+ const clearIdle = () => { if (idleTimer) { clearTimeout(idleTimer); idleTimer = null; } };
163
+ const armIdle = () => { clearIdle(); idleTimer = setTimeout(shutdown, IDLE_MS); };
164
+
165
+ function sendTo(clientId, msg) {
166
+ const s = clients.get(clientId);
167
+ if (!s) return;
168
+ try { s.write(JSON.stringify({ c: clientId, d: JSON.stringify(msg) }) + '\n'); } catch { /* ignore */ }
169
+ }
170
+ function broadcast(msg) {
171
+ const payload = JSON.stringify({ c: '*', d: JSON.stringify(msg) }) + '\n';
172
+ for (const s of clients.values()) { try { s.write(payload); } catch { /* ignore */ } }
173
+ }
174
+ const toServer = (msg) => {
175
+ if (!server || serverDead) return;
176
+ try { server.stdin.write(JSON.stringify(msg) + '\n'); } catch { /* ignore */ }
177
+ };
178
+
179
+ function ensureServer() {
180
+ if (server || serverDead) return;
181
+ log('启动服务:', serverArgv.join(' '));
182
+ // windowsHide:Windows 上服务命令常是控制台 exe(headroom.exe),不隐藏会弹黑窗
183
+ server = spawn(serverArgv[0], serverArgv.slice(1), { stdio: ['pipe', 'pipe', 'inherit'], windowsHide: true });
184
+ server.on('error', (err) => { log('服务进程启动失败:', err.message); serverDead = true; shutdown(); });
185
+ onLines(server.stdout, handleServerLine);
186
+ server.on('exit', () => { serverDead = true; log('服务进程退出'); shutdown(); });
187
+ watchLsFailure();
188
+ }
189
+
190
+ // —— 坏缓存自愈(盯 serena 服务日志)——
191
+ // JDTLS 工作区缓存损坏时语言服务器启动 1 秒即静默猝死,serena 本体活着但符号工具全废
192
+ // (日志里只有 LanguageServerManagerInitialisationError)。启动后 90 秒内盯服务自己的
193
+ // 日志:出现失败就按日志里记录的工作区目录清掉损坏缓存,并退出守护方——下一个连接重新
194
+ // 孵化服务、重建缓存,不用人手工清。找不到日志或工作区路径时静默跳过(自愈只兜底,不为
195
+ // 它冒失删东西)。
196
+ function watchLsFailure() {
197
+ const logsRoot = path.join(homedir(), '.serena', 'logs');
198
+ const before = new Set();
199
+ try {
200
+ for (const d of readdirSync(logsRoot)) {
201
+ for (const n of readdirSync(path.join(logsRoot, d))) before.add(`${d}/${n}`);
202
+ }
203
+ } catch { /* 日志目录还没建:按空基线处理,建好后再对比 */ }
204
+ const deadline = Date.now() + 90000;
205
+ const timer = setInterval(() => {
206
+ if (closing || serverDead || Date.now() > deadline) { clearInterval(timer); return; }
207
+ let fresh = null;
208
+ try {
209
+ const news = [];
210
+ for (const d of readdirSync(logsRoot)) {
211
+ for (const n of readdirSync(path.join(logsRoot, d))) {
212
+ if (!before.has(`${d}/${n}`) && n.startsWith('mcp_') && n.endsWith('.txt')) news.push(path.join(logsRoot, d, n));
213
+ }
214
+ }
215
+ news.sort();
216
+ fresh = news[news.length - 1] || null;
217
+ } catch { return; /* 目录还没出现:下一轮再看 */ }
218
+ if (!fresh) return;
219
+ let text = '';
220
+ try { text = readFileSync(fresh, 'utf8'); } catch { return; }
221
+ if (!/Failed to start \d+ language server|LanguageServerManagerInitialisationError/.test(text)) return;
222
+ clearInterval(timer);
223
+ log('检测到语言服务器启动失败,清坏缓存自愈');
224
+ const m = /EclipseJDTLS[\\/]workspaces[\\/]([0-9a-f]+)/.exec(text);
225
+ if (m) {
226
+ try {
227
+ rmSync(path.join(homedir(), '.serena', 'language_servers', 'static', 'EclipseJDTLS', 'workspaces', m[1]), { recursive: true, force: true });
228
+ } catch { /* ignore */ }
229
+ }
230
+ shutdown();
231
+ }, 5000);
232
+ timer.unref?.();
233
+ }
234
+
235
+ function handleServerLine(line) {
236
+ touchSock();
237
+ let msg;
238
+ try { msg = JSON.parse(line); } catch { log('服务消息解析失败'); return; }
239
+ if (isResponse(msg)) {
240
+ const hit = pending.get(String(msg.id));
241
+ if (!hit) return; // 服务端主动请求的重复应答(已放行首份),丢弃
242
+ pending.delete(String(msg.id));
243
+ if (hit.init) {
244
+ // 首个握手应答:缓存成功结果(失败不缓存,之后的客户端可重新握手),
245
+ // 并扇出给在途期间到达的后来客户端
246
+ initInFlight = false;
247
+ if (msg.result !== undefined) initResult = msg.result;
248
+ for (const w of initWaiters.splice(0)) {
249
+ const out = { jsonrpc: '2.0', id: w.id };
250
+ if (msg.result !== undefined) out.result = msg.result; else out.error = msg.error;
251
+ sendTo(w.client, out);
252
+ }
253
+ }
254
+ const out = { jsonrpc: '2.0', id: hit.id };
255
+ if (msg.result !== undefined) out.result = msg.result; else out.error = msg.error;
256
+ sendTo(hit.client, out);
257
+ return;
258
+ }
259
+ if (isRequest(msg)) serverReqs.add(String(msg.id)); // 应答只收第一份
260
+ broadcast(msg);
261
+ }
262
+
263
+ function handleClientLine(clientId, rawLine) {
264
+ touchSock();
265
+ let msg;
266
+ try { msg = JSON.parse(rawLine); } catch { return; }
267
+ if (isRequest(msg)) {
268
+ if (msg.method === 'initialize') {
269
+ if (initResult) {
270
+ // 握手结果已有缓存:直接应答,服务侧不重复 initialize
271
+ sendTo(clientId, { jsonrpc: '2.0', id: msg.id, result: initResult });
272
+ return;
273
+ }
274
+ if (initInFlight) {
275
+ // 首个 initialize 还在途:挂起等扇出。直接放行会给服务发第二次握手,
276
+ // 服务端通常按协议错误拒绝,该客户端的工具将全部不可用
277
+ initWaiters.push({ client: clientId, id: msg.id });
278
+ return;
279
+ }
280
+ initInFlight = true;
281
+ }
282
+ ensureServer();
283
+ const daemonId = `b${seq++}`;
284
+ pending.set(daemonId, { client: clientId, id: msg.id, init: msg.method === 'initialize' });
285
+ toServer({ ...msg, id: daemonId });
286
+ return;
287
+ }
288
+ if (isNotification(msg)) {
289
+ ensureServer();
290
+ if (msg.method === 'initialized' || msg.method === 'notifications/initialized') {
291
+ if (sawInitNotified) return; // 重复的握手完成通知不再打扰服务
292
+ sawInitNotified = true;
293
+ }
294
+ // 取消通知带的是客户端自己的请求 id:找到本客户端的在途请求改写成守护方
295
+ // id 再转发;找不到(已完成/不属于它)就丢弃——原样转发会误伤服务端认识的
296
+ // 恰好同 id 的其他请求
297
+ if (msg.method === 'notifications/cancelled' && msg.params && msg.params.requestId !== undefined && msg.params.requestId !== null) {
298
+ let target = null;
299
+ for (const [d, hit] of pending) {
300
+ if (hit.client === clientId && String(hit.id) === String(msg.params.requestId)) { target = d; break; }
301
+ }
302
+ if (!target) { log(`client ${clientId} 取消的请求不在途,丢弃`); return; }
303
+ toServer({ ...msg, params: { ...msg.params, requestId: target } });
304
+ return;
305
+ }
306
+ toServer(msg);
307
+ return;
308
+ }
309
+ if (isResponse(msg)) {
310
+ // 客户端应答服务端主动发起的请求:id 与服务端原值一致,只放行第一份
311
+ if (serverReqs.has(String(msg.id))) {
312
+ serverReqs.delete(String(msg.id));
313
+ toServer(msg);
314
+ }
315
+ }
316
+ }
317
+
318
+ function shutdown() {
319
+ if (closing) return;
320
+ closing = true;
321
+ clearIdle();
322
+ for (const s of clients.values()) { try { s.end(); } catch { /* ignore */ } }
323
+ if (server) {
324
+ try { server.kill('SIGTERM'); } catch { /* ignore */ }
325
+ const kill = setTimeout(() => { try { server.kill('SIGKILL'); } catch { /* ignore */ } process.exit(0); }, 3000);
326
+ kill.unref();
327
+ server.on('exit', () => process.exit(0));
328
+ } else {
329
+ process.exit(0);
330
+ }
331
+ }
332
+
333
+ const listener = net.createServer((sock) => {
334
+ clearIdle();
335
+ let clientId = null;
336
+ sock.on('close', () => {
337
+ if (clientId) {
338
+ clients.delete(clientId);
339
+ log(`client ${clientId} 断开,剩余 ${clients.size}`);
340
+ }
341
+ // 未注册就断开的静默连接也要能重新进入空闲计时,否则守护方永不退出
342
+ if (clients.size === 0) armIdle();
343
+ });
344
+ sock.on('error', () => { try { sock.destroy(); } catch { /* ignore */ } });
345
+ onLines(sock, (line) => {
346
+ let env;
347
+ try { env = JSON.parse(line); } catch { return; }
348
+ if (!env || !env.c || typeof env.d !== 'string') return;
349
+ // 控制指令(不占客户端身份):保温上限踢除时由同伴发来,走优雅关闭
350
+ if (env.c === '@ctl') {
351
+ if (env.d === 'shutdown') { log('收到同伴关闭指令,优雅退出'); shutdown(); }
352
+ return;
353
+ }
354
+ if (!clientId) {
355
+ clientId = env.c;
356
+ clients.set(clientId, sock);
357
+ log(`client ${clientId} 接入`);
358
+ }
359
+ if (env.c === clientId) handleClientLine(clientId, env.d);
360
+ });
361
+ });
362
+
363
+ process.on('SIGINT', shutdown);
364
+ process.on('SIGTERM', shutdown);
365
+ // 只有真正取得监听权的进程才在退出时清理套接字文件,避免误删竞争赢家的
366
+ process.on('exit', () => {
367
+ if (!ownsSock) return;
368
+ try { if (process.platform !== 'win32') rmSync(sockPath, { force: true }); } catch { /* ignore */ }
369
+ });
370
+ return {
371
+ listener,
372
+ start() { ownsSock = true; armIdle(); },
373
+ shutdown,
374
+ };
375
+ }
376
+
377
+ // —— 启动流程 ——
378
+ // 客户端模式:先试连现有守护方;没有则孵化一个独立的守护进程(detached,与任何
379
+ // ZCode 运行时进程无关——运行时被强杀不影响其他客户端),再接入。
380
+ // 守护模式(--daemon-role):只监听 + 持有服务进程,不接 stdio;监听竞争的输家
381
+ // 静默退出,因此多个客户端同时孵化也不会出现两个守护方。
382
+ const probe = (p = sockPath) => new Promise((resolve) => {
383
+ const s = net.connect(p);
384
+ s.once('connect', () => { s.destroy(); resolve(true); });
385
+ s.once('error', () => resolve(false));
386
+ });
387
+
388
+ // 保温上限 2 份:新守护方就绪后清点其它守护方,保留最近活跃的一个(合计两份),其余发
389
+ // 关闭指令走优雅退出;探不到人的死套接字残留顺手清掉。仅 POSIX(Windows 命名管道没法
390
+ // 列目录,那边靠空闲自退兜底)
391
+ async function sweepPeers() {
392
+ if (process.platform === 'win32') return;
393
+ const dir = path.dirname(sockPath);
394
+ let names = [];
395
+ try { names = readdirSync(dir).filter((n) => n.endsWith('.sock')); } catch { return; }
396
+ const alive = [];
397
+ for (const n of names) {
398
+ if (n === path.basename(sockPath)) continue;
399
+ const p = path.join(dir, n);
400
+ let m = 0;
401
+ try { m = statSync(p).mtimeMs; } catch { continue; }
402
+ if (await probe(p)) alive.push({ p, m });
403
+ else { try { rmSync(p, { force: true }); } catch { /* ignore */ } }
404
+ }
405
+ alive.sort((a, b) => b.m - a.m);
406
+ for (const { p } of alive.slice(1)) {
407
+ log('保温上限 2 份,踢除最久未用实例:', p);
408
+ try {
409
+ const s = net.connect(p);
410
+ s.on('connect', () => {
411
+ s.write(JSON.stringify({ c: '@ctl', d: 'shutdown' }) + '\n');
412
+ setTimeout(() => { try { s.destroy(); } catch { /* ignore */ } }, 200);
413
+ });
414
+ s.on('error', () => { try { s.destroy(); } catch { /* ignore */ } });
415
+ } catch { /* ignore */ }
416
+ }
417
+ }
418
+
419
+ // 监听一次:成功 resolve(true);失败 resolve(err)
420
+ const tryListen = (listener, p) => new Promise((resolve) => {
421
+ const onOk = () => { cleanup(); resolve(true); };
422
+ const onErr = (e) => { cleanup(); resolve(e); };
423
+ const cleanup = () => { listener.removeListener('listening', onOk); listener.removeListener('error', onErr); };
424
+ listener.once('listening', onOk);
425
+ listener.once('error', onErr);
426
+ listener.listen(p);
427
+ });
428
+
429
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
430
+
431
+ if (process.argv.includes('--daemon-role')) {
432
+ // 目录不可信时不启动监听(不给劫持者递套接字),上面已记日志
433
+ if (!sockDirOk) process.exit(0);
434
+ const daemon = createDaemon();
435
+ let res = await tryListen(daemon.listener, sockPath);
436
+ if (res !== true && res && res.code === 'EADDRINUSE') {
437
+ // 套接字文件残留(守护方被强杀未及清理):确认确实无人监听后清掉重试一次;
438
+ // 若真有别的守护方,本进程就是多余竞争者,退出
439
+ if (!(await probe())) {
440
+ try { if (process.platform !== 'win32') rmSync(sockPath, { force: true }); } catch { /* ignore */ }
441
+ res = await tryListen(daemon.listener, sockPath);
442
+ }
443
+ }
444
+ if (res === true) {
445
+ daemon.start();
446
+ log('守护进程就绪:', sockPath);
447
+ sweepPeers().catch(() => { /* 清点失败不影响服务 */ });
448
+ } else {
449
+ log('守护监听竞争失败,退出:', res && res.code);
450
+ process.exit(0);
451
+ }
452
+ } else {
453
+ const directRun = () => {
454
+ log('回退直连:', serverArgv.join(' '));
455
+ // windowsHide:服务命令常是控制台 exe,不隐藏会弹黑窗
456
+ const child = spawn(serverArgv[0], serverArgv.slice(1), { stdio: 'inherit', windowsHide: true });
457
+ child.on('error', () => process.exit(127));
458
+ // 被信号杀掉时退出码 c 是 null,这里用 1:报 0 会被上层当成正常结束
459
+ child.on('exit', (c) => process.exit(c ?? 1));
460
+ };
461
+
462
+ // 目录不可信时不孵化守护方、不连套接字,直接执行服务命令
463
+ if (!sockDirOk) {
464
+ directRun();
465
+ } else {
466
+ if (!(await probe())) {
467
+ // 随机小延迟错峰孵化,减少重复 daemon(输了也会自行退出,无副作用)
468
+ await sleep(Math.floor(Math.random() * 150));
469
+ if (!(await probe())) {
470
+ const { realpathSync } = await import('node:fs');
471
+ const self = realpathSync(process.argv[1]);
472
+ const child = spawn(process.execPath, [self, '--daemon-role', '--', ...serverArgv], {
473
+ detached: true,
474
+ stdio: 'ignore',
475
+ env: process.env,
476
+ // 关键:detached 在 Windows 上会为子进程新分配控制台,不配 windowsHide
477
+ // 就是那个可见的 headroom 黑窗(守护方再孵化 headroom.exe 共用该控制台)
478
+ windowsHide: true,
479
+ });
480
+ child.unref();
481
+ // 等守护方就绪(监听竞争输家会退出,赢家通常百毫秒内就绪)
482
+ for (let i = 0; i < 100 && !(await probe()); i++) await sleep(100);
483
+ }
484
+ }
485
+ if (await probe()) runClient();
486
+ else directRun();
487
+ }
488
+ }
@@ -0,0 +1,140 @@
1
+ // 导入会话的入口:列出来源会话、批量导入。
2
+ import { existsSync, mkdirSync } from 'node:fs';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { join } from 'node:path';
5
+ import { isUnder, oneLine } from './util.mjs';
6
+ import { listSourceSessions, readSourceSession, sourceAvailable, sourceList, sourceRoots } from './sources.mjs';
7
+ import {
8
+ aliveTaskIds, aliveTaskStates, getProject, readRegistry, sourceKey, workspaceForImport, writeImportedSession, writeRegistry,
9
+ } from './write.mjs';
10
+
11
+ function present(session) {
12
+ return {
13
+ source: session.source,
14
+ sessionId: session.sessionId,
15
+ title: oneLine(session.title, 200) || session.sessionId,
16
+ cwd: session.cwd || '',
17
+ createdAt: session.createdAt || 0,
18
+ updatedAt: session.updatedAt || 0,
19
+ sourcePath: session.sourcePath,
20
+ archived: !!session.archived,
21
+ subagent: !!session.subagent,
22
+ codexImport: !!session.codexImport,
23
+ large: !!session.large,
24
+ model: session.model || '',
25
+ cwdExists: !!session.cwd && existsSync(session.cwd),
26
+ };
27
+ }
28
+
29
+ export async function listImportSessions({ dataRoot, source, showAll = false, search = '', roots = [] }) {
30
+ if (!source) return { ok: true, sources: sourceList(), sessions: [] };
31
+ if (!sourceList().some((s) => s.id === source)) {
32
+ return { ok: false, code: 'bad-source', error: '未知来源' };
33
+ }
34
+ if (!sourceAvailable(source)) {
35
+ return { ok: true, sources: sourceList(), sessions: [], unavailable: true };
36
+ }
37
+ const all = await listSourceSessions(source, { showAll: !!showAll });
38
+ const filterRoots = (Array.isArray(roots) ? roots : []).filter((r) => typeof r === 'string' && r);
39
+ const needle = String(search || '').trim().toLowerCase();
40
+ const registry = readRegistry(dataRoot);
41
+ const alive = aliveTaskStates(dataRoot);
42
+ const sessions = all
43
+ .filter((s) => (showAll || !s.subagent) && (showAll || !s.codexImport))
44
+ .filter((s) => {
45
+ if (filterRoots.length && !isUnder(s.cwd, filterRoots)) return false;
46
+ if (!needle) return true;
47
+ return `${s.title}\n${s.cwd}`.toLowerCase().includes(needle);
48
+ })
49
+ .map((s) => {
50
+ const rec = registry.imports[sourceKey(source, s.sessionId)];
51
+ const state = rec ? alive.get(rec.taskId) : null;
52
+ return {
53
+ ...present(s),
54
+ imported: !!state,
55
+ importedArchived: !!(state && state.archived),
56
+ importedTaskId: state ? rec.taskId : '',
57
+ };
58
+ });
59
+ return { ok: true, sources: sourceList(), sessions };
60
+ }
61
+
62
+ export async function runImport({ dataRoot, source, items: rawItems, projectId = null }) {
63
+ if (!source || !sourceList().some((s) => s.id === source)) {
64
+ return { ok: false, code: 'bad-source', error: '未知来源' };
65
+ }
66
+ if (!sourceAvailable(source)) {
67
+ return { ok: false, code: 'source-unavailable', error: '没有找到该工具的会话目录' };
68
+ }
69
+ const items = Array.isArray(rawItems) ? rawItems : [];
70
+ if (!items.length) return { ok: false, code: 'bad-request', error: '没有选择会话' };
71
+ if (items.length > 1000) {
72
+ return { ok: false, code: 'too-many-items', error: '一次最多导入 1000 条,请分批选择' };
73
+ }
74
+
75
+ let projectRoot = '';
76
+ if (projectId) {
77
+ let project;
78
+ try {
79
+ project = getProject(dataRoot, projectId);
80
+ } catch (err) {
81
+ return { ok: false, code: err.code || 'index-error', error: err.message || String(err) };
82
+ }
83
+ if (!project || !project.roots.length) {
84
+ return { ok: false, code: 'project-not-found', error: '项目不存在或没有可用目录' };
85
+ }
86
+ projectRoot = project.roots.find((r) => r.primary)?.path || project.roots[0].path;
87
+ }
88
+
89
+ const roots = sourceRoots(source);
90
+ const registry = readRegistry(dataRoot);
91
+ const alive = aliveTaskIds(dataRoot);
92
+ const imported = [];
93
+ const skipped = [];
94
+ const failed = [];
95
+
96
+ for (const item of items) {
97
+ const sessionId = String(item && item.sessionId || '');
98
+ const sourcePath = String(item && item.sourcePath || '');
99
+ if (!sessionId || !sourcePath) {
100
+ failed.push({ sessionId, error: '缺少会话 id 或文件路径', code: 'bad-request' });
101
+ continue;
102
+ }
103
+ if (!isUnder(sourcePath, roots) || !existsSync(sourcePath)) {
104
+ failed.push({ sessionId, error: '会话文件不在来源目录内或已不存在', code: 'bad-source-path' });
105
+ continue;
106
+ }
107
+ const key = sourceKey(source, sessionId);
108
+ const prev = registry.imports[key];
109
+ if (prev && alive.has(prev.taskId)) {
110
+ skipped.push({ sessionId, taskId: prev.taskId, reason: 'already-imported' });
111
+ continue;
112
+ }
113
+ try {
114
+ const parsed = await readSourceSession(source, { ...item, sessionId, sourcePath });
115
+ if (parsed.sessionId && parsed.sessionId !== sessionId) {
116
+ throw Object.assign(new Error('会话 id 与文件内容不一致'), { code: 'session-mismatch' });
117
+ }
118
+ let workspace = workspaceForImport({ cwd: parsed.cwd, projectRoot });
119
+ if (!workspace) {
120
+ workspace = join(dataRoot, 'workspace', `draft-${randomUUID()}`);
121
+ mkdirSync(workspace, { recursive: true });
122
+ }
123
+ const result = writeImportedSession({
124
+ dataRoot, source, parsed, workspace, projectId: projectId || null,
125
+ });
126
+ registry.imports[key] = {
127
+ taskId: result.taskId,
128
+ sourcePath,
129
+ title: result.title,
130
+ importedAt: Date.now(),
131
+ };
132
+ writeRegistry(dataRoot, registry);
133
+ imported.push({ sessionId, taskId: result.taskId, title: result.title, workspace });
134
+ } catch (err) {
135
+ failed.push({ sessionId, error: err.message || String(err), code: err.code || 'import-failed' });
136
+ }
137
+ }
138
+
139
+ return { ok: true, imported, skipped, failed };
140
+ }