a4phone 1.1.6 → 1.1.7

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
@@ -64,7 +64,7 @@ a4p status # 查看当前模式
64
64
 
65
65
  ### 手机自由文本作答
66
66
 
67
- `AskUserQuestion` 提问推送手机后,除了点选选项按钮,还可以**直接向响应话题 `{topic}-response` 发送文字**作为答案,自由回答不受选项限制。
67
+ `AskUserQuestion` 提问推送手机后,除了点选选项按钮,还可以**直接向响应话题 `{topic}-response` 发送文字**作为答案,自由回答不受选项限制。ntfy 单条推送最多 3 个按钮,选项超过 3 个时自动降级为编号列表,回复对应编号即可选中选项。
68
68
 
69
69
  ### 远程续聊
70
70
 
@@ -1,151 +1,173 @@
1
- // phone-hooks.mjs — dsh-hook 的手机交互实现
2
- //
3
- // 将 a4phone(Claude Code/Codex 手机远程交互包)的 ntfy 交互逻辑适配到 DSH:
4
- // 1. task-complete 任务完成 → 手机推送(含 AI 最后输出)
5
- // 2. question-asked ask_user_question 工具调用 → 手机点选/文字作答
6
- // 3. permission-request approval/request → 手机 Approve/Deny/Always
7
- //
8
- // 适配说明(与 a4phone 的差异):
9
- // - a4phone 走 Claude Code/Codex 的 hook 协议(hook_event_name、stdin JSON);
10
- // DSH 没有该协议,本模块改为监听 DSH 的 Cordis 事件(session/event、
11
- // tools/execute、approval/request)。
12
- // - 配置/模式/推送复用 a4phone 的 ~/.a4phone/config.json 与 mode.json
13
- // (手机端无需重新订阅,同一话题即可收到 DSH 推送)。
14
- // - 外出模式(out)时手机优先;终端优先(home)时走 DSH 原生交互,不阻塞。
15
- //
16
- // 整合到 a4phone 后,配置/模式/推送直接复用 a4phone 的 src/ 模块(零拷贝),
17
- // 不再保留独立的 lib/phone/ 副本。
18
-
19
- import crypto from 'crypto';
20
- import { loadConfig } from '../../src/config.mjs';
21
- import { readMode } from '../../src/mode.mjs';
22
- import { sendNotification, waitForResponse } from '../../src/ntfy.mjs';
23
- import { systemNotify } from '../../src/notify.mjs';
24
-
25
- /** 单条手机交互的最大等待时间(秒),取自 a4phone 配置的 timeout。 */
26
-
27
- // 记录最近一次任务完成的 AI 最后输出(供 task-complete 推送;session 级缓存,避免跨会话串扰)
28
- const lastAssistantOutput = new Map();
29
-
30
- /**
31
- * 缓存某会话最近的 AI 文本输出(由 session/event 的 assistant/message 驱动)。
32
- * @param {string} sessionId
33
- * @param {import('@deepseek-ai/dsh-session').AssistantMessage} message
34
- */
35
- export function rememberAssistantOutput(sessionId, message) {
36
- if (!message?.content) return;
37
- const texts = message.content
38
- .filter((b) => b?.type === 'text' && b.text)
39
- .map((b) => b.text);
40
- if (texts.length) lastAssistantOutput.set(sessionId, texts.join('\n'));
41
- }
42
-
43
- /** 判断手机交互是否启用:外出模式 + 已配置话题。 */
44
- function phoneActive() {
45
- const cfg = loadConfig();
46
- return readMode() === 'out' && Boolean(cfg.topic);
47
- }
48
-
49
- /**
50
- * Hook 1: 任务完成 → 系统通知 + 手机推送(含 AI 最后输出)。
51
- * 与 a4phone 的 handleStop 对齐:Stop 事件 → 通知 + 推送。
52
- * @param {string} sessionId
53
- * @param {object} extra 附加信息(如 turn 号)
54
- */
55
- export async function handleTaskComplete(sessionId, extra = {}) {
56
- const cfg = loadConfig();
57
- const shortId = sessionId ? sessionId.slice(0, 8) : '—';
58
- const details = `任务已完成\n会话: ${shortId}${extra.turn != null ? `\n轮次: ${extra.turn}` : ''}`;
59
-
60
- await systemNotify('DSH', '任务已完成');
61
-
62
- if (cfg.topic) {
63
- const lastOutput = lastAssistantOutput.get(sessionId);
64
- const message = lastOutput ? `${details}\n\nAI 最后输出:\n${lastOutput}` : details;
65
- await sendNotification({ ...cfg, title: 'DSH', message });
66
- }
67
- }
68
-
69
- /**
70
- * Hook 2: 问题询问 → 拦截 ask_user_question 工具调用,推送手机点选/文字作答。
71
- * 复用 a4phone 的 buildAskOutput 思路:DSH 的 ask_user_question 输出契约是
72
- * { answers: [{ id, selected, custom? }] },因此直接返回该结构即可。
73
- * 手机超时/推送失败/终端模式 → 返回 null 表示放行 DSH 原生提问。
74
- * @param {import('@deepseek-ai/dsh-tools').ToolExecution} exec
75
- * @returns {Promise<{answers: Array<object>} | null>}
76
- */
77
- export async function handleAskUserQuestion(exec) {
78
- if (!phoneActive()) return null;
79
- const cfg = loadConfig();
80
- const args = exec.arguments || {};
81
- const questions = Array.isArray(args.questions) ? args.questions : [];
82
- if (!questions.length) return null;
83
-
84
- const answers = [];
85
- for (const q of questions) {
86
- const options = Array.isArray(q.options) ? q.options : [];
87
- const requestId = crypto.randomUUID();
88
- const actions = options.map((o) => ({
89
- action: 'http',
90
- label: o.label,
91
- url: `${cfg.server}/${cfg.topic}-response`,
92
- method: 'POST',
93
- clear: false,
94
- body: JSON.stringify({ requestId, answer: o.label }),
95
- }));
96
- const lines = [q.question || 'Question'];
97
- options.forEach((o, i) => lines.push(`${i + 1}. ${o.label}`));
98
- lines.push('');
99
- lines.push(`(也可直接向话题 ${cfg.topic}-response 发送文字作答)`);
100
-
101
- const sent = await sendNotification({
102
- ...cfg,
103
- title: `DSH: ${q.header || 'Question'}`,
104
- message: lines.join('\n'),
105
- actions,
106
- });
107
- if (!sent) return null; // 推送失败 → 回退终端
108
-
109
- const resp = await waitForResponse({ ...cfg, requestId, timeout: cfg.timeout * 1000 });
110
- if (!resp?.answer) return null; // 手机超时 → 回退终端
111
-
112
- answers.push({
113
- id: q.id,
114
- selected: [resp.answer],
115
- ...(resp.custom ? { custom: resp.custom } : {}),
116
- });
117
- }
118
- return { answers };
119
- }
120
-
121
- /**
122
- * Hook 3: 权限请求 → 拦截 approval/request,推送手机 Approve/Deny/Always。
123
- * 复用 a4phone 的 handlePermissionRequest 思路;DSH 的 ApprovalOutcome 契约是
124
- * 'allowed-once' | 'rejected' | 'cancelled' | 'unavailable',手机点选映射为
125
- * allowed-once / rejected。手机超时/推送失败/终端模式 → 返回 null 放行原链。
126
- * @param {import('@deepseek-ai/dsh-user-approval').ApprovalRequest} req
127
- * @returns {Promise<import('@deepseek-ai/dsh-user-approval').ApprovalOutcome | null>}
128
- */
129
- export async function handleApprovalRequest(req) {
130
- if (!phoneActive()) return null;
131
- const cfg = loadConfig();
132
-
133
- const toolName = req.toolName || 'Unknown';
134
- const message = req.reason || `工具 ${toolName} 请求权限`;
135
- const requestId = crypto.randomUUID();
136
- const url = `${cfg.server}/${cfg.topic}-response`;
137
- const actions = [
138
- { action: 'http', label: 'Approve', url, method: 'POST', clear: false, body: JSON.stringify({ requestId, approved: true }) },
139
- { action: 'http', label: 'Deny', url, method: 'POST', clear: false, body: JSON.stringify({ requestId, approved: false }) },
140
- ];
141
-
142
- const sent = await sendNotification({ ...cfg, title: `DSH: ${toolName}`, message, actions });
143
- if (!sent) return null;
144
-
145
- const resp = await waitForResponse({ ...cfg, requestId, timeout: cfg.timeout * 1000 });
146
- if (!resp) return null; // 手机超时 → 回退
147
-
148
- return resp.approved === false ? 'rejected' : 'allowed-once';
149
- }
150
-
151
- export { systemNotify };
1
+ // phone-hooks.mjs — dsh-hook 的手机交互实现
2
+ //
3
+ // 将 a4phone(Claude Code/Codex 手机远程交互包)的 ntfy 交互逻辑适配到 DSH:
4
+ // 1. task-complete 任务完成 → 手机推送(含 AI 最后输出)
5
+ // 2. question-asked ask_user_question 工具调用 → 手机点选/文字作答
6
+ // 3. permission-request approval/request → 手机 Approve/Deny/Always
7
+ //
8
+ // 适配说明(与 a4phone 的差异):
9
+ // - a4phone 走 Claude Code/Codex 的 hook 协议(hook_event_name、stdin JSON);
10
+ // DSH 没有该协议,本模块改为监听 DSH 的 Cordis 事件(session/event、
11
+ // tools/execute、approval/request)。
12
+ // - 配置/模式/推送复用 a4phone 的 ~/.a4phone/config.json 与 mode.json
13
+ // (手机端无需重新订阅,同一话题即可收到 DSH 推送)。
14
+ // - 外出模式(out)时手机优先;终端优先(home)时走 DSH 原生交互,不阻塞。
15
+ //
16
+ // 整合到 a4phone 后,配置/模式/推送直接复用 a4phone 的 src/ 模块(零拷贝),
17
+ // 不再保留独立的 lib/phone/ 副本。
18
+
19
+ import crypto from 'crypto';
20
+ import { loadConfig } from '../../src/config.mjs';
21
+ import { readMode } from '../../src/mode.mjs';
22
+ import { sendNotification, waitForResponse } from '../../src/ntfy.mjs';
23
+ import { systemNotify } from '../../src/notify.mjs';
24
+
25
+ /** 单条手机交互的最大等待时间(秒),取自 a4phone 配置的 timeout。 */
26
+
27
+ // 记录最近一次任务完成的 AI 最后输出(供 task-complete 推送;session 级缓存,避免跨会话串扰)
28
+ const lastAssistantOutput = new Map();
29
+
30
+ /**
31
+ * 缓存某会话最近的 AI 文本输出(由 session/event 的 assistant/message 驱动)。
32
+ * @param {string} sessionId
33
+ * @param {import('@deepseek-ai/dsh-session').AssistantMessage} message
34
+ */
35
+ export function rememberAssistantOutput(sessionId, message) {
36
+ if (!message?.content) return;
37
+ const texts = message.content
38
+ .filter((b) => b?.type === 'text' && b.text)
39
+ .map((b) => b.text);
40
+ if (texts.length) lastAssistantOutput.set(sessionId, texts.join('\n'));
41
+ }
42
+
43
+ /** 判断手机交互是否启用:外出模式 + 已配置话题。 */
44
+ function phoneActive() {
45
+ const cfg = loadConfig();
46
+ return readMode() === 'out' && Boolean(cfg.topic);
47
+ }
48
+
49
+ /**
50
+ * Hook 1: 任务完成 → 系统通知 + 手机推送(含 AI 最后输出)。
51
+ * 与 a4phone 的 handleStop 对齐:Stop 事件 → 通知 + 推送。
52
+ * @param {string} sessionId
53
+ * @param {object} extra 附加信息(如 turn 号)
54
+ */
55
+ export async function handleTaskComplete(sessionId, extra = {}) {
56
+ const cfg = loadConfig();
57
+ const shortId = sessionId ? sessionId.slice(0, 8) : '—';
58
+ const details = `任务已完成\n会话: ${shortId}${extra.turn != null ? `\n轮次: ${extra.turn}` : ''}`;
59
+
60
+ await systemNotify('DSH', '任务已完成');
61
+
62
+ if (cfg.topic) {
63
+ const lastOutput = lastAssistantOutput.get(sessionId);
64
+ const message = lastOutput ? `${details}\n\nAI 最后输出:\n${lastOutput}` : details;
65
+ await sendNotification({ ...cfg, title: 'DSH', message });
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Hook 2: 问题询问 → 拦截 ask_user_question 工具调用,推送手机点选/文字作答。
71
+ * 复用 a4phone 的 buildAskOutput 思路:DSH 的 ask_user_question 输出契约是
72
+ * { answers: [{ id, selected, custom? }] },因此直接返回该结构即可。
73
+ * 手机超时/推送失败/终端模式 → 返回 null 表示放行 DSH 原生提问。
74
+ * @param {import('@deepseek-ai/dsh-tools').ToolExecution} exec
75
+ * @returns {Promise<{answers: Array<object>} | null>}
76
+ */
77
+ export async function handleAskUserQuestion(exec) {
78
+ if (!phoneActive()) return null;
79
+ const cfg = loadConfig();
80
+ const args = exec.arguments || {};
81
+ const questions = Array.isArray(args.questions) ? args.questions : [];
82
+ if (!questions.length) return null;
83
+
84
+ const answers = [];
85
+ for (const q of questions) {
86
+ const options = Array.isArray(q.options) ? q.options : [];
87
+ const requestId = crypto.randomUUID();
88
+ // ntfy 最多允许 3 个 action 按钮(超过返回 HTTP 400,推送失败)。
89
+ // 选项 ≤3 → 按钮点选;>3 → 降级为文本编号列表 + 文字作答(waitForResponse 支持自由文本)。
90
+ const useActions = options.length > 0 && options.length <= 3;
91
+ const actions = useActions
92
+ ? options.map((o) => ({
93
+ action: 'http',
94
+ label: o.label,
95
+ url: `${cfg.server}/${cfg.topic}-response`,
96
+ method: 'POST',
97
+ clear: false,
98
+ body: JSON.stringify({ requestId, answer: o.label }),
99
+ }))
100
+ : undefined;
101
+ const lines = [q.question || 'Question'];
102
+ options.forEach((o, i) => lines.push(`${i + 1}. ${o.label}`));
103
+ lines.push('');
104
+ lines.push(
105
+ useActions
106
+ ? `(也可直接向话题 ${cfg.topic}-response 发送文字作答)`
107
+ : `(选项较多,请回复编号如「3」,或直接向话题 ${cfg.topic}-response 发送文字作答)`
108
+ );
109
+ if (!useActions && options.length > 3) {
110
+ process.stderr.write(`[dsh-hook] 选项 ${options.length} 个超 ntfy 按钮上限(3),已降级为文字作答\n`);
111
+ }
112
+
113
+ const sent = await sendNotification({
114
+ ...cfg,
115
+ title: `DSH: ${q.header || 'Question'}`,
116
+ message: lines.join('\n'),
117
+ ...(actions ? { actions } : {}),
118
+ });
119
+ if (!sent) return null; // 推送失败 → 回退终端
120
+
121
+ const resp = await waitForResponse({ ...cfg, requestId, timeout: cfg.timeout * 1000 });
122
+ if (!resp?.answer) return null; // 手机超时 → 回退终端
123
+
124
+ // 降级场景下手机可能回编号(如「3」),映射回选项 label;
125
+ // 按钮场景 answer 本就是 label;自由文本则原样作为答案。
126
+ let answer = resp.answer;
127
+ if (!useActions) {
128
+ const idx = Number(String(answer).trim());
129
+ if (Number.isInteger(idx) && idx >= 1 && idx <= options.length) {
130
+ answer = options[idx - 1].label;
131
+ }
132
+ }
133
+
134
+ answers.push({
135
+ id: q.id,
136
+ selected: [answer],
137
+ ...(resp.custom ? { custom: resp.custom } : {}),
138
+ });
139
+ }
140
+ return { answers };
141
+ }
142
+
143
+ /**
144
+ * Hook 3: 权限请求 → 拦截 approval/request,推送手机 Approve/Deny/Always。
145
+ * 复用 a4phone 的 handlePermissionRequest 思路;DSH 的 ApprovalOutcome 契约是
146
+ * 'allowed-once' | 'rejected' | 'cancelled' | 'unavailable',手机点选映射为
147
+ * allowed-once / rejected。手机超时/推送失败/终端模式 → 返回 null 放行原链。
148
+ * @param {import('@deepseek-ai/dsh-user-approval').ApprovalRequest} req
149
+ * @returns {Promise<import('@deepseek-ai/dsh-user-approval').ApprovalOutcome | null>}
150
+ */
151
+ export async function handleApprovalRequest(req) {
152
+ if (!phoneActive()) return null;
153
+ const cfg = loadConfig();
154
+
155
+ const toolName = req.toolName || 'Unknown';
156
+ const message = req.reason || `工具 ${toolName} 请求权限`;
157
+ const requestId = crypto.randomUUID();
158
+ const url = `${cfg.server}/${cfg.topic}-response`;
159
+ const actions = [
160
+ { action: 'http', label: 'Approve', url, method: 'POST', clear: false, body: JSON.stringify({ requestId, approved: true }) },
161
+ { action: 'http', label: 'Deny', url, method: 'POST', clear: false, body: JSON.stringify({ requestId, approved: false }) },
162
+ ];
163
+
164
+ const sent = await sendNotification({ ...cfg, title: `DSH: ${toolName}`, message, actions });
165
+ if (!sent) return null;
166
+
167
+ const resp = await waitForResponse({ ...cfg, requestId, timeout: cfg.timeout * 1000 });
168
+ if (!resp) return null; // 手机超时 → 回退
169
+
170
+ return resp.approved === false ? 'rejected' : 'allowed-once';
171
+ }
172
+
173
+ export { systemNotify };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "a4phone",
3
- "version": "1.1.6",
3
+ "version": "1.1.7",
4
4
  "description": "Claude Code / Codex 远程手机交互:任务完成通知(含 AI 最后输出)、提问/权限请求手机点选或文字作答、远程续聊(ntfy.sh)",
5
5
  "type": "module",
6
6
  "bin": {
package/src/asku.mjs CHANGED
@@ -40,28 +40,46 @@ export async function handleAskUserQuestion(input, agentName, agent = 'claude')
40
40
  const options = q.options || [];
41
41
  if (!options.length) continue;
42
42
  const requestId = crypto.randomUUID();
43
- const actions = options.map((o) => ({
44
- action: 'http',
45
- label: o.label,
46
- url: `${config.server}/${config.topic}-response`,
47
- method: 'POST',
48
- clear: false,
49
- body: JSON.stringify({ requestId, answer: o.label }),
50
- }));
43
+ // ntfy 最多允许 3 个 action 按钮(超过返回 HTTP 400,推送失败)。
44
+ // 选项 ≤3 → 按钮点选;>3 → 降级为文本编号列表 + 文字作答(waitForResponse 支持自由文本)。
45
+ const useActions = options.length <= 3;
46
+ const actions = useActions
47
+ ? options.map((o) => ({
48
+ action: 'http',
49
+ label: o.label,
50
+ url: `${config.server}/${config.topic}-response`,
51
+ method: 'POST',
52
+ clear: false,
53
+ body: JSON.stringify({ requestId, answer: o.label }),
54
+ }))
55
+ : undefined;
51
56
  const lines = [q.question];
52
57
  options.forEach((o, i) => lines.push(`${i + 1}. ${o.label}`));
53
58
  lines.push(''); // 留空行分隔
54
- lines.push(`(也可直接向话题 ${config.topic}-response 发送文字作答)`);
59
+ lines.push(
60
+ useActions
61
+ ? `(也可直接向话题 ${config.topic}-response 发送文字作答)`
62
+ : `(选项较多,请回复编号如「3」,或直接向话题 ${config.topic}-response 发送文字作答)`
63
+ );
55
64
  const sent = await sendNotification({
56
65
  ...config,
57
66
  title: `${agentName}: ${q.header || 'Question'}`,
58
67
  message: lines.join('\n'),
59
- actions,
68
+ ...(actions ? { actions } : {}),
60
69
  });
61
70
  if (!sent) return null; // 推送失败 → 回退终端
62
71
  const resp = await waitForResponse({ ...config, requestId, timeout: config.timeout * 1000 });
63
72
  if (!resp?.answer) return null; // 手机超时 → 回退终端
64
- answers[q.question] = resp.answer;
73
+ // 降级场景下手机可能回编号(如「3」),映射回选项 label;
74
+ // 按钮场景 answer 本就是 label;自由文本则原样作为答案。
75
+ let answer = resp.answer;
76
+ if (!useActions) {
77
+ const idx = Number(String(answer).trim());
78
+ if (Number.isInteger(idx) && idx >= 1 && idx <= options.length) {
79
+ answer = options[idx - 1].label;
80
+ }
81
+ }
82
+ answers[q.question] = answer;
65
83
  }
66
84
 
67
85
  return buildAskOutput(agent, questions, answers);