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/README.md +278 -278
- package/bin/a4p.mjs +194 -194
- package/package.json +1 -1
- package/src/hook.mjs +48 -48
- package/src/listen.mjs +207 -207
- package/src/notify.mjs +43 -21
- package/src/resume.mjs +334 -334
- package/src/setup.mjs +540 -540
- package/src/stop.mjs +3 -2
- package/src/transcript.mjs +20 -4
package/src/listen.mjs
CHANGED
|
@@ -1,207 +1,207 @@
|
|
|
1
|
-
// 续聊守护进程:订阅主话题,手机向主话题发送文字即触发一次续聊。
|
|
2
|
-
// 断线自动重连(since 从上次消息之后继续),续聊请求串行处理(避免并发会话冲突)。
|
|
3
|
-
// 积压合并:一轮续聊最长 resumeTimeout(默认 1800 秒),忙时到达的手机消息
|
|
4
|
-
// 合并为一个批次,当前轮结束后一次续聊处理整批(任意数量积压最多只多一轮),
|
|
5
|
-
// 保证手机内容一定能送达 AI;批次持久化到 ~/.a4phone/pending-batch.json,
|
|
6
|
-
// 守护进程重启后自动恢复,避免积压消息丢失。
|
|
7
|
-
// 按消息时间戳过滤:如果新会话开启时间晚于用户的消息时间,则跳过该消息,
|
|
8
|
-
// 避免旧消息被注入到新会话中。
|
|
9
|
-
import fs from 'fs';
|
|
10
|
-
import path from 'path';
|
|
11
|
-
import { loadConfig, loadLastSession } from './config.mjs';
|
|
12
|
-
import { runResume } from './resume.mjs';
|
|
13
|
-
import { createBatcher } from './batcher.mjs';
|
|
14
|
-
import { checkForUpdate, makePhoneNotifier } from './update-check.mjs';
|
|
15
|
-
import { parseNtfyMessage } from './ntfy.mjs';
|
|
16
|
-
import { processNotifyQueue } from './notify.mjs';
|
|
17
|
-
import { PENDING_PATH, ensureDir } from './paths.mjs';
|
|
18
|
-
import { configureDsh } from './setup.mjs';
|
|
19
|
-
|
|
20
|
-
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
21
|
-
const RETRY_DELAY = 5000;
|
|
22
|
-
// DSH profile 自动发现扫描间隔:新装 profile(如后续安装的 tui/dsh-tui 变体)
|
|
23
|
-
// 无需重跑 a4p setup,守护进程周期重扫自动补挂
|
|
24
|
-
const PROFILE_SCAN_INTERVAL_MS = 10 * 60 * 1000;
|
|
25
|
-
// 桌面通知队列扫描间隔:hook 写请求文件后,守护进程尽快代发(不阻塞续聊循环)
|
|
26
|
-
const NOTIFY_SCAN_INTERVAL_MS = 2000;
|
|
27
|
-
|
|
28
|
-
/**
|
|
29
|
-
* 扫描 ~/.dsh/profiles 并为所有 profile 补挂 dsh-hook(幂等),
|
|
30
|
-
* 有新挂载时写日志。导出便于测试与手动调用。
|
|
31
|
-
* @param {(msg: string) => void} [onLog]
|
|
32
|
-
* @param {object} [opts] 透传给 configureDsh(profilesDir/pluginEntry,测试用)
|
|
33
|
-
* @returns {string[]} 本次新挂载的 profile 名列表
|
|
34
|
-
*/
|
|
35
|
-
export function ensureDshProfiles(onLog = () => {}, opts = {}) {
|
|
36
|
-
try {
|
|
37
|
-
const r = configureDsh(opts);
|
|
38
|
-
if (r && Array.isArray(r.mounted) && r.mounted.length) {
|
|
39
|
-
onLog(`发现 DSH profile,已自动挂载手机交互插件:${r.mounted.join('、')}`);
|
|
40
|
-
return r.mounted;
|
|
41
|
-
}
|
|
42
|
-
} catch {}
|
|
43
|
-
return [];
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
export function createLogWriter(logPath) {
|
|
47
|
-
const stream = fs.createWriteStream(logPath, { flags: 'a' });
|
|
48
|
-
return (msg) => {
|
|
49
|
-
const line = `[${new Date().toISOString()}] ${msg}\n`;
|
|
50
|
-
stream.write(line);
|
|
51
|
-
};
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
// 原子写 JSON(临时文件 + rename,避免读者读到半个文件)
|
|
55
|
-
function atomicWriteJson(filePath, data) {
|
|
56
|
-
const tmp = `${filePath}.${process.pid}.${Date.now()}.tmp`;
|
|
57
|
-
fs.writeFileSync(tmp, JSON.stringify(data));
|
|
58
|
-
fs.renameSync(tmp, filePath);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
export async function runListen({ onLog = (s) => console.log(s) } = {}) {
|
|
62
|
-
const config = loadConfig();
|
|
63
|
-
if (!config.topic) {
|
|
64
|
-
onLog('未配置话题,请先运行 a4p setup。');
|
|
65
|
-
return false;
|
|
66
|
-
}
|
|
67
|
-
const url = `${config.server}/${config.topic}/json`;
|
|
68
|
-
onLog(`续聊守护进程已启动,监听: ${url}`);
|
|
69
|
-
onLog(`提示:手机向话题 ${config.topic} 发送文字即可与当前会话交流;Ctrl+C 退出。`);
|
|
70
|
-
|
|
71
|
-
// ntfy 的 since 参数只接受 Unix 秒时间戳/时长/all,不接受 "now" 或消息 ID
|
|
72
|
-
let lastTime = Math.floor(Date.now() / 1000); // 首次只收连接之后的新消息
|
|
73
|
-
let knownSessionId = null; // 记录已处理过的会话 ID,用于检测会话切换
|
|
74
|
-
|
|
75
|
-
// 判断消息是否仍应被处理:如果新会话在消息发送之后才创建,则丢弃
|
|
76
|
-
function isMessageStale(msgTime) {
|
|
77
|
-
const last = loadLastSession();
|
|
78
|
-
if (!last?.session_id) return false; // 无最近会话,不过滤
|
|
79
|
-
// 首次处理或会话未变,不过滤
|
|
80
|
-
if (knownSessionId === last.session_id) return false;
|
|
81
|
-
// 会话变了:检查消息是否是在新会话创建之前发送的
|
|
82
|
-
// last.ts 是 Stop 事件的保存时间(毫秒),msgTime 是 ntfy 的 Unix 秒
|
|
83
|
-
if (msgTime * 1000 < last.ts) {
|
|
84
|
-
onLog(`丢弃过时消息(消息时间 ${msgTime} 早于新会话创建时间 ${Math.floor(last.ts / 1000)})`);
|
|
85
|
-
return true;
|
|
86
|
-
}
|
|
87
|
-
// 会话变了但消息更新,更新 knownSessionId 并处理
|
|
88
|
-
knownSessionId = last.session_id;
|
|
89
|
-
return false;
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
// 批次持久化:积压非空写文件,排空后删除(守护进程重启后恢复)
|
|
93
|
-
function persistSnapshot() {
|
|
94
|
-
try {
|
|
95
|
-
ensureDir();
|
|
96
|
-
const snapshot = batcher.pendingSnapshot();
|
|
97
|
-
if (snapshot.texts.length) {
|
|
98
|
-
atomicWriteJson(PENDING_PATH, snapshot);
|
|
99
|
-
} else {
|
|
100
|
-
try { fs.unlinkSync(PENDING_PATH); } catch {}
|
|
101
|
-
}
|
|
102
|
-
} catch {}
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
const batcher = createBatcher({
|
|
106
|
-
log: onLog,
|
|
107
|
-
// 取批即删持久化文件(P4-1 a4p 侧 at-most-once):批次一旦交给续聊管线,
|
|
108
|
-
// 进程崩溃后不再恢复,避免同一条手机消息重复注入会话
|
|
109
|
-
onTake: persistSnapshot,
|
|
110
|
-
run: async ({ text, count, msgTime }) => {
|
|
111
|
-
try {
|
|
112
|
-
if (msgTime != null && isMessageStale(msgTime)) return false; // 旧消息,丢弃
|
|
113
|
-
if (count > 1) onLog(`合并 ${count} 条积压消息为一条续聊请求`);
|
|
114
|
-
onLog(`收到续聊请求:${text.slice(0, 60)}`);
|
|
115
|
-
const result = await runResume(text, { config, onLog });
|
|
116
|
-
onLog(result.ok
|
|
117
|
-
? `消息已处理(resume 续聊${result.code != null ? `,退出码 ${result.code}` : ''}),结果已推送手机。`
|
|
118
|
-
: `续聊失败:${result.reason}`);
|
|
119
|
-
return true;
|
|
120
|
-
} finally {
|
|
121
|
-
// 批次处理完成(或已丢弃)后刷新持久化:
|
|
122
|
-
// 期间若有新积压则保留到文件,否则清空,避免重启后重复处理已完成批次
|
|
123
|
-
persistSnapshot();
|
|
124
|
-
}
|
|
125
|
-
},
|
|
126
|
-
});
|
|
127
|
-
|
|
128
|
-
// 启动恢复:上次未处理完的积压批次(守护进程重启/崩溃不丢消息)
|
|
129
|
-
try {
|
|
130
|
-
const raw = fs.readFileSync(PENDING_PATH, 'utf-8');
|
|
131
|
-
const saved = JSON.parse(raw);
|
|
132
|
-
if (Array.isArray(saved?.texts) && saved.texts.length) {
|
|
133
|
-
onLog(`恢复 ${saved.texts.length} 条重启前未处理的续聊消息,继续处理...`);
|
|
134
|
-
batcher.restore(saved.texts, saved.msgTime ?? null);
|
|
135
|
-
}
|
|
136
|
-
} catch {}
|
|
137
|
-
|
|
138
|
-
// ── 版本更新检查:启动时 + 周期性(默认 6 小时),发现新版本推送手机提醒 ──
|
|
139
|
-
// 限频与去重由 update-check 的缓存保证(同一新版本只提醒一次,未到期不访问网络)
|
|
140
|
-
const checkUpdate = async () => {
|
|
141
|
-
try {
|
|
142
|
-
await checkForUpdate({
|
|
143
|
-
config,
|
|
144
|
-
notify: makePhoneNotifier(config, { onLog }),
|
|
145
|
-
onLog,
|
|
146
|
-
});
|
|
147
|
-
} catch {}
|
|
148
|
-
};
|
|
149
|
-
await checkUpdate();
|
|
150
|
-
const intervalMs = (config.updateIntervalHours ?? 6) * 3600 * 1000;
|
|
151
|
-
setInterval(() => { checkUpdate().catch(() => {}); }, intervalMs).unref();
|
|
152
|
-
|
|
153
|
-
// ── DSH profile 自动发现:启动时 + 周期扫描,新装 profile 自动补挂插件 ──
|
|
154
|
-
ensureDshProfiles(onLog);
|
|
155
|
-
setInterval(() => { ensureDshProfiles(onLog); }, PROFILE_SCAN_INTERVAL_MS).unref();
|
|
156
|
-
|
|
157
|
-
// ── 桌面通知队列代发:hook 进程(尤其 ZCode)退出时会被执行端口杀进程树,
|
|
158
|
-
// fire-and-forget 的气泡来不及渲染;由常驻守护进程读取请求并弹窗 ──
|
|
159
|
-
setInterval(() => {
|
|
160
|
-
try { processNotifyQueue(); } catch {}
|
|
161
|
-
}, NOTIFY_SCAN_INTERVAL_MS).unref();
|
|
162
|
-
|
|
163
|
-
while (true) {
|
|
164
|
-
try {
|
|
165
|
-
const since = `since=${lastTime + 1}`; // 从最后收到的消息之后继续
|
|
166
|
-
const res = await fetch(`${url}?${since}`);
|
|
167
|
-
if (!res.ok) {
|
|
168
|
-
onLog(`连接失败(HTTP ${res.status}),${RETRY_DELAY / 1000} 秒后重连...`);
|
|
169
|
-
await sleep(RETRY_DELAY);
|
|
170
|
-
continue;
|
|
171
|
-
}
|
|
172
|
-
const reader = res.body.getReader();
|
|
173
|
-
const decoder = new TextDecoder();
|
|
174
|
-
let buffer = '';
|
|
175
|
-
while (true) {
|
|
176
|
-
const { done, value } = await reader.read();
|
|
177
|
-
if (done) break;
|
|
178
|
-
buffer += decoder.decode(value, { stream: true });
|
|
179
|
-
const lines = buffer.split('\n');
|
|
180
|
-
buffer = lines.pop();
|
|
181
|
-
for (const line of lines) {
|
|
182
|
-
if (!line.trim()) continue;
|
|
183
|
-
let event;
|
|
184
|
-
try {
|
|
185
|
-
event = JSON.parse(line);
|
|
186
|
-
} catch {
|
|
187
|
-
continue;
|
|
188
|
-
}
|
|
189
|
-
if (event.time) lastTime = Math.max(lastTime, Number(event.time));
|
|
190
|
-
// 有 title 的是系统推送通知(Claude Code 回复),不是手机用户消息,跳过
|
|
191
|
-
if (event.title) continue;
|
|
192
|
-
// 系统推送为 JSON 对象则忽略;纯文本/JSON 原始值(如手机发的单数字"3")作为续聊内容
|
|
193
|
-
const msg = parseNtfyMessage(event.message);
|
|
194
|
-
if (typeof msg === 'string' && msg.trim()) {
|
|
195
|
-
batcher.submit(msg.trim(), event.time ? Number(event.time) : null);
|
|
196
|
-
persistSnapshot();
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
onLog(`连接断开,${RETRY_DELAY / 1000} 秒后重连...`);
|
|
201
|
-
await sleep(RETRY_DELAY);
|
|
202
|
-
} catch (err) {
|
|
203
|
-
onLog(`连接异常(${err.message}),${RETRY_DELAY / 1000} 秒后重连...`);
|
|
204
|
-
await sleep(RETRY_DELAY);
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
}
|
|
1
|
+
// 续聊守护进程:订阅主话题,手机向主话题发送文字即触发一次续聊。
|
|
2
|
+
// 断线自动重连(since 从上次消息之后继续),续聊请求串行处理(避免并发会话冲突)。
|
|
3
|
+
// 积压合并:一轮续聊最长 resumeTimeout(默认 1800 秒),忙时到达的手机消息
|
|
4
|
+
// 合并为一个批次,当前轮结束后一次续聊处理整批(任意数量积压最多只多一轮),
|
|
5
|
+
// 保证手机内容一定能送达 AI;批次持久化到 ~/.a4phone/pending-batch.json,
|
|
6
|
+
// 守护进程重启后自动恢复,避免积压消息丢失。
|
|
7
|
+
// 按消息时间戳过滤:如果新会话开启时间晚于用户的消息时间,则跳过该消息,
|
|
8
|
+
// 避免旧消息被注入到新会话中。
|
|
9
|
+
import fs from 'fs';
|
|
10
|
+
import path from 'path';
|
|
11
|
+
import { loadConfig, loadLastSession } from './config.mjs';
|
|
12
|
+
import { runResume } from './resume.mjs';
|
|
13
|
+
import { createBatcher } from './batcher.mjs';
|
|
14
|
+
import { checkForUpdate, makePhoneNotifier } from './update-check.mjs';
|
|
15
|
+
import { parseNtfyMessage } from './ntfy.mjs';
|
|
16
|
+
import { processNotifyQueue } from './notify.mjs';
|
|
17
|
+
import { PENDING_PATH, ensureDir } from './paths.mjs';
|
|
18
|
+
import { configureDsh } from './setup.mjs';
|
|
19
|
+
|
|
20
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
21
|
+
const RETRY_DELAY = 5000;
|
|
22
|
+
// DSH profile 自动发现扫描间隔:新装 profile(如后续安装的 tui/dsh-tui 变体)
|
|
23
|
+
// 无需重跑 a4p setup,守护进程周期重扫自动补挂
|
|
24
|
+
const PROFILE_SCAN_INTERVAL_MS = 10 * 60 * 1000;
|
|
25
|
+
// 桌面通知队列扫描间隔:hook 写请求文件后,守护进程尽快代发(不阻塞续聊循环)
|
|
26
|
+
const NOTIFY_SCAN_INTERVAL_MS = 2000;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* 扫描 ~/.dsh/profiles 并为所有 profile 补挂 dsh-hook(幂等),
|
|
30
|
+
* 有新挂载时写日志。导出便于测试与手动调用。
|
|
31
|
+
* @param {(msg: string) => void} [onLog]
|
|
32
|
+
* @param {object} [opts] 透传给 configureDsh(profilesDir/pluginEntry,测试用)
|
|
33
|
+
* @returns {string[]} 本次新挂载的 profile 名列表
|
|
34
|
+
*/
|
|
35
|
+
export function ensureDshProfiles(onLog = () => {}, opts = {}) {
|
|
36
|
+
try {
|
|
37
|
+
const r = configureDsh(opts);
|
|
38
|
+
if (r && Array.isArray(r.mounted) && r.mounted.length) {
|
|
39
|
+
onLog(`发现 DSH profile,已自动挂载手机交互插件:${r.mounted.join('、')}`);
|
|
40
|
+
return r.mounted;
|
|
41
|
+
}
|
|
42
|
+
} catch {}
|
|
43
|
+
return [];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function createLogWriter(logPath) {
|
|
47
|
+
const stream = fs.createWriteStream(logPath, { flags: 'a' });
|
|
48
|
+
return (msg) => {
|
|
49
|
+
const line = `[${new Date().toISOString()}] ${msg}\n`;
|
|
50
|
+
stream.write(line);
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// 原子写 JSON(临时文件 + rename,避免读者读到半个文件)
|
|
55
|
+
function atomicWriteJson(filePath, data) {
|
|
56
|
+
const tmp = `${filePath}.${process.pid}.${Date.now()}.tmp`;
|
|
57
|
+
fs.writeFileSync(tmp, JSON.stringify(data));
|
|
58
|
+
fs.renameSync(tmp, filePath);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export async function runListen({ onLog = (s) => console.log(s) } = {}) {
|
|
62
|
+
const config = loadConfig();
|
|
63
|
+
if (!config.topic) {
|
|
64
|
+
onLog('未配置话题,请先运行 a4p setup。');
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
const url = `${config.server}/${config.topic}/json`;
|
|
68
|
+
onLog(`续聊守护进程已启动,监听: ${url}`);
|
|
69
|
+
onLog(`提示:手机向话题 ${config.topic} 发送文字即可与当前会话交流;Ctrl+C 退出。`);
|
|
70
|
+
|
|
71
|
+
// ntfy 的 since 参数只接受 Unix 秒时间戳/时长/all,不接受 "now" 或消息 ID
|
|
72
|
+
let lastTime = Math.floor(Date.now() / 1000); // 首次只收连接之后的新消息
|
|
73
|
+
let knownSessionId = null; // 记录已处理过的会话 ID,用于检测会话切换
|
|
74
|
+
|
|
75
|
+
// 判断消息是否仍应被处理:如果新会话在消息发送之后才创建,则丢弃
|
|
76
|
+
function isMessageStale(msgTime) {
|
|
77
|
+
const last = loadLastSession();
|
|
78
|
+
if (!last?.session_id) return false; // 无最近会话,不过滤
|
|
79
|
+
// 首次处理或会话未变,不过滤
|
|
80
|
+
if (knownSessionId === last.session_id) return false;
|
|
81
|
+
// 会话变了:检查消息是否是在新会话创建之前发送的
|
|
82
|
+
// last.ts 是 Stop 事件的保存时间(毫秒),msgTime 是 ntfy 的 Unix 秒
|
|
83
|
+
if (msgTime * 1000 < last.ts) {
|
|
84
|
+
onLog(`丢弃过时消息(消息时间 ${msgTime} 早于新会话创建时间 ${Math.floor(last.ts / 1000)})`);
|
|
85
|
+
return true;
|
|
86
|
+
}
|
|
87
|
+
// 会话变了但消息更新,更新 knownSessionId 并处理
|
|
88
|
+
knownSessionId = last.session_id;
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// 批次持久化:积压非空写文件,排空后删除(守护进程重启后恢复)
|
|
93
|
+
function persistSnapshot() {
|
|
94
|
+
try {
|
|
95
|
+
ensureDir();
|
|
96
|
+
const snapshot = batcher.pendingSnapshot();
|
|
97
|
+
if (snapshot.texts.length) {
|
|
98
|
+
atomicWriteJson(PENDING_PATH, snapshot);
|
|
99
|
+
} else {
|
|
100
|
+
try { fs.unlinkSync(PENDING_PATH); } catch {}
|
|
101
|
+
}
|
|
102
|
+
} catch {}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const batcher = createBatcher({
|
|
106
|
+
log: onLog,
|
|
107
|
+
// 取批即删持久化文件(P4-1 a4p 侧 at-most-once):批次一旦交给续聊管线,
|
|
108
|
+
// 进程崩溃后不再恢复,避免同一条手机消息重复注入会话
|
|
109
|
+
onTake: persistSnapshot,
|
|
110
|
+
run: async ({ text, count, msgTime }) => {
|
|
111
|
+
try {
|
|
112
|
+
if (msgTime != null && isMessageStale(msgTime)) return false; // 旧消息,丢弃
|
|
113
|
+
if (count > 1) onLog(`合并 ${count} 条积压消息为一条续聊请求`);
|
|
114
|
+
onLog(`收到续聊请求:${text.slice(0, 60)}`);
|
|
115
|
+
const result = await runResume(text, { config, onLog });
|
|
116
|
+
onLog(result.ok
|
|
117
|
+
? `消息已处理(resume 续聊${result.code != null ? `,退出码 ${result.code}` : ''}),结果已推送手机。`
|
|
118
|
+
: `续聊失败:${result.reason}`);
|
|
119
|
+
return true;
|
|
120
|
+
} finally {
|
|
121
|
+
// 批次处理完成(或已丢弃)后刷新持久化:
|
|
122
|
+
// 期间若有新积压则保留到文件,否则清空,避免重启后重复处理已完成批次
|
|
123
|
+
persistSnapshot();
|
|
124
|
+
}
|
|
125
|
+
},
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
// 启动恢复:上次未处理完的积压批次(守护进程重启/崩溃不丢消息)
|
|
129
|
+
try {
|
|
130
|
+
const raw = fs.readFileSync(PENDING_PATH, 'utf-8');
|
|
131
|
+
const saved = JSON.parse(raw);
|
|
132
|
+
if (Array.isArray(saved?.texts) && saved.texts.length) {
|
|
133
|
+
onLog(`恢复 ${saved.texts.length} 条重启前未处理的续聊消息,继续处理...`);
|
|
134
|
+
batcher.restore(saved.texts, saved.msgTime ?? null);
|
|
135
|
+
}
|
|
136
|
+
} catch {}
|
|
137
|
+
|
|
138
|
+
// ── 版本更新检查:启动时 + 周期性(默认 6 小时),发现新版本推送手机提醒 ──
|
|
139
|
+
// 限频与去重由 update-check 的缓存保证(同一新版本只提醒一次,未到期不访问网络)
|
|
140
|
+
const checkUpdate = async () => {
|
|
141
|
+
try {
|
|
142
|
+
await checkForUpdate({
|
|
143
|
+
config,
|
|
144
|
+
notify: makePhoneNotifier(config, { onLog }),
|
|
145
|
+
onLog,
|
|
146
|
+
});
|
|
147
|
+
} catch {}
|
|
148
|
+
};
|
|
149
|
+
await checkUpdate();
|
|
150
|
+
const intervalMs = (config.updateIntervalHours ?? 6) * 3600 * 1000;
|
|
151
|
+
setInterval(() => { checkUpdate().catch(() => {}); }, intervalMs).unref();
|
|
152
|
+
|
|
153
|
+
// ── DSH profile 自动发现:启动时 + 周期扫描,新装 profile 自动补挂插件 ──
|
|
154
|
+
ensureDshProfiles(onLog);
|
|
155
|
+
setInterval(() => { ensureDshProfiles(onLog); }, PROFILE_SCAN_INTERVAL_MS).unref();
|
|
156
|
+
|
|
157
|
+
// ── 桌面通知队列代发:hook 进程(尤其 ZCode)退出时会被执行端口杀进程树,
|
|
158
|
+
// fire-and-forget 的气泡来不及渲染;由常驻守护进程读取请求并弹窗 ──
|
|
159
|
+
setInterval(() => {
|
|
160
|
+
try { processNotifyQueue(); } catch {}
|
|
161
|
+
}, NOTIFY_SCAN_INTERVAL_MS).unref();
|
|
162
|
+
|
|
163
|
+
while (true) {
|
|
164
|
+
try {
|
|
165
|
+
const since = `since=${lastTime + 1}`; // 从最后收到的消息之后继续
|
|
166
|
+
const res = await fetch(`${url}?${since}`);
|
|
167
|
+
if (!res.ok) {
|
|
168
|
+
onLog(`连接失败(HTTP ${res.status}),${RETRY_DELAY / 1000} 秒后重连...`);
|
|
169
|
+
await sleep(RETRY_DELAY);
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
const reader = res.body.getReader();
|
|
173
|
+
const decoder = new TextDecoder();
|
|
174
|
+
let buffer = '';
|
|
175
|
+
while (true) {
|
|
176
|
+
const { done, value } = await reader.read();
|
|
177
|
+
if (done) break;
|
|
178
|
+
buffer += decoder.decode(value, { stream: true });
|
|
179
|
+
const lines = buffer.split('\n');
|
|
180
|
+
buffer = lines.pop();
|
|
181
|
+
for (const line of lines) {
|
|
182
|
+
if (!line.trim()) continue;
|
|
183
|
+
let event;
|
|
184
|
+
try {
|
|
185
|
+
event = JSON.parse(line);
|
|
186
|
+
} catch {
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
if (event.time) lastTime = Math.max(lastTime, Number(event.time));
|
|
190
|
+
// 有 title 的是系统推送通知(Claude Code 回复),不是手机用户消息,跳过
|
|
191
|
+
if (event.title) continue;
|
|
192
|
+
// 系统推送为 JSON 对象则忽略;纯文本/JSON 原始值(如手机发的单数字"3")作为续聊内容
|
|
193
|
+
const msg = parseNtfyMessage(event.message);
|
|
194
|
+
if (typeof msg === 'string' && msg.trim()) {
|
|
195
|
+
batcher.submit(msg.trim(), event.time ? Number(event.time) : null);
|
|
196
|
+
persistSnapshot();
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
onLog(`连接断开,${RETRY_DELAY / 1000} 秒后重连...`);
|
|
201
|
+
await sleep(RETRY_DELAY);
|
|
202
|
+
} catch (err) {
|
|
203
|
+
onLog(`连接异常(${err.message}),${RETRY_DELAY / 1000} 秒后重连...`);
|
|
204
|
+
await sleep(RETRY_DELAY);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
package/src/notify.mjs
CHANGED
|
@@ -1,36 +1,58 @@
|
|
|
1
1
|
// 系统原生通知(跨平台)
|
|
2
2
|
// 桌面通知的默认路径:守护进程在跑 → 写请求文件由守护进程代发(hook 进程,尤其 ZCode,
|
|
3
|
-
// 退出时会被执行端口杀掉整棵进程树,fire-and-forget
|
|
4
|
-
// 守护进程不在 → 直接 spawn
|
|
3
|
+
// 退出时会被执行端口杀掉整棵进程树,fire-and-forget 的通知来不及渲染);
|
|
4
|
+
// 守护进程不在 → 直接 spawn 弹通知(Claude Code / Codex / DSH 宿主进程常驻,可正常工作)。
|
|
5
|
+
// Windows 走 WinRT Toast(系统通知):NotifyIcon.ShowBalloonTip 在 Windows 11 上经常
|
|
6
|
+
// 不显示(旧系统托盘机制已被系统通知层取代),WinRT Toast 后台进程可可靠显示并进入操作中心。
|
|
5
7
|
import fs from 'fs';
|
|
6
8
|
import path from 'path';
|
|
7
9
|
import { spawn } from 'child_process';
|
|
8
10
|
import { DAEMON_JSON, NOTIFY_QUEUE_DIR, ensureDir } from './paths.mjs';
|
|
9
11
|
|
|
10
|
-
//
|
|
12
|
+
// WinRT Toast 脚本(Windows 10/11):标题/正文经环境变量传入,规避 PowerShell
|
|
13
|
+
// 引号与 XML 转义问题。AppId 必须用已注册的 AUMID,否则 Win10 1903+ 会静默丢弃
|
|
14
|
+
// 通知——a4phone 未打包注册,因此借 PowerShell 的注册 AUMID 显示
|
|
15
|
+
// (taost 归属显示为 Windows PowerShell;这是 BurntToast 等库的通用做法)。
|
|
16
|
+
const WINDOWS_POWERSHELL_AUMID = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe';
|
|
17
|
+
const WINDOWS_TOAST_SCRIPT = `$ErrorActionPreference = 'Stop'
|
|
18
|
+
Add-Type -AssemblyName System.Runtime.WindowsRuntime | Out-Null
|
|
19
|
+
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
|
|
20
|
+
[Windows.UI.Notifications.ToastNotification, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
|
|
21
|
+
[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null
|
|
22
|
+
function Xml-Escape([string]\$value) {
|
|
23
|
+
return \$value.Replace('&','&').Replace('<','<').Replace('>','>').Replace('"','"').Replace("'",''')
|
|
24
|
+
}
|
|
25
|
+
\$title = Xml-Escape \$env:A4P_TOAST_TITLE
|
|
26
|
+
\$body = Xml-Escape \$env:A4P_TOAST_BODY
|
|
27
|
+
\$xmlDocument = [Windows.Data.Xml.Dom.XmlDocument]::new()
|
|
28
|
+
\$xmlDocument.LoadXml("<toast><visual><binding template='ToastGeneric'><text>\$title</text><text>\$body</text></binding></visual></toast>")
|
|
29
|
+
\$toast = [Windows.UI.Notifications.ToastNotification]::new(\$xmlDocument)
|
|
30
|
+
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier(\$env:A4P_TOAST_APPID).Show(\$toast)`;
|
|
31
|
+
|
|
32
|
+
// 直接 spawn PowerShell 弹系统通知(低层原语,守护进程代发时用)
|
|
11
33
|
function showBalloon(title, message) {
|
|
12
34
|
// 立即返回,不阻塞调用方
|
|
13
35
|
const clean = (s) => (s || '').replace(/"/g, "'");
|
|
14
|
-
const t = clean(title);
|
|
15
|
-
const m = clean(message);
|
|
16
|
-
let cmd;
|
|
17
36
|
if (process.platform === 'win32') {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
37
|
+
const child = spawn('powershell', ['-NoProfile', '-Sta', '-WindowStyle', 'Hidden', '-Command', WINDOWS_TOAST_SCRIPT], {
|
|
38
|
+
env: {
|
|
39
|
+
...process.env,
|
|
40
|
+
A4P_TOAST_APPID: WINDOWS_POWERSHELL_AUMID,
|
|
41
|
+
A4P_TOAST_TITLE: String(title || '').slice(0, 64),
|
|
42
|
+
A4P_TOAST_BODY: String(message || '').slice(0, 256),
|
|
43
|
+
},
|
|
44
|
+
// windowsHide 隐藏 PowerShell 控制台窗口(否则每次弹通知都会闪出一个黑窗)
|
|
45
|
+
stdio: 'ignore',
|
|
46
|
+
windowsHide: true,
|
|
47
|
+
});
|
|
48
|
+
child.unref();
|
|
49
|
+
return;
|
|
27
50
|
}
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
: spawn('notify-send', cmd, { stdio: 'ignore' });
|
|
51
|
+
const t = clean(title);
|
|
52
|
+
const m = clean(message);
|
|
53
|
+
const child = process.platform === 'darwin'
|
|
54
|
+
? spawn('osascript', ['-e', `display notification "${m}" with title "${t}"`], { stdio: 'ignore' })
|
|
55
|
+
: spawn('notify-send', [t, m], { stdio: 'ignore' });
|
|
34
56
|
child.unref();
|
|
35
57
|
}
|
|
36
58
|
|