a4phone 1.1.3 → 1.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/mode.mjs CHANGED
@@ -1,9 +1,8 @@
1
- // 交互模式读写:~/.a4phone-mode.json(out=外出/手机优先,home=终端优先)
1
+ // 交互模式读写:~/.a4phone/mode.json(out=外出/手机优先,home=终端优先)
2
2
  import fs from 'fs';
3
- import os from 'os';
4
- import path from 'path';
3
+ import { MODE_PATH, ensureDir } from './paths.mjs';
5
4
 
6
- export const MODE_PATH = path.join(os.homedir(), '.a4phone-mode.json');
5
+ export { MODE_PATH } from './paths.mjs'; // 兼容旧引用
7
6
 
8
7
  export function readMode() {
9
8
  try {
@@ -14,5 +13,6 @@ export function readMode() {
14
13
  }
15
14
 
16
15
  export function setMode(mode) {
16
+ ensureDir();
17
17
  fs.writeFileSync(MODE_PATH, JSON.stringify({ mode: mode === 'out' ? 'out' : 'home' }));
18
18
  }
package/src/ntfy.mjs CHANGED
@@ -12,7 +12,9 @@ export async function sendNotification({ server, topic, title, message, actions
12
12
  }
13
13
  }
14
14
 
15
- // 订阅响应话题(NDJSON 流),等待匹配 requestId 的决策
15
+ // 订阅响应话题(NDJSON 流),等待决策
16
+ // HTTP action 回传:正文为 JSON { requestId, answer },仅匹配相同 requestId
17
+ // 手机自由文本:正文为纯文本,无 requestId,直接作为答案接受
16
18
  export async function waitForResponse({ server, topic, requestId, timeout }) {
17
19
  const url = `${server}/${topic}-response/json`;
18
20
  const controller = new AbortController();
@@ -32,8 +34,17 @@ export async function waitForResponse({ server, topic, requestId, timeout }) {
32
34
  if (!line.trim()) continue;
33
35
  try {
34
36
  const event = JSON.parse(line);
35
- const msg = JSON.parse(event.message);
36
- if (msg.requestId === requestId) {
37
+ // ntfy /json 连接建立后会先发 open 事件、之后周期发 keepalive,
38
+ // 这些事件没有 message 字段,跳过以免被误判为“手机自由文本”立即返回。
39
+ if (event.event !== 'message' || event.message == null) continue;
40
+ let msg;
41
+ try {
42
+ msg = JSON.parse(event.message);
43
+ } catch {
44
+ msg = { answer: event.message }; // 纯文本:手机自由作答
45
+ }
46
+ // action 回执:requestId 必须匹配;自由文本:无 requestId 且有 answer 才接受
47
+ if (msg.requestId === requestId || (msg.requestId === undefined && msg.answer)) {
37
48
  clearTimeout(timer);
38
49
  controller.abort();
39
50
  return msg;
package/src/paths.mjs ADDED
@@ -0,0 +1,58 @@
1
+ // a4phone 状态文件统一存放目录:~/.a4phone/(替代散落在家目录的单点文件)
2
+ // config.json ← ~/.a4phone.json
3
+ // mode.json ← ~/.a4phone-mode.json
4
+ // last.json ← ~/.a4phone-last.json
5
+ // daemon.json ← ~/.a4phone-daemon.json
6
+ // daemon.log ← ~/.a4phone-daemon.log
7
+ import fs from 'fs';
8
+ import os from 'os';
9
+ import path from 'path';
10
+
11
+ export const A4P_DIR = path.join(os.homedir(), '.a4phone');
12
+ export const CONFIG_PATH = path.join(A4P_DIR, 'config.json');
13
+ export const MODE_PATH = path.join(A4P_DIR, 'mode.json');
14
+ export const LAST_PATH = path.join(A4P_DIR, 'last.json');
15
+ export const DAEMON_JSON = path.join(A4P_DIR, 'daemon.json');
16
+ export const LOG_PATH = path.join(A4P_DIR, 'daemon.log');
17
+
18
+ // 旧版散落在家目录的单文件 → 迁移到 ~/.a4phone/(新路径不存在时才移动)
19
+ const LEGACY_PATHS = {
20
+ [CONFIG_PATH]: path.join(os.homedir(), '.a4phone.json'),
21
+ [MODE_PATH]: path.join(os.homedir(), '.a4phone-mode.json'),
22
+ [LAST_PATH]: path.join(os.homedir(), '.a4phone-last.json'),
23
+ [DAEMON_JSON]: path.join(os.homedir(), '.a4phone-daemon.json'),
24
+ [LOG_PATH]: path.join(os.homedir(), '.a4phone-daemon.log'),
25
+ };
26
+
27
+ function moveIfExists(oldPath, newPath) {
28
+ try {
29
+ fs.renameSync(oldPath, newPath);
30
+ return true;
31
+ } catch {
32
+ // rename 失败(如日志被占用)则回退复制+删除
33
+ try {
34
+ fs.copyFileSync(oldPath, newPath);
35
+ fs.unlinkSync(oldPath);
36
+ return true;
37
+ } catch {
38
+ return false; // 迁移失败则保留旧文件
39
+ }
40
+ }
41
+ }
42
+
43
+ // 确保目录存在,并把旧版散点文件迁移进来;返回是否发生过迁移
44
+ export function migrateLegacy() {
45
+ fs.mkdirSync(A4P_DIR, { recursive: true });
46
+ let migrated = false;
47
+ for (const [newPath, oldPath] of Object.entries(LEGACY_PATHS)) {
48
+ if (fs.existsSync(oldPath) && !fs.existsSync(newPath)) {
49
+ if (moveIfExists(oldPath, newPath)) migrated = true;
50
+ }
51
+ }
52
+ return migrated;
53
+ }
54
+
55
+ // 确保目录存在(写入前调用)
56
+ export function ensureDir() {
57
+ fs.mkdirSync(A4P_DIR, { recursive: true });
58
+ }
@@ -31,6 +31,11 @@ export async function handlePermissionRequest(input, agentName) {
31
31
  const config = loadConfig();
32
32
  if (!config.topic) return null;
33
33
 
34
+ // AskUserQuestion 的交互由 asku 处理器负责,此处直接放行,避免冗余的原始 JSON 推送
35
+ if (input.tool_name === 'AskUserQuestion') {
36
+ return { hookSpecificOutput: { hookEventName: 'PermissionRequest', decision: { behavior: 'allow' } } };
37
+ }
38
+
34
39
  const tool_name = input.tool_name || 'Unknown';
35
40
  const message = formatMessage(tool_name, input.tool_input);
36
41
  const requestId = crypto.randomUUID();
package/src/resume.mjs ADDED
@@ -0,0 +1,261 @@
1
+ // 续聊:把手机发来的文本作为下一条用户消息,续聊当前会话并回推回复
2
+ // Claude Code:claude --resume <id> --continue -p(headless,stdin 作为消息、stdout 捕获回复)
3
+ // Codex:codex exec resume <id> -o <文件> -(headless,stdin 作为消息、-o 把最后一条回复写入文件)
4
+ // 若 Codex 会话被窗口占用(thread-store conflict),自动 fork 成新线程续聊,无需关闭原窗口
5
+ import fs from 'fs';
6
+ import path from 'path';
7
+ import os from 'os';
8
+ import crypto from 'crypto';
9
+ import { spawn } from 'child_process';
10
+ import { loadConfig, loadLastSession, saveLastSession } from './config.mjs';
11
+ import { sendNotification } from './ntfy.mjs';
12
+ import { readMode, setMode } from './mode.mjs';
13
+
14
+ const MAX_REPLY = 1000; // 回推输出截断长度
15
+
16
+ // 去除 ANSI 转义与空行,取末尾一段(headless 模式输出尾部即最终回复)
17
+ function extractReply(output) {
18
+ const clean = (output || '')
19
+ .replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, '')
20
+ .replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, '')
21
+ .split('\n')
22
+ .map((l) => l.trim())
23
+ .filter(Boolean)
24
+ .join('\n');
25
+ if (!clean) return null;
26
+ return clean.length > MAX_REPLY ? '...(输出较长已截断)\n' + clean.slice(-MAX_REPLY) : clean;
27
+ }
28
+
29
+ // 按最近会话的 agent 构建续聊命令(纯函数,便于测试)
30
+ export function buildResumeArgs(agent, sessionId, cwd, replyFile) {
31
+ if (agent === 'Codex') {
32
+ // codex exec resume 不接受 -C(工作目录存在会话里),仅由 spawn 的 cwd 决定启动目录
33
+ return {
34
+ command: 'codex',
35
+ args: [
36
+ 'exec', 'resume',
37
+ '--dangerously-bypass-hook-trust', // 自动化场景:hook 信任已由用户确认,避免信任失效导致 exec 中断
38
+ '--skip-git-repo-check',
39
+ '-o', replyFile, // 最后一条回复写入该文件
40
+ sessionId,
41
+ '-', // 提示词从 stdin 读取
42
+ ],
43
+ };
44
+ }
45
+ return { command: 'claude', args: ['--resume', sessionId, '--continue', '-p'] };
46
+ }
47
+
48
+ // Codex 续聊独占约束:会话仍被其他进程持有写锁时,给出可操作的提示(而非裸错误文本)
49
+ export function codexConflictReason(stderr) {
50
+ const s = stderr || '';
51
+ if (/thread-store conflict|already has an active writer/.test(s)) {
52
+ return '续聊未执行:该 Codex 会话仍被占用(对应的 Codex 窗口还开着,会话持有独占锁)。\n' +
53
+ '请先关闭那个 Codex 终端窗口,让会话释放锁,再从手机重新发送消息。';
54
+ }
55
+ return null;
56
+ }
57
+
58
+ // 生成近似 codex 线程 ID 格式的随机 ID(32 位十六进制按 8-4-4-4-12 连字符)
59
+ export function generateThreadId() {
60
+ const hex = crypto.randomBytes(16).toString('hex');
61
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
62
+ }
63
+
64
+ // 定位会话的 rollout 文件:优先用记录路径,兜底扫描 ~/.codex/sessions/**/rollout-*-<id>.jsonl
65
+ function findCodexRollout(sessionId, transcriptPath) {
66
+ if (transcriptPath && fs.existsSync(transcriptPath)) return transcriptPath;
67
+ const base = path.join(os.homedir(), '.codex', 'sessions');
68
+ try {
69
+ for (const year of fs.readdirSync(base)) {
70
+ const yDir = path.join(base, year);
71
+ if (!fs.statSync(yDir).isDirectory()) continue;
72
+ for (const month of fs.readdirSync(yDir)) {
73
+ const mDir = path.join(yDir, month);
74
+ if (!fs.statSync(mDir).isDirectory()) continue;
75
+ for (const day of fs.readdirSync(mDir)) {
76
+ const dDir = path.join(mDir, day);
77
+ if (!fs.statSync(dDir).isDirectory()) continue;
78
+ for (const f of fs.readdirSync(dDir)) {
79
+ if (f.includes(sessionId) && f.endsWith('.jsonl')) {
80
+ const p = path.join(dDir, f);
81
+ if (fs.existsSync(p)) return p;
82
+ }
83
+ }
84
+ }
85
+ }
86
+ }
87
+ } catch {}
88
+ return null;
89
+ }
90
+
91
+ // fork Codex 会话:复制 rollout 文件为新线程 ID(不建写锁),返回新会话信息;失败返回 null
92
+ // - 原会话(含原窗口)毫发无损,可继续使用
93
+ // - 手机续聊在 fork 上继续,多轮对话天然成立
94
+ export function forkCodexSession({ sessionId, transcriptPath }) {
95
+ const src = findCodexRollout(sessionId, transcriptPath);
96
+ if (!src) return null;
97
+ const newId = generateThreadId();
98
+ const now = new Date();
99
+ const pad = (n) => String(n).padStart(2, '0');
100
+ const ts = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}T${pad(now.getHours())}-${pad(now.getMinutes())}-${pad(now.getSeconds())}`;
101
+ const dst = path.join(path.dirname(src), `rollout-${ts}-${newId}.jsonl`);
102
+ let content;
103
+ try {
104
+ content = fs.readFileSync(src, 'utf-8');
105
+ } catch {
106
+ return null;
107
+ }
108
+ // 替换所有旧线程 ID,并把 session_meta 时间戳更新为现在(使其成为最新会话)
109
+ const replaced = content.split(sessionId).join(newId);
110
+ const lines = replaced.split('\n');
111
+ if (lines[0]) {
112
+ try {
113
+ const meta = JSON.parse(lines[0]);
114
+ if (meta.type === 'session_meta' && meta.payload) {
115
+ meta.payload.timestamp = now.toISOString();
116
+ lines[0] = JSON.stringify(meta);
117
+ }
118
+ } catch {}
119
+ }
120
+ try {
121
+ fs.writeFileSync(dst, lines.join('\n'));
122
+ } catch {
123
+ return null;
124
+ }
125
+ return { newId, newTranscriptPath: dst };
126
+ }
127
+
128
+ // 等待 CLI 进程结束,返回 { ok, code, stdout, stderr, reason, timedOut }
129
+ function spawnCli({ command, args, cwd, input, timeoutMs }) {
130
+ return new Promise((resolve) => {
131
+ const useCmd = process.platform === 'win32';
132
+ // 用 ComSpec 全路径启动 cmd,避免依赖 PATH 里能找到 cmd(沙箱/受限环境可能没有)
133
+ const cmd = useCmd ? process.env.ComSpec || 'cmd' : command;
134
+ const cmdArgs = useCmd ? ['/c', command, ...args] : args;
135
+ let child;
136
+ try {
137
+ // A4P_RESUME 标记:让 Stop Hook 识别这是续聊子进程,避免重复推送"任务已完成"
138
+ child = spawn(cmd, cmdArgs, { cwd, shell: false, env: { ...process.env, A4P_RESUME: '1' } });
139
+ } catch (err) {
140
+ resolve({ ok: false, reason: `无法启动 ${command}:${err.message}` });
141
+ return;
142
+ }
143
+ let stdout = '';
144
+ let stderr = '';
145
+ let timedOut = false;
146
+ const timer = setTimeout(() => {
147
+ timedOut = true;
148
+ if (useCmd) {
149
+ const taskkill = path.join(process.env.WINDIR || 'C:\\Windows', 'System32', 'taskkill.exe');
150
+ spawn(taskkill, ['/pid', String(child.pid), '/f', '/t']).on('error', () => child.kill());
151
+ } else {
152
+ child.kill('SIGKILL');
153
+ }
154
+ }, timeoutMs);
155
+ child.stdout.on('data', (d) => { stdout += d; });
156
+ child.stderr.on('data', (d) => { stderr += d; });
157
+ child.on('error', (err) => {
158
+ clearTimeout(timer);
159
+ resolve({ ok: false, reason: `无法启动 ${command}:${err.message}` });
160
+ });
161
+ child.on('close', (code) => {
162
+ clearTimeout(timer);
163
+ resolve({ ok: true, code, stdout, stderr, timedOut });
164
+ });
165
+ try {
166
+ child.stdin.write(input + '\n');
167
+ child.stdin.end();
168
+ } catch {}
169
+ });
170
+ }
171
+
172
+ // 执行一次续聊,返回 { ok, reason?, code? }
173
+ export async function runResume(text, { config = null, onLog = (s) => {} } = {}) {
174
+ config = config || loadConfig();
175
+ if (!config.topic) return { ok: false, reason: '未配置话题,请先运行 a4p setup。' };
176
+
177
+ const last = loadLastSession();
178
+ if (!last?.session_id) return { ok: false, reason: '暂无最近会话,请先完成一次任务触发 Stop 事件。' };
179
+ const agent = last.agent || 'Claude Code';
180
+ if (agent !== 'Claude Code' && agent !== 'Codex') {
181
+ return { ok: false, reason: `续聊暂不支持 ${agent} 会话。` };
182
+ }
183
+ const textClean = (text || '').trim();
184
+ if (!textClean) return { ok: false, reason: '续聊内容为空。' };
185
+
186
+ // 续聊期间锁定外出模式(人在手机端),结束后恢复原模式
187
+ const prevMode = readMode();
188
+ const lockedOut = prevMode !== 'out';
189
+ if (lockedOut) setMode('out');
190
+
191
+ const cwd = last.cwd && last.cwd !== '未知目录' ? last.cwd : process.cwd();
192
+ let sessionId = last.session_id;
193
+ let transcriptPath = last.transcript_path;
194
+ let replyFile = path.join(os.tmpdir(), `a4p-reply-${process.pid}-${Date.now()}.txt`);
195
+ let { command, args } = buildResumeArgs(agent, sessionId, cwd, replyFile);
196
+
197
+ let proc = await spawnCli({
198
+ command,
199
+ args,
200
+ cwd,
201
+ input: textClean,
202
+ timeoutMs: config.resumeTimeout * 1000,
203
+ });
204
+
205
+ // Codex 会话被窗口占用(thread-store conflict)时自动 fork 续聊:不关窗口也能续聊
206
+ // 原会话(含原窗口)毫发无损;手机续聊在 fork 上继续,多轮对话天然成立
207
+ let forked = false;
208
+ if (proc.ok && command === 'codex' && codexConflictReason(proc.stderr)) {
209
+ const fork = forkCodexSession({ sessionId, transcriptPath });
210
+ if (fork) {
211
+ forked = true;
212
+ sessionId = fork.newId;
213
+ transcriptPath = fork.newTranscriptPath;
214
+ onLog(`Codex 会话被占用,已 fork 为新会话 ${fork.newId.slice(0, 8)} 继续续聊(原窗口不受影响)`);
215
+ saveLastSession({ session_id: fork.newId, cwd, agent: 'Codex', transcript_path: fork.newTranscriptPath });
216
+ try { fs.unlinkSync(replyFile); } catch {}
217
+ replyFile = path.join(os.tmpdir(), `a4p-reply-${process.pid}-${Date.now()}.txt`);
218
+ ({ command, args } = buildResumeArgs(agent, fork.newId, cwd, replyFile));
219
+ proc = await spawnCli({
220
+ command,
221
+ args,
222
+ cwd,
223
+ input: textClean,
224
+ timeoutMs: config.resumeTimeout * 1000,
225
+ });
226
+ }
227
+ }
228
+
229
+ if (lockedOut) setMode(prevMode);
230
+
231
+ if (!proc.ok) return { ok: false, reason: proc.reason };
232
+
233
+ // 回复来源:Codex 用 -o 写入的文件(若已生成),其余走 stdout 尾部
234
+ let reply = extractReply(proc.stdout) || extractReply(proc.stderr);
235
+ if (command === 'codex') {
236
+ try {
237
+ const fileReply = fs.readFileSync(replyFile, 'utf-8');
238
+ reply = extractReply(fileReply) || reply;
239
+ } catch {}
240
+ }
241
+ try { fs.unlinkSync(replyFile); } catch {}
242
+
243
+ const name = agent === 'Codex' ? 'Codex' : 'Claude Code';
244
+ let message;
245
+ const conflict = command === 'codex' && !forked ? codexConflictReason(proc.stderr) : null;
246
+ if (conflict) {
247
+ onLog('续聊失败:Codex 会话仍被占用(独占锁未释放)');
248
+ message = conflict;
249
+ } else if (proc.timedOut) {
250
+ onLog(`续聊超时(超过 ${config.resumeTimeout} 秒)已中断`);
251
+ message = reply
252
+ ? `续聊超时已中断(以下为超时前已生成的回复)\n\n${reply}`
253
+ : `续聊超时,未获取到回复。`;
254
+ } else {
255
+ message = reply
256
+ ? `续聊已完成(退出码 ${proc.code})\n\n${reply}`
257
+ : `续聊已完成(退出码 ${proc.code},无文本输出)`;
258
+ }
259
+ await sendNotification({ ...config, title: name, message });
260
+ return { ok: true, code: proc.code };
261
+ }
package/src/setup.mjs CHANGED
@@ -12,23 +12,38 @@ function generateTopic() {
12
12
  return 'a4p-' + crypto.randomBytes(8).toString('hex');
13
13
  }
14
14
 
15
- // 把 Hook 合并写入 settings.json(保留既有配置)
16
- // 返回 true=新写入,false=已存在跳过
15
+ // 把 Hook 合并写入 settings.json(追加到各事件,保留用户既有 Hook)
16
+ // 返回 true=有写入,false=已存在相同配置跳过
17
17
  export function registerHooks(settingsPath, hookCommand) {
18
18
  let settings = {};
19
19
  try {
20
20
  settings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
21
21
  } catch {}
22
22
 
23
- // 已配置相同 Hook 则跳过
24
- const existing = settings.hooks?.Stop?.[0]?.hooks?.[0]?.command;
25
- if (existing === hookCommand) return false;
23
+ settings.hooks = settings.hooks || {};
26
24
 
27
- settings.hooks = {
25
+ const eventBlocks = {
28
26
  Stop: [{ matcher: '*', hooks: [{ type: 'command', command: hookCommand }] }],
29
27
  PreToolUse: [{ matcher: 'AskUserQuestion', hooks: [{ type: 'command', command: hookCommand }] }],
30
28
  PermissionRequest: [{ matcher: '*', hooks: [{ type: 'command', command: hookCommand }] }],
31
29
  };
30
+
31
+ let changed = false;
32
+ for (const [event, blocks] of Object.entries(eventBlocks)) {
33
+ // 兼容既有配置:事件值可能是数组,也可能被手写成单个对象
34
+ const list = Array.isArray(settings.hooks[event])
35
+ ? settings.hooks[event]
36
+ : settings.hooks[event] ? [settings.hooks[event]] : [];
37
+ const alreadyConfigured = list.some((b) =>
38
+ (b.hooks || []).some((h) => h.command === hookCommand)
39
+ );
40
+ if (alreadyConfigured) continue;
41
+ list.push(...blocks);
42
+ settings.hooks[event] = list;
43
+ changed = true;
44
+ }
45
+
46
+ if (!changed) return false;
32
47
  fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
33
48
  fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
34
49
  return true;
@@ -39,8 +54,27 @@ export function unregisterHooks(settingsPath) {
39
54
  try {
40
55
  settings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
41
56
  } catch {}
42
- delete settings.hooks;
57
+ const hooks = settings.hooks;
58
+ if (!hooks || typeof hooks !== 'object') return false; // 无 Hook 配置:不重写文件
59
+ let changed = false;
60
+ // 只移除 a4phone 的 Hook,保留用户的其他 Hook 与其他事件
61
+ for (const event of Object.keys(hooks)) {
62
+ const entry = hooks[event];
63
+ const isA4p = (b) => (b.hooks || []).some((h) => (h.command || '').includes('a4p hook'));
64
+ if (!Array.isArray(entry)) {
65
+ // 手写的单对象条目(非数组):仅当本身含 a4phone Hook 时才删除,否则原样保留
66
+ if (entry && isA4p(entry)) { delete hooks[event]; changed = true; }
67
+ continue;
68
+ }
69
+ const kept = entry.filter((b) => !isA4p(b));
70
+ if (kept.length !== entry.length) changed = true;
71
+ if (kept.length) hooks[event] = kept;
72
+ else delete hooks[event];
73
+ }
74
+ if (changed && Object.keys(hooks).length === 0) delete settings.hooks;
75
+ if (!changed) return false; // 没有 a4phone 的 Hook:保持用户文件原样,不重写
43
76
  fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
77
+ return true;
44
78
  }
45
79
 
46
80
  // 计算 Hook 命令:依赖全局安装的 a4p(在 PATH 上),路径更稳
@@ -62,7 +96,7 @@ type = "command"
62
96
  command = "a4p hook codex"
63
97
 
64
98
  [[hooks.PreToolUse]]
65
- matcher = "AskUserQuestion"
99
+ matcher = "request_user_input"
66
100
  [[hooks.PreToolUse.hooks]]
67
101
  type = "command"
68
102
  command = "a4p hook codex"
@@ -73,43 +107,153 @@ type = "command"
73
107
  command = "a4p hook codex"`;
74
108
  }
75
109
 
110
+ // 修正既有配置里 a4phone PreToolUse 块的 matcher(Codex 的提问工具实际叫 request_user_input,
111
+ // 旧值 AskUserQuestion 匹配不上导致 hook 不触发)。只改含 a4p hook codex 的 PreToolUse 块。
112
+ export function fixCodexPreToolUseMatcher(content, oldMatcher, newMatcher) {
113
+ const lines = content.split('\n');
114
+ let i = 0;
115
+ let changed = false;
116
+ while (i < lines.length) {
117
+ if (/^\[\[hooks\.PreToolUse\]\]\s*$/.test(lines[i])) {
118
+ const block = [lines[i]];
119
+ let j = i + 1;
120
+ while (j < lines.length && lines[j].trim() !== '') {
121
+ block.push(lines[j]);
122
+ j++;
123
+ }
124
+ if (block.some((l) => l.includes('a4p hook codex'))) {
125
+ const replaced = block.map((l) =>
126
+ l.includes(`matcher = "${oldMatcher}"`)
127
+ ? l.replace(`"${oldMatcher}"`, `"${newMatcher}"`)
128
+ : l
129
+ );
130
+ if (replaced.some((l, k) => l !== block[k])) {
131
+ lines.splice(i, block.length, ...replaced);
132
+ changed = true;
133
+ }
134
+ }
135
+ i = j;
136
+ } else {
137
+ i++;
138
+ }
139
+ }
140
+ return changed ? lines.join('\n') : content;
141
+ }
142
+
76
143
  // 写入 Codex 配置(保留既有内容,幂等)
77
144
  // 追加到文件末尾,用显式表头包裹,避免根级键被吸收
78
- export function configureCodex() {
145
+ export function configureCodex(codexPath = CODEX_PATH) {
79
146
  let content = '';
80
147
  try {
81
- content = fs.readFileSync(CODEX_PATH, 'utf-8');
148
+ content = fs.readFileSync(codexPath, 'utf-8');
82
149
  } catch {}
83
- if (content.includes(CODEX_MARKER_START)) return false; // 已配置
150
+ // 已配置:marker 块存在,或 Codex 已把 a4phone Hook 规范化为内联格式
151
+ if (content.includes(CODEX_MARKER_START) || /\ba4p hook codex\b/.test(content)) {
152
+ // 顺带把旧 matcher 就地修正(Codex 提问工具名是 request_user_input)
153
+ const fixed = fixCodexPreToolUseMatcher(content, 'AskUserQuestion', 'request_user_input');
154
+ if (fixed !== content) fs.writeFileSync(codexPath, fixed);
155
+ return false;
156
+ }
84
157
 
85
- fs.mkdirSync(path.dirname(CODEX_PATH), { recursive: true });
158
+ fs.mkdirSync(path.dirname(codexPath), { recursive: true });
86
159
 
87
160
  const defs = `${CODEX_MARKER_START}\n${codexHooksDefs()}\n${CODEX_MARKER_END}`;
88
161
 
89
- if (/^\[features\]\s*$/m.test(content)) {
90
- // 已有 [features] 表:把 hooks = true 插入该表,末尾追加 Hook 定义
91
- content = content.replace(/^\[features\]\s*$/m, '[features]\nhooks = true');
92
- fs.writeFileSync(CODEX_PATH, content.trimEnd() + '\n\n' + defs + '\n');
162
+ const featuresMatch = content.match(/^\[features\]\s*$/m);
163
+ if (featuresMatch) {
164
+ // 已有 [features] 表:仅当表内尚无 hooks 键时才插入 hooks = true,避免重复键
165
+ const rest = content.slice(featuresMatch.index);
166
+ const nextSection = rest.indexOf('\n[');
167
+ const tableBody = nextSection === -1 ? rest : rest.slice(0, nextSection);
168
+ if (!/^\s*hooks\s*=/m.test(tableBody)) {
169
+ const insertAt = featuresMatch.index + '[features]'.length;
170
+ content = content.slice(0, insertAt) + '\nhooks = true' + content.slice(insertAt);
171
+ }
172
+ fs.writeFileSync(codexPath, content.trimEnd() + '\n\n' + defs + '\n');
93
173
  } else {
94
174
  // 无 [features]:末尾追加完整块([features] 显式表头 + Hook 定义)
95
175
  const block = `${CODEX_MARKER_START}\n[features]\nhooks = true\n\n${codexHooksDefs()}\n${CODEX_MARKER_END}`;
96
- fs.writeFileSync(CODEX_PATH, (content ? content.trimEnd() + '\n\n' : '') + block + '\n');
176
+ fs.writeFileSync(codexPath, (content ? content.trimEnd() + '\n\n' : '') + block + '\n');
97
177
  }
98
178
  return true;
99
179
  }
100
180
 
101
- // 移除 Codex 配置中的 a4phone Hook 段
102
- export function unconfigureCodex() {
181
+ // 移除所有含 a4p hook codex 的 [[hooks.*]] 块(覆盖 marker 嵌套格式与 Codex 内联数组格式)
182
+ function stripA4pHookBlocks(content) {
183
+ const lines = content.split('\n');
184
+ const out = [];
185
+ let i = 0;
186
+ while (i < lines.length) {
187
+ const line = lines[i];
188
+ if (/^\[\[hooks\./.test(line)) {
189
+ const block = [line];
190
+ let j = i + 1;
191
+ while (j < lines.length && lines[j].trim() !== '') {
192
+ block.push(lines[j]);
193
+ j++;
194
+ }
195
+ if (block.join('\n').includes('a4p hook codex')) {
196
+ // a4phone 的 Hook 块:整块丢弃,并吞掉尾随空行
197
+ while (j < lines.length && lines[j].trim() === '') j++;
198
+ } else {
199
+ out.push(...block);
200
+ }
201
+ i = j;
202
+ } else {
203
+ out.push(line);
204
+ i++;
205
+ }
206
+ }
207
+ return out.join('\n');
208
+ }
209
+
210
+ // 清理 configureCodex 写入的 [features] hooks = true 空壳:
211
+ // 仅当 [features] 表只剩下 hooks = true(移除后表变空)时才整表删除,
212
+ // 表里还有其他键时原样保留,避免误删用户自己的 features 配置。
213
+ export function stripFeaturesHooksShell(content) {
214
+ const lines = content.split('\n');
215
+ const out = [];
216
+ let i = 0;
217
+ while (i < lines.length) {
218
+ if (/^\[features\]\s*$/.test(lines[i])) {
219
+ // 收集表体直到下一个 [ 表头或文件末尾
220
+ const body = [];
221
+ let j = i + 1;
222
+ while (j < lines.length && !/^\[/.test(lines[j])) {
223
+ body.push(lines[j]);
224
+ j++;
225
+ }
226
+ const keys = body.map((l) => l.trim()).filter((l) => l && !l.startsWith('#'));
227
+ const onlyHooksTrue = keys.length > 0 && keys.every((k) => k === 'hooks = true');
228
+ if (onlyHooksTrue) {
229
+ // 空壳:整表删除,顺带去掉前导空行
230
+ i = j;
231
+ while (out.length && out[out.length - 1].trim() === '') out.pop();
232
+ continue;
233
+ }
234
+ }
235
+ out.push(lines[i]);
236
+ i++;
237
+ }
238
+ return out.join('\n');
239
+ }
240
+
241
+ // 移除 Codex 配置中的 a4phone Hook(marker 块 + 规范化格式 + features 空壳)
242
+ export function unconfigureCodex(codexPath = CODEX_PATH) {
103
243
  let content = '';
104
244
  try {
105
- content = fs.readFileSync(CODEX_PATH, 'utf-8');
245
+ content = fs.readFileSync(codexPath, 'utf-8');
106
246
  } catch {}
247
+ const original = content;
107
248
  const start = content.indexOf(CODEX_MARKER_START);
108
249
  const end = content.indexOf(CODEX_MARKER_END);
109
250
  if (start !== -1 && end !== -1) {
110
251
  content = content.slice(0, start) + content.slice(end + CODEX_MARKER_END.length);
111
- content = content.replace(/\n{3,}/g, '\n\n').trim();
112
- fs.writeFileSync(CODEX_PATH, content + '\n');
252
+ }
253
+ const stripped = stripFeaturesHooksShell(stripA4pHookBlocks(content)).replace(/\n{3,}/g, '\n\n').trim();
254
+ // 用原始内容判断是否发生变化:slice 后的 content 已不含 marker,与 stripped 恒等会误判"无需写入"
255
+ if (stripped !== original.trim()) {
256
+ fs.writeFileSync(codexPath, stripped + '\n');
113
257
  }
114
258
  }
115
259
 
package/src/stop.mjs CHANGED
@@ -1,19 +1,32 @@
1
- // Stop 事件:任务完成 → 系统通知 + 手机推送
2
- import { loadConfig } from './config.mjs';
1
+ // Stop 事件:任务完成 → 系统通知 + 手机推送(含 AI 最后输出)+ 记录最近会话
2
+ import { loadConfig, saveLastSession } from './config.mjs';
3
3
  import { sendNotification } from './ntfy.mjs';
4
4
  import { systemNotify } from './notify.mjs';
5
+ import { extractLastOutput } from './transcript.mjs';
5
6
 
6
7
  export async function handleStop(input, agentName) {
7
8
  const config = loadConfig();
8
9
  const cwd = input.cwd || '未知目录';
9
10
  const session = input.session_id ? input.session_id.slice(0, 8) : '—';
10
11
  const details = `任务已完成\n目录: ${cwd}\n会话: ${session}`;
12
+
13
+ // 记录最近会话,供续聊(a4p resume / a4p listen)使用
14
+ if (input.session_id) {
15
+ saveLastSession({ session_id: input.session_id, cwd, agent: agentName, transcript_path: input.transcript_path });
16
+ }
17
+
18
+ // 续聊子进程(A4P_RESUME=1)的 Stop 事件:结果已由 runResume 推回手机,此处不重复推送
19
+ if (process.env.A4P_RESUME === '1') return null;
20
+
11
21
  await systemNotify(agentName, '任务已完成');
22
+
12
23
  if (config.topic) {
24
+ const lastOutput = extractLastOutput(input.transcript_path);
25
+ const message = lastOutput ? `${details}\n\nAI 最后输出:\n${lastOutput}` : details;
13
26
  await sendNotification({
14
27
  ...config,
15
28
  title: agentName,
16
- message: details,
29
+ message,
17
30
  });
18
31
  }
19
32
  return null; // Stop Hook 无需输出