a4phone 1.1.4 → 1.1.6

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/package.json CHANGED
@@ -1,18 +1,22 @@
1
1
  {
2
2
  "name": "a4phone",
3
- "version": "1.1.4",
4
- "description": "Claude Code / Codex 远程手机交互:任务完成通知、AskUserQuestion 提问与 PermissionRequest 权限请求手机点选(ntfy.sh)",
3
+ "version": "1.1.6",
4
+ "description": "Claude Code / Codex 远程手机交互:任务完成通知(含 AI 最后输出)、提问/权限请求手机点选或文字作答、远程续聊(ntfy.sh)",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "a4p": "bin/a4p.mjs"
8
8
  },
9
9
  "files": [
10
10
  "bin",
11
- "src"
11
+ "src",
12
+ "dsh"
12
13
  ],
13
14
  "engines": {
14
15
  "node": ">=18"
15
16
  },
17
+ "scripts": {
18
+ "test": "node --test"
19
+ },
16
20
  "dependencies": {
17
21
  "qrcode-terminal": "^0.12.0"
18
22
  },
package/src/asku.mjs CHANGED
@@ -3,7 +3,34 @@ import crypto from 'crypto';
3
3
  import { loadConfig } from './config.mjs';
4
4
  import { sendNotification, waitForResponse } from './ntfy.mjs';
5
5
 
6
- export async function handleAskUserQuestion(input, agentName) {
6
+ // 把手机答案构造成 hook 输出
7
+ // Claude Code:updatedInput.answers 改写工具输入(工具自带跳过用户交互的实现)
8
+ // Codex:提问工具是 request_user_input,其 handler 忽略输入里的 answers,只能阻断该工具调用、
9
+ // 并把答案写进 permissionDecisionReason,让模型看到"用户已作答"后直接采用答案继续
10
+ export function buildAskOutput(agent, questions, answers) {
11
+ if (agent === 'codex') {
12
+ const lines = Object.entries(answers).map(([q, a], i) => `${i + 1}. ${q} → ${a}`);
13
+ const reason =
14
+ '用户在手机端回答了以下提问,请直接采用这些答案继续当前任务,不要再调用 request_user_input 工具:\n' +
15
+ lines.join('\n');
16
+ return {
17
+ hookSpecificOutput: {
18
+ hookEventName: 'PreToolUse',
19
+ permissionDecision: 'deny',
20
+ permissionDecisionReason: reason,
21
+ },
22
+ };
23
+ }
24
+ return {
25
+ hookSpecificOutput: {
26
+ hookEventName: 'PreToolUse',
27
+ permissionDecision: 'allow',
28
+ updatedInput: { questions, answers },
29
+ },
30
+ };
31
+ }
32
+
33
+ export async function handleAskUserQuestion(input, agentName, agent = 'claude') {
7
34
  const config = loadConfig();
8
35
  const questions = input.tool_input?.questions || [];
9
36
  if (!config.topic || !questions.length) return null;
@@ -23,6 +50,8 @@ export async function handleAskUserQuestion(input, agentName) {
23
50
  }));
24
51
  const lines = [q.question];
25
52
  options.forEach((o, i) => lines.push(`${i + 1}. ${o.label}`));
53
+ lines.push(''); // 留空行分隔
54
+ lines.push(`(也可直接向话题 ${config.topic}-response 发送文字作答)`);
26
55
  const sent = await sendNotification({
27
56
  ...config,
28
57
  title: `${agentName}: ${q.header || 'Question'}`,
@@ -35,11 +64,5 @@ export async function handleAskUserQuestion(input, agentName) {
35
64
  answers[q.question] = resp.answer;
36
65
  }
37
66
 
38
- return {
39
- hookSpecificOutput: {
40
- hookEventName: 'PreToolUse',
41
- permissionDecision: 'allow',
42
- updatedInput: { questions, answers },
43
- },
44
- };
67
+ return buildAskOutput(agent, questions, answers);
45
68
  }
package/src/config.mjs CHANGED
@@ -1,24 +1,43 @@
1
- // 配置读写:~/.a4phone.json
1
+ // 配置读写:~/.a4phone/config.json
2
2
  import fs from 'fs';
3
- import os from 'os';
4
- import path from 'path';
3
+ import { CONFIG_PATH, LAST_PATH, ensureDir } from './paths.mjs';
5
4
 
6
- export const CONFIG_PATH = path.join(os.homedir(), '.a4phone.json');
5
+ export { CONFIG_PATH, LAST_PATH } from './paths.mjs'; // 兼容旧引用
7
6
 
8
7
  export function loadConfig() {
9
8
  try {
10
- const cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
9
+ let raw = fs.readFileSync(CONFIG_PATH, 'utf-8');
10
+ if (raw.charCodeAt(0) === 0xfeff) raw = raw.slice(1); // 剥离 UTF-8 BOM(PowerShell 写入可能带)
11
+ const cfg = JSON.parse(raw);
11
12
  return {
12
13
  topic: cfg.topic || '',
13
14
  server: (cfg.server || 'https://ntfy.sh').replace(/\/+$/, ''),
14
- timeout: cfg.timeout ?? 30,
15
+ timeout: cfg.timeout ?? 60,
15
16
  planTimeout: cfg.planTimeout ?? 300,
17
+ resumeTimeout: cfg.resumeTimeout ?? 1800, // 续聊超时(秒),默认 30 分钟
16
18
  };
17
19
  } catch {
18
- return { topic: '', server: 'https://ntfy.sh', timeout: 30, planTimeout: 300 };
20
+ return { topic: '', server: 'https://ntfy.sh', timeout: 60, planTimeout: 300, resumeTimeout: 1800 };
19
21
  }
20
22
  }
21
23
 
22
24
  export function saveConfig(cfg) {
25
+ ensureDir();
23
26
  fs.writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2));
24
27
  }
28
+
29
+ // 最近会话记录:Stop 事件写入,供续聊(a4p resume / a4p listen)读取
30
+ export function loadLastSession() {
31
+ try {
32
+ let raw = fs.readFileSync(LAST_PATH, 'utf-8');
33
+ if (raw.charCodeAt(0) === 0xfeff) raw = raw.slice(1); // 剥离 UTF-8 BOM
34
+ return JSON.parse(raw);
35
+ } catch {
36
+ return null;
37
+ }
38
+ }
39
+
40
+ export function saveLastSession(session) {
41
+ ensureDir();
42
+ fs.writeFileSync(LAST_PATH, JSON.stringify({ ...session, ts: Date.now() }, null, 2));
43
+ }
package/src/daemon.mjs ADDED
@@ -0,0 +1,108 @@
1
+ // 后台守护进程管理:启动、停止、状态查询
2
+ // 启动:spawn 一个隐藏的 Node 子进程运行 a4p listen --daemon-child
3
+ // 停止:读取 PID 文件,taskkill 进程树
4
+ // 状态:检查 PID 是否存活
5
+ import { spawn } from 'child_process';
6
+ import fs from 'fs';
7
+ import path from 'path';
8
+ import os from 'os';
9
+ import { DAEMON_JSON, LOG_PATH, ensureDir } from './paths.mjs';
10
+
11
+ function getScriptPath() {
12
+ // 优先用 process.argv[1](调用入口),兜底用模块路径
13
+ return process.argv[1] || path.join(os.homedir(), 'bin', 'a4p.mjs');
14
+ }
15
+
16
+ function isProcessAlive(pid) {
17
+ try {
18
+ process.kill(pid, 0);
19
+ return true;
20
+ } catch {
21
+ return false;
22
+ }
23
+ }
24
+
25
+ export async function startDaemon() {
26
+ // 检查是否已在运行
27
+ try {
28
+ const existing = JSON.parse(fs.readFileSync(DAEMON_JSON, 'utf-8'));
29
+ if (existing.pid && isProcessAlive(existing.pid)) {
30
+ console.log(`守护进程已在运行中(PID: ${existing.pid})。`);
31
+ console.log(`日志: ${existing.logPath}`);
32
+ return;
33
+ }
34
+ } catch {}
35
+
36
+ const scriptPath = getScriptPath();
37
+ ensureDir();
38
+ const logFd = fs.openSync(LOG_PATH, 'a');
39
+ const child = spawn(process.execPath, [scriptPath, 'listen', '--daemon-child'], {
40
+ detached: true,
41
+ windowsHide: true,
42
+ stdio: ['ignore', logFd, logFd],
43
+ });
44
+ child.unref();
45
+
46
+ const pid = child.pid;
47
+ const daemonInfo = { pid, logPath: LOG_PATH, startedAt: new Date().toISOString() };
48
+ fs.writeFileSync(DAEMON_JSON, JSON.stringify(daemonInfo, null, 2));
49
+
50
+ console.log(`续聊守护进程已后台启动(PID: ${pid})。`);
51
+ console.log(`日志: ${LOG_PATH}`);
52
+ }
53
+
54
+ export async function stopDaemon() {
55
+ let daemonInfo;
56
+ try {
57
+ daemonInfo = JSON.parse(fs.readFileSync(DAEMON_JSON, 'utf-8'));
58
+ } catch {
59
+ console.log('未找到运行中的守护进程记录。');
60
+ return;
61
+ }
62
+
63
+ const pid = daemonInfo.pid;
64
+ if (!isProcessAlive(pid)) {
65
+ console.log(`守护进程(PID: ${pid})已不在运行。`);
66
+ fs.unlinkSync(DAEMON_JSON);
67
+ return;
68
+ }
69
+
70
+ // 结束进程:Windows 用 taskkill 杀进程树,其他平台用 kill
71
+ try {
72
+ if (process.platform === 'win32') {
73
+ spawn('taskkill', ['/pid', String(pid), '/f', '/t'], { stdio: 'ignore' }).on('error', () => {});
74
+ } else {
75
+ process.kill(pid, 'SIGTERM');
76
+ }
77
+ // 给进程一点时间退出
78
+ await new Promise((r) => setTimeout(r, 1000));
79
+ } catch {}
80
+
81
+ if (isProcessAlive(pid)) {
82
+ console.log(`无法停止守护进程(PID: ${pid}),请手动终止。`);
83
+ return;
84
+ }
85
+
86
+ fs.unlinkSync(DAEMON_JSON);
87
+ console.log(`守护进程(PID: ${pid})已停止。`);
88
+ }
89
+
90
+ export async function daemonStatus() {
91
+ try {
92
+ const daemonInfo = JSON.parse(fs.readFileSync(DAEMON_JSON, 'utf-8'));
93
+ const pid = daemonInfo.pid;
94
+ if (isProcessAlive(pid)) {
95
+ console.log(`续聊守护进程运行中`);
96
+ console.log(` PID: ${pid}`);
97
+ console.log(` 启动: ${daemonInfo.startedAt}`);
98
+ console.log(` 日志: ${daemonInfo.logPath}`);
99
+ } else {
100
+ console.log('守护进程记录存在但进程已不运行(可能异常退出)。');
101
+ console.log(` 上次 PID: ${pid}`);
102
+ console.log(` 日志: ${daemonInfo.logPath}`);
103
+ fs.unlinkSync(DAEMON_JSON);
104
+ }
105
+ } catch {
106
+ console.log('续聊守护进程未运行。');
107
+ }
108
+ }
package/src/hook.mjs CHANGED
@@ -20,10 +20,16 @@ export async function dispatchHook(input, agent) {
20
20
  return handleStop(input, name);
21
21
  }
22
22
 
23
- if (event === 'PreToolUse' && input.tool_name === 'AskUserQuestion') {
24
- await systemNotify(name, '有提问需要处理');
25
- if (!isOut) return null; // 终端优先:不阻塞
26
- return handleAskUserQuestion(input, name);
23
+ if (event === 'PreToolUse') {
24
+ // Claude Code 的提问工具叫 AskUserQuestion;Codex 的叫 request_user_input
25
+ const isAsk =
26
+ input.tool_name === 'AskUserQuestion' ||
27
+ (agent === 'codex' && input.tool_name === 'request_user_input');
28
+ if (isAsk) {
29
+ await systemNotify(name, '有提问需要处理');
30
+ if (!isOut) return null; // 终端优先:不阻塞
31
+ return handleAskUserQuestion(input, name, agent);
32
+ }
27
33
  }
28
34
 
29
35
  if (event === 'PermissionRequest') {
package/src/listen.mjs ADDED
@@ -0,0 +1,121 @@
1
+ // 续聊守护进程:订阅主话题,手机向主话题发送文字即触发一次续聊。
2
+ // 断线自动重连(since 从上次消息之后继续),续聊请求串行处理(避免并发会话冲突)。
3
+ // 按消息时间戳过滤:如果新会话开启时间晚于用户的消息时间,则跳过该消息,
4
+ // 避免旧消息被注入到新会话中。
5
+ import fs from 'fs';
6
+ import path from 'path';
7
+ import os from 'os';
8
+ import { loadConfig, loadLastSession } from './config.mjs';
9
+ import { runResume } from './resume.mjs';
10
+
11
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
12
+ const RETRY_DELAY = 5000;
13
+
14
+ export function createLogWriter(logPath) {
15
+ const stream = fs.createWriteStream(logPath, { flags: 'a' });
16
+ return (msg) => {
17
+ const line = `[${new Date().toISOString()}] ${msg}\n`;
18
+ stream.write(line);
19
+ };
20
+ }
21
+
22
+ export async function runListen({ onLog = (s) => console.log(s) } = {}) {
23
+ const config = loadConfig();
24
+ if (!config.topic) {
25
+ onLog('未配置话题,请先运行 a4p setup。');
26
+ return false;
27
+ }
28
+ const url = `${config.server}/${config.topic}/json`;
29
+ onLog(`续聊守护进程已启动,监听: ${url}`);
30
+ onLog(`提示:手机向话题 ${config.topic} 发送文字即可与当前会话交流;Ctrl+C 退出。`);
31
+
32
+ // ntfy 的 since 参数只接受 Unix 秒时间戳/时长/all,不接受 "now" 或消息 ID
33
+ let lastTime = Math.floor(Date.now() / 1000); // 首次只收连接之后的新消息
34
+ let busy = false;
35
+ const queue = [];
36
+ let knownSessionId = null; // 记录已处理过的会话 ID,用于检测会话切换
37
+
38
+ // 判断消息是否仍应被处理:如果新会话在消息发送之后才创建,则丢弃
39
+ function isMessageStale(msgTime) {
40
+ const last = loadLastSession();
41
+ if (!last?.session_id) return false; // 无最近会话,不过滤
42
+ // 首次处理或会话未变,不过滤
43
+ if (knownSessionId === last.session_id) return false;
44
+ // 会话变了:检查消息是否是在新会话创建之前发送的
45
+ // last.ts 是 Stop 事件的保存时间(毫秒),msgTime 是 ntfy 的 Unix 秒
46
+ if (msgTime * 1000 < last.ts) {
47
+ onLog(`丢弃过时消息(消息时间 ${msgTime} 早于新会话创建时间 ${Math.floor(last.ts / 1000)})`);
48
+ return true;
49
+ }
50
+ // 会话变了但消息更新,更新 knownSessionId 并处理
51
+ knownSessionId = last.session_id;
52
+ return false;
53
+ }
54
+
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);
71
+ }
72
+ };
73
+
74
+ while (true) {
75
+ try {
76
+ const since = `since=${lastTime + 1}`; // 从最后收到的消息之后继续
77
+ const res = await fetch(`${url}?${since}`);
78
+ if (!res.ok) {
79
+ onLog(`连接失败(HTTP ${res.status}),${RETRY_DELAY / 1000} 秒后重连...`);
80
+ await sleep(RETRY_DELAY);
81
+ continue;
82
+ }
83
+ const reader = res.body.getReader();
84
+ const decoder = new TextDecoder();
85
+ let buffer = '';
86
+ while (true) {
87
+ const { done, value } = await reader.read();
88
+ if (done) break;
89
+ buffer += decoder.decode(value, { stream: true });
90
+ const lines = buffer.split('\n');
91
+ buffer = lines.pop();
92
+ for (const line of lines) {
93
+ if (!line.trim()) continue;
94
+ let event;
95
+ try {
96
+ event = JSON.parse(line);
97
+ } catch {
98
+ continue;
99
+ }
100
+ if (event.time) lastTime = Math.max(lastTime, Number(event.time));
101
+ // 有 title 的是系统推送通知(Claude Code 回复),不是手机用户消息,跳过
102
+ if (event.title) continue;
103
+ let msg;
104
+ try {
105
+ msg = JSON.parse(event.message); // 系统推送为 JSON,忽略
106
+ } catch {
107
+ msg = event.message; // 纯文本:手机发来的续聊内容
108
+ }
109
+ if (typeof msg === 'string' && msg.trim()) {
110
+ processMessage(msg.trim(), event.time ? Number(event.time) : null);
111
+ }
112
+ }
113
+ }
114
+ onLog(`连接断开,${RETRY_DELAY / 1000} 秒后重连...`);
115
+ await sleep(RETRY_DELAY);
116
+ } catch (err) {
117
+ onLog(`连接异常(${err.message}),${RETRY_DELAY / 1000} 秒后重连...`);
118
+ await sleep(RETRY_DELAY);
119
+ }
120
+ }
121
+ }
package/src/mode.mjs CHANGED
@@ -1,9 +1,8 @@
1
- // 交互模式读写:~/.a4phone-mode.json(out=外出/手机优先,home=终端优先)
1
+ // 交互模式读写:~/.a4phone/mode.json(out=外出/手机优先,home=终端优先)
2
2
  import fs from 'fs';
3
- import os from 'os';
4
- import path from 'path';
3
+ import { MODE_PATH, ensureDir } from './paths.mjs';
5
4
 
6
- export const MODE_PATH = path.join(os.homedir(), '.a4phone-mode.json');
5
+ export { MODE_PATH } from './paths.mjs'; // 兼容旧引用
7
6
 
8
7
  export function readMode() {
9
8
  try {
@@ -14,5 +13,6 @@ export function readMode() {
14
13
  }
15
14
 
16
15
  export function setMode(mode) {
16
+ ensureDir();
17
17
  fs.writeFileSync(MODE_PATH, JSON.stringify({ mode: mode === 'out' ? 'out' : 'home' }));
18
18
  }
package/src/ntfy.mjs CHANGED
@@ -12,7 +12,9 @@ export async function sendNotification({ server, topic, title, message, actions
12
12
  }
13
13
  }
14
14
 
15
- // 订阅响应话题(NDJSON 流),等待匹配 requestId 的决策
15
+ // 订阅响应话题(NDJSON 流),等待决策
16
+ // HTTP action 回传:正文为 JSON { requestId, answer },仅匹配相同 requestId
17
+ // 手机自由文本:正文为纯文本,无 requestId,直接作为答案接受
16
18
  export async function waitForResponse({ server, topic, requestId, timeout }) {
17
19
  const url = `${server}/${topic}-response/json`;
18
20
  const controller = new AbortController();
@@ -32,8 +34,17 @@ export async function waitForResponse({ server, topic, requestId, timeout }) {
32
34
  if (!line.trim()) continue;
33
35
  try {
34
36
  const event = JSON.parse(line);
35
- const msg = JSON.parse(event.message);
36
- if (msg.requestId === requestId) {
37
+ // ntfy /json 连接建立后会先发 open 事件、之后周期发 keepalive,
38
+ // 这些事件没有 message 字段,跳过以免被误判为“手机自由文本”立即返回。
39
+ 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
+ }
46
+ // action 回执:requestId 必须匹配;自由文本:无 requestId 且有 answer 才接受
47
+ if (msg.requestId === requestId || (msg.requestId === undefined && msg.answer)) {
37
48
  clearTimeout(timer);
38
49
  controller.abort();
39
50
  return msg;
package/src/paths.mjs ADDED
@@ -0,0 +1,58 @@
1
+ // a4phone 状态文件统一存放目录:~/.a4phone/(替代散落在家目录的单点文件)
2
+ // config.json ← ~/.a4phone.json
3
+ // mode.json ← ~/.a4phone-mode.json
4
+ // last.json ← ~/.a4phone-last.json
5
+ // daemon.json ← ~/.a4phone-daemon.json
6
+ // daemon.log ← ~/.a4phone-daemon.log
7
+ import fs from 'fs';
8
+ import os from 'os';
9
+ import path from 'path';
10
+
11
+ export const A4P_DIR = path.join(os.homedir(), '.a4phone');
12
+ export const CONFIG_PATH = path.join(A4P_DIR, 'config.json');
13
+ export const MODE_PATH = path.join(A4P_DIR, 'mode.json');
14
+ export const LAST_PATH = path.join(A4P_DIR, 'last.json');
15
+ export const DAEMON_JSON = path.join(A4P_DIR, 'daemon.json');
16
+ export const LOG_PATH = path.join(A4P_DIR, 'daemon.log');
17
+
18
+ // 旧版散落在家目录的单文件 → 迁移到 ~/.a4phone/(新路径不存在时才移动)
19
+ const LEGACY_PATHS = {
20
+ [CONFIG_PATH]: path.join(os.homedir(), '.a4phone.json'),
21
+ [MODE_PATH]: path.join(os.homedir(), '.a4phone-mode.json'),
22
+ [LAST_PATH]: path.join(os.homedir(), '.a4phone-last.json'),
23
+ [DAEMON_JSON]: path.join(os.homedir(), '.a4phone-daemon.json'),
24
+ [LOG_PATH]: path.join(os.homedir(), '.a4phone-daemon.log'),
25
+ };
26
+
27
+ function moveIfExists(oldPath, newPath) {
28
+ try {
29
+ fs.renameSync(oldPath, newPath);
30
+ return true;
31
+ } catch {
32
+ // rename 失败(如日志被占用)则回退复制+删除
33
+ try {
34
+ fs.copyFileSync(oldPath, newPath);
35
+ fs.unlinkSync(oldPath);
36
+ return true;
37
+ } catch {
38
+ return false; // 迁移失败则保留旧文件
39
+ }
40
+ }
41
+ }
42
+
43
+ // 确保目录存在,并把旧版散点文件迁移进来;返回是否发生过迁移
44
+ export function migrateLegacy() {
45
+ fs.mkdirSync(A4P_DIR, { recursive: true });
46
+ let migrated = false;
47
+ for (const [newPath, oldPath] of Object.entries(LEGACY_PATHS)) {
48
+ if (fs.existsSync(oldPath) && !fs.existsSync(newPath)) {
49
+ if (moveIfExists(oldPath, newPath)) migrated = true;
50
+ }
51
+ }
52
+ return migrated;
53
+ }
54
+
55
+ // 确保目录存在(写入前调用)
56
+ export function ensureDir() {
57
+ fs.mkdirSync(A4P_DIR, { recursive: true });
58
+ }