a4phone 1.1.7 → 1.2.1

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
@@ -8,7 +8,8 @@ Claude Code / Codex / DSH(DeepSeek Harness)远程手机交互包。通过 [n
8
8
  - **AI 提问交互**:`AskUserQuestion`(Codex 为 `request_user_input`,DSH 为 `ask_user_question`)→ 手机显示选项按钮点选,也可直接发送文字自由作答
9
9
  - **权限请求交互**:`PermissionRequest` → 手机 Approve/Deny/Always Approve
10
10
  - **DSH 一键挂载**:`a4p setup` 自动把内置 `dsh-hook` 插件挂到 DSH web profile,让 DeepSeek Harness 同样具备手机交互
11
- - **远程续聊**:守护进程监听主话题,手机发文字即可与当前会话交流,形成完整远程对话闭环(Claude Code / Codex)
11
+ - **远程续聊**:守护进程监听主话题,手机发文字即可与当前会话交流,形成完整远程对话闭环(Claude Code / Codex / DSH)
12
+ - **DSH 远程续聊**:手机发文字直接注入 DSH 正在运行的会话(`agent.followup`),手机消息与 AI 回复**实时出现在桌面端会话里**,无需另起进程、无会话锁冲突
12
13
  - **后台守护进程**:`a4p listen` 无窗口后台运行,日志写入文件
13
14
  - **双模式**:外出模式(手机优先)/ 终端优先模式,一键切换
14
15
  - **零第三方依赖**:仅依赖 ntfy.sh 免费服务,无 Google 服务依赖
@@ -68,7 +69,7 @@ a4p status # 查看当前模式
68
69
 
69
70
  ### 远程续聊
70
71
 
71
- 在手机端直接向**主话题 `{topic}`** 发送文字,即可与最近会话(Claude Code / Codex)继续对话——无需额外的续聊话题,你订阅的通知话题就是对话通道。
72
+ 在手机端直接向**主话题 `{topic}`** 发送文字,即可与最近会话(Claude Code / Codex / DSH)继续对话——无需额外的续聊话题,你订阅的通知话题就是对话通道。
72
73
 
73
74
  1. 启动续聊守护进程(后台无窗口运行):
74
75
 
@@ -82,7 +83,7 @@ a4p status # 查看当前模式
82
83
 
83
84
  2. 手机 ntfy App 已订阅主话题 `{topic}`(`a4p setup` 生成,扫描二维码即可),向该话题发送任意文字即可。
84
85
 
85
- 3. 守护进程收到手机消息后,按最近会话的 agent 执行续聊(Claude Code:`claude --resume <会话> --continue -p`;Codex:`codex exec resume <会话> -o <临时文件> -`,`-o` 捕获最后一条回复),均为 headless,stdin 作为下一条消息,捕获回复后推回手机)。Codex 会话若被窗口占用(thread-store conflict),a4phone 会自动把它 fork 成新线程续聊——**不需要关闭原窗口**,原会话原样保留,手机对话在 fork 上继续。
86
+ 3. 守护进程收到手机消息后,按最近会话的 agent 执行续聊(Claude Code:`claude --resume <会话> --continue -p`;Codex:`codex exec resume <会话> -o <临时文件> -`,`-o` 捕获最后一条回复;DSH:经文件队列交给 `dsh web` 进程内的插件直接 `followup` 到当前 live 会话)。均为 headless,捕获回复后推回手机。Codex 会话若被窗口占用(thread-store conflict),a4phone 会自动把它 fork 成新线程续聊——**不需要关闭原窗口**,原会话原样保留,手机对话在 fork 上继续。
86
87
 
87
88
  4. 无需守护进程时,也可在电脑上手动续聊:
88
89
 
@@ -96,7 +97,9 @@ a4p status # 查看当前模式
96
97
  a4p last
97
98
  ```
98
99
 
99
- > 续聊完全 headless 运行(无需窗口标题匹配、前台焦点或剪贴板,也不依赖你当前是否开着终端),支持 Claude Code 与 Codex 会话(按最近会话的 agent 自动选择续聊命令)。续聊回合内若再次触发提问/权限请求,仍会推送手机,形成完整的远程对话闭环。
100
+ > 续聊完全 headless 运行(无需窗口标题匹配、前台焦点或剪贴板,也不依赖你当前是否开着终端),支持 Claude Code、Codex 与 DSH 会话(按最近会话的 agent 自动选择续聊方式)。续聊回合内若再次触发提问/权限请求,仍会推送手机,形成完整的远程对话闭环。
101
+ >
102
+ > **积压合并**:一轮续聊最长可达 `resumeTimeout`(默认 30 分钟),期间手机连续发来的消息会自动**合并为一个批次**一次性续聊(不再逐条排队、每条一个独立轮次),保证手机内容一定能送达 AI;积压批次持久化到 `~/.a4phone/pending-batch.json`,守护进程重启/崩溃后自动恢复,不丢消息。
100
103
 
101
104
  ## Codex
102
105
 
@@ -136,13 +139,25 @@ command = "a4p hook codex"
136
139
  | 任务完成 | `turn/end` 且 `reason.kind === 'completed'` | 系统通知 + 手机推送(含 AI 最后输出) |
137
140
  | 提问 | `ask_user_question` 工具调用 | 手机点选选项 / 文字自由作答 |
138
141
  | 权限请求 | `approval/request` | 手机 Approve / Deny |
142
+ | 远程续聊 | 文件队列 `~/.a4phone/dsh-jobs/`(a4p 写请求,插件回复) | 手机发文字 → `agent.followup` 注入当前会话 → 回复推回手机 |
139
143
 
140
144
  - 插件位于本包 `dsh/` 目录(Cordis 插件,监听 DSH 的 `session/event`、`tools/execute`、`approval/request` 事件),`a4p setup` 以 insert 形式写入 patch,幂等可重复执行
141
145
  - 若检测到旧版手动挂载(指向 `C:\ProgramMine\dsh-hook` 的 `id: dsh-hook`),`a4p setup` 会自动替换为本包路径
142
146
  - `cordis.patch.yml` 被 DSH 热监视(`watchUserPatches`),挂载即时生效;若插件代码有更新,建议重启 `dsh web`(可参考 `restart-dsh-web.ps1` 的思路)
143
147
  - 模式切换复用同一套:`a4p out`(手机优先)/ `a4p home`(终端优先);Hook 日志写入 `~/.a4phone/dsh-logs/`
144
148
  - 目前仅挂载到 `web` profile;`a4p uninstall` 会同时移除该挂载
145
- - 远程续聊(手机发文字继续 DSH 会话)暂未支持,`a4p resume` 仍只服务 Claude Code / Codex 会话
149
+
150
+ ### DSH 远程续聊
151
+
152
+ 手机向主话题发文字即可继续 DSH 会话,机制与 Claude Code / Codex 的续聊不同:
153
+
154
+ 1. **记录最近会话**:插件在每次顶层会话 `turn/end`(completed)时写入 `~/.a4phone/last.json`(`agent: "DSH"`),与 Claude Code / Codex 的 Stop Hook 一致
155
+ 2. **文件队列协议**:`a4p resume` / `a4p listen` 把手机消息原子写入 `~/.a4phone/dsh-jobs/req-<id>.json`;插件每秒扫描,处理后写 `resp-<id>.json`,a4p 轮询取回并推回手机;插件同时刷新 `~/.a4phone/dsh-heartbeat.json` 心跳,a4p 据此快速判断 `dsh web` 是否在运行(未运行会快速失败而非干等超时)
156
+ 3. **注入到桌面会话**:插件用 `agent.followup()` 把手机文字作为普通 `user/message` 写入**桌面上正在运行的同一个会话**(`ctx.agents` 解析:优先 `last.json` 记录的会话,兜底最近顶层会话),`await agent.whenIdle()` 等待轮次结束,提取最后一条 assistant 文本回推——手机消息与 AI 回复都会**实时出现在桌面端会话里**,桌面与手机看到同一段对话
157
+ 4. **无会话锁冲突**:不另起进程,所以不存在 Claude Code `--resume` 式的独占锁问题;续聊轮次内若触发提问/审批,仍走手机交互,形成完整闭环
158
+ 5. 续聊轮次的"任务完成"推送已自动去重(回复由 a4p 推回,插件不再重复通知)
159
+
160
+ > 前提:`dsh web` 正在运行且已挂载新版 `dsh-hook` 插件(`a4p setup` 自动挂载,插件代码更新后需重启 `dsh web`)。未检测到 `dsh web` 时续聊会快速失败并给出提示。
146
161
 
147
162
  ## 原理
148
163
 
@@ -158,8 +173,11 @@ AI助手触发事件 → a4p hook → ntfy.sh 推送手机 → 手机点选/文
158
173
  手机向 {topic} 发文字 → 守护进程 a4p listen
159
174
  → claude --resume <会话> --continue -p(headless,stdin 作为消息)
160
175
  → 或 codex exec resume <会话> -o <临时文件> -(Codex,-o 捕获最后一条回复)
176
+ → 或 DSH:a4p 写 req 文件 → dsh web 进程内插件 agent.followup 注入会话
177
+ → whenIdle 等待轮次结束 → 提取回复写 resp 文件 → a4p 轮询取回
161
178
  → AI 回复写入会话并回推手机
162
179
  →(Codex 会话被窗口占用时自动 fork 新线程续聊,无需关闭原窗口)
180
+ →(DSH 续聊直接发生在桌面正在运行的会话上,手机与桌面看到同一段对话)
163
181
  ```
164
182
 
165
183
  ### Hook 输出格式
@@ -171,15 +189,15 @@ AI助手触发事件 → a4p hook → ntfy.sh 推送手机 → 手机点选/文
171
189
 
172
190
  - 需 Node.js 18+,手机端安装 ntfy App
173
191
  - 手机订阅后,请在**订阅设置**中开启"即时交付",否则消息需手动刷新才能收到
174
- - 续聊支持 Claude Code 与 Codex 会话(按最近会话的 agent 自动选择命令);Codex 续聊通过 `codex exec resume` 执行,需 Codex CLI 已登录、hook 已信任
175
- - DSH 支持任务完成通知 / 提问作答 / 权限审批(经内置 `dsh-hook` 插件),但远程续聊暂未支持
192
+ - 续聊支持 Claude Code、Codex 与 DSH 会话(按最近会话的 agent 自动选择方式);Codex 续聊通过 `codex exec resume` 执行,需 Codex CLI 已登录、hook 已信任;DSH 续聊需 `dsh web` 正在运行且已挂载新版插件
193
+ - DSH 支持任务完成通知 / 提问作答 / 权限审批 / 远程续聊(经内置 `dsh-hook` 插件)
176
194
  - 续聊期间守护进程会自动临时切换为外出模式,结束后恢复原模式
177
195
  - Claude Code 会话同一时间只能被一个进程占用,`--resume` 续聊前请先结束终端里仍在运行的原会话;Codex 会话被占用时 a4phone 会自动 fork 新线程续聊(复制会话为新线程 ID,原窗口不受影响,手机对话在 fork 上继续)
178
196
  - 续聊守护进程需后台常驻:Windows 用 `a4p listen` 或计划任务,WSL/Linux 可用 tmux 或 systemd
179
197
  - **ntfy.sh 免费托管服务有发布速率/消息保留限制**:短时间高频测试可能触发 `limited` 提示,建议降低推送频率(续聊结果已去重推送,不再重复通知)
180
198
  - ntfy.sh 公共话题可被知晓话题名的人读写,重要场景建议自建 ntfy 服务或使用访问令牌
181
199
  - ntfy.sh 为国外服务,国内网络下长连接可能不稳定
182
- - 配置存储于 `~/.a4phone/config.json`,最近会话存储于 `~/.a4phone/last.json`,模式存储于 `~/.a4phone/mode.json`,守护进程信息存储于 `~/.a4phone/daemon.json`,日志写入 `~/.a4phone/daemon.log`;DSH Hook 日志写入 `~/.a4phone/dsh-logs/`
200
+ - 配置存储于 `~/.a4phone/config.json`,最近会话存储于 `~/.a4phone/last.json`,模式存储于 `~/.a4phone/mode.json`,守护进程信息存储于 `~/.a4phone/daemon.json`,日志写入 `~/.a4phone/daemon.log`;DSH Hook 日志写入 `~/.a4phone/dsh-logs/`,DSH 续聊队列位于 `~/.a4phone/dsh-jobs/`,心跳位于 `~/.a4phone/dsh-heartbeat.json`
183
201
 
184
202
  ## 开发
185
203
 
package/dsh/lib/index.js CHANGED
@@ -20,18 +20,21 @@ import { appendFileSync, mkdirSync } from 'node:fs';
20
20
  import path from 'node:path';
21
21
  import { fileURLToPath } from 'node:url';
22
22
  import { A4P_DIR } from '../../src/paths.mjs';
23
+ import { saveLastSession } from '../../src/config.mjs';
23
24
  import {
24
25
  handleTaskComplete,
25
26
  handleAskUserQuestion,
26
27
  handleApprovalRequest,
27
28
  rememberAssistantOutput,
28
29
  } from './phone-hooks.mjs';
30
+ import { startResumeService, isResumeInflight } from './resume-service.mjs';
29
31
 
30
32
  const name = 'dsh-hook';
31
33
 
32
34
  // 监听 tools/execute 与 approval/request 需要注入这两个服务;
33
35
  // session/event 直接 ctx.on 即可(与 dsh-session-telemetry 一致)。
34
- const inject = ['tools', 'approval'];
36
+ // agents 供续聊服务解析目标会话(ctx.agents.get / roots)。
37
+ const inject = ['tools', 'approval', 'agents'];
35
38
 
36
39
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
37
40
 
@@ -78,6 +81,8 @@ function apply(ctx, config = {}) {
78
81
  const enableQuestionAsked = config.questionAsked !== false;
79
82
  // phone: false 可整体关闭手机交互(保留日志记录),默认开启
80
83
  const phoneEnabled = config.phone !== false;
84
+ // resume: false 可关闭 DSH 会话续聊服务(默认开启)
85
+ const enableResume = config.resume !== false;
81
86
 
82
87
  // ── 会话事件流:任务完成 + 问题询问日志 + AI 最后输出缓存 ─────────────
83
88
  ctx.on('session/event', (session, event) => {
@@ -90,16 +95,28 @@ function apply(ctx, config = {}) {
90
95
  }
91
96
 
92
97
  // Hook 1: 任务完成
93
- if (enableTaskComplete && type === 'turn/end' && data?.reason?.kind === 'completed') {
94
- record(ctx, logDir, 'task-complete', {
95
- sessionId: session.id,
96
- turn: data.turn,
97
- reasonKind: data.reason.kind,
98
- });
99
- if (phoneEnabled) {
100
- handleTaskComplete(session.id, { turn: data.turn }).catch((error) =>
101
- ctx.logger.warn(`dsh-hook: 任务完成推送失败: ${String(error)}`)
102
- );
98
+ if (type === 'turn/end' && data?.reason?.kind === 'completed') {
99
+ // 记录最近会话(仅顶层会话,不含 subagent),供续聊(a4p resume / a4p listen)使用
100
+ if (enableResume && !session.header?.parentSession) {
101
+ saveLastSession({
102
+ session_id: session.id,
103
+ cwd: session.header?.cwd || '未知目录',
104
+ agent: 'DSH',
105
+ turn: data.turn,
106
+ });
107
+ }
108
+ if (enableTaskComplete) {
109
+ record(ctx, logDir, 'task-complete', {
110
+ sessionId: session.id,
111
+ turn: data.turn,
112
+ reasonKind: data.reason.kind,
113
+ });
114
+ // 续聊轮次的完成已由 a4p 推回手机(含回复文本),此处跳过重复推送
115
+ if (phoneEnabled && !isResumeInflight(session.id)) {
116
+ handleTaskComplete(session.id, { turn: data.turn }).catch((error) =>
117
+ ctx.logger.warn(`dsh-hook: 任务完成推送失败: ${String(error)}`)
118
+ );
119
+ }
103
120
  }
104
121
  }
105
122
 
@@ -177,7 +194,17 @@ function apply(ctx, config = {}) {
177
194
  });
178
195
  }
179
196
 
180
- ctx.logger.info('dsh-hook: 已挂载三个 hook(task-complete / permission-request / question-asked)');
197
+ // ── 远程续聊服务:手机消息(经 a4p 写入文件队列)→ followup 注入会话 ─────
198
+ // 与桌面端共享同一个 live 会话:手机文字会以 user/message 出现在桌面会话中,
199
+ // AI 回复同样写入会话(桌面实时可见),并经 a4p 推回手机。
200
+ const stopResume = enableResume ? startResumeService(ctx) : () => {};
201
+
202
+ ctx.logger.info('dsh-hook: 已挂载三个 hook(task-complete / permission-request / question-asked)与续聊服务');
203
+
204
+ // 返回卸载函数:插件卸载(HMR / dsh web 退出)时停止轮询
205
+ return () => {
206
+ stopResume();
207
+ };
181
208
  }
182
209
 
183
210
  export { apply, inject, name };
@@ -0,0 +1,262 @@
1
+ // resume-service.mjs — dsh-hook 的 DSH 会话续聊服务(运行在 dsh web 进程内)
2
+ //
3
+ // a4p(续聊守护进程 a4p listen / 手动 a4p resume)把手机消息写成
4
+ // ~/.a4phone/dsh-jobs/req-<id>.json;本服务轮询该目录,对每个请求:
5
+ // 1. 解析出目标 agent(请求指定 sessionId 且仍 live → 用之;否则最近的
6
+ // 顶层会话 root agent)
7
+ // 2. agent.followup(用户消息) —— 与桌面端 web GUI 完全相同的会话、相同
8
+ // 的模型配置;消息以 user/message 事件写入会话日志,桌面端实时可见
9
+ // 3. await agent.whenIdle() 等待该轮次彻底结束
10
+ // 4. 从会话事件日志中提取最后一条 assistant 文本作为回复
11
+ // 5. 写 ~/.a4phone/dsh-jobs/resp-<id>.json 供 a4p 轮询取回
12
+ //
13
+ // 与官方 dsh-headless runner 的驱动方式一致(followup + whenIdle + 提取
14
+ // 最后 assistant 文本)。请求文件先删除再处理(at-most-once 语义:进程中途
15
+ // 崩溃不会导致同一条手机消息被重复注入会话)。
16
+ //
17
+ // 协议(a4p ↔ 插件,同一台机器,目录 = DSH_JOB_DIR):
18
+ // req-<id>.json { id, sessionId?, text, ts } a4p 原子写入
19
+ // resp-<id>.json { id, ok, reply?, reasonKind?, error?, sessionId? }
20
+ // dsh-heartbeat.json { alive: true, ts } 每次轮询刷新
21
+
22
+ import fs from 'node:fs';
23
+ import path from 'node:path';
24
+ import crypto from 'node:crypto';
25
+ import { DSH_JOB_DIR, DSH_HEARTBEAT } from '../../src/paths.mjs';
26
+
27
+ const POLL_INTERVAL_MS = 1000;
28
+ const HEARTBEAT_MAX_AGE_MS = 10_000; // a4p 据此判断 dsh web 是否存活
29
+ // 孤儿 resp 文件清理:daemon 读取后即删;超过该时长仍未取走的视为遗留,回收
30
+ const ORPHAN_RESP_MAX_AGE_MS = 60 * 60 * 1000;
31
+
32
+ /** 正在被续聊服务驱动的会话集合(用于抑制任务完成推送的重复通知) */
33
+ const inflightResume = new Set();
34
+
35
+ /** 续聊是否正在驱动该会话(turn/end 钩子据此跳过手机"任务完成"推送) */
36
+ export function isResumeInflight(sessionId) {
37
+ return inflightResume.has(sessionId);
38
+ }
39
+
40
+ /**
41
+ * 从会话事件日志中提取续聊轮次的回复(纯函数,便于测试)。
42
+ * 语义与 dsh-headless 的 summarize 对齐:只统计 seq >= boundarySeq 的事件,
43
+ * 取其中最后一条非空 assistant 文本;reasonKind 为该区间最后一个 turn/end。
44
+ * @param {Array<{seq:number,type:string,data?:any}>} events 会话事件快照(按 seq 升序)
45
+ * @param {number} boundarySeq followup 前的 seq(日志长度)
46
+ * @returns {{ reply: string|null, reasonKind: string|null, turn: number|null }}
47
+ */
48
+ export function extractReply(events, boundarySeq) {
49
+ let reasonKind = null;
50
+ let turn = null;
51
+ let reply = null;
52
+ for (const event of events) {
53
+ if (event.seq < boundarySeq) continue;
54
+ if (event.type === 'turn/end') {
55
+ reasonKind = event.data?.reason?.kind ?? null;
56
+ turn = event.data?.turn ?? null;
57
+ }
58
+ if (event.type === 'assistant/message') {
59
+ const text = (event.data?.message?.content ?? [])
60
+ .filter((b) => b?.type === 'text' && typeof b.text === 'string')
61
+ .map((b) => b.text)
62
+ .join('');
63
+ if (text) reply = text;
64
+ }
65
+ }
66
+ return { reply, reasonKind, turn };
67
+ }
68
+
69
+ /** 取最近一个顶层(非 subagent)会话作为兜底续聊目标 */
70
+ function mostRecentRoot(agents) {
71
+ const roots = agents.roots?.() ?? [];
72
+ return roots.length ? roots[roots.length - 1] : null;
73
+ }
74
+
75
+ /** 解析目标 agent:请求指定 sessionId 且仍 live → 用之;否则最近的 root */
76
+ function resolveAgent(agents, req) {
77
+ if (req.sessionId) {
78
+ const agent = agents.get?.(req.sessionId);
79
+ if (agent) return agent;
80
+ }
81
+ return mostRecentRoot(agents);
82
+ }
83
+
84
+ /** 原子写 JSON 文件(临时文件 + rename,避免读者读到半个文件) */
85
+ function atomicWriteJson(filePath, data) {
86
+ const tmp = `${filePath}.${process.pid}.${Date.now()}.tmp`;
87
+ fs.writeFileSync(tmp, JSON.stringify(data));
88
+ fs.renameSync(tmp, filePath);
89
+ }
90
+
91
+ /** 构造一条普通用户消息(与 createUserMessage 等价,不引入 @deepseek-ai 依赖) */
92
+ function buildUserMessage(text) {
93
+ return {
94
+ id: crypto.randomUUID(),
95
+ role: 'user',
96
+ content: [{ type: 'text', text }],
97
+ source: { kind: 'user' },
98
+ };
99
+ }
100
+
101
+ /**
102
+ * 在指定 agent 上执行一轮续聊:注入用户消息 → 等待轮次结束 → 提取回复。
103
+ * 与桌面端共享同一个 live 会话(同一模型配置,消息与回复实时写入会话日志)。
104
+ * @param {object} agent Agent(agent.followup / whenIdle / session)
105
+ * @param {string} text 续聊内容
106
+ * @returns {Promise<{reply:string|null, reasonKind:string|null, turn:number|null, failed:boolean, error:string|null, sessionId:string}>}
107
+ */
108
+ export async function executeResumeTurn(agent, text) {
109
+ const boundarySeq = agent.session.seq;
110
+ inflightResume.add(agent.id);
111
+ try {
112
+ agent.followup(buildUserMessage(text));
113
+ await agent.whenIdle();
114
+ const { reply, reasonKind, turn } = extractReply(agent.session.events, boundarySeq);
115
+ const failed =
116
+ reasonKind === 'error' || reasonKind === 'aborted' ||
117
+ reasonKind === 'cancelled' || reasonKind === 'blocked';
118
+ return {
119
+ reply: reply || null,
120
+ reasonKind: reasonKind ?? null,
121
+ turn: turn ?? null,
122
+ failed,
123
+ error: failed
124
+ ? `会话轮次结束状态:${reasonKind}${reasonKind === 'error' ? '(模型调用失败)' : ''}`
125
+ : null,
126
+ sessionId: agent.id,
127
+ };
128
+ } catch (error) {
129
+ return {
130
+ reply: null,
131
+ reasonKind: null,
132
+ turn: null,
133
+ failed: true,
134
+ error: `续聊执行异常:${error instanceof Error ? error.message : String(error)}`,
135
+ sessionId: agent.id,
136
+ };
137
+ } finally {
138
+ inflightResume.delete(agent.id);
139
+ }
140
+ }
141
+
142
+ /**
143
+ * 处理一条续聊请求:解析目标 agent → 执行续聊 → 写 resp 文件。
144
+ * 注意:调用方应确保 agents 服务可用(否则跳过,保留请求文件)。
145
+ * @param {import('@deepseek-ai/cordis').Context} ctx
146
+ * @param {object} agents AgentRegistry 服务(ctx.get('agents'))
147
+ * @param {{id:string, sessionId?:string|null, text:string}} req
148
+ * @param {string} [dir] 响应文件目录(默认 DSH_JOB_DIR)
149
+ */
150
+ async function processRequest(ctx, agents, req, dir = DSH_JOB_DIR) {
151
+ const text = String(req?.text ?? '').trim();
152
+ if (!text) {
153
+ atomicWriteJson(respPath(req.id, dir), { id: req.id, ok: false, error: '续聊内容为空。' });
154
+ return;
155
+ }
156
+
157
+ const agent = resolveAgent(agents, req);
158
+ if (!agent) {
159
+ atomicWriteJson(respPath(req.id, dir), {
160
+ id: req.id,
161
+ ok: false,
162
+ error: '没有可续聊的 DSH 会话(请先在桌面端开始并完成一轮会话)。',
163
+ });
164
+ return;
165
+ }
166
+
167
+ const outcome = await executeResumeTurn(agent, text);
168
+ atomicWriteJson(respPath(req.id, dir), {
169
+ id: req.id,
170
+ ok: !outcome.failed,
171
+ reply: outcome.reply,
172
+ reasonKind: outcome.reasonKind,
173
+ turn: outcome.turn,
174
+ sessionId: outcome.sessionId,
175
+ ...(outcome.error ? { error: outcome.error } : {}),
176
+ });
177
+ }
178
+
179
+ function respPath(id, dir = DSH_JOB_DIR) {
180
+ return path.join(dir, `resp-${id}.json`);
181
+ }
182
+
183
+ /**
184
+ * 启动续聊服务:定期扫描请求目录 + 刷新心跳。返回停止函数(卸载时调用)。
185
+ * @param {import('@deepseek-ai/cordis').Context} ctx
186
+ * @param {{dir?:string, heartbeatPath?:string}} [opts] 覆盖队列目录/心跳路径(测试用)
187
+ */
188
+ export function startResumeService(ctx, { dir = DSH_JOB_DIR, heartbeatPath = DSH_HEARTBEAT } = {}) {
189
+ fs.mkdirSync(dir, { recursive: true });
190
+ let busy = false;
191
+
192
+ const scan = async () => {
193
+ // 心跳:a4p 守护进程据此判断 dsh web 是否在运行(快速失败而非干等超时)
194
+ try {
195
+ atomicWriteJson(heartbeatPath, { alive: true, ts: Date.now() });
196
+ } catch {}
197
+ if (busy) return;
198
+ busy = true;
199
+ try {
200
+ let files = [];
201
+ try {
202
+ files = fs.readdirSync(dir).filter((f) => f.startsWith('req-') && f.endsWith('.json'));
203
+ } catch {
204
+ return;
205
+ }
206
+ // 清理孤儿 resp(daemon 未取走的遗留文件)
207
+ try {
208
+ const now = Date.now();
209
+ for (const f of fs.readdirSync(dir)) {
210
+ if (!f.startsWith('resp-') || !f.endsWith('.json')) continue;
211
+ const p = path.join(dir, f);
212
+ try {
213
+ if (now - fs.statSync(p).mtimeMs > ORPHAN_RESP_MAX_AGE_MS) fs.unlinkSync(p);
214
+ } catch {}
215
+ }
216
+ } catch {}
217
+ for (const f of files.sort()) {
218
+ const id = f.slice('req-'.length, -'.json'.length);
219
+ const reqPath = path.join(dir, f);
220
+ let req;
221
+ try {
222
+ req = JSON.parse(fs.readFileSync(reqPath, 'utf-8'));
223
+ } catch {
224
+ // 请求文件损坏(如带 BOM / 半截写入):写错误响应而非静默丢弃,
225
+ // 让 a4p 能给用户明确提示而不是干等超时
226
+ try { fs.unlinkSync(reqPath); } catch {}
227
+ try {
228
+ atomicWriteJson(respPath(id, dir), { id, ok: false, error: '续聊请求格式无效(文件损坏或被截断)。' });
229
+ } catch {}
230
+ continue;
231
+ }
232
+ // agents 服务未就绪(插件挂载初期):保留请求文件,等下一轮扫描
233
+ const agents = ctx.get('agents');
234
+ if (!agents) continue;
235
+ // 先删请求文件再处理(at-most-once:崩溃不会重复注入同一条消息)
236
+ try { fs.unlinkSync(reqPath); } catch {}
237
+ try {
238
+ await processRequest(ctx, agents, req, dir);
239
+ } catch (error) {
240
+ ctx?.logger?.warn?.(`dsh-resume: 请求 ${id} 处理失败: ${String(error)}`);
241
+ try {
242
+ atomicWriteJson(respPath(id, dir), { id, ok: false, error: String(error?.message ?? error) });
243
+ } catch {}
244
+ }
245
+ }
246
+ } catch (error) {
247
+ ctx?.logger?.warn?.(`dsh-resume: 轮询异常: ${String(error)}`);
248
+ } finally {
249
+ busy = false;
250
+ }
251
+ };
252
+
253
+ const timer = setInterval(() => {
254
+ scan().catch(() => {});
255
+ }, POLL_INTERVAL_MS);
256
+ scan().catch(() => {});
257
+
258
+ return () => clearInterval(timer);
259
+ }
260
+
261
+ /** 仅供测试:暴露轮询间隔常量 */
262
+ export const internals = { POLL_INTERVAL_MS, HEARTBEAT_MAX_AGE_MS };
package/dsh/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "a4phone-dsh-hook",
3
- "description": "a4phone DSH hook plugin: task-complete, permission-request, and question-asked hooks (mounted into DeepSeek Harness via a4p setup)",
3
+ "description": "a4phone DSH plugin: task-complete, permission-request, and question-asked hooks plus remote resume service (mounted into DeepSeek Harness via a4p setup)",
4
4
  "version": "1.0.0",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -16,8 +16,8 @@
16
16
  },
17
17
  "@deepseek-ai/cordis": {
18
18
  "description": {
19
- "en": "Hook: task-complete / permission-request / question-asked",
20
- "zh": "Hook:任务完成 / 权限请求 / 问题询问"
19
+ "en": "Hooks: task-complete / permission-request / question-asked + remote resume",
20
+ "zh": "Hook:任务完成 / 权限请求 / 问题询问 + 远程续聊"
21
21
  }
22
22
  }
23
23
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "a4phone",
3
- "version": "1.1.7",
4
- "description": "Claude Code / Codex 远程手机交互:任务完成通知(含 AI 最后输出)、提问/权限请求手机点选或文字作答、远程续聊(ntfy.sh)",
3
+ "version": "1.2.1",
4
+ "description": "Claude Code / Codex / DSH 远程手机交互:任务完成通知(含 AI 最后输出)、提问/权限请求手机点选或文字作答、远程续聊(ntfy.sh,含 DSH 会话续聊)",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "a4p": "bin/a4p.mjs"
@@ -0,0 +1,75 @@
1
+ // batcher.mjs — 串行批处理器
2
+ //
3
+ // 解决续聊守护进程的积压问题:一轮续聊最长可达 resumeTimeout(默认 1800 秒),
4
+ // 期间手机发来的消息若逐条排队,每条都会触发一个独立的续聊轮次(N 条 = N 轮),
5
+ // 手机内容会被无限期延迟。本模块把忙时到达的消息**合并为一个批次**,
6
+ // 当前轮结束后一次处理整批——任意数量积压最多只产生一条额外续聊轮次,
7
+ // 保证手机内容一定能送达 AI(顺序保留、串行执行、有界延迟)。
8
+ //
9
+ // 用法:
10
+ // const batcher = createBatcher({
11
+ // run: async ({ text, count, msgTime }) => { ...; return true }, // false=丢弃该批
12
+ // log: (msg) => ...,
13
+ // });
14
+ // batcher.submit(text, msgTime); // 立即返回 drain 的 promise(fire-and-forget 也行)
15
+ // batcher.restore(texts, msgTime); // 启动时恢复上次未处理的批次
16
+ // batcher.pendingCount / batcher.pendingSnapshot() // 持久化与检查用
17
+ export function createBatcher({ run, log = () => {} }) {
18
+ let draining = null; // 正在执行的 drain 循环(防止并发)
19
+ const pending = { texts: [], msgTime: null };
20
+
21
+ function enqueue(text, msgTime) {
22
+ pending.texts.push(text);
23
+ pending.msgTime = pending.msgTime == null ? msgTime : Math.min(pending.msgTime, msgTime);
24
+ if (pending.texts.length === 2) {
25
+ log('当前续聊进行中,后续消息将合并为一条续聊请求');
26
+ }
27
+ }
28
+
29
+ // 串行排空循环:一次处理一批,过时/被拒批次丢弃后继续下一批(不会停顿)
30
+ function drain() {
31
+ if (!draining) {
32
+ draining = (async () => {
33
+ try {
34
+ while (pending.texts.length) {
35
+ const texts = pending.texts;
36
+ const msgTime = pending.msgTime;
37
+ pending.texts = [];
38
+ pending.msgTime = null;
39
+ try {
40
+ await run({ text: texts.join('\n\n'), count: texts.length, msgTime });
41
+ } catch (error) {
42
+ log(`批次处理异常(已跳过该批): ${String(error?.message ?? error)}`);
43
+ }
44
+ }
45
+ } finally {
46
+ draining = null;
47
+ }
48
+ })();
49
+ }
50
+ return draining;
51
+ }
52
+
53
+ return {
54
+ /** 提交一条消息;忙时自动合并进当前批次 */
55
+ submit(text, msgTime) {
56
+ enqueue(text, msgTime);
57
+ return drain();
58
+ },
59
+ /** 启动时恢复上次未处理完的批次(触发排空) */
60
+ restore(texts, msgTime) {
61
+ if (!Array.isArray(texts) || !texts.length) return;
62
+ for (const t of texts) pending.texts.push(String(t));
63
+ pending.msgTime = msgTime ?? null;
64
+ drain();
65
+ },
66
+ /** 当前积压条数(0 = 无积压) */
67
+ get pendingCount() {
68
+ return pending.texts.length;
69
+ },
70
+ /** 当前批次快照(供持久化) */
71
+ pendingSnapshot() {
72
+ return { texts: [...pending.texts], msgTime: pending.msgTime };
73
+ },
74
+ };
75
+ }
@@ -0,0 +1,150 @@
1
+ // DSH 续聊(a4p 侧):把手机发来的文本交给 dsh web 进程内的插件续聊,取回回复并推送手机
2
+ //
3
+ // 通信协议(文件队列,同一台机器):
4
+ // a4p 写 ~/.a4phone/dsh-jobs/req-<id>.json { id, sessionId?, text, ts }
5
+ // 插件写 ~/.a4phone/dsh-jobs/resp-<id>.json { id, ok, reply?, reasonKind?, error?, sessionId? }
6
+ // 插件每 ~/.a4phone/dsh-heartbeat.json 刷新一次心跳,a4p 据此快速判断 dsh web 是否存活
7
+ //
8
+ // 与 Claude Code / Codex 续聊的区别:
9
+ // - 不另起进程,而是让 dsh web 进程内直接 followup 到当前 live 会话,
10
+ // 手机消息与 AI 回复都会实时出现在桌面端会话里,且无会话锁冲突
11
+ // - 前提:dsh web 正在运行且已挂载新版 dsh-hook 插件(含续聊服务)
12
+ import fs from 'fs';
13
+ import path from 'path';
14
+ import crypto from 'crypto';
15
+ import { DSH_JOB_DIR, DSH_HEARTBEAT } from './paths.mjs';
16
+ import { loadConfig, loadLastSession } from './config.mjs';
17
+ import { sendNotification } from './ntfy.mjs';
18
+
19
+ const POLL_INTERVAL_MS = 500; // 轮询回复文件的间隔
20
+ const MAX_REPLY = 1000; // 回推输出截断长度(与 Claude/Codex 续聊一致)
21
+ const HEARTBEAT_MAX_AGE_MS = 10_000; // 心跳超过 10 秒视为 dsh web(插件)未运行
22
+
23
+ /** 心跳新鲜度(毫秒);读不到或解析失败返回 Infinity(视为已死) */
24
+ export function heartbeatAgeMs(filePath = DSH_HEARTBEAT) {
25
+ try {
26
+ const hb = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
27
+ if (!hb || typeof hb.ts !== 'number') return Infinity;
28
+ return Date.now() - hb.ts;
29
+ } catch {
30
+ return Infinity;
31
+ }
32
+ }
33
+
34
+ /** dsh web(dsh-hook 插件)是否存活:心跳新鲜且未超龄 */
35
+ export function isDshAlive(maxAgeMs = HEARTBEAT_MAX_AGE_MS, filePath = DSH_HEARTBEAT) {
36
+ return heartbeatAgeMs(filePath) <= maxAgeMs;
37
+ }
38
+
39
+ /** 构造一条续聊请求(纯函数,便于测试) */
40
+ export function buildResumeRequest(text, sessionId) {
41
+ return { id: crypto.randomUUID(), sessionId: sessionId ?? null, text, ts: Date.now() };
42
+ }
43
+
44
+ /** 原子写入请求文件(临时文件 + rename,避免插件读到半个文件) */
45
+ export function writeRequest(req, dir = DSH_JOB_DIR) {
46
+ fs.mkdirSync(dir, { recursive: true });
47
+ const tmp = path.join(dir, `.req-${req.id}.${process.pid}.tmp`);
48
+ const dst = path.join(dir, `req-${req.id}.json`);
49
+ fs.writeFileSync(tmp, JSON.stringify(req));
50
+ fs.renameSync(tmp, dst);
51
+ }
52
+
53
+ /** 读取响应文件;不存在/解析失败返回 null(纯读取,删除由 waitForResponseFile 负责) */
54
+ export function readResponse(id, dir = DSH_JOB_DIR) {
55
+ try {
56
+ return JSON.parse(fs.readFileSync(path.join(dir, `resp-${id}.json`), 'utf-8'));
57
+ } catch {
58
+ return null;
59
+ }
60
+ }
61
+
62
+ /** 清理响应文件(读走后删除,避免队列堆积) */
63
+ export function clearResponse(id, dir = DSH_JOB_DIR) {
64
+ try { fs.unlinkSync(path.join(dir, `resp-${id}.json`)); } catch {}
65
+ }
66
+
67
+ /** 清理请求文件(超时后删除,避免残留) */
68
+ export function clearRequest(id, dir = DSH_JOB_DIR) {
69
+ try { fs.unlinkSync(path.join(dir, `req-${id}.json`)); } catch {}
70
+ }
71
+
72
+ /** 轮询响应文件直到出现或超时;命中后立即删除并返回内容 */
73
+ export async function waitForResponseFile(id, timeoutMs, pollMs = POLL_INTERVAL_MS, dir = DSH_JOB_DIR) {
74
+ const deadline = Date.now() + timeoutMs;
75
+ while (Date.now() < deadline) {
76
+ const resp = readResponse(id, dir);
77
+ if (resp) {
78
+ clearResponse(id, dir);
79
+ return resp;
80
+ }
81
+ await new Promise((r) => setTimeout(r, pollMs));
82
+ }
83
+ return null;
84
+ }
85
+
86
+ /** 回复文本截断:去空行,取末尾一段(与 Claude/Codex 续聊的回推格式一致) */
87
+ export function clipReply(reply) {
88
+ const clean = (reply || '')
89
+ .split('\n')
90
+ .map((l) => l.trim())
91
+ .filter(Boolean)
92
+ .join('\n');
93
+ if (!clean) return null;
94
+ return clean.length > MAX_REPLY ? '...(输出较长已截断)\n' + clean.slice(-MAX_REPLY) : clean;
95
+ }
96
+
97
+ /**
98
+ * 执行一次 DSH 续聊:提交请求 → 轮询回复 → 推回手机。
99
+ * @param {string} text 手机发来的续聊内容
100
+ * @returns {Promise<{ok:boolean, reason?:string, code?:number}>}
101
+ */
102
+ export async function runDshResume(text, { config = null, onLog = (s) => {} } = {}) {
103
+ config = config || loadConfig();
104
+ if (!config.topic) return { ok: false, reason: '未配置话题,请先运行 a4p setup。' };
105
+
106
+ const textClean = (text || '').trim();
107
+ if (!textClean) return { ok: false, reason: '续聊内容为空。' };
108
+
109
+ if (!isDshAlive()) {
110
+ return {
111
+ ok: false,
112
+ reason: '未检测到运行中的 DSH(dsh web 进程心跳过期)。' +
113
+ '请确认 dsh web 正在运行,且已挂载新版 dsh-hook 插件(可重新执行 a4p setup 挂载)。',
114
+ };
115
+ }
116
+
117
+ // 最近 DSH 会话优先指定目标;无则交给插件兜底选最近顶层会话
118
+ const last = loadLastSession();
119
+ const sessionId = last?.agent === 'DSH' ? last.session_id : null;
120
+ const req = buildResumeRequest(textClean, sessionId);
121
+ writeRequest(req);
122
+ onLog(`DSH 续聊请求已提交${sessionId ? `(会话 ${sessionId.slice(0, 8)})` : ''},等待 dsh web 回复…`);
123
+
124
+ const timeoutMs = (config.resumeTimeout ?? 1800) * 1000;
125
+ const resp = await waitForResponseFile(req.id, timeoutMs);
126
+ if (!resp) {
127
+ clearRequest(req.id);
128
+ return {
129
+ ok: false,
130
+ reason: '续聊超时:dsh web 进程未在限时内回复(请确认 dsh web 正在运行,会话未被占用)。',
131
+ };
132
+ }
133
+
134
+ let message;
135
+ if (!resp.ok) {
136
+ onLog(`DSH 续聊失败:${resp.error || '未知错误'}`);
137
+ message = `续聊失败\n\n${resp.error || '未知错误'}`;
138
+ } else {
139
+ const reply = clipReply(resp.reply);
140
+ if (reply) {
141
+ onLog('DSH 续聊完成,结果已推送手机');
142
+ message = `续聊已完成\n\n${reply}`;
143
+ } else {
144
+ onLog(`DSH 续聊完成(无文本输出,轮次状态 ${resp.reasonKind ?? '?'})`);
145
+ message = `续聊已完成(轮次状态 ${resp.reasonKind ?? '?'},无文本输出)`;
146
+ }
147
+ }
148
+ await sendNotification({ ...config, title: 'DSH', message });
149
+ return { ok: resp.ok, code: 0 };
150
+ }
package/src/listen.mjs CHANGED
@@ -1,12 +1,17 @@
1
1
  // 续聊守护进程:订阅主话题,手机向主话题发送文字即触发一次续聊。
2
2
  // 断线自动重连(since 从上次消息之后继续),续聊请求串行处理(避免并发会话冲突)。
3
+ // 积压合并:一轮续聊最长 resumeTimeout(默认 1800 秒),忙时到达的手机消息
4
+ // 合并为一个批次,当前轮结束后一次续聊处理整批(任意数量积压最多只多一轮),
5
+ // 保证手机内容一定能送达 AI;批次持久化到 ~/.a4phone/pending-batch.json,
6
+ // 守护进程重启后自动恢复,避免积压消息丢失。
3
7
  // 按消息时间戳过滤:如果新会话开启时间晚于用户的消息时间,则跳过该消息,
4
8
  // 避免旧消息被注入到新会话中。
5
9
  import fs from 'fs';
6
10
  import path from 'path';
7
- import os from 'os';
8
11
  import { loadConfig, loadLastSession } from './config.mjs';
9
12
  import { runResume } from './resume.mjs';
13
+ import { createBatcher } from './batcher.mjs';
14
+ import { PENDING_PATH, ensureDir } from './paths.mjs';
10
15
 
11
16
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
12
17
  const RETRY_DELAY = 5000;
@@ -19,6 +24,13 @@ export function createLogWriter(logPath) {
19
24
  };
20
25
  }
21
26
 
27
+ // 原子写 JSON(临时文件 + rename,避免读者读到半个文件)
28
+ function atomicWriteJson(filePath, data) {
29
+ const tmp = `${filePath}.${process.pid}.${Date.now()}.tmp`;
30
+ fs.writeFileSync(tmp, JSON.stringify(data));
31
+ fs.renameSync(tmp, filePath);
32
+ }
33
+
22
34
  export async function runListen({ onLog = (s) => console.log(s) } = {}) {
23
35
  const config = loadConfig();
24
36
  if (!config.topic) {
@@ -31,8 +43,6 @@ export async function runListen({ onLog = (s) => console.log(s) } = {}) {
31
43
 
32
44
  // ntfy 的 since 参数只接受 Unix 秒时间戳/时长/all,不接受 "now" 或消息 ID
33
45
  let lastTime = Math.floor(Date.now() / 1000); // 首次只收连接之后的新消息
34
- let busy = false;
35
- const queue = [];
36
46
  let knownSessionId = null; // 记录已处理过的会话 ID,用于检测会话切换
37
47
 
38
48
  // 判断消息是否仍应被处理:如果新会话在消息发送之后才创建,则丢弃
@@ -52,24 +62,48 @@ export async function runListen({ onLog = (s) => console.log(s) } = {}) {
52
62
  return false;
53
63
  }
54
64
 
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);
65
+ // 批次持久化:积压非空写文件,排空后删除(守护进程重启后恢复)
66
+ function persistSnapshot() {
67
+ try {
68
+ ensureDir();
69
+ const snapshot = batcher.pendingSnapshot();
70
+ if (snapshot.texts.length) {
71
+ atomicWriteJson(PENDING_PATH, snapshot);
72
+ } else {
73
+ try { fs.unlinkSync(PENDING_PATH); } catch {}
74
+ }
75
+ } catch {}
76
+ }
77
+
78
+ const batcher = createBatcher({
79
+ log: onLog,
80
+ run: async ({ text, count, msgTime }) => {
81
+ try {
82
+ if (msgTime != null && isMessageStale(msgTime)) return false; // 旧消息,丢弃
83
+ if (count > 1) onLog(`合并 ${count} 条积压消息为一条续聊请求`);
84
+ onLog(`收到续聊请求:${text.slice(0, 60)}`);
85
+ const result = await runResume(text, { config, onLog });
86
+ onLog(result.ok
87
+ ? `消息已处理(resume 续聊${result.code != null ? `,退出码 ${result.code}` : ''}),结果已推送手机。`
88
+ : `续聊失败:${result.reason}`);
89
+ return true;
90
+ } finally {
91
+ // 批次处理完成(或已丢弃)后刷新持久化:
92
+ // 期间若有新积压则保留到文件,否则清空,避免重启后重复处理已完成批次
93
+ persistSnapshot();
94
+ }
95
+ },
96
+ });
97
+
98
+ // 启动恢复:上次未处理完的积压批次(守护进程重启/崩溃不丢消息)
99
+ try {
100
+ const raw = fs.readFileSync(PENDING_PATH, 'utf-8');
101
+ const saved = JSON.parse(raw);
102
+ if (Array.isArray(saved?.texts) && saved.texts.length) {
103
+ onLog(`恢复 ${saved.texts.length} 条重启前未处理的续聊消息,继续处理...`);
104
+ batcher.restore(saved.texts, saved.msgTime ?? null);
71
105
  }
72
- };
106
+ } catch {}
73
107
 
74
108
  while (true) {
75
109
  try {
@@ -107,7 +141,8 @@ export async function runListen({ onLog = (s) => console.log(s) } = {}) {
107
141
  msg = event.message; // 纯文本:手机发来的续聊内容
108
142
  }
109
143
  if (typeof msg === 'string' && msg.trim()) {
110
- processMessage(msg.trim(), event.time ? Number(event.time) : null);
144
+ batcher.submit(msg.trim(), event.time ? Number(event.time) : null);
145
+ persistSnapshot();
111
146
  }
112
147
  }
113
148
  }
package/src/paths.mjs CHANGED
@@ -15,6 +15,15 @@ export const LAST_PATH = path.join(A4P_DIR, 'last.json');
15
15
  export const DAEMON_JSON = path.join(A4P_DIR, 'daemon.json');
16
16
  export const LOG_PATH = path.join(A4P_DIR, 'daemon.log');
17
17
 
18
+ // DSH 续聊文件队列:a4p(守护进程/manual resume)写 req-<id>.json,
19
+ // dsh web 进程内的插件处理后写 resp-<id>.json 并删除请求文件。
20
+ export const DSH_JOB_DIR = path.join(A4P_DIR, 'dsh-jobs');
21
+ // DSH 插件心跳:dsh web 每次轮询刷新,a4p 据此判断 dsh web 是否在运行
22
+ export const DSH_HEARTBEAT = path.join(A4P_DIR, 'dsh-heartbeat.json');
23
+ // 续聊积压批次持久化:长轮次期间到达的消息写入该文件,守护进程重启后恢复,
24
+ // 避免积压消息在重启时丢失
25
+ export const PENDING_PATH = path.join(A4P_DIR, 'pending-batch.json');
26
+
18
27
  // 旧版散落在家目录的单文件 → 迁移到 ~/.a4phone/(新路径不存在时才移动)
19
28
  const LEGACY_PATHS = {
20
29
  [CONFIG_PATH]: path.join(os.homedir(), '.a4phone.json'),
package/src/resume.mjs CHANGED
@@ -1,6 +1,8 @@
1
1
  // 续聊:把手机发来的文本作为下一条用户消息,续聊当前会话并回推回复
2
2
  // Claude Code:claude --resume <id> --continue -p(headless,stdin 作为消息、stdout 捕获回复)
3
3
  // Codex:codex exec resume <id> -o <文件> -(headless,stdin 作为消息、-o 把最后一条回复写入文件)
4
+ // DSH:经 ~/.a4phone/dsh-jobs 文件队列交给 dsh web 进程内的 dsh-hook 插件,
5
+ // 插件直接 followup 到当前 live 会话(手机消息与回复实时出现在桌面会话里)
4
6
  // 若 Codex 会话被窗口占用(thread-store conflict),自动 fork 成新线程续聊,无需关闭原窗口
5
7
  import fs from 'fs';
6
8
  import path from 'path';
@@ -177,6 +179,22 @@ export async function runResume(text, { config = null, onLog = (s) => {} } = {})
177
179
  const last = loadLastSession();
178
180
  if (!last?.session_id) return { ok: false, reason: '暂无最近会话,请先完成一次任务触发 Stop 事件。' };
179
181
  const agent = last.agent || 'Claude Code';
182
+
183
+ // DSH 续聊:不另起进程,而是把消息交给 dsh web 进程内的插件,
184
+ // 直接 followup 到当前 live 会话(手机消息与回复都实时出现在桌面会话里)。
185
+ if (agent === 'DSH') {
186
+ const { runDshResume } = await import('./dsh-resume.mjs');
187
+ // 续聊期间锁定外出模式(人在手机端),结束后恢复原模式
188
+ const prevMode = readMode();
189
+ const lockedOut = prevMode !== 'out';
190
+ if (lockedOut) setMode('out');
191
+ try {
192
+ return await runDshResume(text, { config, onLog });
193
+ } finally {
194
+ if (lockedOut) setMode(prevMode);
195
+ }
196
+ }
197
+
180
198
  if (agent !== 'Claude Code' && agent !== 'Codex') {
181
199
  return { ok: false, reason: `续聊暂不支持 ${agent} 会话。` };
182
200
  }