a4phone 1.7.2 → 1.8.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 +4 -0
- package/bin/a4p.mjs +4 -4
- package/dsh/lib/phone-hooks.mjs +4 -4
- package/package.json +1 -1
- package/src/asku.mjs +2 -2
- package/src/config.mjs +15 -11
- package/src/listen.mjs +3 -3
- package/src/notify.mjs +30 -6
- package/src/ntfy.mjs +46 -11
- package/src/permission.mjs +2 -2
- package/src/setup.mjs +16 -4
- package/src/stop.mjs +3 -2
- package/src/textclean.mjs +52 -0
- package/src/transcript.mjs +73 -0
- package/src/update-check.mjs +2 -2
package/README.md
CHANGED
|
@@ -320,6 +320,10 @@ node bin/a4p.mjs setup # 本地调试
|
|
|
320
320
|
|
|
321
321
|
[MIT](LICENSE)
|
|
322
322
|
|
|
323
|
+
## 致谢
|
|
324
|
+
|
|
325
|
+
- [@ningmengxr](https://github.com/ningmengxr):报告并提交了 DSH 集成中的两个缺陷——`cordis.patch.yml` 在出厂模板 `[]` 之后追加条目生成非法 YAML 导致 `dsh web` 无法启动([#1](https://github.com/eogee/a4phone/pull/1)),以及通知 `spawn` 未挂 `error` 监听、`ENOENT` 时拖垮宿主进程([#2](https://github.com/eogee/a4phone/pull/2))。1.7.3 的跨盘挂载改用 `file://` URL 修复,也是由这份报告定位的。
|
|
326
|
+
|
|
323
327
|
---
|
|
324
328
|
|
|
325
329
|
## 联系方式
|
package/bin/a4p.mjs
CHANGED
|
@@ -63,12 +63,12 @@ if (cmd && !['hook', '--version', '-v', 'version', 'help', '--help', '-h'].inclu
|
|
|
63
63
|
await notifier(latest);
|
|
64
64
|
// 终端提示之外再推送手机,确保用户不会遗落更新消息
|
|
65
65
|
if (cfg.topic) {
|
|
66
|
-
const
|
|
66
|
+
const result = await sendNotification({
|
|
67
67
|
...cfg,
|
|
68
68
|
title: 'a4phone',
|
|
69
69
|
message: `检测到新版本 ${latest}\n\n请运行:npm install -g a4phone 升级`,
|
|
70
70
|
});
|
|
71
|
-
if (!ok) throw new Error('手机推送失败');
|
|
71
|
+
if (!result.ok) throw new Error(result.reason || '手机推送失败');
|
|
72
72
|
}
|
|
73
73
|
},
|
|
74
74
|
}).catch(() => {});
|
|
@@ -190,8 +190,8 @@ if (cmd === '--version' || cmd === '-v' || cmd === 'version') {
|
|
|
190
190
|
console.error('未配置话题,请先运行 a4p setup。');
|
|
191
191
|
process.exit(1);
|
|
192
192
|
}
|
|
193
|
-
const
|
|
194
|
-
console.log(ok ? '测试通知发送成功。' :
|
|
193
|
+
const result = await sendNotification({ ...config, title: 'a4phone', message: '测试通知:如果手机收到,配置正常。' });
|
|
194
|
+
console.log(result.ok ? '测试通知发送成功。' : `发送失败:${result.reason}`);
|
|
195
195
|
} else if (cmd === 'help' || cmd === '--help' || cmd === '-h') {
|
|
196
196
|
showHelp();
|
|
197
197
|
} else {
|
package/dsh/lib/phone-hooks.mjs
CHANGED
|
@@ -118,13 +118,13 @@ export async function handleAskUserQuestion(exec) {
|
|
|
118
118
|
process.stderr.write(`[dsh-hook] 选项 ${options.length} 个超 ntfy 按钮上限(3),已降级为文字作答\n`);
|
|
119
119
|
}
|
|
120
120
|
|
|
121
|
-
const
|
|
121
|
+
const result = await sendNotification({
|
|
122
122
|
...cfg,
|
|
123
123
|
title: `DSH: ${q.header || 'Question'}`,
|
|
124
124
|
message: lines.join('\n'),
|
|
125
125
|
...(actions ? { actions } : {}),
|
|
126
126
|
});
|
|
127
|
-
if (!
|
|
127
|
+
if (!result.ok) return null; // 推送失败 → 回退终端
|
|
128
128
|
|
|
129
129
|
const resp = await waitForResponse({ ...cfg, requestId, timeout: cfg.timeout * 1000 });
|
|
130
130
|
if (!resp?.answer) return null; // 手机超时 → 回退终端
|
|
@@ -173,8 +173,8 @@ export async function handleApprovalRequest(req) {
|
|
|
173
173
|
{ action: 'http', label: 'Deny', url, method: 'POST', clear: false, body: JSON.stringify({ requestId, approved: false }) },
|
|
174
174
|
];
|
|
175
175
|
|
|
176
|
-
const
|
|
177
|
-
if (!
|
|
176
|
+
const result = await sendNotification({ ...cfg, title: `DSH: ${toolName}`, message, actions });
|
|
177
|
+
if (!result.ok) return null;
|
|
178
178
|
|
|
179
179
|
const resp = await waitForResponse({ ...cfg, requestId, timeout: cfg.timeout * 1000 });
|
|
180
180
|
if (!resp) return null; // 手机超时 → 回退
|
package/package.json
CHANGED
package/src/asku.mjs
CHANGED
|
@@ -63,13 +63,13 @@ export async function handleAskUserQuestion(input, agentName, agent = 'claude',
|
|
|
63
63
|
);
|
|
64
64
|
// 浏览器兜底:未订阅响应话题的用户可打开网页版直接回复(自由作答/编号回复都需要)
|
|
65
65
|
lines.push(`(如未订阅响应话题,可浏览器打开 ${config.server}/${config.topic}-response 直接回复)`);
|
|
66
|
-
const
|
|
66
|
+
const result = await sendNotification({
|
|
67
67
|
...config,
|
|
68
68
|
title: `${agentName}: ${q.header || 'Question'}`,
|
|
69
69
|
message: lines.join('\n'),
|
|
70
70
|
...(actions ? { actions } : {}),
|
|
71
71
|
});
|
|
72
|
-
if (!
|
|
72
|
+
if (!result.ok) return null; // 推送失败 → 回退终端
|
|
73
73
|
// waitSeconds 由调用方按宿主 hook 超时约束收窄(WorkBuddy 会被截到 45s),未传入回退配置值
|
|
74
74
|
const wait = waitSeconds ?? config.timeout;
|
|
75
75
|
const resp = await waitForResponse({ ...config, requestId, timeout: wait * 1000 });
|
package/src/config.mjs
CHANGED
|
@@ -4,22 +4,26 @@ import { CONFIG_PATH, LAST_PATH, ensureDir } from './paths.mjs';
|
|
|
4
4
|
|
|
5
5
|
export { CONFIG_PATH, LAST_PATH } from './paths.mjs'; // 兼容旧引用
|
|
6
6
|
|
|
7
|
+
export function normalizeConfig(cfg = {}) {
|
|
8
|
+
return {
|
|
9
|
+
topic: cfg.topic || '',
|
|
10
|
+
server: (cfg.server || 'https://ntfy.sh').replace(/\/+$/, ''),
|
|
11
|
+
token: String(cfg.token || '').trim(),
|
|
12
|
+
timeout: cfg.timeout ?? 60,
|
|
13
|
+
planTimeout: cfg.planTimeout ?? 300,
|
|
14
|
+
resumeTimeout: cfg.resumeTimeout ?? 1800, // 续聊超时(秒),默认 30 分钟
|
|
15
|
+
checkUpdates: cfg.checkUpdates ?? true, // 版本更新检查(守护进程推手机 / 命令终端提示)
|
|
16
|
+
updateIntervalHours: cfg.updateIntervalHours ?? 6, // 检查间隔(小时)
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
|
|
7
20
|
export function loadConfig() {
|
|
8
21
|
try {
|
|
9
22
|
let raw = fs.readFileSync(CONFIG_PATH, 'utf-8');
|
|
10
23
|
if (raw.charCodeAt(0) === 0xfeff) raw = raw.slice(1); // 剥离 UTF-8 BOM(PowerShell 写入可能带)
|
|
11
|
-
|
|
12
|
-
return {
|
|
13
|
-
topic: cfg.topic || '',
|
|
14
|
-
server: (cfg.server || 'https://ntfy.sh').replace(/\/+$/, ''),
|
|
15
|
-
timeout: cfg.timeout ?? 60,
|
|
16
|
-
planTimeout: cfg.planTimeout ?? 300,
|
|
17
|
-
resumeTimeout: cfg.resumeTimeout ?? 1800, // 续聊超时(秒),默认 30 分钟
|
|
18
|
-
checkUpdates: cfg.checkUpdates ?? true, // 版本更新检查(守护进程推手机 / 命令终端提示)
|
|
19
|
-
updateIntervalHours: cfg.updateIntervalHours ?? 6, // 检查间隔(小时)
|
|
20
|
-
};
|
|
24
|
+
return normalizeConfig(JSON.parse(raw));
|
|
21
25
|
} catch {
|
|
22
|
-
return
|
|
26
|
+
return normalizeConfig();
|
|
23
27
|
}
|
|
24
28
|
}
|
|
25
29
|
|
package/src/listen.mjs
CHANGED
|
@@ -12,7 +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
|
+
import { ntfyAuthHeaders, ntfyFailureReason, parseNtfyMessage } from './ntfy.mjs';
|
|
16
16
|
import { processNotifyQueue } from './notify.mjs';
|
|
17
17
|
import { PENDING_PATH, ensureDir } from './paths.mjs';
|
|
18
18
|
import { configureDsh } from './setup.mjs';
|
|
@@ -163,9 +163,9 @@ export async function runListen({ onLog = (s) => console.log(s) } = {}) {
|
|
|
163
163
|
while (true) {
|
|
164
164
|
try {
|
|
165
165
|
const since = `since=${lastTime + 1}`; // 从最后收到的消息之后继续
|
|
166
|
-
const res = await fetch(`${url}?${since}
|
|
166
|
+
const res = await fetch(`${url}?${since}`, { headers: ntfyAuthHeaders(config.token) });
|
|
167
167
|
if (!res.ok) {
|
|
168
|
-
onLog(
|
|
168
|
+
onLog(`连接失败(${ntfyFailureReason(res.status)}),${RETRY_DELAY / 1000} 秒后重连...`);
|
|
169
169
|
await sleep(RETRY_DELAY);
|
|
170
170
|
continue;
|
|
171
171
|
}
|
package/src/notify.mjs
CHANGED
|
@@ -29,12 +29,36 @@ function Xml-Escape([string]\$value) {
|
|
|
29
29
|
\$toast = [Windows.UI.Notifications.ToastNotification]::new(\$xmlDocument)
|
|
30
30
|
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier(\$env:A4P_TOAST_APPID).Show(\$toast)`;
|
|
31
31
|
|
|
32
|
+
// PowerShell 绝对路径(不走 PATH 解析:部分宿主进程的 PATH 不含
|
|
33
|
+
// System32\WindowsPowerShell\v1.0,spawn('powershell') 会直接 ENOENT)
|
|
34
|
+
function powershellExe() {
|
|
35
|
+
const root = process.env.SystemRoot || process.env.windir;
|
|
36
|
+
if (root) {
|
|
37
|
+
const abs = path.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
|
38
|
+
try { if (fs.existsSync(abs)) return abs; } catch {}
|
|
39
|
+
}
|
|
40
|
+
return 'powershell'; // 找不到就回退 PATH 解析,失败由 error 监听器兜住
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// spawn 一个脱离的子进程弹通知。
|
|
44
|
+
// 关键:spawn 失败(ENOENT 等)是以 'error' 事件抛出的,没有监听器时属于
|
|
45
|
+
// unhandled error,会直接杀掉宿主进程——DSH/Codex 这类常驻进程每次任务完成都
|
|
46
|
+
// 调通知,一旦 PATH 异常就表现为“每完成一个任务进程就退出”。通知是尽力而为,
|
|
47
|
+
// 失败必须静默降级。
|
|
48
|
+
// 导出仅为便于单测覆盖监听器是否存在。
|
|
49
|
+
export function spawnDetached(cmd, args, opts) {
|
|
50
|
+
const child = spawn(cmd, args, opts);
|
|
51
|
+
child.on('error', () => {});
|
|
52
|
+
child.unref();
|
|
53
|
+
return child;
|
|
54
|
+
}
|
|
55
|
+
|
|
32
56
|
// 直接 spawn PowerShell 弹系统通知(低层原语,守护进程代发时用)
|
|
33
57
|
function showBalloon(title, message) {
|
|
34
58
|
// 立即返回,不阻塞调用方
|
|
35
59
|
const clean = (s) => (s || '').replace(/"/g, "'");
|
|
36
60
|
if (process.platform === 'win32') {
|
|
37
|
-
|
|
61
|
+
spawnDetached(powershellExe(), ['-NoProfile', '-Sta', '-WindowStyle', 'Hidden', '-Command', WINDOWS_TOAST_SCRIPT], {
|
|
38
62
|
env: {
|
|
39
63
|
...process.env,
|
|
40
64
|
A4P_TOAST_APPID: WINDOWS_POWERSHELL_AUMID,
|
|
@@ -45,15 +69,15 @@ function showBalloon(title, message) {
|
|
|
45
69
|
stdio: 'ignore',
|
|
46
70
|
windowsHide: true,
|
|
47
71
|
});
|
|
48
|
-
child.unref();
|
|
49
72
|
return;
|
|
50
73
|
}
|
|
51
74
|
const t = clean(title);
|
|
52
75
|
const m = clean(message);
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
76
|
+
if (process.platform === 'darwin') {
|
|
77
|
+
spawnDetached('osascript', ['-e', `display notification "${m}" with title "${t}"`], { stdio: 'ignore' });
|
|
78
|
+
} else {
|
|
79
|
+
spawnDetached('notify-send', [t, m], { stdio: 'ignore' });
|
|
80
|
+
}
|
|
57
81
|
}
|
|
58
82
|
|
|
59
83
|
// 守护进程是否在运行(读 daemon.json 的 pid 探测存活)
|
package/src/ntfy.mjs
CHANGED
|
@@ -18,28 +18,63 @@ export function parseNtfyMessage(raw) {
|
|
|
18
18
|
}
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
-
export
|
|
21
|
+
export const MAX_MESSAGE_BYTES = 4096;
|
|
22
|
+
const DEFAULT_TIMEOUT_MS = 8000;
|
|
23
|
+
|
|
24
|
+
export function ntfyAuthHeaders(token) {
|
|
25
|
+
const value = String(token || '').trim();
|
|
26
|
+
return value ? { Authorization: `Bearer ${value}` } : {};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function ntfyFailureReason(status) {
|
|
30
|
+
if (status === 403) return 'HTTP 403(令牌无效或话题无访问权限)';
|
|
31
|
+
if (status === 429) return 'HTTP 429(触发服务限速,请降低推送频率)';
|
|
32
|
+
return `HTTP ${status}`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function truncateUtf8(text, maxBytes = MAX_MESSAGE_BYTES) {
|
|
36
|
+
if (maxBytes <= 0) return '';
|
|
37
|
+
const value = String(text ?? '');
|
|
38
|
+
const buffer = Buffer.from(value, 'utf8');
|
|
39
|
+
if (buffer.length <= maxBytes) return value;
|
|
40
|
+
const suffix = '...';
|
|
41
|
+
if (maxBytes <= suffix.length) return suffix.slice(0, maxBytes);
|
|
42
|
+
let end = maxBytes - suffix.length;
|
|
43
|
+
// Back up to a UTF-8 character boundary so the suffix never follows a broken character.
|
|
44
|
+
while (end > 0 && (buffer[end] & 0xc0) === 0x80) end--;
|
|
45
|
+
return buffer.subarray(0, end).toString('utf8') + suffix;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function sendNotification({ server, topic, title, message, actions, token, timeoutMs = DEFAULT_TIMEOUT_MS }) {
|
|
49
|
+
if (!topic) return { ok: false, reason: '话题未配置' };
|
|
50
|
+
const controller = new AbortController();
|
|
51
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
22
52
|
try {
|
|
23
53
|
const res = await fetch(server, {
|
|
24
54
|
method: 'POST',
|
|
25
|
-
headers: { 'Content-Type': 'application/json' },
|
|
26
|
-
body: JSON.stringify({ topic, title, message, actions }),
|
|
55
|
+
headers: { 'Content-Type': 'application/json', ...ntfyAuthHeaders(token) },
|
|
56
|
+
body: JSON.stringify({ topic, title, message: truncateUtf8(message), actions }),
|
|
57
|
+
signal: controller.signal,
|
|
27
58
|
});
|
|
28
|
-
return res.ok;
|
|
29
|
-
} catch {
|
|
30
|
-
|
|
59
|
+
return res.ok ? { ok: true, reason: '' } : { ok: false, reason: ntfyFailureReason(res.status) };
|
|
60
|
+
} catch (error) {
|
|
61
|
+
const timedOut = error?.name === 'AbortError' || error?.name === 'TimeoutError';
|
|
62
|
+
return { ok: false, reason: timedOut ? '请求超时' : (error?.message || String(error)) };
|
|
63
|
+
} finally {
|
|
64
|
+
clearTimeout(timer);
|
|
31
65
|
}
|
|
32
66
|
}
|
|
33
67
|
|
|
34
68
|
// 订阅响应话题(NDJSON 流),等待决策
|
|
35
69
|
// HTTP action 回传:正文为 JSON { requestId, answer },仅匹配相同 requestId
|
|
36
70
|
// 手机自由文本:正文为纯文本,无 requestId,直接作为答案接受
|
|
37
|
-
export async function waitForResponse({ server, topic, requestId, timeout }) {
|
|
71
|
+
export async function waitForResponse({ server, topic, requestId, timeout, token }) {
|
|
38
72
|
const url = `${server}/${topic}-response/json`;
|
|
39
73
|
const controller = new AbortController();
|
|
40
74
|
const timer = setTimeout(() => controller.abort(), timeout);
|
|
41
75
|
try {
|
|
42
|
-
const res = await fetch(url, { signal: controller.signal });
|
|
76
|
+
const res = await fetch(url, { signal: controller.signal, headers: ntfyAuthHeaders(token) });
|
|
77
|
+
if (!res.ok) return null;
|
|
43
78
|
const reader = res.body.getReader();
|
|
44
79
|
const decoder = new TextDecoder();
|
|
45
80
|
let buffer = '';
|
|
@@ -60,14 +95,14 @@ export async function waitForResponse({ server, topic, requestId, timeout }) {
|
|
|
60
95
|
const msg = typeof parsed === 'object' ? parsed : { answer: parsed };
|
|
61
96
|
// action 回执:requestId 必须匹配;自由文本:无 requestId 且有 answer 才接受
|
|
62
97
|
if (msg.requestId === requestId || (msg.requestId === undefined && msg.answer)) {
|
|
63
|
-
clearTimeout(timer);
|
|
64
98
|
controller.abort();
|
|
65
99
|
return msg;
|
|
66
100
|
}
|
|
67
101
|
} catch {}
|
|
68
102
|
}
|
|
69
103
|
}
|
|
70
|
-
} catch {}
|
|
71
|
-
|
|
104
|
+
} catch {} finally {
|
|
105
|
+
clearTimeout(timer);
|
|
106
|
+
}
|
|
72
107
|
return null;
|
|
73
108
|
}
|
package/src/permission.mjs
CHANGED
|
@@ -48,8 +48,8 @@ export async function handlePermissionRequest(input, agentName, waitSeconds) {
|
|
|
48
48
|
actions.splice(1, 0, { action: 'http', label: 'Always Approve', url, method: 'POST', clear: false, body: JSON.stringify({ requestId, approved: true, alwaysAllow: true }) });
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
-
const
|
|
52
|
-
if (!
|
|
51
|
+
const result = await sendNotification({ ...config, title: `${agentName}: ${tool_name}`, message, actions });
|
|
52
|
+
if (!result.ok) return null;
|
|
53
53
|
|
|
54
54
|
const isPlan = tool_name === 'ExitPlanMode';
|
|
55
55
|
// waitSeconds 由调用方按宿主 hook 超时约束收窄(WorkBuddy 上限 60s,会被截到 45s);
|
package/src/setup.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import crypto from 'crypto';
|
|
|
3
3
|
import fs from 'fs';
|
|
4
4
|
import os from 'os';
|
|
5
5
|
import path from 'path';
|
|
6
|
-
import { fileURLToPath } from 'url';
|
|
6
|
+
import { fileURLToPath, pathToFileURL } from 'url';
|
|
7
7
|
import { loadConfig, saveConfig } from './config.mjs';
|
|
8
8
|
|
|
9
9
|
const SETTINGS_PATH = path.join(os.homedir(), '.claude', 'settings.json');
|
|
@@ -353,7 +353,8 @@ export function unconfigureZcode(zcodePath = ZCODE_CONFIG_PATH) {
|
|
|
353
353
|
// 以 insert 形式追加到各 profile 的 cordis.patch.yml(热生效,无需重启)。
|
|
354
354
|
// profile 发现机制:扫描 ~/.dsh/profiles/ 下所有含 cordis.yml 的子目录
|
|
355
355
|
// (web / tui / dsh-tui 及后续新装的变体均可覆盖),插件 name 按各 profile
|
|
356
|
-
//
|
|
356
|
+
// 目录分别计算(同盘相对路径;跨盘退化为 file:// URL,见 dshPluginName);
|
|
357
|
+
// 守护进程(a4p listen)周期重扫,新装 profile 自动补挂。
|
|
357
358
|
const DSH_PROFILES_DIR = path.join(os.homedir(), '.dsh', 'profiles');
|
|
358
359
|
const DSH_MARKER_START = '# ===== a4phone dsh-hook (auto-generated) =====';
|
|
359
360
|
const DSH_MARKER_END = '# ===== end a4phone dsh-hook =====';
|
|
@@ -368,6 +369,17 @@ function toPosix(p) {
|
|
|
368
369
|
return p.split(path.sep).join('/');
|
|
369
370
|
}
|
|
370
371
|
|
|
372
|
+
// 计算挂载条目里的插件 name(DSH loader 把它当 URL 解析):
|
|
373
|
+
// 同盘 → profile 相对路径(可移植,profile 目录整体搬家后仍有效);
|
|
374
|
+
// 跨盘 → Windows 的 path.relative 会直接返回绝对路径(如 E:/a4phone/...),
|
|
375
|
+
// loader 会把 `e:` 当成 URL 协议,启动即报 ERR_UNSUPPORTED_ESM_URL_SCHEME。
|
|
376
|
+
// 这种情况改用 file:// URL(唯一合法的 Windows 绝对路径写法)。
|
|
377
|
+
function dshPluginName(profileDir, pluginEntry) {
|
|
378
|
+
const rel = path.relative(profileDir, pluginEntry);
|
|
379
|
+
if (path.isAbsolute(rel)) return pathToFileURL(pluginEntry).href;
|
|
380
|
+
return toPosix(rel);
|
|
381
|
+
}
|
|
382
|
+
|
|
371
383
|
// 生成 dsh-hook 的 patch 挂载块(marker 包裹,便于幂等替换/清理)
|
|
372
384
|
function dshHookBlock(relName) {
|
|
373
385
|
return `${DSH_MARKER_START}\n- insert:\n - id: dsh-hook\n name: "${relName}"\n${DSH_MARKER_END}`;
|
|
@@ -433,8 +445,8 @@ function mountDshHook({ profileDir, pluginEntry }) {
|
|
|
433
445
|
let content = '';
|
|
434
446
|
try { content = fs.readFileSync(patchPath, 'utf-8'); } catch {}
|
|
435
447
|
|
|
436
|
-
//
|
|
437
|
-
const rel =
|
|
448
|
+
// 已挂载本插件的最新路径 → 幂等跳过
|
|
449
|
+
const rel = dshPluginName(profileDir, pluginEntry);
|
|
438
450
|
const block = dshHookBlock(rel);
|
|
439
451
|
if (content.includes(DSH_MARKER_START) && content.includes(block)) return false;
|
|
440
452
|
|
package/src/stop.mjs
CHANGED
|
@@ -2,12 +2,13 @@
|
|
|
2
2
|
import { loadConfig, saveLastSession } from './config.mjs';
|
|
3
3
|
import { sendNotification } from './ntfy.mjs';
|
|
4
4
|
import { systemNotify } from './notify.mjs';
|
|
5
|
-
import { resolveLastOutput } from './transcript.mjs';
|
|
5
|
+
import { resolveLastOutput, resolveSessionTopic } from './transcript.mjs';
|
|
6
6
|
|
|
7
7
|
export async function handleStop(input, agentName) {
|
|
8
8
|
const config = loadConfig();
|
|
9
9
|
const cwd = input.cwd || '未知目录';
|
|
10
10
|
const session = input.session_id ? input.session_id.slice(0, 8) : '—';
|
|
11
|
+
const title = resolveSessionTopic(input, agentName);
|
|
11
12
|
const details = `任务已完成\n目录: ${cwd}\n会话: ${session}`;
|
|
12
13
|
|
|
13
14
|
// 记录最近会话,供续聊(a4p resume / a4p listen)使用
|
|
@@ -26,7 +27,7 @@ export async function handleStop(input, agentName) {
|
|
|
26
27
|
const message = lastOutput ? `${details}\n\nAI 最后输出:\n${lastOutput}` : details;
|
|
27
28
|
await sendNotification({
|
|
28
29
|
...config,
|
|
29
|
-
title
|
|
30
|
+
title,
|
|
30
31
|
message,
|
|
31
32
|
});
|
|
32
33
|
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
const INJECTED_TAG_BLOCKS = [
|
|
2
|
+
'system-reminder',
|
|
3
|
+
'user_instructions',
|
|
4
|
+
'environment_context',
|
|
5
|
+
'INSTRUCTIONS',
|
|
6
|
+
'task-notification',
|
|
7
|
+
'long_text_quote',
|
|
8
|
+
'image_local_path',
|
|
9
|
+
];
|
|
10
|
+
|
|
11
|
+
const INJECTED_LINE_PATTERNS = [
|
|
12
|
+
/^# AGENTS\.md instructions[^\n]*(?:\n|$)/gm,
|
|
13
|
+
/^Caveat:[^\n]*(?:\n|$)/gm,
|
|
14
|
+
/^Use the TaskOutput tool with task_id=[^\n]*(?:\n|$)/gm,
|
|
15
|
+
/^\[SYSTEM NOTIFICATION - NOT USER INPUT\][^\n]*(?:\n|$)/gm,
|
|
16
|
+
];
|
|
17
|
+
|
|
18
|
+
const USER_QUERY_SHELL = /<\/?user_query\b[^>]*>/gi;
|
|
19
|
+
const IMAGE_TOKEN = /@image#\d+\s*:\s*(?:"[^"\n]*"|[^\s"\n]+)\s*/gi;
|
|
20
|
+
const LONG_TEXT_TOKEN = /@long[-_]text\s*:\s*"([^"\n]*)"\s*/gi;
|
|
21
|
+
const SKILL_TOKEN = /@skill\s*:\s*"([^"\n]*)"\s*/gi;
|
|
22
|
+
const QUOTED_REF = /@"[^"\n]*"\s*/gi;
|
|
23
|
+
|
|
24
|
+
function skillName(value) {
|
|
25
|
+
const parts = value.replaceAll('\\', '/').split('/').filter(Boolean);
|
|
26
|
+
if (parts.at(-1)?.toLowerCase() === 'skill.md') parts.pop();
|
|
27
|
+
return parts.at(-1) || '';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function stripHostMarkup(text) {
|
|
31
|
+
let value = String(text ?? '');
|
|
32
|
+
// Only strip known host tags so user-supplied HTML/XML survives.
|
|
33
|
+
for (const tag of INJECTED_TAG_BLOCKS) {
|
|
34
|
+
value = value.replace(new RegExp(`<${tag}\\b[^>]*>.*?</${tag}>`, 'gis'), '');
|
|
35
|
+
}
|
|
36
|
+
for (const pattern of INJECTED_LINE_PATTERNS) value = value.replace(pattern, '');
|
|
37
|
+
value = value.replace(USER_QUERY_SHELL, '');
|
|
38
|
+
value = value.replace(LONG_TEXT_TOKEN, (_, preview) => preview.replace(/[..…]+$/, '') + ' ');
|
|
39
|
+
value = value.replace(SKILL_TOKEN, (_, value) => skillName(value) + ' ');
|
|
40
|
+
value = value.replace(IMAGE_TOKEN, '');
|
|
41
|
+
return value.replace(QUOTED_REF, '').trim();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function oneLine(text, maxLength = 80) {
|
|
45
|
+
const cleaned = String(text ?? '').replace(/\s+/g, ' ').trim();
|
|
46
|
+
if (!cleaned) return '';
|
|
47
|
+
return cleaned.length > maxLength ? cleaned.slice(0, maxLength) + '...' : cleaned;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function cleanTitle(text, maxLength = 80) {
|
|
51
|
+
return oneLine(stripHostMarkup(text), maxLength);
|
|
52
|
+
}
|
package/src/transcript.mjs
CHANGED
|
@@ -11,8 +11,11 @@
|
|
|
11
11
|
// (三个字段都与 Claude Code 不同:type 不是 assistant、role 不在 message.role、
|
|
12
12
|
// 块类型不是 text),会话文件 ~/.workbuddy/projects/<slug>/<sessionId>.jsonl
|
|
13
13
|
import fs from 'fs';
|
|
14
|
+
import path from 'path';
|
|
15
|
+
import { cleanTitle, oneLine, stripHostMarkup } from './textclean.mjs';
|
|
14
16
|
|
|
15
17
|
const MAX_LENGTH = 1000; // 推送内容截断长度(中文约 3000 字节,留足 ntfy 4KB 上限余量)
|
|
18
|
+
const FIRST_PROMPT_READ_BYTES = 256 * 1024;
|
|
16
19
|
|
|
17
20
|
// 截断/清洗:空文本返回 null(extractLastOutput 与直送字段共用同一上限)
|
|
18
21
|
export function clampOutput(text) {
|
|
@@ -73,3 +76,73 @@ export function extractLastOutput(transcriptPath) {
|
|
|
73
76
|
export function resolveLastOutput({ last_assistant_message, transcript_path } = {}) {
|
|
74
77
|
return clampOutput(last_assistant_message) ?? extractLastOutput(transcript_path);
|
|
75
78
|
}
|
|
79
|
+
|
|
80
|
+
function textBlocks(content, types) {
|
|
81
|
+
if (!Array.isArray(content)) return null;
|
|
82
|
+
const parts = content
|
|
83
|
+
.filter((block) => block && types.includes(block.type) && block.text)
|
|
84
|
+
.map((block) => block.text);
|
|
85
|
+
return parts.length ? parts.join('\n') : null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function userText(record) {
|
|
89
|
+
const message = record?.message;
|
|
90
|
+
if (record?.type === 'user' || message?.role === 'user') {
|
|
91
|
+
if (typeof message?.content === 'string') return message.content;
|
|
92
|
+
const text = textBlocks(message?.content, ['text', 'input_text']);
|
|
93
|
+
if (text) return text;
|
|
94
|
+
}
|
|
95
|
+
if (record?.type === 'message' && record.role === 'user') {
|
|
96
|
+
const text = textBlocks(record.content, ['input_text', 'output_text', 'text']);
|
|
97
|
+
if (text) return text;
|
|
98
|
+
}
|
|
99
|
+
if (record?.type === 'response_item' && record.payload?.type === 'message' && record.payload.role === 'user') {
|
|
100
|
+
return textBlocks(record.payload.content, ['input_text', 'text']);
|
|
101
|
+
}
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function readHead(transcriptPath, maxBytes) {
|
|
106
|
+
let fd;
|
|
107
|
+
try {
|
|
108
|
+
fd = fs.openSync(transcriptPath, 'r');
|
|
109
|
+
const buffer = Buffer.alloc(maxBytes);
|
|
110
|
+
const bytesRead = fs.readSync(fd, buffer, 0, maxBytes, 0);
|
|
111
|
+
return buffer.subarray(0, bytesRead).toString('utf8');
|
|
112
|
+
} catch {
|
|
113
|
+
return '';
|
|
114
|
+
} finally {
|
|
115
|
+
if (fd !== undefined) {
|
|
116
|
+
try { fs.closeSync(fd); } catch {}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function extractFirstPrompt(transcriptPath, maxLength = 80, maxBytes = FIRST_PROMPT_READ_BYTES) {
|
|
122
|
+
if (!transcriptPath || maxBytes <= 0) return null;
|
|
123
|
+
for (const line of readHead(transcriptPath, maxBytes).split('\n')) {
|
|
124
|
+
if (!line.trim()) continue;
|
|
125
|
+
let record;
|
|
126
|
+
try {
|
|
127
|
+
record = JSON.parse(line);
|
|
128
|
+
} catch {
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
if (!record || typeof record !== 'object') continue;
|
|
132
|
+
const text = userText(record);
|
|
133
|
+
if (!text?.trim()) continue;
|
|
134
|
+
const title = oneLine(stripHostMarkup(text), maxLength);
|
|
135
|
+
if (title) return title;
|
|
136
|
+
}
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function resolveSessionTopic({ transcript_path, cwd } = {}, fallback = '') {
|
|
141
|
+
const prompt = extractFirstPrompt(transcript_path);
|
|
142
|
+
if (prompt) return prompt;
|
|
143
|
+
if (cwd && cwd !== '未知目录') {
|
|
144
|
+
const title = cleanTitle(path.basename(String(cwd).trim()));
|
|
145
|
+
if (title) return title;
|
|
146
|
+
}
|
|
147
|
+
return fallback;
|
|
148
|
+
}
|
package/src/update-check.mjs
CHANGED
|
@@ -165,12 +165,12 @@ export async function checkForUpdate({
|
|
|
165
165
|
export function makePhoneNotifier(config, { localVersion = getLocalVersion(), onLog = () => {} } = {}) {
|
|
166
166
|
return async (latest) => {
|
|
167
167
|
onLog(`检测到新版本 ${latest}(当前 ${localVersion}),已推送手机提醒`);
|
|
168
|
-
const
|
|
168
|
+
const result = await sendNotification({
|
|
169
169
|
...config,
|
|
170
170
|
title: 'a4phone',
|
|
171
171
|
message: `检测到新版本 ${latest}(当前 ${localVersion})\n\n请运行:npm install -g a4phone 升级`,
|
|
172
172
|
});
|
|
173
|
-
if (!ok) throw new Error('手机推送失败');
|
|
173
|
+
if (!result.ok) throw new Error(result.reason || '手机推送失败');
|
|
174
174
|
};
|
|
175
175
|
}
|
|
176
176
|
|