a4phone 1.6.0 → 1.6.2

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/setup.mjs CHANGED
@@ -1,540 +1,540 @@
1
- // 安装引导:生成话题、写入配置、注册 Hook、显示二维码
2
- import crypto from 'crypto';
3
- import fs from 'fs';
4
- import os from 'os';
5
- import path from 'path';
6
- import { fileURLToPath } from 'url';
7
- import { loadConfig, saveConfig } from './config.mjs';
8
-
9
- const SETTINGS_PATH = path.join(os.homedir(), '.claude', 'settings.json');
10
-
11
- // 生成唯一话题名
12
- function generateTopic() {
13
- return 'a4p-' + crypto.randomBytes(8).toString('hex');
14
- }
15
-
16
- // 把 Hook 合并写入 settings.json(追加到各事件,保留用户既有 Hook)
17
- // 返回 true=有写入,false=已存在相同配置跳过
18
- export function registerHooks(settingsPath, hookCommand) {
19
- let settings = {};
20
- try {
21
- settings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
22
- } catch {}
23
-
24
- settings.hooks = settings.hooks || {};
25
-
26
- const eventBlocks = {
27
- Stop: [{ matcher: '*', hooks: [{ type: 'command', command: hookCommand }] }],
28
- PreToolUse: [{ matcher: 'AskUserQuestion', hooks: [{ type: 'command', command: hookCommand }] }],
29
- PermissionRequest: [{ matcher: '*', hooks: [{ type: 'command', command: hookCommand }] }],
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;
48
- fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
49
- fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
50
- return true;
51
- }
52
-
53
- export function unregisterHooks(settingsPath) {
54
- let settings = {};
55
- try {
56
- settings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
57
- } catch {}
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:保持用户文件原样,不重写
77
- fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
78
- return true;
79
- }
80
-
81
- // 计算 Hook 命令:依赖全局安装的 a4p(在 PATH 上),路径更稳
82
- function hookCommand() {
83
- return 'a4p hook';
84
- }
85
-
86
- // Codex 配置路径与 a4phone 标记
87
- const CODEX_PATH = path.join(os.homedir(), '.codex', 'config.toml');
88
- const CODEX_MARKER_START = '# ===== a4phone hooks (auto-generated) =====';
89
- const CODEX_MARKER_END = '# ===== end a4phone hooks =====';
90
-
91
- // 生成 Codex 的 Hook 定义(数组嵌套表格,根级别)
92
- // 命令带 codex 标识,便于 a4phone 动态显示触发方名称
93
- function codexHooksDefs() {
94
- return `[[hooks.Stop]]
95
- [[hooks.Stop.hooks]]
96
- type = "command"
97
- command = "a4p hook codex"
98
-
99
- [[hooks.PreToolUse]]
100
- matcher = "request_user_input"
101
- [[hooks.PreToolUse.hooks]]
102
- type = "command"
103
- command = "a4p hook codex"
104
-
105
- [[hooks.PermissionRequest]]
106
- [[hooks.PermissionRequest.hooks]]
107
- type = "command"
108
- command = "a4p hook codex"`;
109
- }
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
-
144
- // 写入 Codex 配置(保留既有内容,幂等)
145
- // 追加到文件末尾,用显式表头包裹,避免根级键被吸收
146
- export function configureCodex(codexPath = CODEX_PATH) {
147
- let content = '';
148
- try {
149
- content = fs.readFileSync(codexPath, 'utf-8');
150
- } catch {}
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
- }
158
-
159
- fs.mkdirSync(path.dirname(codexPath), { recursive: true });
160
-
161
- const defs = `${CODEX_MARKER_START}\n${codexHooksDefs()}\n${CODEX_MARKER_END}`;
162
-
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');
174
- } else {
175
- // 无 [features]:末尾追加完整块([features] 显式表头 + Hook 定义)
176
- const block = `${CODEX_MARKER_START}\n[features]\nhooks = true\n\n${codexHooksDefs()}\n${CODEX_MARKER_END}`;
177
- fs.writeFileSync(codexPath, (content ? content.trimEnd() + '\n\n' : '') + block + '\n');
178
- }
179
- return true;
180
- }
181
-
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) {
244
- let content = '';
245
- try {
246
- content = fs.readFileSync(codexPath, 'utf-8');
247
- } catch {}
248
- const original = content;
249
- const start = content.indexOf(CODEX_MARKER_START);
250
- const end = content.indexOf(CODEX_MARKER_END);
251
- if (start !== -1 && end !== -1) {
252
- content = content.slice(0, start) + content.slice(end + CODEX_MARKER_END.length);
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
- // ── ZCode Hook 注册 ─────────────────────────────────────────────────
262
- // ZCode 的 Hook 配置在 ~/.zcode/cli/config.json,形状为
263
- // { hooks: { enabled, events: { <Event>: [ { matcher?, hooks: [...] } ] } } }。
264
- // 与 Claude Code 的差异:事件块挂在 hooks.events 下,且配置文件 Hook 默认禁用,
265
- // 必须显式 hooks.enabled: true 才会运行(plugin Hook 除外)。
266
- const ZCODE_CONFIG_PATH = path.join(os.homedir(), '.zcode', 'cli', 'config.json');
267
- const ZCODE_HOOK_COMMAND = 'a4p hook zcode';
268
-
269
- export function configureZcode(zcodePath = ZCODE_CONFIG_PATH, hookCmd = ZCODE_HOOK_COMMAND) {
270
- let config = {};
271
- try { config = JSON.parse(fs.readFileSync(zcodePath, 'utf-8')); } catch {}
272
- config.hooks = config.hooks && typeof config.hooks === 'object' ? config.hooks : {};
273
- // 记录 enabled 是否有变化,避免"Hook 已配置但 runner 被禁用"时误判为无需写入
274
- let changed = config.hooks.enabled !== true;
275
- config.hooks.enabled = true;
276
- const events = config.hooks.events && typeof config.hooks.events === 'object' ? config.hooks.events : {};
277
-
278
- const eventBlocks = {
279
- Stop: [{ matcher: '*', hooks: [{ type: 'command', command: hookCmd }] }],
280
- PreToolUse: [{ matcher: 'AskUserQuestion', hooks: [{ type: 'command', command: hookCmd }] }],
281
- PermissionRequest: [{ matcher: '*', hooks: [{ type: 'command', command: hookCmd }] }],
282
- };
283
-
284
- for (const [event, blocks] of Object.entries(eventBlocks)) {
285
- // 兼容既有配置:事件值可能是数组,也可能被手写成单个对象
286
- const raw = events[event];
287
- const list = Array.isArray(raw) ? raw : raw && typeof raw === 'object' ? [raw] : [];
288
- const alreadyConfigured = list.some((b) =>
289
- (b.hooks || []).some((h) => h.command === hookCmd)
290
- );
291
- if (alreadyConfigured) continue;
292
- list.push(...blocks);
293
- events[event] = list;
294
- changed = true;
295
- }
296
- config.hooks.events = events;
297
-
298
- if (!changed) return false;
299
- fs.mkdirSync(path.dirname(zcodePath), { recursive: true });
300
- fs.writeFileSync(zcodePath, JSON.stringify(config, null, 2));
301
- return true;
302
- }
303
-
304
- export function unconfigureZcode(zcodePath = ZCODE_CONFIG_PATH) {
305
- let config = {};
306
- try { config = JSON.parse(fs.readFileSync(zcodePath, 'utf-8')); } catch {}
307
- const hooks = config.hooks;
308
- if (!hooks || typeof hooks !== 'object' || !hooks.events) return false;
309
- const events = hooks.events;
310
- let changed = false;
311
- // 只移除 a4phone 的 Hook,保留用户的其他 Hook 与其他事件
312
- const isA4p = (b) => (b.hooks || []).some((h) => (h.command || '').includes('a4p hook zcode'));
313
- for (const event of Object.keys(events)) {
314
- const entry = events[event];
315
- if (!Array.isArray(entry)) {
316
- // 手写的单对象条目(非数组):仅当本身含 a4phone Hook 时才删除,否则原样保留
317
- if (entry && typeof entry === 'object' && isA4p(entry)) { delete events[event]; changed = true; }
318
- continue;
319
- }
320
- const kept = entry.filter((b) => !isA4p(b));
321
- if (kept.length !== entry.length) changed = true;
322
- if (kept.length) events[event] = kept;
323
- else delete events[event];
324
- }
325
- if (!changed) return false; // 没有 a4phone 的 Hook:保持用户文件原样,不重写
326
- if (Object.keys(events).length === 0) delete hooks.events;
327
- if (Object.keys(hooks).length === 0) delete config.hooks;
328
- fs.writeFileSync(zcodePath, JSON.stringify(config, null, 2));
329
- return true;
330
- }
331
-
332
- // ── DSH(DeepSeek Harness)Hook 插件挂载 ─────────────────────────────
333
- // 复用本包 dsh/ 插件(Cordis 插件,监听 DSH 会话事件与工具/审批管线),
334
- // 以 insert 形式追加到各 profile 的 cordis.patch.yml(热生效,无需重启)。
335
- // profile 发现机制:扫描 ~/.dsh/profiles/ 下所有含 cordis.yml 的子目录
336
- // (web / tui / dsh-tui 及后续新装的变体均可覆盖),插件 name 按各 profile
337
- // 目录分别计算相对路径;守护进程(a4p listen)周期重扫,新装 profile 自动补挂。
338
- const DSH_PROFILES_DIR = path.join(os.homedir(), '.dsh', 'profiles');
339
- const DSH_MARKER_START = '# ===== a4phone dsh-hook (auto-generated) =====';
340
- const DSH_MARKER_END = '# ===== end a4phone dsh-hook =====';
341
-
342
- // 本包 dsh 插件入口文件绝对路径(setup.mjs 位于 src/,包根为 ../)
343
- function dshPluginEntry() {
344
- return path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'dsh', 'lib', 'index.js');
345
- }
346
-
347
- // Windows 下把反斜杠路径转正斜杠(loader 按 URL 语义解析 name)
348
- function toPosix(p) {
349
- return p.split(path.sep).join('/');
350
- }
351
-
352
- // 生成 dsh-hook 的 patch 挂载块(marker 包裹,便于幂等替换/清理)
353
- function dshHookBlock(relName) {
354
- return `${DSH_MARKER_START}\n- insert:\n - id: dsh-hook\n name: "${relName}"\n${DSH_MARKER_END}`;
355
- }
356
-
357
- // 移除 cordis.patch.yml 中的 dsh-hook 挂载:
358
- // 1) 本插件 marker 包裹的块;2) 任何顶层 insert 块(含旧版手动挂载 id: dsh-hook)。
359
- // 保留 profile 头注释与其他插件条目。
360
- function stripDshHookBlocks(content) {
361
- const lines = content.split('\n');
362
- const out = [];
363
- let i = 0;
364
- while (i < lines.length) {
365
- const line = lines[i];
366
- // marker 包裹的本插件块:整体移除(含 END 行)
367
- if (line.trim() === DSH_MARKER_START) {
368
- let j = i + 1;
369
- while (j < lines.length && lines[j].trim() !== DSH_MARKER_END) j++;
370
- i = Math.min(j + 1, lines.length);
371
- continue;
372
- }
373
- // 顶层 insert 块:缩进内容随块收集,含 id: dsh-hook 则整块丢弃并吞掉尾随空行
374
- if (/^- insert:\s*$/.test(line)) {
375
- const block = [line];
376
- let j = i + 1;
377
- while (j < lines.length && /^\s/.test(lines[j])) { block.push(lines[j]); j++; }
378
- if (block.join('\n').includes('id: dsh-hook')) {
379
- while (j < lines.length && lines[j].trim() === '') j++;
380
- } else {
381
- out.push(...block);
382
- }
383
- i = j;
384
- continue;
385
- }
386
- out.push(line);
387
- i++;
388
- }
389
- return out.join('\n');
390
- }
391
-
392
- // 发现所有 DSH profile:profiles 目录下含 cordis.yml 的子目录
393
- // (cordis.yml 是 profile 的身份文件;node_modules 等非 profile 目录自动排除)。
394
- // 导出便于测试与守护进程复用。
395
- export function discoverDshProfiles(profilesDir = DSH_PROFILES_DIR) {
396
- let entries;
397
- try {
398
- entries = fs.readdirSync(profilesDir, { withFileTypes: true });
399
- } catch {
400
- return []; // ~/.dsh/profiles 不存在:DSH 未安装
401
- }
402
- return entries
403
- .filter((e) => e.isDirectory() && e.name !== 'node_modules')
404
- .map((e) => path.join(profilesDir, e.name))
405
- .filter((dir) => {
406
- try { return fs.existsSync(path.join(dir, 'cordis.yml')); } catch { return false; }
407
- });
408
- }
409
-
410
- // 单个 profile 的挂载写入(幂等):返回 true=已写入,false=跳过(profile 不存在或已是最新)。
411
- function mountDshHook({ profileDir, pluginEntry }) {
412
- if (!fs.existsSync(profileDir)) return false; // dsh 未初始化,跳过
413
- const patchPath = path.join(profileDir, 'cordis.patch.yml');
414
- let content = '';
415
- try { content = fs.readFileSync(patchPath, 'utf-8'); } catch {}
416
-
417
- // 已挂载本插件的最新相对路径 → 幂等跳过
418
- const rel = toPosix(path.relative(profileDir, pluginEntry));
419
- const block = dshHookBlock(rel);
420
- if (content.includes(DSH_MARKER_START) && content.includes(block)) return false;
421
-
422
- // 默认模板占位符 `[]` 本身就是一个完整的 YAML 文档;若原样保留再往后追加
423
- // 条目,文件会变成两个没有 `---` 分隔的文档,DSH 启动解析时报
424
- // "end of the stream or a document separator is expected",故追加前移除。
425
- const base = stripDshHookBlocks(content)
426
- .replace(/^[ \t]*\[\][ \t]*\r?$/m, '')
427
- .trimEnd().replace(/\n{3,}/g, '\n\n');
428
- const out = (base ? base + '\n\n' : '') + block + '\n';
429
- fs.mkdirSync(profileDir, { recursive: true });
430
- fs.writeFileSync(patchPath, out);
431
- return true;
432
- }
433
-
434
- // 写入 dsh-hook 挂载,两种模式:
435
- // - 显式传入 profileDir:仅处理该 profile,返回 boolean(兼容旧调用与单测)
436
- // - 未传 profileDir:扫描 ~/.dsh/profiles 下全部 profile,
437
- // 返回 { scanned, mounted }(mounted 为本次新写入的 profile 名列表)
438
- // 显式传入参数便于测试(沿用 configureCodex(codexPath) 的模式)。
439
- export function configureDsh({ profileDir, profilesDir = DSH_PROFILES_DIR, pluginEntry = dshPluginEntry() } = {}) {
440
- if (profileDir) return mountDshHook({ profileDir, pluginEntry });
441
- const profiles = discoverDshProfiles(profilesDir);
442
- const mounted = [];
443
- for (const dir of profiles) {
444
- if (mountDshHook({ profileDir: dir, pluginEntry })) mounted.push(path.basename(dir));
445
- }
446
- return { scanned: profiles.length, mounted };
447
- }
448
-
449
- // 移除 dsh-hook 挂载(uninstall),同样支持两种模式:
450
- // - 显式传入 profileDir:仅清理该 profile,返回 boolean
451
- // - 未传:清理所有发现的 profile,任一改写即返回 true
452
- export function unconfigureDsh({ profileDir, profilesDir = DSH_PROFILES_DIR } = {}) {
453
- const dirs = profileDir ? [profileDir] : discoverDshProfiles(profilesDir);
454
- let changed = false;
455
- for (const dir of dirs) {
456
- const patchPath = path.join(dir, 'cordis.patch.yml');
457
- if (!fs.existsSync(patchPath)) continue;
458
- const content = fs.readFileSync(patchPath, 'utf-8');
459
- const stripped = stripDshHookBlocks(content).replace(/\n{3,}/g, '\n\n').trim();
460
- if (stripped === content.trim()) continue; // 该 profile 无 a4phone dsh-hook 挂载
461
- fs.writeFileSync(patchPath, stripped ? stripped + '\n' : '');
462
- changed = true;
463
- }
464
- return changed;
465
- }
466
-
467
- // setup 主流程
468
- export async function runSetup({ generateQR }) {
469
- const config = loadConfig();
470
- if (!config.topic) {
471
- config.topic = generateTopic();
472
- config.server = config.server || 'https://ntfy.sh';
473
- }
474
- saveConfig(config);
475
-
476
- const claudeConfigured = registerHooks(SETTINGS_PATH, hookCommand());
477
- const codexConfigured = configureCodex();
478
- const zcodeConfigured = configureZcode();
479
- const dshResult = configureDsh();
480
-
481
- // ZCode 远程续聊:把默认模型配置写入 ~/.zcode/cli/config.json
482
- // (headless 续聊必需;每次续聊前还会按会话实际模型自动同步)
483
- let zcodeModelStatus = '未配置(未检测到 ZCode 模型注册表)';
484
- try {
485
- const { ensureZcodeModelConfig } = await import('./zcode.mjs');
486
- const synced = ensureZcodeModelConfig();
487
- if (synced.ok) zcodeModelStatus = '已写入默认模型配置(续聊时按会话实际模型自动同步)';
488
- else zcodeModelStatus = `未配置:${synced.reason}`;
489
- } catch {}
490
-
491
- const subscribeUrl = `${config.server}/${config.topic}`;
492
- const ntfyUrl = `ntfy://${new URL(config.server).host}/${config.topic}`;
493
-
494
- process.stdout.write('a4phone 安装完成\n\n');
495
- process.stdout.write(`话题名称: ${config.topic}\n`);
496
- process.stdout.write(`订阅地址: ${subscribeUrl}\n\n`);
497
-
498
- if (generateQR) {
499
- process.stdout.write('在 ntfy App 中扫码订阅:\n\n');
500
- generateQR(ntfyUrl, { small: true }, (qr) => process.stdout.write(qr + '\n'));
501
- }
502
-
503
- process.stdout.write('\n在 ntfy App 添加订阅,输入话题名称或扫描上方二维码。\n');
504
- process.stdout.write(`Claude Code 配置:${claudeConfigured ? '已自动写入 ~/.claude/settings.json' : '已存在,跳过'}\n`);
505
- process.stdout.write(`Codex 配置:${codexConfigured ? '已自动写入 ~/.codex/config.toml' : '已存在,跳过'}\n`);
506
- process.stdout.write(`ZCode 配置:${zcodeConfigured ? '已自动写入 ~/.zcode/cli/config.json' : '已存在,跳过'}\n`);
507
- process.stdout.write(`ZCode 续聊模型:${zcodeModelStatus}\n`);
508
- let dshStatus;
509
- if (!fs.existsSync(DSH_PROFILES_DIR)) {
510
- dshStatus = '未检测到 DSH 环境(~/.dsh/profiles),跳过';
511
- } else if (!dshResult.scanned) {
512
- dshStatus = '~/.dsh/profiles 下暂无 profile,跳过(新装 profile 后守护进程会自动补挂)';
513
- } else {
514
- const names = discoverDshProfiles().map((p) => path.basename(p));
515
- dshStatus = dshResult.mounted.length
516
- ? `已自动写入 cordis.patch.yml:${dshResult.mounted.join('、')}(共 ${names.length} 个 profile:${names.join('、')})`
517
- : `已存在,跳过(共 ${names.length} 个 profile:${names.join('、')})`;
518
- }
519
- process.stdout.write(`DSH 配置:${dshStatus}\n`);
520
- process.stdout.write('模式切换:a4p out(外出/手机优先) / a4p home(终端优先) / a4p status\n');
521
- process.stdout.write('重启 Claude Code / Codex / ZCode 会话后 Hook 生效(DSH 插件热生效,无需重启)。\n');
522
-
523
- // 默认启动续聊守护进程 + 注册开机自启(失败不阻塞 setup,给出提示)
524
- try {
525
- const { startDaemon } = await import('./daemon.mjs');
526
- await startDaemon();
527
- } catch (error) {
528
- process.stdout.write(`续聊守护进程启动失败:${String(error?.message ?? error)}\n`);
529
- }
530
- try {
531
- const { enableAutostart } = await import('./autostart.mjs');
532
- const autostart = enableAutostart();
533
- process.stdout.write(autostart.ok
534
- ? '开机自启:已注册(登录时自动运行续聊守护进程,可用 a4p autostart --off 关闭)\n'
535
- : `开机自启:${autostart.reason}\n`);
536
- } catch (error) {
537
- process.stdout.write(`开机自启注册失败:${String(error?.message ?? error)}\n`);
538
- }
539
- return config;
540
- }
1
+ // 安装引导:生成话题、写入配置、注册 Hook、显示二维码
2
+ import crypto from 'crypto';
3
+ import fs from 'fs';
4
+ import os from 'os';
5
+ import path from 'path';
6
+ import { fileURLToPath } from 'url';
7
+ import { loadConfig, saveConfig } from './config.mjs';
8
+
9
+ const SETTINGS_PATH = path.join(os.homedir(), '.claude', 'settings.json');
10
+
11
+ // 生成唯一话题名
12
+ function generateTopic() {
13
+ return 'a4p-' + crypto.randomBytes(8).toString('hex');
14
+ }
15
+
16
+ // 把 Hook 合并写入 settings.json(追加到各事件,保留用户既有 Hook)
17
+ // 返回 true=有写入,false=已存在相同配置跳过
18
+ export function registerHooks(settingsPath, hookCommand) {
19
+ let settings = {};
20
+ try {
21
+ settings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
22
+ } catch {}
23
+
24
+ settings.hooks = settings.hooks || {};
25
+
26
+ const eventBlocks = {
27
+ Stop: [{ matcher: '*', hooks: [{ type: 'command', command: hookCommand }] }],
28
+ PreToolUse: [{ matcher: 'AskUserQuestion', hooks: [{ type: 'command', command: hookCommand }] }],
29
+ PermissionRequest: [{ matcher: '*', hooks: [{ type: 'command', command: hookCommand }] }],
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;
48
+ fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
49
+ fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
50
+ return true;
51
+ }
52
+
53
+ export function unregisterHooks(settingsPath) {
54
+ let settings = {};
55
+ try {
56
+ settings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
57
+ } catch {}
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:保持用户文件原样,不重写
77
+ fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
78
+ return true;
79
+ }
80
+
81
+ // 计算 Hook 命令:依赖全局安装的 a4p(在 PATH 上),路径更稳
82
+ function hookCommand() {
83
+ return 'a4p hook';
84
+ }
85
+
86
+ // Codex 配置路径与 a4phone 标记
87
+ const CODEX_PATH = path.join(os.homedir(), '.codex', 'config.toml');
88
+ const CODEX_MARKER_START = '# ===== a4phone hooks (auto-generated) =====';
89
+ const CODEX_MARKER_END = '# ===== end a4phone hooks =====';
90
+
91
+ // 生成 Codex 的 Hook 定义(数组嵌套表格,根级别)
92
+ // 命令带 codex 标识,便于 a4phone 动态显示触发方名称
93
+ function codexHooksDefs() {
94
+ return `[[hooks.Stop]]
95
+ [[hooks.Stop.hooks]]
96
+ type = "command"
97
+ command = "a4p hook codex"
98
+
99
+ [[hooks.PreToolUse]]
100
+ matcher = "request_user_input"
101
+ [[hooks.PreToolUse.hooks]]
102
+ type = "command"
103
+ command = "a4p hook codex"
104
+
105
+ [[hooks.PermissionRequest]]
106
+ [[hooks.PermissionRequest.hooks]]
107
+ type = "command"
108
+ command = "a4p hook codex"`;
109
+ }
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
+
144
+ // 写入 Codex 配置(保留既有内容,幂等)
145
+ // 追加到文件末尾,用显式表头包裹,避免根级键被吸收
146
+ export function configureCodex(codexPath = CODEX_PATH) {
147
+ let content = '';
148
+ try {
149
+ content = fs.readFileSync(codexPath, 'utf-8');
150
+ } catch {}
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
+ }
158
+
159
+ fs.mkdirSync(path.dirname(codexPath), { recursive: true });
160
+
161
+ const defs = `${CODEX_MARKER_START}\n${codexHooksDefs()}\n${CODEX_MARKER_END}`;
162
+
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');
174
+ } else {
175
+ // 无 [features]:末尾追加完整块([features] 显式表头 + Hook 定义)
176
+ const block = `${CODEX_MARKER_START}\n[features]\nhooks = true\n\n${codexHooksDefs()}\n${CODEX_MARKER_END}`;
177
+ fs.writeFileSync(codexPath, (content ? content.trimEnd() + '\n\n' : '') + block + '\n');
178
+ }
179
+ return true;
180
+ }
181
+
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) {
244
+ let content = '';
245
+ try {
246
+ content = fs.readFileSync(codexPath, 'utf-8');
247
+ } catch {}
248
+ const original = content;
249
+ const start = content.indexOf(CODEX_MARKER_START);
250
+ const end = content.indexOf(CODEX_MARKER_END);
251
+ if (start !== -1 && end !== -1) {
252
+ content = content.slice(0, start) + content.slice(end + CODEX_MARKER_END.length);
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
+ // ── ZCode Hook 注册 ─────────────────────────────────────────────────
262
+ // ZCode 的 Hook 配置在 ~/.zcode/cli/config.json,形状为
263
+ // { hooks: { enabled, events: { <Event>: [ { matcher?, hooks: [...] } ] } } }。
264
+ // 与 Claude Code 的差异:事件块挂在 hooks.events 下,且配置文件 Hook 默认禁用,
265
+ // 必须显式 hooks.enabled: true 才会运行(plugin Hook 除外)。
266
+ const ZCODE_CONFIG_PATH = path.join(os.homedir(), '.zcode', 'cli', 'config.json');
267
+ const ZCODE_HOOK_COMMAND = 'a4p hook zcode';
268
+
269
+ export function configureZcode(zcodePath = ZCODE_CONFIG_PATH, hookCmd = ZCODE_HOOK_COMMAND) {
270
+ let config = {};
271
+ try { config = JSON.parse(fs.readFileSync(zcodePath, 'utf-8')); } catch {}
272
+ config.hooks = config.hooks && typeof config.hooks === 'object' ? config.hooks : {};
273
+ // 记录 enabled 是否有变化,避免"Hook 已配置但 runner 被禁用"时误判为无需写入
274
+ let changed = config.hooks.enabled !== true;
275
+ config.hooks.enabled = true;
276
+ const events = config.hooks.events && typeof config.hooks.events === 'object' ? config.hooks.events : {};
277
+
278
+ const eventBlocks = {
279
+ Stop: [{ matcher: '*', hooks: [{ type: 'command', command: hookCmd }] }],
280
+ PreToolUse: [{ matcher: 'AskUserQuestion', hooks: [{ type: 'command', command: hookCmd }] }],
281
+ PermissionRequest: [{ matcher: '*', hooks: [{ type: 'command', command: hookCmd }] }],
282
+ };
283
+
284
+ for (const [event, blocks] of Object.entries(eventBlocks)) {
285
+ // 兼容既有配置:事件值可能是数组,也可能被手写成单个对象
286
+ const raw = events[event];
287
+ const list = Array.isArray(raw) ? raw : raw && typeof raw === 'object' ? [raw] : [];
288
+ const alreadyConfigured = list.some((b) =>
289
+ (b.hooks || []).some((h) => h.command === hookCmd)
290
+ );
291
+ if (alreadyConfigured) continue;
292
+ list.push(...blocks);
293
+ events[event] = list;
294
+ changed = true;
295
+ }
296
+ config.hooks.events = events;
297
+
298
+ if (!changed) return false;
299
+ fs.mkdirSync(path.dirname(zcodePath), { recursive: true });
300
+ fs.writeFileSync(zcodePath, JSON.stringify(config, null, 2));
301
+ return true;
302
+ }
303
+
304
+ export function unconfigureZcode(zcodePath = ZCODE_CONFIG_PATH) {
305
+ let config = {};
306
+ try { config = JSON.parse(fs.readFileSync(zcodePath, 'utf-8')); } catch {}
307
+ const hooks = config.hooks;
308
+ if (!hooks || typeof hooks !== 'object' || !hooks.events) return false;
309
+ const events = hooks.events;
310
+ let changed = false;
311
+ // 只移除 a4phone 的 Hook,保留用户的其他 Hook 与其他事件
312
+ const isA4p = (b) => (b.hooks || []).some((h) => (h.command || '').includes('a4p hook zcode'));
313
+ for (const event of Object.keys(events)) {
314
+ const entry = events[event];
315
+ if (!Array.isArray(entry)) {
316
+ // 手写的单对象条目(非数组):仅当本身含 a4phone Hook 时才删除,否则原样保留
317
+ if (entry && typeof entry === 'object' && isA4p(entry)) { delete events[event]; changed = true; }
318
+ continue;
319
+ }
320
+ const kept = entry.filter((b) => !isA4p(b));
321
+ if (kept.length !== entry.length) changed = true;
322
+ if (kept.length) events[event] = kept;
323
+ else delete events[event];
324
+ }
325
+ if (!changed) return false; // 没有 a4phone 的 Hook:保持用户文件原样,不重写
326
+ if (Object.keys(events).length === 0) delete hooks.events;
327
+ if (Object.keys(hooks).length === 0) delete config.hooks;
328
+ fs.writeFileSync(zcodePath, JSON.stringify(config, null, 2));
329
+ return true;
330
+ }
331
+
332
+ // ── DSH(DeepSeek Harness)Hook 插件挂载 ─────────────────────────────
333
+ // 复用本包 dsh/ 插件(Cordis 插件,监听 DSH 会话事件与工具/审批管线),
334
+ // 以 insert 形式追加到各 profile 的 cordis.patch.yml(热生效,无需重启)。
335
+ // profile 发现机制:扫描 ~/.dsh/profiles/ 下所有含 cordis.yml 的子目录
336
+ // (web / tui / dsh-tui 及后续新装的变体均可覆盖),插件 name 按各 profile
337
+ // 目录分别计算相对路径;守护进程(a4p listen)周期重扫,新装 profile 自动补挂。
338
+ const DSH_PROFILES_DIR = path.join(os.homedir(), '.dsh', 'profiles');
339
+ const DSH_MARKER_START = '# ===== a4phone dsh-hook (auto-generated) =====';
340
+ const DSH_MARKER_END = '# ===== end a4phone dsh-hook =====';
341
+
342
+ // 本包 dsh 插件入口文件绝对路径(setup.mjs 位于 src/,包根为 ../)
343
+ function dshPluginEntry() {
344
+ return path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'dsh', 'lib', 'index.js');
345
+ }
346
+
347
+ // Windows 下把反斜杠路径转正斜杠(loader 按 URL 语义解析 name)
348
+ function toPosix(p) {
349
+ return p.split(path.sep).join('/');
350
+ }
351
+
352
+ // 生成 dsh-hook 的 patch 挂载块(marker 包裹,便于幂等替换/清理)
353
+ function dshHookBlock(relName) {
354
+ return `${DSH_MARKER_START}\n- insert:\n - id: dsh-hook\n name: "${relName}"\n${DSH_MARKER_END}`;
355
+ }
356
+
357
+ // 移除 cordis.patch.yml 中的 dsh-hook 挂载:
358
+ // 1) 本插件 marker 包裹的块;2) 任何顶层 insert 块(含旧版手动挂载 id: dsh-hook)。
359
+ // 保留 profile 头注释与其他插件条目。
360
+ function stripDshHookBlocks(content) {
361
+ const lines = content.split('\n');
362
+ const out = [];
363
+ let i = 0;
364
+ while (i < lines.length) {
365
+ const line = lines[i];
366
+ // marker 包裹的本插件块:整体移除(含 END 行)
367
+ if (line.trim() === DSH_MARKER_START) {
368
+ let j = i + 1;
369
+ while (j < lines.length && lines[j].trim() !== DSH_MARKER_END) j++;
370
+ i = Math.min(j + 1, lines.length);
371
+ continue;
372
+ }
373
+ // 顶层 insert 块:缩进内容随块收集,含 id: dsh-hook 则整块丢弃并吞掉尾随空行
374
+ if (/^- insert:\s*$/.test(line)) {
375
+ const block = [line];
376
+ let j = i + 1;
377
+ while (j < lines.length && /^\s/.test(lines[j])) { block.push(lines[j]); j++; }
378
+ if (block.join('\n').includes('id: dsh-hook')) {
379
+ while (j < lines.length && lines[j].trim() === '') j++;
380
+ } else {
381
+ out.push(...block);
382
+ }
383
+ i = j;
384
+ continue;
385
+ }
386
+ out.push(line);
387
+ i++;
388
+ }
389
+ return out.join('\n');
390
+ }
391
+
392
+ // 发现所有 DSH profile:profiles 目录下含 cordis.yml 的子目录
393
+ // (cordis.yml 是 profile 的身份文件;node_modules 等非 profile 目录自动排除)。
394
+ // 导出便于测试与守护进程复用。
395
+ export function discoverDshProfiles(profilesDir = DSH_PROFILES_DIR) {
396
+ let entries;
397
+ try {
398
+ entries = fs.readdirSync(profilesDir, { withFileTypes: true });
399
+ } catch {
400
+ return []; // ~/.dsh/profiles 不存在:DSH 未安装
401
+ }
402
+ return entries
403
+ .filter((e) => e.isDirectory() && e.name !== 'node_modules')
404
+ .map((e) => path.join(profilesDir, e.name))
405
+ .filter((dir) => {
406
+ try { return fs.existsSync(path.join(dir, 'cordis.yml')); } catch { return false; }
407
+ });
408
+ }
409
+
410
+ // 单个 profile 的挂载写入(幂等):返回 true=已写入,false=跳过(profile 不存在或已是最新)。
411
+ function mountDshHook({ profileDir, pluginEntry }) {
412
+ if (!fs.existsSync(profileDir)) return false; // dsh 未初始化,跳过
413
+ const patchPath = path.join(profileDir, 'cordis.patch.yml');
414
+ let content = '';
415
+ try { content = fs.readFileSync(patchPath, 'utf-8'); } catch {}
416
+
417
+ // 已挂载本插件的最新相对路径 → 幂等跳过
418
+ const rel = toPosix(path.relative(profileDir, pluginEntry));
419
+ const block = dshHookBlock(rel);
420
+ if (content.includes(DSH_MARKER_START) && content.includes(block)) return false;
421
+
422
+ // 默认模板占位符 `[]` 本身就是一个完整的 YAML 文档;若原样保留再往后追加
423
+ // 条目,文件会变成两个没有 `---` 分隔的文档,DSH 启动解析时报
424
+ // "end of the stream or a document separator is expected",故追加前移除。
425
+ const base = stripDshHookBlocks(content)
426
+ .replace(/^[ \t]*\[\][ \t]*\r?$/m, '')
427
+ .trimEnd().replace(/\n{3,}/g, '\n\n');
428
+ const out = (base ? base + '\n\n' : '') + block + '\n';
429
+ fs.mkdirSync(profileDir, { recursive: true });
430
+ fs.writeFileSync(patchPath, out);
431
+ return true;
432
+ }
433
+
434
+ // 写入 dsh-hook 挂载,两种模式:
435
+ // - 显式传入 profileDir:仅处理该 profile,返回 boolean(兼容旧调用与单测)
436
+ // - 未传 profileDir:扫描 ~/.dsh/profiles 下全部 profile,
437
+ // 返回 { scanned, mounted }(mounted 为本次新写入的 profile 名列表)
438
+ // 显式传入参数便于测试(沿用 configureCodex(codexPath) 的模式)。
439
+ export function configureDsh({ profileDir, profilesDir = DSH_PROFILES_DIR, pluginEntry = dshPluginEntry() } = {}) {
440
+ if (profileDir) return mountDshHook({ profileDir, pluginEntry });
441
+ const profiles = discoverDshProfiles(profilesDir);
442
+ const mounted = [];
443
+ for (const dir of profiles) {
444
+ if (mountDshHook({ profileDir: dir, pluginEntry })) mounted.push(path.basename(dir));
445
+ }
446
+ return { scanned: profiles.length, mounted };
447
+ }
448
+
449
+ // 移除 dsh-hook 挂载(uninstall),同样支持两种模式:
450
+ // - 显式传入 profileDir:仅清理该 profile,返回 boolean
451
+ // - 未传:清理所有发现的 profile,任一改写即返回 true
452
+ export function unconfigureDsh({ profileDir, profilesDir = DSH_PROFILES_DIR } = {}) {
453
+ const dirs = profileDir ? [profileDir] : discoverDshProfiles(profilesDir);
454
+ let changed = false;
455
+ for (const dir of dirs) {
456
+ const patchPath = path.join(dir, 'cordis.patch.yml');
457
+ if (!fs.existsSync(patchPath)) continue;
458
+ const content = fs.readFileSync(patchPath, 'utf-8');
459
+ const stripped = stripDshHookBlocks(content).replace(/\n{3,}/g, '\n\n').trim();
460
+ if (stripped === content.trim()) continue; // 该 profile 无 a4phone dsh-hook 挂载
461
+ fs.writeFileSync(patchPath, stripped ? stripped + '\n' : '');
462
+ changed = true;
463
+ }
464
+ return changed;
465
+ }
466
+
467
+ // setup 主流程
468
+ export async function runSetup({ generateQR }) {
469
+ const config = loadConfig();
470
+ if (!config.topic) {
471
+ config.topic = generateTopic();
472
+ config.server = config.server || 'https://ntfy.sh';
473
+ }
474
+ saveConfig(config);
475
+
476
+ const claudeConfigured = registerHooks(SETTINGS_PATH, hookCommand());
477
+ const codexConfigured = configureCodex();
478
+ const zcodeConfigured = configureZcode();
479
+ const dshResult = configureDsh();
480
+
481
+ // ZCode 远程续聊:把默认模型配置写入 ~/.zcode/cli/config.json
482
+ // (headless 续聊必需;每次续聊前还会按会话实际模型自动同步)
483
+ let zcodeModelStatus = '未配置(未检测到 ZCode 模型注册表)';
484
+ try {
485
+ const { ensureZcodeModelConfig } = await import('./zcode.mjs');
486
+ const synced = ensureZcodeModelConfig();
487
+ if (synced.ok) zcodeModelStatus = '已写入默认模型配置(续聊时按会话实际模型自动同步)';
488
+ else zcodeModelStatus = `未配置:${synced.reason}`;
489
+ } catch {}
490
+
491
+ const subscribeUrl = `${config.server}/${config.topic}`;
492
+ const ntfyUrl = `ntfy://${new URL(config.server).host}/${config.topic}`;
493
+
494
+ process.stdout.write('a4phone 安装完成\n\n');
495
+ process.stdout.write(`话题名称: ${config.topic}\n`);
496
+ process.stdout.write(`订阅地址: ${subscribeUrl}\n\n`);
497
+
498
+ if (generateQR) {
499
+ process.stdout.write('在 ntfy App 中扫码订阅:\n\n');
500
+ generateQR(ntfyUrl, { small: true }, (qr) => process.stdout.write(qr + '\n'));
501
+ }
502
+
503
+ process.stdout.write('\n在 ntfy App 添加订阅,输入话题名称或扫描上方二维码。\n');
504
+ process.stdout.write(`Claude Code 配置:${claudeConfigured ? '已自动写入 ~/.claude/settings.json' : '已存在,跳过'}\n`);
505
+ process.stdout.write(`Codex 配置:${codexConfigured ? '已自动写入 ~/.codex/config.toml' : '已存在,跳过'}\n`);
506
+ process.stdout.write(`ZCode 配置:${zcodeConfigured ? '已自动写入 ~/.zcode/cli/config.json' : '已存在,跳过'}\n`);
507
+ process.stdout.write(`ZCode 续聊模型:${zcodeModelStatus}\n`);
508
+ let dshStatus;
509
+ if (!fs.existsSync(DSH_PROFILES_DIR)) {
510
+ dshStatus = '未检测到 DSH 环境(~/.dsh/profiles),跳过';
511
+ } else if (!dshResult.scanned) {
512
+ dshStatus = '~/.dsh/profiles 下暂无 profile,跳过(新装 profile 后守护进程会自动补挂)';
513
+ } else {
514
+ const names = discoverDshProfiles().map((p) => path.basename(p));
515
+ dshStatus = dshResult.mounted.length
516
+ ? `已自动写入 cordis.patch.yml:${dshResult.mounted.join('、')}(共 ${names.length} 个 profile:${names.join('、')})`
517
+ : `已存在,跳过(共 ${names.length} 个 profile:${names.join('、')})`;
518
+ }
519
+ process.stdout.write(`DSH 配置:${dshStatus}\n`);
520
+ process.stdout.write('模式切换:a4p out(外出/手机优先) / a4p home(终端优先) / a4p status\n');
521
+ process.stdout.write('重启 Claude Code / Codex / ZCode 会话后 Hook 生效(DSH 插件热生效,无需重启)。\n');
522
+
523
+ // 默认启动续聊守护进程 + 注册开机自启(失败不阻塞 setup,给出提示)
524
+ try {
525
+ const { startDaemon } = await import('./daemon.mjs');
526
+ await startDaemon();
527
+ } catch (error) {
528
+ process.stdout.write(`续聊守护进程启动失败:${String(error?.message ?? error)}\n`);
529
+ }
530
+ try {
531
+ const { enableAutostart } = await import('./autostart.mjs');
532
+ const autostart = enableAutostart();
533
+ process.stdout.write(autostart.ok
534
+ ? '开机自启:已注册(登录时自动运行续聊守护进程,可用 a4p autostart --off 关闭)\n'
535
+ : `开机自启:${autostart.reason}\n`);
536
+ } catch (error) {
537
+ process.stdout.write(`开机自启注册失败:${String(error?.message ?? error)}\n`);
538
+ }
539
+ return config;
540
+ }