a4phone 1.1.4 → 1.1.6
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/README.md +109 -22
- package/bin/a4p.mjs +69 -6
- package/dsh/lib/index.js +183 -0
- package/dsh/lib/phone-hooks.mjs +151 -0
- package/dsh/package.json +23 -0
- package/package.json +7 -3
- package/src/asku.mjs +31 -8
- package/src/config.mjs +26 -7
- package/src/daemon.mjs +108 -0
- package/src/hook.mjs +10 -4
- package/src/listen.mjs +121 -0
- package/src/mode.mjs +4 -4
- package/src/ntfy.mjs +14 -3
- package/src/paths.mjs +58 -0
- package/src/resume.mjs +261 -0
- package/src/setup.mjs +264 -23
- package/src/stop.mjs +16 -3
- package/src/transcript.mjs +48 -0
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
|
@@ -3,6 +3,7 @@ import crypto from 'crypto';
|
|
|
3
3
|
import fs from 'fs';
|
|
4
4
|
import os from 'os';
|
|
5
5
|
import path from 'path';
|
|
6
|
+
import { fileURLToPath } from 'url';
|
|
6
7
|
import { loadConfig, saveConfig } from './config.mjs';
|
|
7
8
|
|
|
8
9
|
const SETTINGS_PATH = path.join(os.homedir(), '.claude', 'settings.json');
|
|
@@ -12,23 +13,38 @@ function generateTopic() {
|
|
|
12
13
|
return 'a4p-' + crypto.randomBytes(8).toString('hex');
|
|
13
14
|
}
|
|
14
15
|
|
|
15
|
-
// 把 Hook 合并写入 settings.json
|
|
16
|
-
// 返回 true
|
|
16
|
+
// 把 Hook 合并写入 settings.json(追加到各事件,保留用户既有 Hook)
|
|
17
|
+
// 返回 true=有写入,false=已存在相同配置跳过
|
|
17
18
|
export function registerHooks(settingsPath, hookCommand) {
|
|
18
19
|
let settings = {};
|
|
19
20
|
try {
|
|
20
21
|
settings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
|
|
21
22
|
} catch {}
|
|
22
23
|
|
|
23
|
-
|
|
24
|
-
const existing = settings.hooks?.Stop?.[0]?.hooks?.[0]?.command;
|
|
25
|
-
if (existing === hookCommand) return false;
|
|
24
|
+
settings.hooks = settings.hooks || {};
|
|
26
25
|
|
|
27
|
-
|
|
26
|
+
const eventBlocks = {
|
|
28
27
|
Stop: [{ matcher: '*', hooks: [{ type: 'command', command: hookCommand }] }],
|
|
29
28
|
PreToolUse: [{ matcher: 'AskUserQuestion', hooks: [{ type: 'command', command: hookCommand }] }],
|
|
30
29
|
PermissionRequest: [{ matcher: '*', hooks: [{ type: 'command', command: hookCommand }] }],
|
|
31
30
|
};
|
|
31
|
+
|
|
32
|
+
let changed = false;
|
|
33
|
+
for (const [event, blocks] of Object.entries(eventBlocks)) {
|
|
34
|
+
// 兼容既有配置:事件值可能是数组,也可能被手写成单个对象
|
|
35
|
+
const list = Array.isArray(settings.hooks[event])
|
|
36
|
+
? settings.hooks[event]
|
|
37
|
+
: settings.hooks[event] ? [settings.hooks[event]] : [];
|
|
38
|
+
const alreadyConfigured = list.some((b) =>
|
|
39
|
+
(b.hooks || []).some((h) => h.command === hookCommand)
|
|
40
|
+
);
|
|
41
|
+
if (alreadyConfigured) continue;
|
|
42
|
+
list.push(...blocks);
|
|
43
|
+
settings.hooks[event] = list;
|
|
44
|
+
changed = true;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if (!changed) return false;
|
|
32
48
|
fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
|
|
33
49
|
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
|
|
34
50
|
return true;
|
|
@@ -39,8 +55,27 @@ export function unregisterHooks(settingsPath) {
|
|
|
39
55
|
try {
|
|
40
56
|
settings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
|
|
41
57
|
} catch {}
|
|
42
|
-
|
|
58
|
+
const hooks = settings.hooks;
|
|
59
|
+
if (!hooks || typeof hooks !== 'object') return false; // 无 Hook 配置:不重写文件
|
|
60
|
+
let changed = false;
|
|
61
|
+
// 只移除 a4phone 的 Hook,保留用户的其他 Hook 与其他事件
|
|
62
|
+
for (const event of Object.keys(hooks)) {
|
|
63
|
+
const entry = hooks[event];
|
|
64
|
+
const isA4p = (b) => (b.hooks || []).some((h) => (h.command || '').includes('a4p hook'));
|
|
65
|
+
if (!Array.isArray(entry)) {
|
|
66
|
+
// 手写的单对象条目(非数组):仅当本身含 a4phone Hook 时才删除,否则原样保留
|
|
67
|
+
if (entry && isA4p(entry)) { delete hooks[event]; changed = true; }
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
const kept = entry.filter((b) => !isA4p(b));
|
|
71
|
+
if (kept.length !== entry.length) changed = true;
|
|
72
|
+
if (kept.length) hooks[event] = kept;
|
|
73
|
+
else delete hooks[event];
|
|
74
|
+
}
|
|
75
|
+
if (changed && Object.keys(hooks).length === 0) delete settings.hooks;
|
|
76
|
+
if (!changed) return false; // 没有 a4phone 的 Hook:保持用户文件原样,不重写
|
|
43
77
|
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
|
|
78
|
+
return true;
|
|
44
79
|
}
|
|
45
80
|
|
|
46
81
|
// 计算 Hook 命令:依赖全局安装的 a4p(在 PATH 上),路径更稳
|
|
@@ -62,7 +97,7 @@ type = "command"
|
|
|
62
97
|
command = "a4p hook codex"
|
|
63
98
|
|
|
64
99
|
[[hooks.PreToolUse]]
|
|
65
|
-
matcher = "
|
|
100
|
+
matcher = "request_user_input"
|
|
66
101
|
[[hooks.PreToolUse.hooks]]
|
|
67
102
|
type = "command"
|
|
68
103
|
command = "a4p hook codex"
|
|
@@ -73,44 +108,245 @@ type = "command"
|
|
|
73
108
|
command = "a4p hook codex"`;
|
|
74
109
|
}
|
|
75
110
|
|
|
111
|
+
// 修正既有配置里 a4phone PreToolUse 块的 matcher(Codex 的提问工具实际叫 request_user_input,
|
|
112
|
+
// 旧值 AskUserQuestion 匹配不上导致 hook 不触发)。只改含 a4p hook codex 的 PreToolUse 块。
|
|
113
|
+
export function fixCodexPreToolUseMatcher(content, oldMatcher, newMatcher) {
|
|
114
|
+
const lines = content.split('\n');
|
|
115
|
+
let i = 0;
|
|
116
|
+
let changed = false;
|
|
117
|
+
while (i < lines.length) {
|
|
118
|
+
if (/^\[\[hooks\.PreToolUse\]\]\s*$/.test(lines[i])) {
|
|
119
|
+
const block = [lines[i]];
|
|
120
|
+
let j = i + 1;
|
|
121
|
+
while (j < lines.length && lines[j].trim() !== '') {
|
|
122
|
+
block.push(lines[j]);
|
|
123
|
+
j++;
|
|
124
|
+
}
|
|
125
|
+
if (block.some((l) => l.includes('a4p hook codex'))) {
|
|
126
|
+
const replaced = block.map((l) =>
|
|
127
|
+
l.includes(`matcher = "${oldMatcher}"`)
|
|
128
|
+
? l.replace(`"${oldMatcher}"`, `"${newMatcher}"`)
|
|
129
|
+
: l
|
|
130
|
+
);
|
|
131
|
+
if (replaced.some((l, k) => l !== block[k])) {
|
|
132
|
+
lines.splice(i, block.length, ...replaced);
|
|
133
|
+
changed = true;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
i = j;
|
|
137
|
+
} else {
|
|
138
|
+
i++;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return changed ? lines.join('\n') : content;
|
|
142
|
+
}
|
|
143
|
+
|
|
76
144
|
// 写入 Codex 配置(保留既有内容,幂等)
|
|
77
145
|
// 追加到文件末尾,用显式表头包裹,避免根级键被吸收
|
|
78
|
-
export function configureCodex() {
|
|
146
|
+
export function configureCodex(codexPath = CODEX_PATH) {
|
|
79
147
|
let content = '';
|
|
80
148
|
try {
|
|
81
|
-
content = fs.readFileSync(
|
|
149
|
+
content = fs.readFileSync(codexPath, 'utf-8');
|
|
82
150
|
} catch {}
|
|
83
|
-
|
|
151
|
+
// 已配置:marker 块存在,或 Codex 已把 a4phone Hook 规范化为内联格式
|
|
152
|
+
if (content.includes(CODEX_MARKER_START) || /\ba4p hook codex\b/.test(content)) {
|
|
153
|
+
// 顺带把旧 matcher 就地修正(Codex 提问工具名是 request_user_input)
|
|
154
|
+
const fixed = fixCodexPreToolUseMatcher(content, 'AskUserQuestion', 'request_user_input');
|
|
155
|
+
if (fixed !== content) fs.writeFileSync(codexPath, fixed);
|
|
156
|
+
return false;
|
|
157
|
+
}
|
|
84
158
|
|
|
85
|
-
fs.mkdirSync(path.dirname(
|
|
159
|
+
fs.mkdirSync(path.dirname(codexPath), { recursive: true });
|
|
86
160
|
|
|
87
161
|
const defs = `${CODEX_MARKER_START}\n${codexHooksDefs()}\n${CODEX_MARKER_END}`;
|
|
88
162
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
163
|
+
const featuresMatch = content.match(/^\[features\]\s*$/m);
|
|
164
|
+
if (featuresMatch) {
|
|
165
|
+
// 已有 [features] 表:仅当表内尚无 hooks 键时才插入 hooks = true,避免重复键
|
|
166
|
+
const rest = content.slice(featuresMatch.index);
|
|
167
|
+
const nextSection = rest.indexOf('\n[');
|
|
168
|
+
const tableBody = nextSection === -1 ? rest : rest.slice(0, nextSection);
|
|
169
|
+
if (!/^\s*hooks\s*=/m.test(tableBody)) {
|
|
170
|
+
const insertAt = featuresMatch.index + '[features]'.length;
|
|
171
|
+
content = content.slice(0, insertAt) + '\nhooks = true' + content.slice(insertAt);
|
|
172
|
+
}
|
|
173
|
+
fs.writeFileSync(codexPath, content.trimEnd() + '\n\n' + defs + '\n');
|
|
93
174
|
} else {
|
|
94
175
|
// 无 [features]:末尾追加完整块([features] 显式表头 + Hook 定义)
|
|
95
176
|
const block = `${CODEX_MARKER_START}\n[features]\nhooks = true\n\n${codexHooksDefs()}\n${CODEX_MARKER_END}`;
|
|
96
|
-
fs.writeFileSync(
|
|
177
|
+
fs.writeFileSync(codexPath, (content ? content.trimEnd() + '\n\n' : '') + block + '\n');
|
|
97
178
|
}
|
|
98
179
|
return true;
|
|
99
180
|
}
|
|
100
181
|
|
|
101
|
-
//
|
|
102
|
-
|
|
182
|
+
// 移除所有含 a4p hook codex 的 [[hooks.*]] 块(覆盖 marker 嵌套格式与 Codex 内联数组格式)
|
|
183
|
+
function stripA4pHookBlocks(content) {
|
|
184
|
+
const lines = content.split('\n');
|
|
185
|
+
const out = [];
|
|
186
|
+
let i = 0;
|
|
187
|
+
while (i < lines.length) {
|
|
188
|
+
const line = lines[i];
|
|
189
|
+
if (/^\[\[hooks\./.test(line)) {
|
|
190
|
+
const block = [line];
|
|
191
|
+
let j = i + 1;
|
|
192
|
+
while (j < lines.length && lines[j].trim() !== '') {
|
|
193
|
+
block.push(lines[j]);
|
|
194
|
+
j++;
|
|
195
|
+
}
|
|
196
|
+
if (block.join('\n').includes('a4p hook codex')) {
|
|
197
|
+
// a4phone 的 Hook 块:整块丢弃,并吞掉尾随空行
|
|
198
|
+
while (j < lines.length && lines[j].trim() === '') j++;
|
|
199
|
+
} else {
|
|
200
|
+
out.push(...block);
|
|
201
|
+
}
|
|
202
|
+
i = j;
|
|
203
|
+
} else {
|
|
204
|
+
out.push(line);
|
|
205
|
+
i++;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return out.join('\n');
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// 清理 configureCodex 写入的 [features] hooks = true 空壳:
|
|
212
|
+
// 仅当 [features] 表只剩下 hooks = true(移除后表变空)时才整表删除,
|
|
213
|
+
// 表里还有其他键时原样保留,避免误删用户自己的 features 配置。
|
|
214
|
+
export function stripFeaturesHooksShell(content) {
|
|
215
|
+
const lines = content.split('\n');
|
|
216
|
+
const out = [];
|
|
217
|
+
let i = 0;
|
|
218
|
+
while (i < lines.length) {
|
|
219
|
+
if (/^\[features\]\s*$/.test(lines[i])) {
|
|
220
|
+
// 收集表体直到下一个 [ 表头或文件末尾
|
|
221
|
+
const body = [];
|
|
222
|
+
let j = i + 1;
|
|
223
|
+
while (j < lines.length && !/^\[/.test(lines[j])) {
|
|
224
|
+
body.push(lines[j]);
|
|
225
|
+
j++;
|
|
226
|
+
}
|
|
227
|
+
const keys = body.map((l) => l.trim()).filter((l) => l && !l.startsWith('#'));
|
|
228
|
+
const onlyHooksTrue = keys.length > 0 && keys.every((k) => k === 'hooks = true');
|
|
229
|
+
if (onlyHooksTrue) {
|
|
230
|
+
// 空壳:整表删除,顺带去掉前导空行
|
|
231
|
+
i = j;
|
|
232
|
+
while (out.length && out[out.length - 1].trim() === '') out.pop();
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
out.push(lines[i]);
|
|
237
|
+
i++;
|
|
238
|
+
}
|
|
239
|
+
return out.join('\n');
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// 移除 Codex 配置中的 a4phone Hook(marker 块 + 规范化格式 + features 空壳)
|
|
243
|
+
export function unconfigureCodex(codexPath = CODEX_PATH) {
|
|
103
244
|
let content = '';
|
|
104
245
|
try {
|
|
105
|
-
content = fs.readFileSync(
|
|
246
|
+
content = fs.readFileSync(codexPath, 'utf-8');
|
|
106
247
|
} catch {}
|
|
248
|
+
const original = content;
|
|
107
249
|
const start = content.indexOf(CODEX_MARKER_START);
|
|
108
250
|
const end = content.indexOf(CODEX_MARKER_END);
|
|
109
251
|
if (start !== -1 && end !== -1) {
|
|
110
252
|
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');
|
|
113
253
|
}
|
|
254
|
+
const stripped = stripFeaturesHooksShell(stripA4pHookBlocks(content)).replace(/\n{3,}/g, '\n\n').trim();
|
|
255
|
+
// 用原始内容判断是否发生变化:slice 后的 content 已不含 marker,与 stripped 恒等会误判"无需写入"
|
|
256
|
+
if (stripped !== original.trim()) {
|
|
257
|
+
fs.writeFileSync(codexPath, stripped + '\n');
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// ── DSH(DeepSeek Harness)Hook 插件挂载 ─────────────────────────────
|
|
262
|
+
// 复用本包 dsh/ 插件(Cordis 插件,监听 DSH 会话事件与工具/审批管线),
|
|
263
|
+
// 以 insert 形式追加到 web profile 的 cordis.patch.yml(热生效,无需重启)。
|
|
264
|
+
// 目标 profile 与插件的 name 相对路径在运行时计算,避免硬编码。
|
|
265
|
+
const DSH_PROFILE_NAME = 'web';
|
|
266
|
+
const DSH_PROFILE_DIR = path.join(os.homedir(), '.dsh', 'profiles', DSH_PROFILE_NAME);
|
|
267
|
+
const DSH_PATCH_PATH = path.join(DSH_PROFILE_DIR, 'cordis.patch.yml');
|
|
268
|
+
const DSH_MARKER_START = '# ===== a4phone dsh-hook (auto-generated) =====';
|
|
269
|
+
const DSH_MARKER_END = '# ===== end a4phone dsh-hook =====';
|
|
270
|
+
|
|
271
|
+
// 本包 dsh 插件入口文件绝对路径(setup.mjs 位于 src/,包根为 ../)
|
|
272
|
+
function dshPluginEntry() {
|
|
273
|
+
return path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'dsh', 'lib', 'index.js');
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// Windows 下把反斜杠路径转正斜杠(loader 按 URL 语义解析 name)
|
|
277
|
+
function toPosix(p) {
|
|
278
|
+
return p.split(path.sep).join('/');
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// 生成 dsh-hook 的 patch 挂载块(marker 包裹,便于幂等替换/清理)
|
|
282
|
+
function dshHookBlock(relName) {
|
|
283
|
+
return `${DSH_MARKER_START}\n- insert:\n - id: dsh-hook\n name: "${relName}"\n${DSH_MARKER_END}`;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// 移除 cordis.patch.yml 中的 dsh-hook 挂载:
|
|
287
|
+
// 1) 本插件 marker 包裹的块;2) 任何顶层 insert 块(含旧版手动挂载 id: dsh-hook)。
|
|
288
|
+
// 保留 profile 头注释与其他插件条目。
|
|
289
|
+
function stripDshHookBlocks(content) {
|
|
290
|
+
const lines = content.split('\n');
|
|
291
|
+
const out = [];
|
|
292
|
+
let i = 0;
|
|
293
|
+
while (i < lines.length) {
|
|
294
|
+
const line = lines[i];
|
|
295
|
+
// marker 包裹的本插件块:整体移除(含 END 行)
|
|
296
|
+
if (line.trim() === DSH_MARKER_START) {
|
|
297
|
+
let j = i + 1;
|
|
298
|
+
while (j < lines.length && lines[j].trim() !== DSH_MARKER_END) j++;
|
|
299
|
+
i = Math.min(j + 1, lines.length);
|
|
300
|
+
continue;
|
|
301
|
+
}
|
|
302
|
+
// 顶层 insert 块:缩进内容随块收集,含 id: dsh-hook 则整块丢弃并吞掉尾随空行
|
|
303
|
+
if (/^- insert:\s*$/.test(line)) {
|
|
304
|
+
const block = [line];
|
|
305
|
+
let j = i + 1;
|
|
306
|
+
while (j < lines.length && /^\s/.test(lines[j])) { block.push(lines[j]); j++; }
|
|
307
|
+
if (block.join('\n').includes('id: dsh-hook')) {
|
|
308
|
+
while (j < lines.length && lines[j].trim() === '') j++;
|
|
309
|
+
} else {
|
|
310
|
+
out.push(...block);
|
|
311
|
+
}
|
|
312
|
+
i = j;
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
315
|
+
out.push(line);
|
|
316
|
+
i++;
|
|
317
|
+
}
|
|
318
|
+
return out.join('\n');
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// 写入 dsh-hook 挂载(幂等):返回 true=已写入,false=跳过(未检测到 profile 或已是最新)。
|
|
322
|
+
// 显式传入 profileDir/pluginEntry 便于测试(沿用 configureCodex(codexPath) 的模式)。
|
|
323
|
+
export function configureDsh({ profileDir = DSH_PROFILE_DIR, pluginEntry = dshPluginEntry() } = {}) {
|
|
324
|
+
if (!fs.existsSync(profileDir)) return false; // dsh 未初始化,跳过
|
|
325
|
+
const patchPath = path.join(profileDir, 'cordis.patch.yml');
|
|
326
|
+
let content = '';
|
|
327
|
+
try { content = fs.readFileSync(patchPath, 'utf-8'); } catch {}
|
|
328
|
+
|
|
329
|
+
// 已挂载本插件的最新相对路径 → 幂等跳过
|
|
330
|
+
const rel = toPosix(path.relative(profileDir, pluginEntry));
|
|
331
|
+
const block = dshHookBlock(rel);
|
|
332
|
+
if (content.includes(DSH_MARKER_START) && content.includes(block)) return false;
|
|
333
|
+
|
|
334
|
+
const base = stripDshHookBlocks(content).trimEnd().replace(/\n{3,}/g, '\n\n');
|
|
335
|
+
const out = (base ? base + '\n\n' : '') + block + '\n';
|
|
336
|
+
fs.mkdirSync(profileDir, { recursive: true });
|
|
337
|
+
fs.writeFileSync(patchPath, out);
|
|
338
|
+
return true;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// 移除 dsh-hook 挂载(uninstall):返回 true=已改写,false=无挂载/未检测到 profile。
|
|
342
|
+
export function unconfigureDsh({ profileDir = DSH_PROFILE_DIR } = {}) {
|
|
343
|
+
const patchPath = path.join(profileDir, 'cordis.patch.yml');
|
|
344
|
+
if (!fs.existsSync(patchPath)) return false;
|
|
345
|
+
const content = fs.readFileSync(patchPath, 'utf-8');
|
|
346
|
+
const stripped = stripDshHookBlocks(content).replace(/\n{3,}/g, '\n\n').trim();
|
|
347
|
+
if (stripped === content.trim()) return false; // 无 a4phone dsh-hook 挂载
|
|
348
|
+
fs.writeFileSync(patchPath, stripped ? stripped + '\n' : '');
|
|
349
|
+
return true;
|
|
114
350
|
}
|
|
115
351
|
|
|
116
352
|
// setup 主流程
|
|
@@ -124,6 +360,7 @@ export async function runSetup({ generateQR }) {
|
|
|
124
360
|
|
|
125
361
|
const claudeConfigured = registerHooks(SETTINGS_PATH, hookCommand());
|
|
126
362
|
const codexConfigured = configureCodex();
|
|
363
|
+
const dshConfigured = configureDsh();
|
|
127
364
|
|
|
128
365
|
const subscribeUrl = `${config.server}/${config.topic}`;
|
|
129
366
|
const ntfyUrl = `ntfy://${new URL(config.server).host}/${config.topic}`;
|
|
@@ -140,7 +377,11 @@ export async function runSetup({ generateQR }) {
|
|
|
140
377
|
process.stdout.write('\n在 ntfy App 添加订阅,输入话题名称或扫描上方二维码。\n');
|
|
141
378
|
process.stdout.write(`Claude Code 配置:${claudeConfigured ? '已自动写入 ~/.claude/settings.json' : '已存在,跳过'}\n`);
|
|
142
379
|
process.stdout.write(`Codex 配置:${codexConfigured ? '已自动写入 ~/.codex/config.toml' : '已存在,跳过'}\n`);
|
|
380
|
+
const dshStatus = !fs.existsSync(DSH_PROFILE_DIR)
|
|
381
|
+
? '未检测到 DSH 环境(~/.dsh/profiles/web),跳过'
|
|
382
|
+
: dshConfigured ? '已自动写入 ~/.dsh/profiles/web/cordis.patch.yml' : '已存在,跳过';
|
|
383
|
+
process.stdout.write(`DSH 配置:${dshStatus}\n`);
|
|
143
384
|
process.stdout.write('模式切换:a4p out(外出/手机优先) / a4p home(终端优先) / a4p status\n');
|
|
144
|
-
process.stdout.write('重启 Claude Code / Codex 会话后 Hook
|
|
385
|
+
process.stdout.write('重启 Claude Code / Codex 会话后 Hook 生效(DSH 插件热生效,无需重启)。\n');
|
|
145
386
|
return config;
|
|
146
387
|
}
|
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
|
|
29
|
+
message,
|
|
17
30
|
});
|
|
18
31
|
}
|
|
19
32
|
return null; // Stop Hook 无需输出
|