a4phone 1.2.0 → 1.3.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
 
@@ -98,6 +99,8 @@ a4p status # 查看当前模式
98
99
  ```
99
100
 
100
101
  > 续聊完全 headless 运行(无需窗口标题匹配、前台焦点或剪贴板,也不依赖你当前是否开着终端),支持 Claude Code、Codex 与 DSH 会话(按最近会话的 agent 自动选择续聊方式)。续聊回合内若再次触发提问/权限请求,仍会推送手机,形成完整的远程对话闭环。
102
+ >
103
+ > **积压合并**:一轮续聊最长可达 `resumeTimeout`(默认 30 分钟),期间手机连续发来的消息会自动**合并为一个批次**一次性续聊(不再逐条排队、每条一个独立轮次),保证手机内容一定能送达 AI;积压批次持久化到 `~/.a4phone/pending-batch.json`,守护进程重启/崩溃后自动恢复,不丢消息。
101
104
 
102
105
  ## Codex
103
106
 
@@ -195,7 +198,8 @@ AI助手触发事件 → a4p hook → ntfy.sh 推送手机 → 手机点选/文
195
198
  - **ntfy.sh 免费托管服务有发布速率/消息保留限制**:短时间高频测试可能触发 `limited` 提示,建议降低推送频率(续聊结果已去重推送,不再重复通知)
196
199
  - ntfy.sh 公共话题可被知晓话题名的人读写,重要场景建议自建 ntfy 服务或使用访问令牌
197
200
  - ntfy.sh 为国外服务,国内网络下长连接可能不稳定
198
- - 配置存储于 `~/.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`
201
+ - **自动更新提醒**:默认开启(`checkUpdates: true`)。守护进程(`a4p listen`)启动时及每 `updateIntervalHours` 小时(默认 6)检查一次 npm registry(npmmirror 优先、官方兜底),发现新版本推送手机提醒;其他命令(`a4p status`/`a4p resume` 等)在终端提示。同一新版本只提醒一次,查询失败静默跳过,不影响正常功能;可在 `~/.a4phone/config.json` 设 `checkUpdates: false` 关闭
202
+ - 配置存储于 `~/.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`
199
203
 
200
204
  ## 开发
201
205
 
package/bin/a4p.mjs CHANGED
@@ -40,6 +40,21 @@ function showHelp() {
40
40
  }
41
41
 
42
42
  const cmd = process.argv[2];
43
+ const sub = process.argv[3];
44
+
45
+ // ── 版本更新检查(默认开启)───────────────────────────────────────────
46
+ // 守护进程(listen --daemon-child)自己有周期检查 + 手机推送,这里跳过;
47
+ // hook 是 AI 每次事件都调用的热路径,跳过避免延迟;version/help 是脚本/查询场景跳过。
48
+ // 其余命令在终端提示新版本;限频与去重由 update-check 缓存保证(未到期零开销)。
49
+ if (cmd && !['hook', '--version', '-v', 'version', 'help', '--help', '-h'].includes(cmd)
50
+ && !(cmd === 'listen' && sub === '--daemon-child')) {
51
+ const { checkForUpdate, makeConsoleNotifier } = await import('../src/update-check.mjs');
52
+ const { loadConfig } = await import('../src/config.mjs');
53
+ checkForUpdate({
54
+ config: loadConfig(),
55
+ notify: makeConsoleNotifier(),
56
+ }).catch(() => {});
57
+ }
43
58
 
44
59
  if (cmd === '--version' || cmd === '-v' || cmd === 'version') {
45
60
  const pkg = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf-8'));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "a4phone",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "Claude Code / Codex / DSH 远程手机交互:任务完成通知(含 AI 最后输出)、提问/权限请求手机点选或文字作答、远程续聊(ntfy.sh,含 DSH 会话续聊)",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,75 @@
1
+ // batcher.mjs — 串行批处理器
2
+ //
3
+ // 解决续聊守护进程的积压问题:一轮续聊最长可达 resumeTimeout(默认 1800 秒),
4
+ // 期间手机发来的消息若逐条排队,每条都会触发一个独立的续聊轮次(N 条 = N 轮),
5
+ // 手机内容会被无限期延迟。本模块把忙时到达的消息**合并为一个批次**,
6
+ // 当前轮结束后一次处理整批——任意数量积压最多只产生一条额外续聊轮次,
7
+ // 保证手机内容一定能送达 AI(顺序保留、串行执行、有界延迟)。
8
+ //
9
+ // 用法:
10
+ // const batcher = createBatcher({
11
+ // run: async ({ text, count, msgTime }) => { ...; return true }, // false=丢弃该批
12
+ // log: (msg) => ...,
13
+ // });
14
+ // batcher.submit(text, msgTime); // 立即返回 drain 的 promise(fire-and-forget 也行)
15
+ // batcher.restore(texts, msgTime); // 启动时恢复上次未处理的批次
16
+ // batcher.pendingCount / batcher.pendingSnapshot() // 持久化与检查用
17
+ export function createBatcher({ run, log = () => {} }) {
18
+ let draining = null; // 正在执行的 drain 循环(防止并发)
19
+ const pending = { texts: [], msgTime: null };
20
+
21
+ function enqueue(text, msgTime) {
22
+ pending.texts.push(text);
23
+ pending.msgTime = pending.msgTime == null ? msgTime : Math.min(pending.msgTime, msgTime);
24
+ if (pending.texts.length === 2) {
25
+ log('当前续聊进行中,后续消息将合并为一条续聊请求');
26
+ }
27
+ }
28
+
29
+ // 串行排空循环:一次处理一批,过时/被拒批次丢弃后继续下一批(不会停顿)
30
+ function drain() {
31
+ if (!draining) {
32
+ draining = (async () => {
33
+ try {
34
+ while (pending.texts.length) {
35
+ const texts = pending.texts;
36
+ const msgTime = pending.msgTime;
37
+ pending.texts = [];
38
+ pending.msgTime = null;
39
+ try {
40
+ await run({ text: texts.join('\n\n'), count: texts.length, msgTime });
41
+ } catch (error) {
42
+ log(`批次处理异常(已跳过该批): ${String(error?.message ?? error)}`);
43
+ }
44
+ }
45
+ } finally {
46
+ draining = null;
47
+ }
48
+ })();
49
+ }
50
+ return draining;
51
+ }
52
+
53
+ return {
54
+ /** 提交一条消息;忙时自动合并进当前批次 */
55
+ submit(text, msgTime) {
56
+ enqueue(text, msgTime);
57
+ return drain();
58
+ },
59
+ /** 启动时恢复上次未处理完的批次(触发排空) */
60
+ restore(texts, msgTime) {
61
+ if (!Array.isArray(texts) || !texts.length) return;
62
+ for (const t of texts) pending.texts.push(String(t));
63
+ pending.msgTime = msgTime ?? null;
64
+ drain();
65
+ },
66
+ /** 当前积压条数(0 = 无积压) */
67
+ get pendingCount() {
68
+ return pending.texts.length;
69
+ },
70
+ /** 当前批次快照(供持久化) */
71
+ pendingSnapshot() {
72
+ return { texts: [...pending.texts], msgTime: pending.msgTime };
73
+ },
74
+ };
75
+ }
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
@@ -1,12 +1,18 @@
1
1
  // 续聊守护进程:订阅主话题,手机向主话题发送文字即触发一次续聊。
2
2
  // 断线自动重连(since 从上次消息之后继续),续聊请求串行处理(避免并发会话冲突)。
3
+ // 积压合并:一轮续聊最长 resumeTimeout(默认 1800 秒),忙时到达的手机消息
4
+ // 合并为一个批次,当前轮结束后一次续聊处理整批(任意数量积压最多只多一轮),
5
+ // 保证手机内容一定能送达 AI;批次持久化到 ~/.a4phone/pending-batch.json,
6
+ // 守护进程重启后自动恢复,避免积压消息丢失。
3
7
  // 按消息时间戳过滤:如果新会话开启时间晚于用户的消息时间,则跳过该消息,
4
8
  // 避免旧消息被注入到新会话中。
5
9
  import fs from 'fs';
6
10
  import path from 'path';
7
- import os from 'os';
8
11
  import { loadConfig, loadLastSession } from './config.mjs';
9
12
  import { runResume } from './resume.mjs';
13
+ import { createBatcher } from './batcher.mjs';
14
+ import { checkForUpdate, makePhoneNotifier } from './update-check.mjs';
15
+ import { PENDING_PATH, ensureDir } from './paths.mjs';
10
16
 
11
17
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
12
18
  const RETRY_DELAY = 5000;
@@ -19,6 +25,13 @@ export function createLogWriter(logPath) {
19
25
  };
20
26
  }
21
27
 
28
+ // 原子写 JSON(临时文件 + rename,避免读者读到半个文件)
29
+ function atomicWriteJson(filePath, data) {
30
+ const tmp = `${filePath}.${process.pid}.${Date.now()}.tmp`;
31
+ fs.writeFileSync(tmp, JSON.stringify(data));
32
+ fs.renameSync(tmp, filePath);
33
+ }
34
+
22
35
  export async function runListen({ onLog = (s) => console.log(s) } = {}) {
23
36
  const config = loadConfig();
24
37
  if (!config.topic) {
@@ -31,8 +44,6 @@ export async function runListen({ onLog = (s) => console.log(s) } = {}) {
31
44
 
32
45
  // ntfy 的 since 参数只接受 Unix 秒时间戳/时长/all,不接受 "now" 或消息 ID
33
46
  let lastTime = Math.floor(Date.now() / 1000); // 首次只收连接之后的新消息
34
- let busy = false;
35
- const queue = [];
36
47
  let knownSessionId = null; // 记录已处理过的会话 ID,用于检测会话切换
37
48
 
38
49
  // 判断消息是否仍应被处理:如果新会话在消息发送之后才创建,则丢弃
@@ -52,24 +63,63 @@ export async function runListen({ onLog = (s) => console.log(s) } = {}) {
52
63
  return false;
53
64
  }
54
65
 
55
- const processMessage = async (text, msgTime) => {
56
- if (busy) {
57
- queue.push({ text, msgTime });
58
- return;
59
- }
60
- if (msgTime != null && isMessageStale(msgTime)) return; // 旧消息,丢弃
61
- busy = true;
62
- onLog(`收到续聊请求:${text.slice(0, 60)}`);
63
- const result = await runResume(text, { config, onLog });
64
- onLog(result.ok
65
- ? `消息已处理(resume 续聊${result.code != null ? `,退出码 ${result.code}` : ''}),结果已推送手机。`
66
- : `续聊失败:${result.reason}`);
67
- busy = false;
68
- if (queue.length) {
69
- const next = queue.shift();
70
- processMessage(next.text, next.msgTime);
66
+ // 批次持久化:积压非空写文件,排空后删除(守护进程重启后恢复)
67
+ function persistSnapshot() {
68
+ try {
69
+ ensureDir();
70
+ const snapshot = batcher.pendingSnapshot();
71
+ if (snapshot.texts.length) {
72
+ atomicWriteJson(PENDING_PATH, snapshot);
73
+ } else {
74
+ try { fs.unlinkSync(PENDING_PATH); } catch {}
75
+ }
76
+ } catch {}
77
+ }
78
+
79
+ const batcher = createBatcher({
80
+ log: onLog,
81
+ run: async ({ text, count, msgTime }) => {
82
+ try {
83
+ if (msgTime != null && isMessageStale(msgTime)) return false; // 旧消息,丢弃
84
+ if (count > 1) onLog(`合并 ${count} 条积压消息为一条续聊请求`);
85
+ onLog(`收到续聊请求:${text.slice(0, 60)}`);
86
+ const result = await runResume(text, { config, onLog });
87
+ onLog(result.ok
88
+ ? `消息已处理(resume 续聊${result.code != null ? `,退出码 ${result.code}` : ''}),结果已推送手机。`
89
+ : `续聊失败:${result.reason}`);
90
+ return true;
91
+ } finally {
92
+ // 批次处理完成(或已丢弃)后刷新持久化:
93
+ // 期间若有新积压则保留到文件,否则清空,避免重启后重复处理已完成批次
94
+ persistSnapshot();
95
+ }
96
+ },
97
+ });
98
+
99
+ // 启动恢复:上次未处理完的积压批次(守护进程重启/崩溃不丢消息)
100
+ try {
101
+ const raw = fs.readFileSync(PENDING_PATH, 'utf-8');
102
+ const saved = JSON.parse(raw);
103
+ if (Array.isArray(saved?.texts) && saved.texts.length) {
104
+ onLog(`恢复 ${saved.texts.length} 条重启前未处理的续聊消息,继续处理...`);
105
+ batcher.restore(saved.texts, saved.msgTime ?? null);
71
106
  }
107
+ } catch {}
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 {}
72
119
  };
120
+ await checkUpdate();
121
+ const intervalMs = (config.updateIntervalHours ?? 6) * 3600 * 1000;
122
+ setInterval(() => { checkUpdate().catch(() => {}); }, intervalMs).unref();
73
123
 
74
124
  while (true) {
75
125
  try {
@@ -107,7 +157,8 @@ export async function runListen({ onLog = (s) => console.log(s) } = {}) {
107
157
  msg = event.message; // 纯文本:手机发来的续聊内容
108
158
  }
109
159
  if (typeof msg === 'string' && msg.trim()) {
110
- processMessage(msg.trim(), event.time ? Number(event.time) : null);
160
+ batcher.submit(msg.trim(), event.time ? Number(event.time) : null);
161
+ persistSnapshot();
111
162
  }
112
163
  }
113
164
  }
package/src/paths.mjs CHANGED
@@ -20,6 +20,11 @@ export const LOG_PATH = path.join(A4P_DIR, 'daemon.log');
20
20
  export const DSH_JOB_DIR = path.join(A4P_DIR, 'dsh-jobs');
21
21
  // DSH 插件心跳:dsh web 每次轮询刷新,a4p 据此判断 dsh web 是否在运行
22
22
  export const DSH_HEARTBEAT = path.join(A4P_DIR, 'dsh-heartbeat.json');
23
+ // 续聊积压批次持久化:长轮次期间到达的消息写入该文件,守护进程重启后恢复,
24
+ // 避免积压消息在重启时丢失
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');
23
28
 
24
29
  // 旧版散落在家目录的单文件 → 迁移到 ~/.a4phone/(新路径不存在时才移动)
25
30
  const LEGACY_PATHS = {
@@ -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
+ }