a4phone 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 a4phone contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,103 @@
1
+ # a4phone
2
+
3
+ Claude Code / Codex 远程手机交互包。通过 [ntfy.sh](https://ntfy.sh) 在手机上接收任务完成通知,并对 AI 提问与权限请求进行远程点选确认。
4
+
5
+ ## 功能
6
+
7
+ - **任务完成通知**:`Stop` 事件 → 电脑弹窗 + 手机推送(含目录、会话信息)
8
+ - **AI 提问交互**:`AskUserQuestion` → 手机显示选项按钮,点选后答案回传会话
9
+ - **权限请求交互**:`PermissionRequest` → 手机 Approve/Deny/Always Approve
10
+ - **双模式**:外出模式(手机优先)/ 终端优先模式,一键切换
11
+ - **零第三方依赖**:仅依赖 ntfy.sh 免费服务,无 Google 服务依赖
12
+
13
+ ## 安装
14
+
15
+ ```bash
16
+ npm install -g a4phone
17
+ ```
18
+
19
+ ## 使用
20
+
21
+ ```bash
22
+ a4p setup # 安装引导:生成话题、注册 Hook、显示二维码
23
+ a4p out # 外出模式(手机优先)
24
+ a4p home # 终端优先模式(默认)
25
+ a4p status # 查看当前模式
26
+ a4p test # 发送测试通知
27
+ a4p uninstall # 移除 Hook 和配置
28
+ ```
29
+
30
+ ### 安装引导
31
+
32
+ `a4p setup` 自动完成:
33
+
34
+ 1. 生成独一无二的话题名称(如 `a4p-xxxx`),写入 `~/.a4phone.json`
35
+ 2. 在 `~/.claude/settings.json` 注册三个 Hook(Stop / AskUserQuestion / PermissionRequest)
36
+ 3. 在终端显示二维码
37
+
38
+ 然后用手机 ntfy App 扫描二维码或输入话题名称订阅,重启 Claude Code 会话生效。
39
+
40
+ ### 模式切换
41
+
42
+ ```bash
43
+ a4p out # 外出模式:提问/权限请求优先推送手机,超时兜底终端
44
+ a4p home # 终端优先模式(默认):直接走终端,手机不参与
45
+ a4p status # 查看当前模式
46
+ ```
47
+
48
+ > 切换即时生效,无需重启会话。
49
+
50
+ ## Codex
51
+
52
+ 使用 Codex 的读者在 `~/.codex/config.toml` 手动配置:
53
+
54
+ ```toml
55
+ hooks = true
56
+
57
+ [[hooks.Stop]]
58
+ [[hooks.Stop.hooks]]
59
+ type = "command"
60
+ command = "a4p hook"
61
+
62
+ [[hooks.PreToolUse]]
63
+ matcher = "AskUserQuestion"
64
+ [[hooks.PreToolUse.hooks]]
65
+ type = "command"
66
+ command = "a4p hook"
67
+
68
+ [[hooks.PermissionRequest]]
69
+ [[hooks.PermissionRequest.hooks]]
70
+ type = "command"
71
+ command = "a4p hook"
72
+ ```
73
+
74
+ ## 原理
75
+
76
+ Claude Code Hook 拦截事件后,通过 ntfy.sh 推送带按钮的通知到手机;手机点击后,决策经响应话题回传并注入会话。
77
+
78
+ ```
79
+ AI助手触发事件 → a4p hook → ntfy.sh 推送手机 → 手机点选 → 决策回传 → 注入会话
80
+ ```
81
+
82
+ ### Hook 输出格式
83
+
84
+ - 提问(PreToolUse):`hookEventName: "PreToolUse"` + `permissionDecision: "allow"` + `updatedInput.answers`
85
+ - 权限请求(PermissionRequest):`hookEventName: "PermissionRequest"` + `decision.behavior`
86
+
87
+ ## 注意事项
88
+
89
+ - 需 Node.js 18+,手机端安装 ntfy App
90
+ - 手机订阅后,请在**订阅设置**中开启"即时交付",否则消息需手动刷新才能收到
91
+ - ntfy.sh 为国外服务,国内网络下长连接可能不稳定
92
+ - 配置存储于 `~/.a4phone.json`,模式存储于 `~/.a4phone-mode.json`
93
+
94
+ ## 开发
95
+
96
+ ```bash
97
+ npm install # 安装依赖
98
+ node bin/a4p.mjs setup # 本地调试
99
+ ```
100
+
101
+ ## 开源协议
102
+
103
+ [MIT](LICENSE)
package/bin/a4p.mjs ADDED
@@ -0,0 +1,68 @@
1
+ #!/usr/bin/env node
2
+ // a4phone 命令行入口
3
+ // a4p setup 安装引导(生成话题、注册 Hook、显示二维码)
4
+ // a4p out 外出模式(手机优先)
5
+ // a4p home 终端优先模式(默认)
6
+ // a4p status 查看当前模式
7
+ // a4p hook 处理 Claude Code Hook(内部调用)
8
+ // a4p uninstall 移除 Hook 和配置
9
+ import fs from 'fs';
10
+ import path from 'path';
11
+ import os from 'os';
12
+ import qrcode from 'qrcode-terminal';
13
+
14
+ const SETTINGS_PATH = path.join(os.homedir(), '.claude', 'settings.json');
15
+
16
+ const cmd = process.argv[2];
17
+
18
+ if (cmd === 'setup') {
19
+ const { runSetup } = await import('../src/setup.mjs');
20
+ qrcode.setErrorLevel('L');
21
+ await runSetup({ generateQR: (text, opts, cb) => qrcode.generate(text, opts, cb) });
22
+ } else if (cmd === 'out' || cmd === 'home') {
23
+ const { setMode } = await import('../src/mode.mjs');
24
+ setMode(cmd);
25
+ console.log(cmd === 'out'
26
+ ? '外出模式已开启:提问/权限请求优先推送手机,超时兜底终端。'
27
+ : '终端优先模式:提问/权限请求直接走终端,手机不参与。');
28
+ } else if (cmd === 'status') {
29
+ const { readMode } = await import('../src/mode.mjs');
30
+ console.log(readMode() === 'out' ? '当前模式:外出(手机优先)' : '当前模式:终端优先(默认)');
31
+ } else if (cmd === 'hook') {
32
+ let input;
33
+ try {
34
+ input = JSON.parse(fs.readFileSync(0, 'utf-8'));
35
+ } catch {
36
+ process.exit(0);
37
+ }
38
+ const { dispatchHook } = await import('../src/hook.mjs');
39
+ const result = await dispatchHook(input);
40
+ if (result) {
41
+ process.stdout.write(JSON.stringify(result) + '\n');
42
+ }
43
+ } else if (cmd === 'uninstall') {
44
+ const { unregisterHooks } = await import('../src/setup.mjs');
45
+ unregisterHooks(SETTINGS_PATH);
46
+ try { fs.unlinkSync(path.join(os.homedir(), '.a4phone.json')); } catch {}
47
+ try { fs.unlinkSync(path.join(os.homedir(), '.a4phone-mode.json')); } catch {}
48
+ console.log('a4phone 已卸载:Hook 已移除,配置已删除。');
49
+ } else if (cmd === 'test') {
50
+ const { loadConfig } = await import('../src/config.mjs');
51
+ const { sendNotification } = await import('../src/ntfy.mjs');
52
+ const config = loadConfig();
53
+ if (!config.topic) {
54
+ console.error('未配置话题,请先运行 a4p setup。');
55
+ process.exit(1);
56
+ }
57
+ const ok = await sendNotification({ ...config, title: 'a4phone', message: '测试通知:如果手机收到,配置正常。' });
58
+ console.log(ok ? '测试通知发送成功。' : '发送失败,请检查网络。');
59
+ } else {
60
+ console.log('a4phone — Claude Code 远程手机交互\n');
61
+ console.log('用法:');
62
+ console.log(' a4p setup 安装引导(生成话题、注册 Hook)');
63
+ console.log(' a4p out 外出模式(手机优先)');
64
+ console.log(' a4p home 终端优先模式(默认)');
65
+ console.log(' a4p status 查看当前模式');
66
+ console.log(' a4p test 发送测试通知');
67
+ console.log(' a4p uninstall 移除 Hook 和配置');
68
+ }
package/package.json ADDED
@@ -0,0 +1,20 @@
1
+ {
2
+ "name": "a4phone",
3
+ "version": "1.0.0",
4
+ "description": "Claude Code 远程手机交互:任务完成通知、AskUserQuestion 提问与 PermissionRequest 权限请求手机点选(ntfy.sh)",
5
+ "type": "module",
6
+ "bin": {
7
+ "a4p": "./bin/a4p.mjs"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "src"
12
+ ],
13
+ "engines": {
14
+ "node": ">=18"
15
+ },
16
+ "dependencies": {
17
+ "qrcode-terminal": "^0.12.0"
18
+ },
19
+ "license": "MIT"
20
+ }
package/src/asku.mjs ADDED
@@ -0,0 +1,45 @@
1
+ // AskUserQuestion 事件(外出模式):推送提问到手机,手机点选后注入答案
2
+ import crypto from 'crypto';
3
+ import { loadConfig } from './config.mjs';
4
+ import { sendNotification, waitForResponse } from './ntfy.mjs';
5
+
6
+ export async function handleAskUserQuestion(input) {
7
+ const config = loadConfig();
8
+ const questions = input.tool_input?.questions || [];
9
+ if (!config.topic || !questions.length) return null;
10
+
11
+ const answers = {};
12
+ for (const q of questions) {
13
+ const options = q.options || [];
14
+ if (!options.length) continue;
15
+ const requestId = crypto.randomUUID();
16
+ const actions = options.map((o) => ({
17
+ action: 'http',
18
+ label: o.label,
19
+ url: `${config.server}/${config.topic}-response`,
20
+ method: 'POST',
21
+ clear: false,
22
+ body: JSON.stringify({ requestId, answer: o.label }),
23
+ }));
24
+ const lines = [q.question];
25
+ options.forEach((o, i) => lines.push(`${i + 1}. ${o.label}`));
26
+ const sent = await sendNotification({
27
+ ...config,
28
+ title: `Claude Code: ${q.header || 'Question'}`,
29
+ message: lines.join('\n'),
30
+ actions,
31
+ });
32
+ if (!sent) return null; // 推送失败 → 回退终端
33
+ const resp = await waitForResponse({ ...config, requestId, timeout: config.timeout * 1000 });
34
+ if (!resp?.answer) return null; // 手机超时 → 回退终端
35
+ answers[q.question] = resp.answer;
36
+ }
37
+
38
+ return {
39
+ hookSpecificOutput: {
40
+ hookEventName: 'PreToolUse',
41
+ permissionDecision: 'allow',
42
+ updatedInput: { questions, answers },
43
+ },
44
+ };
45
+ }
package/src/config.mjs ADDED
@@ -0,0 +1,24 @@
1
+ // 配置读写:~/.a4phone.json
2
+ import fs from 'fs';
3
+ import os from 'os';
4
+ import path from 'path';
5
+
6
+ export const CONFIG_PATH = path.join(os.homedir(), '.a4phone.json');
7
+
8
+ export function loadConfig() {
9
+ try {
10
+ const cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
11
+ return {
12
+ topic: cfg.topic || '',
13
+ server: (cfg.server || 'https://ntfy.sh').replace(/\/+$/, ''),
14
+ timeout: cfg.timeout ?? 30,
15
+ planTimeout: cfg.planTimeout ?? 300,
16
+ };
17
+ } catch {
18
+ return { topic: '', server: 'https://ntfy.sh', timeout: 30, planTimeout: 300 };
19
+ }
20
+ }
21
+
22
+ export function saveConfig(cfg) {
23
+ fs.writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2));
24
+ }
package/src/hook.mjs ADDED
@@ -0,0 +1,30 @@
1
+ // Hook 分发器:根据 hook_event_name 决定处理逻辑
2
+ import { readMode } from './mode.mjs';
3
+ import { systemNotify } from './notify.mjs';
4
+ import { handleStop } from './stop.mjs';
5
+ import { handleAskUserQuestion } from './asku.mjs';
6
+ import { handlePermissionRequest } from './permission.mjs';
7
+
8
+ // 返回 hook 输出对象,或 null(null = 不干预,走终端默认流程)
9
+ export async function dispatchHook(input) {
10
+ const event = input.hook_event_name;
11
+ const isOut = readMode() === 'out';
12
+
13
+ if (event === 'Stop') {
14
+ return handleStop(input);
15
+ }
16
+
17
+ if (event === 'PreToolUse' && input.tool_name === 'AskUserQuestion') {
18
+ await systemNotify('Claude Code', '有提问需要处理');
19
+ if (!isOut) return null; // 终端优先:不阻塞
20
+ return handleAskUserQuestion(input);
21
+ }
22
+
23
+ if (event === 'PermissionRequest') {
24
+ await systemNotify('Claude Code', '有权限请求需要处理');
25
+ if (!isOut) return null; // 终端优先:不阻塞
26
+ return handlePermissionRequest(input);
27
+ }
28
+
29
+ return null;
30
+ }
package/src/mode.mjs ADDED
@@ -0,0 +1,18 @@
1
+ // 交互模式读写:~/.a4phone-mode.json(out=外出/手机优先,home=终端优先)
2
+ import fs from 'fs';
3
+ import os from 'os';
4
+ import path from 'path';
5
+
6
+ export const MODE_PATH = path.join(os.homedir(), '.a4phone-mode.json');
7
+
8
+ export function readMode() {
9
+ try {
10
+ return JSON.parse(fs.readFileSync(MODE_PATH, 'utf-8')).mode === 'out' ? 'out' : 'home';
11
+ } catch {
12
+ return 'home';
13
+ }
14
+ }
15
+
16
+ export function setMode(mode) {
17
+ fs.writeFileSync(MODE_PATH, JSON.stringify({ mode: mode === 'out' ? 'out' : 'home' }));
18
+ }
package/src/notify.mjs ADDED
@@ -0,0 +1,27 @@
1
+ // 系统原生通知(跨平台)
2
+ import { spawn } from 'child_process';
3
+
4
+ export function systemNotify(title, message) {
5
+ // 立即返回,不阻塞调用方
6
+ const clean = (s) => (s || '').replace(/"/g, "'");
7
+ const t = clean(title);
8
+ const m = clean(message);
9
+ let cmd;
10
+ if (process.platform === 'win32') {
11
+ // Windows:NotifyIcon 气泡通知(非阻塞,后台显示 3 秒)
12
+ cmd = [
13
+ '-NoProfile', '-Command',
14
+ `Add-Type -AssemblyName System.Windows.Forms; Add-Type -AssemblyName System.Drawing; $n=New-Object System.Windows.Forms.NotifyIcon; $n.Icon=[System.Drawing.SystemIcons]::Information; $n.Visible=$true; $n.ShowBalloonTip(3000,"${t}","${m}",[System.Windows.Forms.ToolTipIcon]::Info); Start-Sleep 3; $n.Dispose()`,
15
+ ];
16
+ } else if (process.platform === 'darwin') {
17
+ cmd = ['-e', `display notification "${m}" with title "${t}"`];
18
+ } else {
19
+ cmd = [t, m];
20
+ }
21
+ const child = process.platform === 'win32'
22
+ ? spawn('powershell', cmd, { stdio: 'ignore', detached: process.platform !== 'win32' })
23
+ : process.platform === 'darwin'
24
+ ? spawn('osascript', cmd, { stdio: 'ignore' })
25
+ : spawn('notify-send', cmd, { stdio: 'ignore' });
26
+ child.unref();
27
+ }
package/src/ntfy.mjs ADDED
@@ -0,0 +1,47 @@
1
+ // ntfy.sh 推送与响应订阅
2
+ export async function sendNotification({ server, topic, title, message, actions }) {
3
+ try {
4
+ const res = await fetch(server, {
5
+ method: 'POST',
6
+ headers: { 'Content-Type': 'application/json' },
7
+ body: JSON.stringify({ topic, title, message, actions }),
8
+ });
9
+ return res.ok;
10
+ } catch {
11
+ return false;
12
+ }
13
+ }
14
+
15
+ // 订阅响应话题(NDJSON 流),等待匹配 requestId 的决策
16
+ export async function waitForResponse({ server, topic, requestId, timeout }) {
17
+ const url = `${server}/${topic}-response/json`;
18
+ const controller = new AbortController();
19
+ const timer = setTimeout(() => controller.abort(), timeout);
20
+ try {
21
+ const res = await fetch(url, { signal: controller.signal });
22
+ const reader = res.body.getReader();
23
+ const decoder = new TextDecoder();
24
+ let buffer = '';
25
+ while (true) {
26
+ const { done, value } = await reader.read();
27
+ if (done) break;
28
+ buffer += decoder.decode(value, { stream: true });
29
+ const lines = buffer.split('\n');
30
+ buffer = lines.pop();
31
+ for (const line of lines) {
32
+ if (!line.trim()) continue;
33
+ try {
34
+ const event = JSON.parse(line);
35
+ const msg = JSON.parse(event.message);
36
+ if (msg.requestId === requestId) {
37
+ clearTimeout(timer);
38
+ controller.abort();
39
+ return msg;
40
+ }
41
+ } catch {}
42
+ }
43
+ }
44
+ } catch {}
45
+ clearTimeout(timer);
46
+ return null;
47
+ }
@@ -0,0 +1,59 @@
1
+ // PermissionRequest 事件(外出模式):推送 Approve/Deny 到手机,点击后返回决策
2
+ import crypto from 'crypto';
3
+ import { loadConfig } from './config.mjs';
4
+ import { sendNotification, waitForResponse } from './ntfy.mjs';
5
+
6
+ const MESSAGE_MAX_LENGTH = 1000;
7
+
8
+ function formatMessage(tool_name, tool_input) {
9
+ let message;
10
+ if (tool_name === 'ExitPlanMode' && typeof tool_input?.plan === 'string') {
11
+ message = tool_input.plan.trim() || '(empty plan)';
12
+ } else {
13
+ switch (tool_name) {
14
+ case 'Bash':
15
+ message = tool_input?.command ?? JSON.stringify(tool_input);
16
+ break;
17
+ case 'Read':
18
+ case 'Write':
19
+ case 'Edit':
20
+ message = tool_input?.file_path ?? JSON.stringify(tool_input);
21
+ break;
22
+ default:
23
+ message = JSON.stringify(tool_input);
24
+ break;
25
+ }
26
+ }
27
+ return message.length > MESSAGE_MAX_LENGTH ? message.slice(0, MESSAGE_MAX_LENGTH) + '...' : message;
28
+ }
29
+
30
+ export async function handlePermissionRequest(input) {
31
+ const config = loadConfig();
32
+ if (!config.topic) return null;
33
+
34
+ const tool_name = input.tool_name || 'Unknown';
35
+ const message = formatMessage(tool_name, input.tool_input);
36
+ const requestId = crypto.randomUUID();
37
+ const url = `${config.server}/${config.topic}-response`;
38
+ const actions = [
39
+ { action: 'http', label: 'Approve', url, method: 'POST', clear: false, body: JSON.stringify({ requestId, approved: true }) },
40
+ { action: 'http', label: 'Deny', url, method: 'POST', clear: false, body: JSON.stringify({ requestId, approved: false }) },
41
+ ];
42
+ if (input.permission_suggestions?.length > 0) {
43
+ actions.splice(1, 0, { action: 'http', label: 'Always Approve', url, method: 'POST', clear: false, body: JSON.stringify({ requestId, approved: true, alwaysAllow: true }) });
44
+ }
45
+
46
+ const sent = await sendNotification({ ...config, title: `Claude Code: ${tool_name}`, message, actions });
47
+ if (!sent) return null;
48
+
49
+ const isPlan = tool_name === 'ExitPlanMode';
50
+ const timeout = (isPlan ? config.planTimeout : config.timeout) * 1000;
51
+ const resp = await waitForResponse({ ...config, requestId, timeout });
52
+ if (!resp) return null; // 手机超时 → 回退终端
53
+
54
+ const decision = { behavior: resp.approved === false ? 'deny' : 'allow' };
55
+ if (resp.alwaysAllow === true && input.permission_suggestions?.length > 0) {
56
+ decision.updatedPermissions = input.permission_suggestions;
57
+ }
58
+ return { hookSpecificOutput: { hookEventName: 'PermissionRequest', decision } };
59
+ }
package/src/setup.mjs ADDED
@@ -0,0 +1,72 @@
1
+ // 安装引导:生成话题、写入配置、注册 Hook、显示二维码
2
+ import crypto from 'crypto';
3
+ import fs from 'fs';
4
+ import os from 'os';
5
+ import path from 'path';
6
+ import { loadConfig, saveConfig } from './config.mjs';
7
+
8
+ const SETTINGS_PATH = path.join(os.homedir(), '.claude', 'settings.json');
9
+
10
+ // 生成唯一话题名
11
+ function generateTopic() {
12
+ return 'a4p-' + crypto.randomBytes(8).toString('hex');
13
+ }
14
+
15
+ // 把 Hook 合并写入 settings.json(保留既有配置)
16
+ export function registerHooks(settingsPath, hookCommand) {
17
+ let settings = {};
18
+ try {
19
+ settings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
20
+ } catch {}
21
+
22
+ settings.hooks = {
23
+ Stop: [{ matcher: '*', hooks: [{ type: 'command', command: hookCommand }] }],
24
+ PreToolUse: [{ matcher: 'AskUserQuestion', hooks: [{ type: 'command', command: hookCommand }] }],
25
+ PermissionRequest: [{ matcher: '*', hooks: [{ type: 'command', command: hookCommand }] }],
26
+ };
27
+ fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
28
+ fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
29
+ }
30
+
31
+ export function unregisterHooks(settingsPath) {
32
+ let settings = {};
33
+ try {
34
+ settings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
35
+ } catch {}
36
+ delete settings.hooks;
37
+ fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
38
+ }
39
+
40
+ // 计算 Hook 命令:依赖全局安装的 a4p(在 PATH 上),路径更稳
41
+ function hookCommand() {
42
+ return 'a4p hook';
43
+ }
44
+
45
+ // setup 主流程
46
+ export async function runSetup({ generateQR }) {
47
+ const config = loadConfig();
48
+ if (!config.topic) {
49
+ config.topic = generateTopic();
50
+ config.server = config.server || 'https://ntfy.sh';
51
+ }
52
+ saveConfig(config);
53
+
54
+ registerHooks(SETTINGS_PATH, hookCommand());
55
+
56
+ const subscribeUrl = `${config.server}/${config.topic}`;
57
+ const ntfyUrl = `ntfy://${new URL(config.server).host}/${config.topic}`;
58
+
59
+ process.stdout.write('a4phone 安装完成\n\n');
60
+ process.stdout.write(`话题名称: ${config.topic}\n`);
61
+ process.stdout.write(`订阅地址: ${subscribeUrl}\n\n`);
62
+
63
+ if (generateQR) {
64
+ process.stdout.write('在 ntfy App 中扫码订阅:\n\n');
65
+ generateQR(ntfyUrl, { small: true }, (qr) => process.stdout.write(qr + '\n'));
66
+ }
67
+
68
+ process.stdout.write('\n在 ntfy App 添加订阅,输入话题名称或扫描上方二维码。\n');
69
+ process.stdout.write('模式切换:a4p out(外出/手机优先) / a4p home(终端优先) / a4p status\n');
70
+ process.stdout.write('重启 Claude Code 会话后 Hook 生效。\n');
71
+ return config;
72
+ }
package/src/stop.mjs ADDED
@@ -0,0 +1,20 @@
1
+ // Stop 事件:任务完成 → 系统通知 + 手机推送
2
+ import { loadConfig } from './config.mjs';
3
+ import { sendNotification } from './ntfy.mjs';
4
+ import { systemNotify } from './notify.mjs';
5
+
6
+ export async function handleStop(input) {
7
+ const config = loadConfig();
8
+ const cwd = input.cwd || '未知目录';
9
+ const session = input.session_id ? input.session_id.slice(0, 8) : '—';
10
+ const details = `任务已完成\n目录: ${cwd}\n会话: ${session}`;
11
+ await systemNotify('Claude Code', '任务已完成');
12
+ if (config.topic) {
13
+ await sendNotification({
14
+ ...config,
15
+ title: 'Claude Code',
16
+ message: details,
17
+ });
18
+ }
19
+ return null; // Stop Hook 无需输出
20
+ }