a4phone 1.3.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,7 +11,7 @@ Claude Code / Codex / DSH(DeepSeek Harness)远程手机交互包。通过 [n
11
11
  - **远程续聊**:守护进程监听主话题,手机发文字即可与当前会话交流,形成完整远程对话闭环(Claude Code / Codex / DSH)
12
12
  - **DSH 远程续聊**:手机发文字直接注入 DSH 正在运行的会话(`agent.followup`),手机消息与 AI 回复**实时出现在桌面端会话里**,无需另起进程、无会话锁冲突
13
13
  - **后台守护进程**:`a4p listen` 无窗口后台运行,日志写入文件
14
- - **自动更新提醒**:守护进程周期检查 npm 新版本并**推送手机提醒**;其他命令在终端提示(默认开启,可在配置关闭)
14
+ - **自动更新提醒**:守护进程周期检查 npm 新版本并**推送手机提醒**;其他命令发现新版本时终端提示 + 手机推送(默认开启,可在配置关闭)
15
15
  - **双模式**:外出模式(手机优先)/ 终端优先模式,一键切换
16
16
  - **零第三方依赖**:仅依赖 ntfy.sh 免费服务,无 Google 服务依赖
17
17
 
@@ -24,13 +24,14 @@ npm install -g a4phone
24
24
  ## 使用
25
25
 
26
26
  ```bash
27
- a4p setup # 安装引导:生成话题、注册 Hook、显示二维码
27
+ a4p setup # 安装引导:生成话题、注册 Hook、启动守护进程、注册开机自启、显示二维码
28
28
  a4p out # 外出模式(手机优先)
29
29
  a4p home # 终端优先模式(默认)
30
30
  a4p status # 查看当前模式
31
31
  a4p listen # 后台运行续聊守护进程(无窗口)
32
32
  a4p listen --stop # 停止守护进程
33
33
  a4p listen --status # 查看守护进程状态
34
+ a4p autostart # 查看开机自启状态(--on 开启 / --off 关闭)
34
35
  a4p resume # 手动续聊最近会话:a4p resume 要追加的内容
35
36
  a4p last # 查看最近会话记录
36
37
  a4p test # 发送测试通知
@@ -46,10 +47,14 @@ a4p help # 显示帮助
46
47
  1. 生成独一无二的话题名称(如 `a4p-xxxx`),写入 `~/.a4phone/config.json`
47
48
  2. 在 `~/.claude/settings.json` 注册三个 Hook(Stop / AskUserQuestion / PermissionRequest),并同时写入 `~/.codex/config.toml` 的 Codex Hook(见下文 [Codex](#codex) 一节)
48
49
  3. 检测到 DSH 环境时,把内置 `dsh-hook` 插件挂载到 `~/.dsh/profiles/web/cordis.patch.yml`(见下文 [DSH](#dshdeepseek-harness) 一节)
49
- 4. 在终端显示二维码
50
+ 4. **默认启动续聊守护进程**(`a4p listen` 后台运行)
51
+ 5. **默认注册开机自启**(Windows 启动文件夹写入隐藏 VBS,登录时自动运行守护进程)
52
+ 6. 在终端显示二维码
50
53
 
51
54
  然后用手机 ntfy App 扫描二维码或输入话题名称订阅,重启 Claude Code / Codex 会话后 Hook 生效。
52
55
 
56
+ > 开机自启无需管理员权限(当前用户启动文件夹),可用 `a4p autostart --off` 关闭、`--on` 重新开启;`a4p uninstall` 会一并移除。WSL/Linux 暂不支持自动注册,可手动用 tmux / systemd 常驻。
57
+
53
58
  ### 模式切换
54
59
 
55
60
  ```bash
@@ -194,11 +199,11 @@ AI助手触发事件 → a4p hook → ntfy.sh 推送手机 → 手机点选/文
194
199
  - DSH 支持任务完成通知 / 提问作答 / 权限审批 / 远程续聊(经内置 `dsh-hook` 插件)
195
200
  - 续聊期间守护进程会自动临时切换为外出模式,结束后恢复原模式
196
201
  - Claude Code 会话同一时间只能被一个进程占用,`--resume` 续聊前请先结束终端里仍在运行的原会话;Codex 会话被占用时 a4phone 会自动 fork 新线程续聊(复制会话为新线程 ID,原窗口不受影响,手机对话在 fork 上继续)
197
- - 续聊守护进程需后台常驻:Windows 用 `a4p listen` 或计划任务,WSL/Linux 可用 tmux 或 systemd
202
+ - 续聊守护进程默认随 `a4p setup` 启动并注册**开机自启**(Windows 登录时自动运行);也可手动 `a4p listen`,WSL/Linux 可用 tmux 或 systemd
198
203
  - **ntfy.sh 免费托管服务有发布速率/消息保留限制**:短时间高频测试可能触发 `limited` 提示,建议降低推送频率(续聊结果已去重推送,不再重复通知)
199
204
  - ntfy.sh 公共话题可被知晓话题名的人读写,重要场景建议自建 ntfy 服务或使用访问令牌
200
205
  - ntfy.sh 为国外服务,国内网络下长连接可能不稳定
201
- - **自动更新提醒**:默认开启(`checkUpdates: true`)。守护进程(`a4p listen`)启动时及每 `updateIntervalHours` 小时(默认 6)检查一次 npm registry(npmmirror 优先、官方兜底),发现新版本推送手机提醒;其他命令(`a4p status`/`a4p resume` 等)在终端提示。同一新版本只提醒一次,查询失败静默跳过,不影响正常功能;可在 `~/.a4phone/config.json` 设 `checkUpdates: false` 关闭
206
+ - **自动更新提醒**:默认开启(`checkUpdates: true`)。守护进程(`a4p listen`)启动时及每 `updateIntervalHours` 小时(默认 6)检查一次 npm registry(npmmirror 优先、官方兜底),发现新版本**推送手机提醒**;其他命令(`a4p status`/`a4p resume` 等)发现新版本时**终端提示 + 手机推送**(与守护进程共用去重缓存,同一版本只提醒一次)。查询失败静默跳过,不影响正常功能;可在 `~/.a4phone/config.json` 设 `checkUpdates: false` 关闭
202
207
  - 配置存储于 `~/.a4phone/config.json`,最近会话存储于 `~/.a4phone/last.json`,模式存储于 `~/.a4phone/mode.json`,守护进程信息存储于 `~/.a4phone/daemon.json`,日志写入 `~/.a4phone/daemon.log`;DSH Hook 日志写入 `~/.a4phone/dsh-logs/`,DSH 续聊队列位于 `~/.a4phone/dsh-jobs/`,心跳位于 `~/.a4phone/dsh-heartbeat.json`,更新检查缓存位于 `~/.a4phone/update-cache.json`
203
208
 
204
209
  ## 开发
package/bin/a4p.mjs CHANGED
@@ -31,6 +31,7 @@ function showHelp() {
31
31
  console.log(' a4p listen 后台运行续聊守护进程(无窗口)');
32
32
  console.log(' a4p listen --stop 停止守护进程');
33
33
  console.log(' a4p listen --status 查看守护进程状态');
34
+ console.log(' a4p autostart 开机自启状态(--on 开启 / --off 关闭)');
34
35
  console.log(' a4p resume 手动续聊最近会话:a4p resume 要追加的内容');
35
36
  console.log(' a4p last 查看最近会话记录');
36
37
  console.log(' a4p test 发送测试通知');
@@ -45,14 +46,28 @@ const sub = process.argv[3];
45
46
  // ── 版本更新检查(默认开启)───────────────────────────────────────────
46
47
  // 守护进程(listen --daemon-child)自己有周期检查 + 手机推送,这里跳过;
47
48
  // hook 是 AI 每次事件都调用的热路径,跳过避免延迟;version/help 是脚本/查询场景跳过。
48
- // 其余命令在终端提示新版本;限频与去重由 update-check 缓存保证(未到期零开销)。
49
+ // 其余命令:发现新版本时终端提示 + 手机推送(共用去重缓存,同一版本只提醒一次)。
49
50
  if (cmd && !['hook', '--version', '-v', 'version', 'help', '--help', '-h'].includes(cmd)
50
51
  && !(cmd === 'listen' && sub === '--daemon-child')) {
51
52
  const { checkForUpdate, makeConsoleNotifier } = await import('../src/update-check.mjs');
53
+ const { sendNotification } = await import('../src/ntfy.mjs');
52
54
  const { loadConfig } = await import('../src/config.mjs');
55
+ const cfg = loadConfig();
56
+ const notifier = makeConsoleNotifier();
53
57
  checkForUpdate({
54
- config: loadConfig(),
55
- notify: makeConsoleNotifier(),
58
+ config: cfg,
59
+ notify: async (latest) => {
60
+ await notifier(latest);
61
+ // 终端提示之外再推送手机,确保用户不会遗落更新消息
62
+ if (cfg.topic) {
63
+ const ok = await sendNotification({
64
+ ...cfg,
65
+ title: 'a4phone',
66
+ message: `检测到新版本 ${latest}\n\n请运行:npm install -g a4phone 升级`,
67
+ });
68
+ if (!ok) throw new Error('手机推送失败');
69
+ }
70
+ },
56
71
  }).catch(() => {});
57
72
  }
58
73
 
@@ -89,8 +104,10 @@ if (cmd === '--version' || cmd === '-v' || cmd === 'version') {
89
104
  } else if (cmd === 'uninstall') {
90
105
  const { unregisterHooks, unconfigureCodex, unconfigureDsh } = await import('../src/setup.mjs');
91
106
  const { stopDaemon } = await import('../src/daemon.mjs');
107
+ const { disableAutostart } = await import('../src/autostart.mjs');
92
108
  // 先停守护进程:Windows 上守护进程持有 daemon.log 句柄,直接删目录会失败且异常被静默吞掉
93
109
  await stopDaemon();
110
+ disableAutostart();
94
111
  unregisterHooks(SETTINGS_PATH);
95
112
  unconfigureCodex();
96
113
  unconfigureDsh();
@@ -99,7 +116,21 @@ if (cmd === '--version' || cmd === '-v' || cmd === 'version') {
99
116
  for (const f of ['.a4phone.json', '.a4phone-mode.json', '.a4phone-last.json', '.a4phone-daemon.json', '.a4phone-daemon.log']) {
100
117
  try { fs.unlinkSync(path.join(os.homedir(), f)); } catch {}
101
118
  }
102
- console.log('a4phone 已卸载:Claude Code / Codex / DSH Hook 已移除,配置已删除。');
119
+ console.log('a4phone 已卸载:Claude Code / Codex / DSH Hook 已移除,开机自启与配置已删除。');
120
+ } else if (cmd === 'autostart') {
121
+ const { enableAutostart, disableAutostart, isAutostartEnabled } = await import('../src/autostart.mjs');
122
+ const mode = process.argv[3];
123
+ if (mode === '--off') {
124
+ const r = disableAutostart();
125
+ console.log(r.ok ? '开机自启已关闭。' : `关闭失败:${r.reason}`);
126
+ } else if (mode === '--on') {
127
+ const r = enableAutostart();
128
+ console.log(r.ok ? '开机自启已开启(登录时自动运行续聊守护进程)。' : `开启失败:${r.reason}`);
129
+ } else {
130
+ console.log(isAutostartEnabled()
131
+ ? '开机自启:已开启(登录时自动运行续聊守护进程)'
132
+ : '开机自启:未开启(运行 a4p autostart --on 开启)');
133
+ }
103
134
  } else if (cmd === 'listen') {
104
135
  const sub = process.argv[3];
105
136
  if (sub === '--stop') {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "a4phone",
3
- "version": "1.3.0",
3
+ "version": "1.4.1",
4
4
  "description": "Claude Code / Codex / DSH 远程手机交互:任务完成通知(含 AI 最后输出)、提问/权限请求手机点选或文字作答、远程续聊(ntfy.sh,含 DSH 会话续聊)",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,83 @@
1
+ // autostart.mjs — 开机自启管理(Windows)
2
+ //
3
+ // 原理:在 Windows 启动文件夹(%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup)
4
+ // 写入一个隐藏启动的 VBS 脚本,登录时自动运行 `a4p listen`(守护进程本身无窗口、
5
+ // 后台运行)。不依赖注册表,无管理员权限要求,删除文件即关闭。
6
+ //
7
+ // 非 Windows 平台(WSL/Linux)暂不支持自动注册,返回明确提示(可手动用 tmux/systemd)。
8
+
9
+ import fs from 'fs';
10
+ import os from 'os';
11
+ import path from 'path';
12
+ import { fileURLToPath } from 'url';
13
+ import { A4P_DIR, ensureDir } from './paths.mjs';
14
+
15
+ /** 本包 bin 目录下 a4p 入口的绝对路径 */
16
+ function binEntryPath() {
17
+ return path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'bin', 'a4p.mjs');
18
+ }
19
+
20
+ /** Windows 启动文件夹路径(当前用户) */
21
+ export function startupDir(platform = process.platform) {
22
+ if (platform !== 'win32') return null;
23
+ return path.join(os.homedir(), 'AppData', 'Roaming', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup');
24
+ }
25
+
26
+ export function startupVbsPath(platform = process.platform) {
27
+ const dir = startupDir(platform);
28
+ return dir ? path.join(dir, 'a4phone.vbs') : null;
29
+ }
30
+
31
+ /**
32
+ * 生成 VBS 内容:隐藏窗口运行 `node <a4p 入口> listen`(绝对路径,不依赖 PATH)。
33
+ * 纯函数便于测试。
34
+ * 注意:shell.Run 的完整命令行必须是一个整体字符串,内嵌双引号需成对转义("")。
35
+ * @param {string} nodePath Node 可执行文件绝对路径
36
+ * @param {string} binPath a4p.mjs 绝对路径
37
+ */
38
+ export function buildVbsContent(nodePath, binPath) {
39
+ const command = `"${nodePath}" "${binPath}" listen`;
40
+ const escaped = command.replace(/"/g, '""');
41
+ return [
42
+ 'Set shell = CreateObject("WScript.Shell")',
43
+ `shell.Run "${escaped}", 0, False`,
44
+ '',
45
+ ].join('\r\n');
46
+ }
47
+
48
+ /** 开机自启是否已注册(启动文件夹 VBS 存在) */
49
+ export function isAutostartEnabled(platform = process.platform, vbsPath = startupVbsPath(platform)) {
50
+ if (platform !== 'win32' || !vbsPath) return false;
51
+ try {
52
+ return fs.existsSync(vbsPath);
53
+ } catch {
54
+ return false;
55
+ }
56
+ }
57
+
58
+ /** 开启开机自启:写入启动文件夹 VBS。返回 { ok, reason? } */
59
+ export function enableAutostart({ platform = process.platform, nodePath = process.execPath, binPath = binEntryPath(), vbsPath = startupVbsPath(platform) } = {}) {
60
+ if (platform !== 'win32') {
61
+ return { ok: false, reason: '非 Windows 平台暂不支持自动注册,可用 tmux / systemd 手动常驻。' };
62
+ }
63
+ if (!vbsPath) return { ok: false, reason: '无法确定启动文件夹位置。' };
64
+ try {
65
+ ensureDir(); // 确保 ~/.a4phone 存在(VBS 里用不到,但保持目录一致)
66
+ fs.writeFileSync(vbsPath, buildVbsContent(nodePath, binPath));
67
+ return { ok: true };
68
+ } catch (error) {
69
+ return { ok: false, reason: `写入启动项失败:${error instanceof Error ? error.message : String(error)}` };
70
+ }
71
+ }
72
+
73
+ /** 关闭开机自启:删除启动文件夹 VBS。返回 { ok, reason? } */
74
+ export function disableAutostart({ platform = process.platform, vbsPath = startupVbsPath(platform) } = {}) {
75
+ if (platform !== 'win32') return { ok: false, reason: '非 Windows 平台。' };
76
+ if (!vbsPath) return { ok: false };
77
+ try {
78
+ if (fs.existsSync(vbsPath)) fs.unlinkSync(vbsPath);
79
+ return { ok: true };
80
+ } catch (error) {
81
+ return { ok: false, reason: `移除启动项失败:${error instanceof Error ? error.message : String(error)}` };
82
+ }
83
+ }
package/src/listen.mjs CHANGED
@@ -12,6 +12,7 @@ import { loadConfig, loadLastSession } from './config.mjs';
12
12
  import { runResume } from './resume.mjs';
13
13
  import { createBatcher } from './batcher.mjs';
14
14
  import { checkForUpdate, makePhoneNotifier } from './update-check.mjs';
15
+ import { parseNtfyMessage } from './ntfy.mjs';
15
16
  import { PENDING_PATH, ensureDir } from './paths.mjs';
16
17
 
17
18
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -150,12 +151,8 @@ export async function runListen({ onLog = (s) => console.log(s) } = {}) {
150
151
  if (event.time) lastTime = Math.max(lastTime, Number(event.time));
151
152
  // 有 title 的是系统推送通知(Claude Code 回复),不是手机用户消息,跳过
152
153
  if (event.title) continue;
153
- let msg;
154
- try {
155
- msg = JSON.parse(event.message); // 系统推送为 JSON,忽略
156
- } catch {
157
- msg = event.message; // 纯文本:手机发来的续聊内容
158
- }
154
+ // 系统推送为 JSON 对象则忽略;纯文本/JSON 原始值(如手机发的单数字"3")作为续聊内容
155
+ const msg = parseNtfyMessage(event.message);
159
156
  if (typeof msg === 'string' && msg.trim()) {
160
157
  batcher.submit(msg.trim(), event.time ? Number(event.time) : null);
161
158
  persistSnapshot();
package/src/ntfy.mjs CHANGED
@@ -1,4 +1,23 @@
1
1
  // ntfy.sh 推送与响应订阅
2
+
3
+ /**
4
+ * 解析 ntfy 消息体:
5
+ * - JSON 对象(如按钮回执 { requestId, answer })→ 原样返回对象
6
+ * - JSON 原始值("4" / "true" / "null" 等合法 JSON 字面量)→ 按文本返回
7
+ * (修复:JSON.parse('4') 会返回数字 4,导致纯数字自由文本被误判为 JSON 对象而丢失)
8
+ * - 非 JSON 文本 → 原样返回
9
+ * @param {string} raw ntfy 事件的 message 字段
10
+ * @returns {object|string}
11
+ */
12
+ export function parseNtfyMessage(raw) {
13
+ try {
14
+ const parsed = JSON.parse(raw);
15
+ return parsed !== null && typeof parsed === 'object' ? parsed : raw;
16
+ } catch {
17
+ return raw;
18
+ }
19
+ }
20
+
2
21
  export async function sendNotification({ server, topic, title, message, actions }) {
3
22
  try {
4
23
  const res = await fetch(server, {
@@ -37,12 +56,8 @@ export async function waitForResponse({ server, topic, requestId, timeout }) {
37
56
  // ntfy /json 连接建立后会先发 open 事件、之后周期发 keepalive,
38
57
  // 这些事件没有 message 字段,跳过以免被误判为“手机自由文本”立即返回。
39
58
  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
- }
59
+ const parsed = parseNtfyMessage(event.message);
60
+ const msg = typeof parsed === 'object' ? parsed : { answer: parsed };
46
61
  // action 回执:requestId 必须匹配;自由文本:无 requestId 且有 answer 才接受
47
62
  if (msg.requestId === requestId || (msg.requestId === undefined && msg.answer)) {
48
63
  clearTimeout(timer);
package/src/setup.mjs CHANGED
@@ -383,5 +383,22 @@ export async function runSetup({ generateQR }) {
383
383
  process.stdout.write(`DSH 配置:${dshStatus}\n`);
384
384
  process.stdout.write('模式切换:a4p out(外出/手机优先) / a4p home(终端优先) / a4p status\n');
385
385
  process.stdout.write('重启 Claude Code / Codex 会话后 Hook 生效(DSH 插件热生效,无需重启)。\n');
386
+
387
+ // 默认启动续聊守护进程 + 注册开机自启(失败不阻塞 setup,给出提示)
388
+ try {
389
+ const { startDaemon } = await import('./daemon.mjs');
390
+ await startDaemon();
391
+ } catch (error) {
392
+ process.stdout.write(`续聊守护进程启动失败:${String(error?.message ?? error)}\n`);
393
+ }
394
+ try {
395
+ const { enableAutostart } = await import('./autostart.mjs');
396
+ const autostart = enableAutostart();
397
+ process.stdout.write(autostart.ok
398
+ ? '开机自启:已注册(登录时自动运行续聊守护进程,可用 a4p autostart --off 关闭)\n'
399
+ : `开机自启:${autostart.reason}\n`);
400
+ } catch (error) {
401
+ process.stdout.write(`开机自启注册失败:${String(error?.message ?? error)}\n`);
402
+ }
386
403
  return config;
387
404
  }