a4phone 1.2.1 → 1.4.0

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,6 +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
15
  - **双模式**:外出模式(手机优先)/ 终端优先模式,一键切换
15
16
  - **零第三方依赖**:仅依赖 ntfy.sh 免费服务,无 Google 服务依赖
16
17
 
@@ -23,13 +24,14 @@ npm install -g a4phone
23
24
  ## 使用
24
25
 
25
26
  ```bash
26
- a4p setup # 安装引导:生成话题、注册 Hook、显示二维码
27
+ a4p setup # 安装引导:生成话题、注册 Hook、启动守护进程、注册开机自启、显示二维码
27
28
  a4p out # 外出模式(手机优先)
28
29
  a4p home # 终端优先模式(默认)
29
30
  a4p status # 查看当前模式
30
31
  a4p listen # 后台运行续聊守护进程(无窗口)
31
32
  a4p listen --stop # 停止守护进程
32
33
  a4p listen --status # 查看守护进程状态
34
+ a4p autostart # 查看开机自启状态(--on 开启 / --off 关闭)
33
35
  a4p resume # 手动续聊最近会话:a4p resume 要追加的内容
34
36
  a4p last # 查看最近会话记录
35
37
  a4p test # 发送测试通知
@@ -45,10 +47,14 @@ a4p help # 显示帮助
45
47
  1. 生成独一无二的话题名称(如 `a4p-xxxx`),写入 `~/.a4phone/config.json`
46
48
  2. 在 `~/.claude/settings.json` 注册三个 Hook(Stop / AskUserQuestion / PermissionRequest),并同时写入 `~/.codex/config.toml` 的 Codex Hook(见下文 [Codex](#codex) 一节)
47
49
  3. 检测到 DSH 环境时,把内置 `dsh-hook` 插件挂载到 `~/.dsh/profiles/web/cordis.patch.yml`(见下文 [DSH](#dshdeepseek-harness) 一节)
48
- 4. 在终端显示二维码
50
+ 4. **默认启动续聊守护进程**(`a4p listen` 后台运行)
51
+ 5. **默认注册开机自启**(Windows 启动文件夹写入隐藏 VBS,登录时自动运行守护进程)
52
+ 6. 在终端显示二维码
49
53
 
50
54
  然后用手机 ntfy App 扫描二维码或输入话题名称订阅,重启 Claude Code / Codex 会话后 Hook 生效。
51
55
 
56
+ > 开机自启无需管理员权限(当前用户启动文件夹),可用 `a4p autostart --off` 关闭、`--on` 重新开启;`a4p uninstall` 会一并移除。WSL/Linux 暂不支持自动注册,可手动用 tmux / systemd 常驻。
57
+
52
58
  ### 模式切换
53
59
 
54
60
  ```bash
@@ -193,11 +199,12 @@ AI助手触发事件 → a4p hook → ntfy.sh 推送手机 → 手机点选/文
193
199
  - DSH 支持任务完成通知 / 提问作答 / 权限审批 / 远程续聊(经内置 `dsh-hook` 插件)
194
200
  - 续聊期间守护进程会自动临时切换为外出模式,结束后恢复原模式
195
201
  - Claude Code 会话同一时间只能被一个进程占用,`--resume` 续聊前请先结束终端里仍在运行的原会话;Codex 会话被占用时 a4phone 会自动 fork 新线程续聊(复制会话为新线程 ID,原窗口不受影响,手机对话在 fork 上继续)
196
- - 续聊守护进程需后台常驻:Windows 用 `a4p listen` 或计划任务,WSL/Linux 可用 tmux 或 systemd
202
+ - 续聊守护进程默认随 `a4p setup` 启动并注册**开机自启**(Windows 登录时自动运行);也可手动 `a4p listen`,WSL/Linux 可用 tmux 或 systemd
197
203
  - **ntfy.sh 免费托管服务有发布速率/消息保留限制**:短时间高频测试可能触发 `limited` 提示,建议降低推送频率(续聊结果已去重推送,不再重复通知)
198
204
  - ntfy.sh 公共话题可被知晓话题名的人读写,重要场景建议自建 ntfy 服务或使用访问令牌
199
205
  - ntfy.sh 为国外服务,国内网络下长连接可能不稳定
200
- - 配置存储于 `~/.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`
206
+ - **自动更新提醒**:默认开启(`checkUpdates: true`)。守护进程(`a4p listen`)启动时及每 `updateIntervalHours` 小时(默认 6)检查一次 npm registry(npmmirror 优先、官方兜底),发现新版本**推送手机提醒**;其他命令(`a4p status`/`a4p resume` 等)发现新版本时**终端提示 + 手机推送**(与守护进程共用去重缓存,同一版本只提醒一次)。查询失败静默跳过,不影响正常功能;可在 `~/.a4phone/config.json` 设 `checkUpdates: false` 关闭
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`
201
208
 
202
209
  ## 开发
203
210
 
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 发送测试通知');
@@ -40,6 +41,35 @@ function showHelp() {
40
41
  }
41
42
 
42
43
  const cmd = process.argv[2];
44
+ const sub = process.argv[3];
45
+
46
+ // ── 版本更新检查(默认开启)───────────────────────────────────────────
47
+ // 守护进程(listen --daemon-child)自己有周期检查 + 手机推送,这里跳过;
48
+ // hook 是 AI 每次事件都调用的热路径,跳过避免延迟;version/help 是脚本/查询场景跳过。
49
+ // 其余命令:发现新版本时终端提示 + 手机推送(共用去重缓存,同一版本只提醒一次)。
50
+ if (cmd && !['hook', '--version', '-v', 'version', 'help', '--help', '-h'].includes(cmd)
51
+ && !(cmd === 'listen' && sub === '--daemon-child')) {
52
+ const { checkForUpdate, makeConsoleNotifier } = await import('../src/update-check.mjs');
53
+ const { sendNotification } = await import('../src/ntfy.mjs');
54
+ const { loadConfig } = await import('../src/config.mjs');
55
+ const cfg = loadConfig();
56
+ const notifier = makeConsoleNotifier();
57
+ checkForUpdate({
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
+ },
71
+ }).catch(() => {});
72
+ }
43
73
 
44
74
  if (cmd === '--version' || cmd === '-v' || cmd === 'version') {
45
75
  const pkg = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf-8'));
@@ -74,8 +104,10 @@ if (cmd === '--version' || cmd === '-v' || cmd === 'version') {
74
104
  } else if (cmd === 'uninstall') {
75
105
  const { unregisterHooks, unconfigureCodex, unconfigureDsh } = await import('../src/setup.mjs');
76
106
  const { stopDaemon } = await import('../src/daemon.mjs');
107
+ const { disableAutostart } = await import('../src/autostart.mjs');
77
108
  // 先停守护进程:Windows 上守护进程持有 daemon.log 句柄,直接删目录会失败且异常被静默吞掉
78
109
  await stopDaemon();
110
+ disableAutostart();
79
111
  unregisterHooks(SETTINGS_PATH);
80
112
  unconfigureCodex();
81
113
  unconfigureDsh();
@@ -84,7 +116,21 @@ if (cmd === '--version' || cmd === '-v' || cmd === 'version') {
84
116
  for (const f of ['.a4phone.json', '.a4phone-mode.json', '.a4phone-last.json', '.a4phone-daemon.json', '.a4phone-daemon.log']) {
85
117
  try { fs.unlinkSync(path.join(os.homedir(), f)); } catch {}
86
118
  }
87
- 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
+ }
88
134
  } else if (cmd === 'listen') {
89
135
  const sub = process.argv[3];
90
136
  if (sub === '--stop') {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "a4phone",
3
- "version": "1.2.1",
3
+ "version": "1.4.0",
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/config.mjs CHANGED
@@ -15,9 +15,11 @@ export function loadConfig() {
15
15
  timeout: cfg.timeout ?? 60,
16
16
  planTimeout: cfg.planTimeout ?? 300,
17
17
  resumeTimeout: cfg.resumeTimeout ?? 1800, // 续聊超时(秒),默认 30 分钟
18
+ checkUpdates: cfg.checkUpdates ?? true, // 版本更新检查(守护进程推手机 / 命令终端提示)
19
+ updateIntervalHours: cfg.updateIntervalHours ?? 6, // 检查间隔(小时)
18
20
  };
19
21
  } catch {
20
- return { topic: '', server: 'https://ntfy.sh', timeout: 60, planTimeout: 300, resumeTimeout: 1800 };
22
+ return { topic: '', server: 'https://ntfy.sh', timeout: 60, planTimeout: 300, resumeTimeout: 1800, checkUpdates: true, updateIntervalHours: 6 };
21
23
  }
22
24
  }
23
25
 
package/src/listen.mjs CHANGED
@@ -11,6 +11,7 @@ import path from 'path';
11
11
  import { loadConfig, loadLastSession } from './config.mjs';
12
12
  import { runResume } from './resume.mjs';
13
13
  import { createBatcher } from './batcher.mjs';
14
+ import { checkForUpdate, makePhoneNotifier } from './update-check.mjs';
14
15
  import { PENDING_PATH, ensureDir } from './paths.mjs';
15
16
 
16
17
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -105,6 +106,21 @@ export async function runListen({ onLog = (s) => console.log(s) } = {}) {
105
106
  }
106
107
  } catch {}
107
108
 
109
+ // ── 版本更新检查:启动时 + 周期性(默认 6 小时),发现新版本推送手机提醒 ──
110
+ // 限频与去重由 update-check 的缓存保证(同一新版本只提醒一次,未到期不访问网络)
111
+ const checkUpdate = async () => {
112
+ try {
113
+ await checkForUpdate({
114
+ config,
115
+ notify: makePhoneNotifier(config, { onLog }),
116
+ onLog,
117
+ });
118
+ } catch {}
119
+ };
120
+ await checkUpdate();
121
+ const intervalMs = (config.updateIntervalHours ?? 6) * 3600 * 1000;
122
+ setInterval(() => { checkUpdate().catch(() => {}); }, intervalMs).unref();
123
+
108
124
  while (true) {
109
125
  try {
110
126
  const since = `since=${lastTime + 1}`; // 从最后收到的消息之后继续
package/src/paths.mjs CHANGED
@@ -23,6 +23,8 @@ export const DSH_HEARTBEAT = path.join(A4P_DIR, 'dsh-heartbeat.json');
23
23
  // 续聊积压批次持久化:长轮次期间到达的消息写入该文件,守护进程重启后恢复,
24
24
  // 避免积压消息在重启时丢失
25
25
  export const PENDING_PATH = path.join(A4P_DIR, 'pending-batch.json');
26
+ // 版本更新检查缓存:{ lastCheck, knownLatest },用于限频与"同一新版本只提醒一次"
27
+ export const UPDATE_CACHE_PATH = path.join(A4P_DIR, 'update-cache.json');
26
28
 
27
29
  // 旧版散落在家目录的单文件 → 迁移到 ~/.a4phone/(新路径不存在时才移动)
28
30
  const LEGACY_PATHS = {
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
  }
@@ -0,0 +1,169 @@
1
+ // update-check.mjs — a4phone 版本更新检查
2
+ //
3
+ // 查询 npm registry 最新版本,与本地版本比对,发现新版本时提醒用户:
4
+ // - 守护进程(a4p listen):经 ntfy 推送手机提醒
5
+ // - 其他命令(a4p status/setup/resume 等):终端打印提示
6
+ // - 缓存(~/.a4phone/update-cache.json)保证同一新版本只提醒一次 + 限频
7
+ // (默认 6 小时查一次,避免每次命令都访问网络)
8
+ // - registry 查询失败静默跳过(国内网络可能连不上,不影响正常功能)
9
+ //
10
+ // 纯函数(版本比对、缓存、到期判断)便于单元测试。
11
+ import fs from 'fs';
12
+ import { UPDATE_CACHE_PATH, ensureDir } from './paths.mjs';
13
+ import { sendNotification } from './ntfy.mjs';
14
+
15
+ /** 默认检查间隔(小时):守护进程周期检查与命令级限频共用 */
16
+ export const DEFAULT_INTERVAL_HOURS = 6;
17
+
18
+ /** 查询源:国内镜像优先(与用户 npm 配置一致,国内网络更稳),官方兜底 */
19
+ const REGISTRIES = [
20
+ 'https://registry.npmmirror.com',
21
+ 'https://registry.npmjs.org',
22
+ ];
23
+
24
+ /** 读取本地包版本号;读不到返回 '0.0.0' */
25
+ export function getLocalVersion() {
26
+ try {
27
+ const pkg = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf-8'));
28
+ return typeof pkg.version === 'string' ? pkg.version : '0.0.0';
29
+ } catch {
30
+ return '0.0.0';
31
+ }
32
+ }
33
+
34
+ /**
35
+ * 简单 semver 数值比较(无第三方依赖):
36
+ * compareVersions('1.2.10', '1.2.9') > 0
37
+ * @param {string} a
38
+ * @param {string} b
39
+ * @returns {number} 1 | 0 | -1
40
+ */
41
+ export function compareVersions(a, b) {
42
+ const pa = String(a).split('.').map((n) => Number(n) || 0);
43
+ const pb = String(b).split('.').map((n) => Number(n) || 0);
44
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
45
+ const da = pa[i] || 0;
46
+ const db = pb[i] || 0;
47
+ if (da !== db) return da > db ? 1 : -1;
48
+ }
49
+ return 0;
50
+ }
51
+
52
+ /** 读取更新检查缓存;无/损坏返回空对象 */
53
+ export function loadCache(cachePath = UPDATE_CACHE_PATH) {
54
+ try {
55
+ const cache = JSON.parse(fs.readFileSync(cachePath, 'utf-8'));
56
+ return cache && typeof cache === 'object' ? cache : {};
57
+ } catch {
58
+ return {};
59
+ }
60
+ }
61
+
62
+ /** 写缓存(原子写) */
63
+ export function saveCache(cache, cachePath = UPDATE_CACHE_PATH) {
64
+ try {
65
+ ensureDir();
66
+ const tmp = `${cachePath}.${process.pid}.${Date.now()}.tmp`;
67
+ fs.writeFileSync(tmp, JSON.stringify(cache));
68
+ fs.renameSync(tmp, cachePath);
69
+ } catch {}
70
+ }
71
+
72
+ /**
73
+ * 查询 npm registry 最新版本号;全部源失败返回 null。
74
+ * @param {{timeoutMs?: number}} [opts]
75
+ * @returns {Promise<string|null>}
76
+ */
77
+ export async function fetchLatestVersion({ timeoutMs = 8000 } = {}) {
78
+ for (const base of REGISTRIES) {
79
+ try {
80
+ const controller = new AbortController();
81
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
82
+ const res = await fetch(`${base}/a4phone/latest`, { signal: controller.signal });
83
+ clearTimeout(timer);
84
+ if (!res.ok) continue;
85
+ const data = await res.json();
86
+ if (typeof data?.version === 'string' && data.version) return data.version;
87
+ } catch {}
88
+ }
89
+ return null;
90
+ }
91
+
92
+ /**
93
+ * 检查一次更新(含限频与提醒去重)。未到期/未开启/查询失败均静默跳过。
94
+ * @param {object} [opts]
95
+ * @param {object} [opts.config] a4phone 配置(checkUpdates=false 则跳过;updateIntervalHours 调整间隔)
96
+ * @param {(latest:string)=>Promise<void>|void} [opts.notify] 发现新版本且未提醒过时的回调(推送/终端提示)
97
+ * @param {(msg:string)=>void} [opts.onLog]
98
+ * @param {number} [opts.now] 注入当前时间(测试用)
99
+ * @param {string} [opts.cachePath] 注入缓存路径(测试用)
100
+ * @param {number} [opts.minIntervalMs] 最小检查间隔(默认 updateIntervalHours 或 6 小时)
101
+ * @param {string} [opts.localVersion] 注入本地版本(测试用)
102
+ * @param {string|null} [opts.latestVersion] 注入最新版本(测试用;undefined 则实际查询,null 视为查询失败)
103
+ * @returns {Promise<{checked:boolean, hasUpdate:boolean, local:string, latest:string|null, notified:boolean}>}
104
+ */
105
+ export async function checkForUpdate({
106
+ config = null,
107
+ notify = null,
108
+ onLog = () => {},
109
+ now = Date.now(),
110
+ cachePath = UPDATE_CACHE_PATH,
111
+ minIntervalMs = null,
112
+ localVersion = getLocalVersion(),
113
+ latestVersion = undefined,
114
+ } = {}) {
115
+ const cfg = config || {};
116
+ if (cfg.checkUpdates === false) {
117
+ return { checked: false, hasUpdate: false, local: localVersion, latest: null, notified: false };
118
+ }
119
+
120
+ const cache = loadCache(cachePath);
121
+ const intervalMs = minIntervalMs ?? (cfg.updateIntervalHours ?? DEFAULT_INTERVAL_HOURS) * 3600 * 1000;
122
+ if (now - (cache.lastCheck || 0) < intervalMs) {
123
+ // 未到期:限频跳过(不访问网络)
124
+ return { checked: false, hasUpdate: false, local: localVersion, latest: cache.knownLatest || null, notified: false };
125
+ }
126
+
127
+ const latest = latestVersion !== undefined ? latestVersion : await fetchLatestVersion();
128
+ if (!latest) {
129
+ // 查询失败:静默跳过(不记录 lastCheck,下次再试)
130
+ return { checked: true, hasUpdate: false, local: localVersion, latest: null, notified: false };
131
+ }
132
+
133
+ const hasUpdate = compareVersions(latest, localVersion) > 0;
134
+ const isNewVersion = hasUpdate && cache.knownLatest !== latest;
135
+
136
+ if (isNewVersion && notify) {
137
+ try {
138
+ await notify(latest);
139
+ } catch (error) {
140
+ onLog(`更新提醒发送失败(将在下次检查重试): ${String(error?.message ?? error)}`);
141
+ // 提醒失败:不更新 knownLatest,下次检查会重试;只记录检查时间
142
+ saveCache({ lastCheck: now, knownLatest: cache.knownLatest }, cachePath);
143
+ return { checked: true, hasUpdate, local: localVersion, latest, notified: false };
144
+ }
145
+ }
146
+
147
+ saveCache({ lastCheck: now, knownLatest: hasUpdate ? latest : cache.knownLatest }, cachePath);
148
+ return { checked: true, hasUpdate, local: localVersion, latest, notified: isNewVersion };
149
+ }
150
+
151
+ /** 守护进程专用:发现新版本 → 推送手机提醒 */
152
+ export function makePhoneNotifier(config, { localVersion = getLocalVersion(), onLog = () => {} } = {}) {
153
+ return async (latest) => {
154
+ onLog(`检测到新版本 ${latest}(当前 ${localVersion}),已推送手机提醒`);
155
+ const ok = await sendNotification({
156
+ ...config,
157
+ title: 'a4phone',
158
+ message: `检测到新版本 ${latest}(当前 ${localVersion})\n\n请运行:npm install -g a4phone 升级`,
159
+ });
160
+ if (!ok) throw new Error('手机推送失败');
161
+ };
162
+ }
163
+
164
+ /** 命令级专用:发现新版本 → 终端打印提示 */
165
+ export function makeConsoleNotifier({ localVersion = getLocalVersion() } = {}) {
166
+ return async (latest) => {
167
+ console.log(`\n[提醒] a4phone 有新版本 ${latest}(当前 ${localVersion}),可运行 npm install -g a4phone 升级。\n`);
168
+ };
169
+ }