a4phone 1.6.0 → 1.6.1

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/src/resume.mjs CHANGED
@@ -1,334 +1,334 @@
1
- // 续聊:把手机发来的文本作为下一条用户消息,续聊当前会话并回推回复
2
- // Claude Code:claude --resume <id> --continue -p(headless,stdin 作为消息、stdout 捕获回复)
3
- // Codex:codex exec resume <id> -o <文件> -(headless,stdin 作为消息、-o 把最后一条回复写入文件)
4
- // DSH:经 ~/.a4phone/dsh-jobs 文件队列交给 dsh web 进程内的 dsh-hook 插件,
5
- // 插件直接 followup 到当前 live 会话(手机消息与回复实时出现在桌面会话里)
6
- // 若 Codex 会话被窗口占用(thread-store conflict),自动 fork 成新线程续聊,无需关闭原窗口
7
- import fs from 'fs';
8
- import path from 'path';
9
- import os from 'os';
10
- import crypto from 'crypto';
11
- import { spawn } from 'child_process';
12
- import { loadConfig, loadLastSession, saveLastSession } from './config.mjs';
13
- import { sendNotification } from './ntfy.mjs';
14
- import { readMode, setMode } from './mode.mjs';
15
-
16
- const MAX_REPLY = 1000; // 回推输出截断长度
17
-
18
- // 去除 ANSI 转义与空行,取末尾一段(headless 模式输出尾部即最终回复)
19
- function extractReply(output) {
20
- const clean = (output || '')
21
- .replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, '')
22
- .replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, '')
23
- .split('\n')
24
- .map((l) => l.trim())
25
- .filter(Boolean)
26
- .join('\n');
27
- if (!clean) return null;
28
- return clean.length > MAX_REPLY ? '...(输出较长已截断)\n' + clean.slice(-MAX_REPLY) : clean;
29
- }
30
-
31
- // 按最近会话的 agent 构建续聊命令(纯函数,便于测试)
32
- export function buildResumeArgs(agent, sessionId, cwd, replyFile) {
33
- if (agent === 'Codex') {
34
- // codex exec resume 不接受 -C(工作目录存在会话里),仅由 spawn 的 cwd 决定启动目录
35
- return {
36
- command: 'codex',
37
- args: [
38
- 'exec', 'resume',
39
- '--dangerously-bypass-hook-trust', // 自动化场景:hook 信任已由用户确认,避免信任失效导致 exec 中断
40
- '--skip-git-repo-check',
41
- '-o', replyFile, // 最后一条回复写入该文件
42
- sessionId,
43
- '-', // 提示词从 stdin 读取
44
- ],
45
- };
46
- }
47
- return { command: 'claude', args: ['--resume', sessionId, '--continue', '-p'] };
48
- }
49
-
50
- // Codex 续聊独占约束:会话仍被其他进程持有写锁时,给出可操作的提示(而非裸错误文本)
51
- export function codexConflictReason(stderr) {
52
- const s = stderr || '';
53
- if (/thread-store conflict|already has an active writer/.test(s)) {
54
- return '续聊未执行:该 Codex 会话仍被占用(对应的 Codex 窗口还开着,会话持有独占锁)。\n' +
55
- '请先关闭那个 Codex 终端窗口,让会话释放锁,再从手机重新发送消息。';
56
- }
57
- return null;
58
- }
59
-
60
- // 生成近似 codex 线程 ID 格式的随机 ID(32 位十六进制按 8-4-4-4-12 连字符)
61
- export function generateThreadId() {
62
- const hex = crypto.randomBytes(16).toString('hex');
63
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
64
- }
65
-
66
- // 定位会话的 rollout 文件:优先用记录路径,兜底扫描 ~/.codex/sessions/**/rollout-*-<id>.jsonl
67
- function findCodexRollout(sessionId, transcriptPath) {
68
- if (transcriptPath && fs.existsSync(transcriptPath)) return transcriptPath;
69
- const base = path.join(os.homedir(), '.codex', 'sessions');
70
- try {
71
- for (const year of fs.readdirSync(base)) {
72
- const yDir = path.join(base, year);
73
- if (!fs.statSync(yDir).isDirectory()) continue;
74
- for (const month of fs.readdirSync(yDir)) {
75
- const mDir = path.join(yDir, month);
76
- if (!fs.statSync(mDir).isDirectory()) continue;
77
- for (const day of fs.readdirSync(mDir)) {
78
- const dDir = path.join(mDir, day);
79
- if (!fs.statSync(dDir).isDirectory()) continue;
80
- for (const f of fs.readdirSync(dDir)) {
81
- if (f.includes(sessionId) && f.endsWith('.jsonl')) {
82
- const p = path.join(dDir, f);
83
- if (fs.existsSync(p)) return p;
84
- }
85
- }
86
- }
87
- }
88
- }
89
- } catch {}
90
- return null;
91
- }
92
-
93
- // fork Codex 会话:复制 rollout 文件为新线程 ID(不建写锁),返回新会话信息;失败返回 null
94
- // - 原会话(含原窗口)毫发无损,可继续使用
95
- // - 手机续聊在 fork 上继续,多轮对话天然成立
96
- export function forkCodexSession({ sessionId, transcriptPath }) {
97
- const src = findCodexRollout(sessionId, transcriptPath);
98
- if (!src) return null;
99
- const newId = generateThreadId();
100
- const now = new Date();
101
- const pad = (n) => String(n).padStart(2, '0');
102
- const ts = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}T${pad(now.getHours())}-${pad(now.getMinutes())}-${pad(now.getSeconds())}`;
103
- const dst = path.join(path.dirname(src), `rollout-${ts}-${newId}.jsonl`);
104
- let content;
105
- try {
106
- content = fs.readFileSync(src, 'utf-8');
107
- } catch {
108
- return null;
109
- }
110
- // 替换所有旧线程 ID,并把 session_meta 时间戳更新为现在(使其成为最新会话)
111
- const replaced = content.split(sessionId).join(newId);
112
- const lines = replaced.split('\n');
113
- if (lines[0]) {
114
- try {
115
- const meta = JSON.parse(lines[0]);
116
- if (meta.type === 'session_meta' && meta.payload) {
117
- meta.payload.timestamp = now.toISOString();
118
- lines[0] = JSON.stringify(meta);
119
- }
120
- } catch {}
121
- }
122
- try {
123
- fs.writeFileSync(dst, lines.join('\n'));
124
- } catch {
125
- return null;
126
- }
127
- return { newId, newTranscriptPath: dst };
128
- }
129
-
130
- // 等待 CLI 进程结束,返回 { ok, code, stdout, stderr, reason, timedOut }
131
- // opts.wrapCmd=false:直接 spawn command(Windows 下跳过 cmd /c 包装,避免参数引号被破坏)
132
- // opts.writeStdin=false:不写 stdin(如 ZCode 用 --prompt 传消息)
133
- function spawnCli({ command, args, cwd, input, timeoutMs }, opts = {}) {
134
- return new Promise((resolve) => {
135
- const wrapCmd = opts.wrapCmd !== false && process.platform === 'win32';
136
- // 用 ComSpec 全路径启动 cmd,避免依赖 PATH 里能找到 cmd(沙箱/受限环境可能没有)
137
- const cmd = wrapCmd ? process.env.ComSpec || 'cmd' : command;
138
- const cmdArgs = wrapCmd ? ['/c', command, ...args] : args;
139
- let child;
140
- try {
141
- // A4P_RESUME 标记:让 Stop Hook 识别这是续聊子进程,避免重复推送"任务已完成"
142
- child = spawn(cmd, cmdArgs, { cwd, shell: false, env: { ...process.env, A4P_RESUME: '1' } });
143
- } catch (err) {
144
- resolve({ ok: false, reason: `无法启动 ${command}:${err.message}` });
145
- return;
146
- }
147
- let stdout = '';
148
- let stderr = '';
149
- let timedOut = false;
150
- const timer = setTimeout(() => {
151
- timedOut = true;
152
- if (process.platform === 'win32') {
153
- const taskkill = path.join(process.env.WINDIR || 'C:\\Windows', 'System32', 'taskkill.exe');
154
- spawn(taskkill, ['/pid', String(child.pid), '/f', '/t']).on('error', () => child.kill());
155
- } else {
156
- child.kill('SIGKILL');
157
- }
158
- }, timeoutMs);
159
- child.stdout.on('data', (d) => { stdout += d; });
160
- child.stderr.on('data', (d) => { stderr += d; });
161
- child.on('error', (err) => {
162
- clearTimeout(timer);
163
- resolve({ ok: false, reason: `无法启动 ${command}:${err.message}` });
164
- });
165
- child.on('close', (code) => {
166
- clearTimeout(timer);
167
- resolve({ ok: true, code, stdout, stderr, timedOut });
168
- });
169
- if (opts.writeStdin !== false && input != null) {
170
- try {
171
- child.stdin.write(input + '\n');
172
- child.stdin.end();
173
- } catch {}
174
- }
175
- });
176
- }
177
-
178
- // ZCode 续聊:headless 调 zcode CLI 续聊指定会话,回推回复到手机
179
- async function runZcodeResume(text, { config, onLog, last }) {
180
- const { findZcodeCli, ensureZcodeModelConfig, buildZcodeArgs, extractZcodeReply } = await import('./zcode.mjs');
181
-
182
- const cliPath = findZcodeCli();
183
- if (!cliPath) {
184
- return { ok: false, reason: '未找到 ZCode CLI(zcode.cjs),请确认 ZCode 桌面端已安装。' };
185
- }
186
-
187
- // 同步会话当前模型到 cli/config.json(桌面端切换模型后,续聊跟随会话实际模型)
188
- const synced = ensureZcodeModelConfig({ sessionId: last.session_id });
189
- if (!synced.ok) {
190
- onLog(`ZCode 模型配置同步失败:${synced.reason}`);
191
- return { ok: false, reason: `ZCode 模型配置同步失败:${synced.reason}` };
192
- }
193
-
194
- const cwd = last.cwd && last.cwd !== '未知目录' ? last.cwd : process.cwd();
195
- const { command, args } = buildZcodeArgs(text, last.session_id, cwd, cliPath);
196
- const proc = await spawnCli({ command, args, cwd, timeoutMs: config.resumeTimeout * 1000 }, { wrapCmd: false, writeStdin: false });
197
-
198
- if (!proc.ok) return { ok: false, reason: proc.reason };
199
-
200
- let reply = extractZcodeReply(proc.stdout) || extractReply(proc.stdout) || extractReply(proc.stderr);
201
- let message;
202
- if (proc.timedOut) {
203
- onLog(`续聊超时(超过 ${config.resumeTimeout} 秒)已中断`);
204
- message = reply
205
- ? `续聊超时已中断(以下为超时前已生成的回复)\n\n${reply}`
206
- : `续聊超时,未获取到回复。`;
207
- } else {
208
- message = reply
209
- ? `续聊已完成(退出码 ${proc.code})\n\n${reply}`
210
- : `续聊已完成(退出码 ${proc.code},无文本输出)`;
211
- }
212
- await sendNotification({ ...config, title: 'ZCode', message });
213
- return { ok: true, code: proc.code };
214
- }
215
-
216
- // 执行一次续聊,返回 { ok, reason?, code? }
217
- export async function runResume(text, { config = null, onLog = (s) => {} } = {}) {
218
- config = config || loadConfig();
219
- if (!config.topic) return { ok: false, reason: '未配置话题,请先运行 a4p setup。' };
220
-
221
- const last = loadLastSession();
222
- if (!last?.session_id) return { ok: false, reason: '暂无最近会话,请先完成一次任务触发 Stop 事件。' };
223
- const agent = last.agent || 'Claude Code';
224
-
225
- // DSH 续聊:不另起进程,而是把消息交给 dsh web 进程内的插件,
226
- // 直接 followup 到当前 live 会话(手机消息与回复都实时出现在桌面会话里)。
227
- if (agent === 'DSH') {
228
- const { runDshResume } = await import('./dsh-resume.mjs');
229
- // 续聊期间锁定外出模式(人在手机端),结束后恢复原模式
230
- const prevMode = readMode();
231
- const lockedOut = prevMode !== 'out';
232
- if (lockedOut) setMode('out');
233
- try {
234
- return await runDshResume(text, { config, onLog });
235
- } finally {
236
- if (lockedOut) setMode(prevMode);
237
- }
238
- }
239
-
240
- if (agent !== 'Claude Code' && agent !== 'Codex' && agent !== 'ZCode') {
241
- return { ok: false, reason: `续聊暂不支持 ${agent} 会话。` };
242
- }
243
- const textClean = (text || '').trim();
244
- if (!textClean) return { ok: false, reason: '续聊内容为空。' };
245
-
246
- // ZCode 续聊:headless 调用 zcode CLI(--prompt/--resume),
247
- // 续聊前自动同步会话当前模型到 ~/.zcode/cli/config.json(桌面端切换模型后跟随)。
248
- if (agent === 'ZCode') {
249
- const prevMode = readMode();
250
- const lockedOut = prevMode !== 'out';
251
- if (lockedOut) setMode('out');
252
- try {
253
- return await runZcodeResume(textClean, { config, onLog, last });
254
- } finally {
255
- if (lockedOut) setMode(prevMode);
256
- }
257
- }
258
-
259
- // 续聊期间锁定外出模式(人在手机端),结束后恢复原模式
260
- const prevMode = readMode();
261
- const lockedOut = prevMode !== 'out';
262
- if (lockedOut) setMode('out');
263
-
264
- const cwd = last.cwd && last.cwd !== '未知目录' ? last.cwd : process.cwd();
265
- let sessionId = last.session_id;
266
- let transcriptPath = last.transcript_path;
267
- let replyFile = path.join(os.tmpdir(), `a4p-reply-${process.pid}-${Date.now()}.txt`);
268
- let { command, args } = buildResumeArgs(agent, sessionId, cwd, replyFile);
269
-
270
- let proc = await spawnCli({
271
- command,
272
- args,
273
- cwd,
274
- input: textClean,
275
- timeoutMs: config.resumeTimeout * 1000,
276
- });
277
-
278
- // Codex 会话被窗口占用(thread-store conflict)时自动 fork 续聊:不关窗口也能续聊
279
- // 原会话(含原窗口)毫发无损;手机续聊在 fork 上继续,多轮对话天然成立
280
- let forked = false;
281
- if (proc.ok && command === 'codex' && codexConflictReason(proc.stderr)) {
282
- const fork = forkCodexSession({ sessionId, transcriptPath });
283
- if (fork) {
284
- forked = true;
285
- sessionId = fork.newId;
286
- transcriptPath = fork.newTranscriptPath;
287
- onLog(`Codex 会话被占用,已 fork 为新会话 ${fork.newId.slice(0, 8)} 继续续聊(原窗口不受影响)`);
288
- saveLastSession({ session_id: fork.newId, cwd, agent: 'Codex', transcript_path: fork.newTranscriptPath });
289
- try { fs.unlinkSync(replyFile); } catch {}
290
- replyFile = path.join(os.tmpdir(), `a4p-reply-${process.pid}-${Date.now()}.txt`);
291
- ({ command, args } = buildResumeArgs(agent, fork.newId, cwd, replyFile));
292
- proc = await spawnCli({
293
- command,
294
- args,
295
- cwd,
296
- input: textClean,
297
- timeoutMs: config.resumeTimeout * 1000,
298
- });
299
- }
300
- }
301
-
302
- if (lockedOut) setMode(prevMode);
303
-
304
- if (!proc.ok) return { ok: false, reason: proc.reason };
305
-
306
- // 回复来源:Codex 用 -o 写入的文件(若已生成),其余走 stdout 尾部
307
- let reply = extractReply(proc.stdout) || extractReply(proc.stderr);
308
- if (command === 'codex') {
309
- try {
310
- const fileReply = fs.readFileSync(replyFile, 'utf-8');
311
- reply = extractReply(fileReply) || reply;
312
- } catch {}
313
- }
314
- try { fs.unlinkSync(replyFile); } catch {}
315
-
316
- const name = agent === 'Codex' ? 'Codex' : 'Claude Code';
317
- let message;
318
- const conflict = command === 'codex' && !forked ? codexConflictReason(proc.stderr) : null;
319
- if (conflict) {
320
- onLog('续聊失败:Codex 会话仍被占用(独占锁未释放)');
321
- message = conflict;
322
- } else if (proc.timedOut) {
323
- onLog(`续聊超时(超过 ${config.resumeTimeout} 秒)已中断`);
324
- message = reply
325
- ? `续聊超时已中断(以下为超时前已生成的回复)\n\n${reply}`
326
- : `续聊超时,未获取到回复。`;
327
- } else {
328
- message = reply
329
- ? `续聊已完成(退出码 ${proc.code})\n\n${reply}`
330
- : `续聊已完成(退出码 ${proc.code},无文本输出)`;
331
- }
332
- await sendNotification({ ...config, title: name, message });
333
- return { ok: true, code: proc.code };
334
- }
1
+ // 续聊:把手机发来的文本作为下一条用户消息,续聊当前会话并回推回复
2
+ // Claude Code:claude --resume <id> --continue -p(headless,stdin 作为消息、stdout 捕获回复)
3
+ // Codex:codex exec resume <id> -o <文件> -(headless,stdin 作为消息、-o 把最后一条回复写入文件)
4
+ // DSH:经 ~/.a4phone/dsh-jobs 文件队列交给 dsh web 进程内的 dsh-hook 插件,
5
+ // 插件直接 followup 到当前 live 会话(手机消息与回复实时出现在桌面会话里)
6
+ // 若 Codex 会话被窗口占用(thread-store conflict),自动 fork 成新线程续聊,无需关闭原窗口
7
+ import fs from 'fs';
8
+ import path from 'path';
9
+ import os from 'os';
10
+ import crypto from 'crypto';
11
+ import { spawn } from 'child_process';
12
+ import { loadConfig, loadLastSession, saveLastSession } from './config.mjs';
13
+ import { sendNotification } from './ntfy.mjs';
14
+ import { readMode, setMode } from './mode.mjs';
15
+
16
+ const MAX_REPLY = 1000; // 回推输出截断长度
17
+
18
+ // 去除 ANSI 转义与空行,取末尾一段(headless 模式输出尾部即最终回复)
19
+ function extractReply(output) {
20
+ const clean = (output || '')
21
+ .replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, '')
22
+ .replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, '')
23
+ .split('\n')
24
+ .map((l) => l.trim())
25
+ .filter(Boolean)
26
+ .join('\n');
27
+ if (!clean) return null;
28
+ return clean.length > MAX_REPLY ? '...(输出较长已截断)\n' + clean.slice(-MAX_REPLY) : clean;
29
+ }
30
+
31
+ // 按最近会话的 agent 构建续聊命令(纯函数,便于测试)
32
+ export function buildResumeArgs(agent, sessionId, cwd, replyFile) {
33
+ if (agent === 'Codex') {
34
+ // codex exec resume 不接受 -C(工作目录存在会话里),仅由 spawn 的 cwd 决定启动目录
35
+ return {
36
+ command: 'codex',
37
+ args: [
38
+ 'exec', 'resume',
39
+ '--dangerously-bypass-hook-trust', // 自动化场景:hook 信任已由用户确认,避免信任失效导致 exec 中断
40
+ '--skip-git-repo-check',
41
+ '-o', replyFile, // 最后一条回复写入该文件
42
+ sessionId,
43
+ '-', // 提示词从 stdin 读取
44
+ ],
45
+ };
46
+ }
47
+ return { command: 'claude', args: ['--resume', sessionId, '--continue', '-p'] };
48
+ }
49
+
50
+ // Codex 续聊独占约束:会话仍被其他进程持有写锁时,给出可操作的提示(而非裸错误文本)
51
+ export function codexConflictReason(stderr) {
52
+ const s = stderr || '';
53
+ if (/thread-store conflict|already has an active writer/.test(s)) {
54
+ return '续聊未执行:该 Codex 会话仍被占用(对应的 Codex 窗口还开着,会话持有独占锁)。\n' +
55
+ '请先关闭那个 Codex 终端窗口,让会话释放锁,再从手机重新发送消息。';
56
+ }
57
+ return null;
58
+ }
59
+
60
+ // 生成近似 codex 线程 ID 格式的随机 ID(32 位十六进制按 8-4-4-4-12 连字符)
61
+ export function generateThreadId() {
62
+ const hex = crypto.randomBytes(16).toString('hex');
63
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
64
+ }
65
+
66
+ // 定位会话的 rollout 文件:优先用记录路径,兜底扫描 ~/.codex/sessions/**/rollout-*-<id>.jsonl
67
+ function findCodexRollout(sessionId, transcriptPath) {
68
+ if (transcriptPath && fs.existsSync(transcriptPath)) return transcriptPath;
69
+ const base = path.join(os.homedir(), '.codex', 'sessions');
70
+ try {
71
+ for (const year of fs.readdirSync(base)) {
72
+ const yDir = path.join(base, year);
73
+ if (!fs.statSync(yDir).isDirectory()) continue;
74
+ for (const month of fs.readdirSync(yDir)) {
75
+ const mDir = path.join(yDir, month);
76
+ if (!fs.statSync(mDir).isDirectory()) continue;
77
+ for (const day of fs.readdirSync(mDir)) {
78
+ const dDir = path.join(mDir, day);
79
+ if (!fs.statSync(dDir).isDirectory()) continue;
80
+ for (const f of fs.readdirSync(dDir)) {
81
+ if (f.includes(sessionId) && f.endsWith('.jsonl')) {
82
+ const p = path.join(dDir, f);
83
+ if (fs.existsSync(p)) return p;
84
+ }
85
+ }
86
+ }
87
+ }
88
+ }
89
+ } catch {}
90
+ return null;
91
+ }
92
+
93
+ // fork Codex 会话:复制 rollout 文件为新线程 ID(不建写锁),返回新会话信息;失败返回 null
94
+ // - 原会话(含原窗口)毫发无损,可继续使用
95
+ // - 手机续聊在 fork 上继续,多轮对话天然成立
96
+ export function forkCodexSession({ sessionId, transcriptPath }) {
97
+ const src = findCodexRollout(sessionId, transcriptPath);
98
+ if (!src) return null;
99
+ const newId = generateThreadId();
100
+ const now = new Date();
101
+ const pad = (n) => String(n).padStart(2, '0');
102
+ const ts = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}T${pad(now.getHours())}-${pad(now.getMinutes())}-${pad(now.getSeconds())}`;
103
+ const dst = path.join(path.dirname(src), `rollout-${ts}-${newId}.jsonl`);
104
+ let content;
105
+ try {
106
+ content = fs.readFileSync(src, 'utf-8');
107
+ } catch {
108
+ return null;
109
+ }
110
+ // 替换所有旧线程 ID,并把 session_meta 时间戳更新为现在(使其成为最新会话)
111
+ const replaced = content.split(sessionId).join(newId);
112
+ const lines = replaced.split('\n');
113
+ if (lines[0]) {
114
+ try {
115
+ const meta = JSON.parse(lines[0]);
116
+ if (meta.type === 'session_meta' && meta.payload) {
117
+ meta.payload.timestamp = now.toISOString();
118
+ lines[0] = JSON.stringify(meta);
119
+ }
120
+ } catch {}
121
+ }
122
+ try {
123
+ fs.writeFileSync(dst, lines.join('\n'));
124
+ } catch {
125
+ return null;
126
+ }
127
+ return { newId, newTranscriptPath: dst };
128
+ }
129
+
130
+ // 等待 CLI 进程结束,返回 { ok, code, stdout, stderr, reason, timedOut }
131
+ // opts.wrapCmd=false:直接 spawn command(Windows 下跳过 cmd /c 包装,避免参数引号被破坏)
132
+ // opts.writeStdin=false:不写 stdin(如 ZCode 用 --prompt 传消息)
133
+ function spawnCli({ command, args, cwd, input, timeoutMs }, opts = {}) {
134
+ return new Promise((resolve) => {
135
+ const wrapCmd = opts.wrapCmd !== false && process.platform === 'win32';
136
+ // 用 ComSpec 全路径启动 cmd,避免依赖 PATH 里能找到 cmd(沙箱/受限环境可能没有)
137
+ const cmd = wrapCmd ? process.env.ComSpec || 'cmd' : command;
138
+ const cmdArgs = wrapCmd ? ['/c', command, ...args] : args;
139
+ let child;
140
+ try {
141
+ // A4P_RESUME 标记:让 Stop Hook 识别这是续聊子进程,避免重复推送"任务已完成"
142
+ child = spawn(cmd, cmdArgs, { cwd, shell: false, env: { ...process.env, A4P_RESUME: '1' } });
143
+ } catch (err) {
144
+ resolve({ ok: false, reason: `无法启动 ${command}:${err.message}` });
145
+ return;
146
+ }
147
+ let stdout = '';
148
+ let stderr = '';
149
+ let timedOut = false;
150
+ const timer = setTimeout(() => {
151
+ timedOut = true;
152
+ if (process.platform === 'win32') {
153
+ const taskkill = path.join(process.env.WINDIR || 'C:\\Windows', 'System32', 'taskkill.exe');
154
+ spawn(taskkill, ['/pid', String(child.pid), '/f', '/t']).on('error', () => child.kill());
155
+ } else {
156
+ child.kill('SIGKILL');
157
+ }
158
+ }, timeoutMs);
159
+ child.stdout.on('data', (d) => { stdout += d; });
160
+ child.stderr.on('data', (d) => { stderr += d; });
161
+ child.on('error', (err) => {
162
+ clearTimeout(timer);
163
+ resolve({ ok: false, reason: `无法启动 ${command}:${err.message}` });
164
+ });
165
+ child.on('close', (code) => {
166
+ clearTimeout(timer);
167
+ resolve({ ok: true, code, stdout, stderr, timedOut });
168
+ });
169
+ if (opts.writeStdin !== false && input != null) {
170
+ try {
171
+ child.stdin.write(input + '\n');
172
+ child.stdin.end();
173
+ } catch {}
174
+ }
175
+ });
176
+ }
177
+
178
+ // ZCode 续聊:headless 调 zcode CLI 续聊指定会话,回推回复到手机
179
+ async function runZcodeResume(text, { config, onLog, last }) {
180
+ const { findZcodeCli, ensureZcodeModelConfig, buildZcodeArgs, extractZcodeReply } = await import('./zcode.mjs');
181
+
182
+ const cliPath = findZcodeCli();
183
+ if (!cliPath) {
184
+ return { ok: false, reason: '未找到 ZCode CLI(zcode.cjs),请确认 ZCode 桌面端已安装。' };
185
+ }
186
+
187
+ // 同步会话当前模型到 cli/config.json(桌面端切换模型后,续聊跟随会话实际模型)
188
+ const synced = ensureZcodeModelConfig({ sessionId: last.session_id });
189
+ if (!synced.ok) {
190
+ onLog(`ZCode 模型配置同步失败:${synced.reason}`);
191
+ return { ok: false, reason: `ZCode 模型配置同步失败:${synced.reason}` };
192
+ }
193
+
194
+ const cwd = last.cwd && last.cwd !== '未知目录' ? last.cwd : process.cwd();
195
+ const { command, args } = buildZcodeArgs(text, last.session_id, cwd, cliPath);
196
+ const proc = await spawnCli({ command, args, cwd, timeoutMs: config.resumeTimeout * 1000 }, { wrapCmd: false, writeStdin: false });
197
+
198
+ if (!proc.ok) return { ok: false, reason: proc.reason };
199
+
200
+ let reply = extractZcodeReply(proc.stdout) || extractReply(proc.stdout) || extractReply(proc.stderr);
201
+ let message;
202
+ if (proc.timedOut) {
203
+ onLog(`续聊超时(超过 ${config.resumeTimeout} 秒)已中断`);
204
+ message = reply
205
+ ? `续聊超时已中断(以下为超时前已生成的回复)\n\n${reply}`
206
+ : `续聊超时,未获取到回复。`;
207
+ } else {
208
+ message = reply
209
+ ? `续聊已完成(退出码 ${proc.code})\n\n${reply}`
210
+ : `续聊已完成(退出码 ${proc.code},无文本输出)`;
211
+ }
212
+ await sendNotification({ ...config, title: 'ZCode', message });
213
+ return { ok: true, code: proc.code };
214
+ }
215
+
216
+ // 执行一次续聊,返回 { ok, reason?, code? }
217
+ export async function runResume(text, { config = null, onLog = (s) => {} } = {}) {
218
+ config = config || loadConfig();
219
+ if (!config.topic) return { ok: false, reason: '未配置话题,请先运行 a4p setup。' };
220
+
221
+ const last = loadLastSession();
222
+ if (!last?.session_id) return { ok: false, reason: '暂无最近会话,请先完成一次任务触发 Stop 事件。' };
223
+ const agent = last.agent || 'Claude Code';
224
+
225
+ // DSH 续聊:不另起进程,而是把消息交给 dsh web 进程内的插件,
226
+ // 直接 followup 到当前 live 会话(手机消息与回复都实时出现在桌面会话里)。
227
+ if (agent === 'DSH') {
228
+ const { runDshResume } = await import('./dsh-resume.mjs');
229
+ // 续聊期间锁定外出模式(人在手机端),结束后恢复原模式
230
+ const prevMode = readMode();
231
+ const lockedOut = prevMode !== 'out';
232
+ if (lockedOut) setMode('out');
233
+ try {
234
+ return await runDshResume(text, { config, onLog });
235
+ } finally {
236
+ if (lockedOut) setMode(prevMode);
237
+ }
238
+ }
239
+
240
+ if (agent !== 'Claude Code' && agent !== 'Codex' && agent !== 'ZCode') {
241
+ return { ok: false, reason: `续聊暂不支持 ${agent} 会话。` };
242
+ }
243
+ const textClean = (text || '').trim();
244
+ if (!textClean) return { ok: false, reason: '续聊内容为空。' };
245
+
246
+ // ZCode 续聊:headless 调用 zcode CLI(--prompt/--resume),
247
+ // 续聊前自动同步会话当前模型到 ~/.zcode/cli/config.json(桌面端切换模型后跟随)。
248
+ if (agent === 'ZCode') {
249
+ const prevMode = readMode();
250
+ const lockedOut = prevMode !== 'out';
251
+ if (lockedOut) setMode('out');
252
+ try {
253
+ return await runZcodeResume(textClean, { config, onLog, last });
254
+ } finally {
255
+ if (lockedOut) setMode(prevMode);
256
+ }
257
+ }
258
+
259
+ // 续聊期间锁定外出模式(人在手机端),结束后恢复原模式
260
+ const prevMode = readMode();
261
+ const lockedOut = prevMode !== 'out';
262
+ if (lockedOut) setMode('out');
263
+
264
+ const cwd = last.cwd && last.cwd !== '未知目录' ? last.cwd : process.cwd();
265
+ let sessionId = last.session_id;
266
+ let transcriptPath = last.transcript_path;
267
+ let replyFile = path.join(os.tmpdir(), `a4p-reply-${process.pid}-${Date.now()}.txt`);
268
+ let { command, args } = buildResumeArgs(agent, sessionId, cwd, replyFile);
269
+
270
+ let proc = await spawnCli({
271
+ command,
272
+ args,
273
+ cwd,
274
+ input: textClean,
275
+ timeoutMs: config.resumeTimeout * 1000,
276
+ });
277
+
278
+ // Codex 会话被窗口占用(thread-store conflict)时自动 fork 续聊:不关窗口也能续聊
279
+ // 原会话(含原窗口)毫发无损;手机续聊在 fork 上继续,多轮对话天然成立
280
+ let forked = false;
281
+ if (proc.ok && command === 'codex' && codexConflictReason(proc.stderr)) {
282
+ const fork = forkCodexSession({ sessionId, transcriptPath });
283
+ if (fork) {
284
+ forked = true;
285
+ sessionId = fork.newId;
286
+ transcriptPath = fork.newTranscriptPath;
287
+ onLog(`Codex 会话被占用,已 fork 为新会话 ${fork.newId.slice(0, 8)} 继续续聊(原窗口不受影响)`);
288
+ saveLastSession({ session_id: fork.newId, cwd, agent: 'Codex', transcript_path: fork.newTranscriptPath });
289
+ try { fs.unlinkSync(replyFile); } catch {}
290
+ replyFile = path.join(os.tmpdir(), `a4p-reply-${process.pid}-${Date.now()}.txt`);
291
+ ({ command, args } = buildResumeArgs(agent, fork.newId, cwd, replyFile));
292
+ proc = await spawnCli({
293
+ command,
294
+ args,
295
+ cwd,
296
+ input: textClean,
297
+ timeoutMs: config.resumeTimeout * 1000,
298
+ });
299
+ }
300
+ }
301
+
302
+ if (lockedOut) setMode(prevMode);
303
+
304
+ if (!proc.ok) return { ok: false, reason: proc.reason };
305
+
306
+ // 回复来源:Codex 用 -o 写入的文件(若已生成),其余走 stdout 尾部
307
+ let reply = extractReply(proc.stdout) || extractReply(proc.stderr);
308
+ if (command === 'codex') {
309
+ try {
310
+ const fileReply = fs.readFileSync(replyFile, 'utf-8');
311
+ reply = extractReply(fileReply) || reply;
312
+ } catch {}
313
+ }
314
+ try { fs.unlinkSync(replyFile); } catch {}
315
+
316
+ const name = agent === 'Codex' ? 'Codex' : 'Claude Code';
317
+ let message;
318
+ const conflict = command === 'codex' && !forked ? codexConflictReason(proc.stderr) : null;
319
+ if (conflict) {
320
+ onLog('续聊失败:Codex 会话仍被占用(独占锁未释放)');
321
+ message = conflict;
322
+ } else if (proc.timedOut) {
323
+ onLog(`续聊超时(超过 ${config.resumeTimeout} 秒)已中断`);
324
+ message = reply
325
+ ? `续聊超时已中断(以下为超时前已生成的回复)\n\n${reply}`
326
+ : `续聊超时,未获取到回复。`;
327
+ } else {
328
+ message = reply
329
+ ? `续聊已完成(退出码 ${proc.code})\n\n${reply}`
330
+ : `续聊已完成(退出码 ${proc.code},无文本输出)`;
331
+ }
332
+ await sendNotification({ ...config, title: name, message });
333
+ return { ok: true, code: proc.code };
334
+ }