@duke-dsh-plugins/dsh-remote-control 0.0.0-stage → 1.1.3
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 +21 -0
- package/README.md +88 -3
- package/client.js +747 -0
- package/cordis.patch.yml +12 -0
- package/icon.svg +20 -0
- package/index.js +731 -0
- package/lib/config.mjs +270 -0
- package/lib/host-bridge.mjs +2848 -0
- package/lib/images.mjs +458 -0
- package/lib/pairing.mjs +266 -0
- package/lib/protocol.mjs +390 -0
- package/lib/push.mjs +229 -0
- package/lib/qr.mjs +439 -0
- package/lib/relay-client.mjs +741 -0
- package/lib/relay-supervisor.mjs +798 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +75 -6
- package/typert.host.js +243 -0
- package/vendor/relay/server.js +777 -0
|
@@ -0,0 +1,2848 @@
|
|
|
1
|
+
// lib/host-bridge.mjs — DSH Host 服务桥接(契约 §5 业务层 / §5.5 瀑布语义 /
|
|
2
|
+
// §5.2 事件桥接 / §5.7 工作步骤 / §5.8 模式与权限 / §8.1 模块划分)。
|
|
3
|
+
//
|
|
4
|
+
// 四个职责:
|
|
5
|
+
// 1. 业务请求分发:手机 → host 的请求(§5.1),全部经
|
|
6
|
+
// sessionController / 本机状态处理,每个调用点 try/catch,
|
|
7
|
+
// 错误统一回 result {ok:false, error:{code,message}}。
|
|
8
|
+
// 2. 事件桥接(§5.2):api-session/*、agent/assistant-stream(按
|
|
9
|
+
// sessionId 合并节流 ≤8 条/秒)、agent/status、agent/error、
|
|
10
|
+
// session/event 总闸(v1.0.6:tool.call / tool.result / system.message)
|
|
11
|
+
// → 推给手机。
|
|
12
|
+
// 3. 瀑布答案器(§5.5,安全关键):approval/request 与
|
|
13
|
+
// user-questions/request 以 {prepend:true} 抢占在桌面答案器之前;
|
|
14
|
+
// **仅当**手机在线且开关打开才拦截;超时(默认 120s)/出错/取消
|
|
15
|
+
// 一律 return next() 放行,绝不 fail-closed 卡死任务;
|
|
16
|
+
// 迟到的手机回答回 applied:false。
|
|
17
|
+
// 4. 新建会话的模式与权限(§5.8):session.capabilities 目录 +
|
|
18
|
+
// session.create 的 agentPreset / permission 字段。
|
|
19
|
+
// 5. v1.0.9(§5.10):会话消息里的图片——历史消息带 images[](内联缩略图)、
|
|
20
|
+
// 直播 assistant.image 事件、image.fetch 拉大图。
|
|
21
|
+
// 6. present 工具投递的文件(deliverables/presented 事件)里的**图片**:
|
|
22
|
+
// 宿主把它们记成「文件路径」,不是图片附件块 → 不桥接的话手机端永远看不到
|
|
23
|
+
// (用户反馈:桌面看得到、手机消息里没有)。故按扩展名认图片、读字节、
|
|
24
|
+
// 生成缩略图,按 §5.10 的 assistant.image / image.fetch 通道发给手机。
|
|
25
|
+
import { randomUUID, createHash } from "node:crypto";
|
|
26
|
+
import { readFileSync } from "node:fs";
|
|
27
|
+
import { readFile } from "node:fs/promises";
|
|
28
|
+
import { hostname } from "node:os";
|
|
29
|
+
import { createRequire } from "node:module";
|
|
30
|
+
import { msg, sanitizeEnvelope } from "./protocol.mjs";
|
|
31
|
+
import { ASSISTANT_THROTTLE_PER_SEC } from "./config.mjs";
|
|
32
|
+
import {
|
|
33
|
+
LARGE_MAX_BASE64,
|
|
34
|
+
REPLY_PLAIN_MAX_BYTES,
|
|
35
|
+
THUMB_DATA_URI_PREFIX,
|
|
36
|
+
THUMB_PAGE_BUDGET,
|
|
37
|
+
attachmentRefOf,
|
|
38
|
+
clampMaxEdge,
|
|
39
|
+
fitReplyBudget,
|
|
40
|
+
imageBlocksOf,
|
|
41
|
+
imageMetaOf,
|
|
42
|
+
imageRefMeta,
|
|
43
|
+
makeLarge,
|
|
44
|
+
makeThumb,
|
|
45
|
+
mediaTypeOfPath,
|
|
46
|
+
} from "./images.mjs";
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* present 投递文件的字节上限(超过就不桥接:内存与带宽都不值得)。
|
|
50
|
+
* 20MB 足够覆盖绝大多数截图/预览图。
|
|
51
|
+
*/
|
|
52
|
+
const DELIVERED_MAX_BYTES = 20 * 1024 * 1024;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 单会话待执行消息的条数上限(契约 §5.2 session.queue)。
|
|
56
|
+
*
|
|
57
|
+
* 内存态追踪,异常事件流(重连回放等)不该把内存吃满;超了就不再记新的。
|
|
58
|
+
*/
|
|
59
|
+
const QUEUE_MAX_ITEMS = 200;
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 宿主「繁忙时的发送行为」设置的命名空间与字段(契约 §5.1 v1.1.2)。
|
|
63
|
+
*
|
|
64
|
+
* 与 DSH 桌面端 composer 读的是**同一处**(ui-conversation 插件的 user-settings 文档,
|
|
65
|
+
* 字段 busyEnter:'queue' | 'steer',缺省 'queue')。
|
|
66
|
+
* 手机端不提供切换——发消息走哪种行为由宿主设置决定。
|
|
67
|
+
*/
|
|
68
|
+
const BUSY_ENTER_NAMESPACE = "ui-conversation";
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* present 投递文件的 imageId:`d` + sha1(path+turn) 前 16 位。
|
|
72
|
+
*
|
|
73
|
+
* 命名空间与宿主附件 id(随机 uuid)不冲突;同一文件在同一 turn 里稳定,
|
|
74
|
+
* 重复 present 同一张图 → 同一 imageId → 手机端幂等不重复挂。
|
|
75
|
+
* @param {string} path 文件绝对路径
|
|
76
|
+
* @param {unknown} turn 宿主回合号
|
|
77
|
+
* @returns {string} imageId
|
|
78
|
+
*/
|
|
79
|
+
function deliveredImageId(path, turn) {
|
|
80
|
+
const h = createHash("sha1").update(`${path}#${String(turn ?? "")}`).digest("hex");
|
|
81
|
+
return `d${h.slice(0, 16)}`;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** 从本包 package.json 读版本;失败给 unknown(不抛出)。 */
|
|
85
|
+
function pluginVersion() {
|
|
86
|
+
try {
|
|
87
|
+
const req = createRequire(import.meta.url);
|
|
88
|
+
const pkg = req("../package.json");
|
|
89
|
+
return typeof pkg?.version === "string" ? pkg.version : "unknown";
|
|
90
|
+
} catch {
|
|
91
|
+
return "unknown";
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** DSH 运行时版本(尽力而为)。 */
|
|
96
|
+
function dshVersion() {
|
|
97
|
+
try {
|
|
98
|
+
const req = createRequire(import.meta.url);
|
|
99
|
+
const pkg = req("@deepseek-ai/dsh/package.json");
|
|
100
|
+
if (pkg && typeof pkg.version === "string") return pkg.version;
|
|
101
|
+
} catch {
|
|
102
|
+
/* 包可能不暴露 ./package.json */
|
|
103
|
+
}
|
|
104
|
+
return process.env.DSH_VERSION || "unknown";
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** 契约 §5.3 SessionSummary ← Host SessionSummary(title 来自投影)。
|
|
108
|
+
* v1.0.4:透传 Host 原生 origin/parentSessionId/blank(§5.3 客户端据此隐藏
|
|
109
|
+
* subagent 行与 blank 会话;wire 字段名与 Host 逐字一致)。
|
|
110
|
+
* v1.0.5:删 archived——Host 会话域无归档概念(归档属 Workspace 注册表),
|
|
111
|
+
* 之前的常量 false 是纯误导。
|
|
112
|
+
* v1.0.7:archived 重新加入,但**来源改为 Workspace 注册表**
|
|
113
|
+
* (ctx.workspaceRegistry.archivedSessionIds,§5.9)——由调用方以可选参数
|
|
114
|
+
* 传入;不传(宿主没有注册表)时**不产出该字段**,客户端按 false 处理,
|
|
115
|
+
* 不在本机伪造归档状态。 */
|
|
116
|
+
function mapSummary(raw, archivedIds) {
|
|
117
|
+
const values = raw?.projections?.values;
|
|
118
|
+
const title = values && typeof values.title === "string" ? values.title : "";
|
|
119
|
+
const sessionId = String(raw?.sessionId ?? "");
|
|
120
|
+
const summary = {
|
|
121
|
+
sessionId,
|
|
122
|
+
title,
|
|
123
|
+
cwd: typeof raw?.cwd === "string" ? raw.cwd : "",
|
|
124
|
+
running: raw?.running === true,
|
|
125
|
+
updatedAt: typeof raw?.updatedAt === "number" ? raw.updatedAt : 0,
|
|
126
|
+
origin: raw?.origin === "subagent" ? "subagent" : "",
|
|
127
|
+
parentSessionId: typeof raw?.parentSessionId === "string" ? raw.parentSessionId : "",
|
|
128
|
+
blank: raw?.blank === true,
|
|
129
|
+
};
|
|
130
|
+
if (Array.isArray(archivedIds)) {
|
|
131
|
+
summary.archived = archivedIds.includes(sessionId);
|
|
132
|
+
}
|
|
133
|
+
return summary;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** 契约 §5.1 session.history 默认/上限页大小(宿主 DEFAULT_MAX_MESSAGES=50)。 */
|
|
137
|
+
const HISTORY_DEFAULT_MAX = 50;
|
|
138
|
+
const HISTORY_MAX_LIMIT = 200;
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* 内容块 → 纯文本(契约 §5.7 / 附录 B)。
|
|
142
|
+
* text 块取 text 拼接;image/file 给占位符;reasoning/tool-call 等忽略。
|
|
143
|
+
*
|
|
144
|
+
* 注意:这是**工具结果**口径(§5.7 StepRecord.resultText)——工具结果里的图片没有
|
|
145
|
+
* 独立的渲染通道,占位符是有用信息。会话消息正文用 messageText(§5.10:图片单独渲染)。
|
|
146
|
+
* @param {unknown} blocks ContentBlock[]
|
|
147
|
+
* @returns {string}
|
|
148
|
+
*/
|
|
149
|
+
export function contentText(blocks) {
|
|
150
|
+
if (!Array.isArray(blocks)) return "";
|
|
151
|
+
let text = "";
|
|
152
|
+
for (const block of blocks) {
|
|
153
|
+
if (!block || typeof block !== "object") continue;
|
|
154
|
+
if (block.type === "text" && typeof block.text === "string") {
|
|
155
|
+
text += block.text;
|
|
156
|
+
} else if (block.type === "image") {
|
|
157
|
+
text += "[图片]";
|
|
158
|
+
} else if (block.type === "file") {
|
|
159
|
+
text += "[文件]";
|
|
160
|
+
}
|
|
161
|
+
// reasoning / tool-call / tool-addition / tool-removal / 未知块:跳过
|
|
162
|
+
}
|
|
163
|
+
return text;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* 会话消息正文文本(契约 §5.10):**图片块不占位**。
|
|
168
|
+
*
|
|
169
|
+
* 图片在 ChatMessage.images[] 里单独渲染(客户端画缩略图气泡),正文里再写一遍
|
|
170
|
+
* "[图片]" 会出现重复的假文字。file 块仍保留占位符(文件没有独立渲染通道)。
|
|
171
|
+
* @param {unknown} blocks ContentBlock[]
|
|
172
|
+
* @returns {string}
|
|
173
|
+
*/
|
|
174
|
+
export function messageText(blocks) {
|
|
175
|
+
if (!Array.isArray(blocks)) return "";
|
|
176
|
+
let text = "";
|
|
177
|
+
for (const block of blocks) {
|
|
178
|
+
if (!block || typeof block !== "object") continue;
|
|
179
|
+
if (block.type === "text" && typeof block.text === "string") {
|
|
180
|
+
text += block.text;
|
|
181
|
+
} else if (block.type === "file") {
|
|
182
|
+
text += "[文件]";
|
|
183
|
+
}
|
|
184
|
+
// image:单独渲染(§5.10),不占位;reasoning / tool-call 等:跳过
|
|
185
|
+
}
|
|
186
|
+
return text;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* 契约 §5.2 `session.queue`:待执行消息的文本口径。
|
|
191
|
+
*
|
|
192
|
+
* 只取 content 里 `type==='text'` 的块拼接——与正文口径(messageText)刻意不同:
|
|
193
|
+
* 正文会把 file 块渲染成 "[文件]" 占位符,而排队列表要的是**用户实际打的字**。
|
|
194
|
+
* @param {unknown} content ContentBlock[]
|
|
195
|
+
* @returns {string}
|
|
196
|
+
*/
|
|
197
|
+
export function queueItemText(content) {
|
|
198
|
+
if (!Array.isArray(content)) return "";
|
|
199
|
+
let text = "";
|
|
200
|
+
for (const block of content) {
|
|
201
|
+
if (!block || typeof block !== "object") continue;
|
|
202
|
+
if (block.type === "text" && typeof block.text === "string") text += block.text;
|
|
203
|
+
}
|
|
204
|
+
return text;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* 思考块 → 纯文本(契约 §5.3 / 附录 C)。
|
|
209
|
+
* 只取 type==='reasoning' 的块;普通正文与工具结果**不**进这里。
|
|
210
|
+
* @param {unknown} blocks ContentBlock[]
|
|
211
|
+
* @returns {string}
|
|
212
|
+
*/
|
|
213
|
+
export function reasoningText(blocks) {
|
|
214
|
+
if (!Array.isArray(blocks)) return "";
|
|
215
|
+
let text = "";
|
|
216
|
+
for (const block of blocks) {
|
|
217
|
+
if (!block || typeof block !== "object") continue;
|
|
218
|
+
if (block.type === "reasoning" && typeof block.text === "string") text += block.text;
|
|
219
|
+
}
|
|
220
|
+
return text;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* 契约 §5.1 ChatMessage 提取(v1.0.7):SessionWireEvent → ChatMessage[]。
|
|
225
|
+
*
|
|
226
|
+
* 一个事件可能产出**两条**消息:assistant/message 里 `type:"reasoning"` 的块
|
|
227
|
+
* 独立成条(role:"reasoning",id = "<sessionId>:<seq>:reasoning"),
|
|
228
|
+
* 排在普通 assistant 正文**之前**;正文仍按 contentText 口径(忽略 reasoning)。
|
|
229
|
+
*
|
|
230
|
+
* 事件形态(@deepseek-ai/dsh-session 类型实证):
|
|
231
|
+
* user/message data = UserMessage {content:[ContentBlock], source:{kind}}
|
|
232
|
+
* assistant/message data = {turn, step, message: AssistantMessage, stream, usage?}
|
|
233
|
+
* 显示口径(自行权衡,宁缺勿崩):
|
|
234
|
+
* - 只收 append-origin 表面事件(surfaceOp==='append')——replace 副本是
|
|
235
|
+
* 模型可见的压缩影子,不是人看的逐字记录(宿主 surface 语义);
|
|
236
|
+
* - user 只收 source.kind==='user' 的真人输入(agent.inject 的注入跳过);
|
|
237
|
+
* - ContentBlock 只取 type==='text' 的纯文本(reasoning/tool-call 跳过);
|
|
238
|
+
* **image 块不占位**(v1.0.9 §5.10:图片单独渲染,见 messageText);
|
|
239
|
+
* - v1.0.9(§5.10):消息里有 image 块时,ChatMessage 追加 `images: ImageRef[]`
|
|
240
|
+
* (只带元数据,thumb 由上层 attachThumbs 补);**纯图片消息(无正文)也要成条**,
|
|
241
|
+
* 否则手机端永远看不到这张图;
|
|
242
|
+
* - 没有任何内容的消息跳过(不产生空泡);
|
|
243
|
+
* - 任何不认识的形态返回 [](跳过),绝不抛出。
|
|
244
|
+
* @returns {object[]} ChatMessage[]
|
|
245
|
+
*/
|
|
246
|
+
export function mapHistoryMessages(sessionId, record) {
|
|
247
|
+
const event = record?.event ?? record;
|
|
248
|
+
if (!event || typeof event !== "object") return [];
|
|
249
|
+
const type = event.type;
|
|
250
|
+
if (type !== "user/message" && type !== "assistant/message") return [];
|
|
251
|
+
if (event.surfaceOp !== "append") return [];
|
|
252
|
+
const seq = Number(event?.seq);
|
|
253
|
+
const time = Number(event?.time);
|
|
254
|
+
if (!Number.isSafeInteger(seq) || seq < 0) return [];
|
|
255
|
+
const data = event.data;
|
|
256
|
+
if (!data || typeof data !== "object") return [];
|
|
257
|
+
|
|
258
|
+
let role;
|
|
259
|
+
let content;
|
|
260
|
+
if (type === "user/message") {
|
|
261
|
+
if (data?.source?.kind !== "user") return [];
|
|
262
|
+
role = "user";
|
|
263
|
+
content = data.content;
|
|
264
|
+
} else {
|
|
265
|
+
role = "assistant";
|
|
266
|
+
content = data?.message?.content;
|
|
267
|
+
}
|
|
268
|
+
if (!Array.isArray(content)) return [];
|
|
269
|
+
|
|
270
|
+
const ts = Number.isSafeInteger(time) && time > 0 ? time : 0;
|
|
271
|
+
const out = [];
|
|
272
|
+
// 思考过程独立成条,排在正文之前(v1.0.7 §5.3)
|
|
273
|
+
if (role === "assistant") {
|
|
274
|
+
const thinking = reasoningText(content);
|
|
275
|
+
if (thinking.trim() !== "") {
|
|
276
|
+
out.push({ id: `${sessionId}:${seq}:reasoning`, role: "reasoning", text: thinking, ts, seq });
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
const text = messageText(content);
|
|
280
|
+
// v1.0.9(§5.10):图片单独成字段,**不带缩略图**(纯函数读不到附件字节)
|
|
281
|
+
const images = imageBlocksOf(content).map((ref) => imageRefMeta(ref));
|
|
282
|
+
if (text.trim() !== "" || images.length > 0) {
|
|
283
|
+
const message = { id: `${sessionId}:${seq}`, role, text, ts, seq };
|
|
284
|
+
if (images.length > 0) message.images = images;
|
|
285
|
+
out.push(message);
|
|
286
|
+
}
|
|
287
|
+
return out;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* 契约 §5.1 ChatMessage 提取(单条口径,保留旧签名):只回**非思考**的那条,
|
|
292
|
+
* 没有正文时返回 null(与 v1.0.6 行为逐字一致)。
|
|
293
|
+
* @returns {object|null}
|
|
294
|
+
*/
|
|
295
|
+
export function mapHistoryMessage(sessionId, record) {
|
|
296
|
+
for (const message of mapHistoryMessages(sessionId, record)) {
|
|
297
|
+
if (message.role !== "reasoning") return message;
|
|
298
|
+
}
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// ---------------------------------------------------------------------------
|
|
303
|
+
// v1.0.9:会话消息里的图片(契约 §5.10)——附件读字节 + 缩略图补齐
|
|
304
|
+
// ---------------------------------------------------------------------------
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* 取宿主附件服务(服务名 `attachments`;本地后端 dsh-attachment-local)。
|
|
308
|
+
* ctx.get 对不存在的服务会抛,故 try/catch + ctx[name] 直取兜底。
|
|
309
|
+
* @param {any} ctx Cordis ctx
|
|
310
|
+
* @returns {any|null} 附件服务或 null(宿主没装附件后端)
|
|
311
|
+
*/
|
|
312
|
+
export function attachmentsOf(ctx) {
|
|
313
|
+
try {
|
|
314
|
+
const svc = ctx?.get?.("attachments");
|
|
315
|
+
if (svc) return svc;
|
|
316
|
+
} catch {
|
|
317
|
+
/* 服务未注册 */
|
|
318
|
+
}
|
|
319
|
+
try {
|
|
320
|
+
const svc = ctx?.attachments;
|
|
321
|
+
return svc ?? null;
|
|
322
|
+
} catch {
|
|
323
|
+
return null;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* 读一张附件的**原始字节**。
|
|
329
|
+
*
|
|
330
|
+
* 优先 `attachments.readImage(ref, signal)`(本地后端有实现,返回 {ref, data} 或裸字节,
|
|
331
|
+
* 且带完整性校验);不可用/失败时回退 `readFileSync(imageHostPath(ref))`
|
|
332
|
+
* (宿主文件系统绝对路径;非文件后端时 imageHostPath 返回 undefined)。
|
|
333
|
+
* @param {any} attachments 附件服务
|
|
334
|
+
* @param {any} ref 宿主附件引用
|
|
335
|
+
* @param {AbortSignal} [signal]
|
|
336
|
+
* @returns {Promise<Buffer|null>} 字节;读不到返回 null
|
|
337
|
+
*/
|
|
338
|
+
export async function readAttachmentBytes(attachments, ref, signal) {
|
|
339
|
+
if (!attachments || !ref) return null;
|
|
340
|
+
try {
|
|
341
|
+
if (typeof attachments.readImage === "function") {
|
|
342
|
+
const out = await attachments.readImage(ref, signal);
|
|
343
|
+
const data = out && typeof out === "object" && "data" in out ? out.data : out;
|
|
344
|
+
const bytes = toBuffer(data);
|
|
345
|
+
if (bytes && bytes.length > 0) return bytes;
|
|
346
|
+
}
|
|
347
|
+
} catch {
|
|
348
|
+
/* 落到回退路径 */
|
|
349
|
+
}
|
|
350
|
+
try {
|
|
351
|
+
if (typeof attachments.imageHostPath === "function") {
|
|
352
|
+
const path = attachments.imageHostPath(ref);
|
|
353
|
+
if (typeof path === "string" && path !== "") {
|
|
354
|
+
const bytes = readFileSync(path);
|
|
355
|
+
if (bytes.length > 0) return bytes;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
} catch {
|
|
359
|
+
/* 读不到就是读不到(上层降级) */
|
|
360
|
+
}
|
|
361
|
+
return null;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** 各种字节形态 → Buffer。 */
|
|
365
|
+
function toBuffer(input) {
|
|
366
|
+
if (input === null || input === undefined) return null;
|
|
367
|
+
if (Buffer.isBuffer(input)) return input;
|
|
368
|
+
if (input instanceof Uint8Array) return Buffer.from(input.buffer, input.byteOffset, input.byteLength);
|
|
369
|
+
if (input instanceof ArrayBuffer) return Buffer.from(input);
|
|
370
|
+
if (typeof input === "object" && input.data !== undefined && input.data !== null) return toBuffer(input.data);
|
|
371
|
+
return null;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* 给消息里的图片补**内联缩略图**(契约 §5.10)。
|
|
376
|
+
*
|
|
377
|
+
* mapHistoryMessages 是纯函数(拿不到附件字节),只产元数据;这里负责读字节 +
|
|
378
|
+
* 压缩,并把 base64 ≤96KB 的 JPEG data URI 写回 image.thumb。
|
|
379
|
+
*
|
|
380
|
+
* 降级(**绝不抛**):附件服务缺失 / 读不到字节 / sharp 不可用 / 压不进 96KB
|
|
381
|
+
* → thumb 留空,客户端显示占位框;图片功能失败**不影响**消息流其余内容。
|
|
382
|
+
*
|
|
383
|
+
* 预算(重要):一页历史可能有几十张图,每张 96KB 内联会**顶爆中继的 1MiB 帧**
|
|
384
|
+
* (帧里还有 base64 密文的 4/3 放大)。所以整页缩略图有**总预算**
|
|
385
|
+
* (默认 THUMB_PAGE_BUDGET);超预算的后续图片只发元数据(thumb 留空)。
|
|
386
|
+
* 回包发出去前还有一道**帧预算守卫**(fitReplyBudget)兜底。
|
|
387
|
+
*
|
|
388
|
+
* @param {object[]} messages ChatMessage[]
|
|
389
|
+
* @param {any} ctx Cordis ctx(用来取 attachments 服务)
|
|
390
|
+
* @param {{budgetBytes?:number}} [options]
|
|
391
|
+
* @returns {Promise<object[]>} 同一个 messages 数组
|
|
392
|
+
*/
|
|
393
|
+
export async function attachThumbs(messages, ctx, options) {
|
|
394
|
+
const list = Array.isArray(messages) ? messages : [];
|
|
395
|
+
if (list.length === 0) return list;
|
|
396
|
+
const attachments = attachmentsOf(ctx);
|
|
397
|
+
if (!attachments) return list;
|
|
398
|
+
const budget = Number.isSafeInteger(options?.budgetBytes) ? options.budgetBytes : THUMB_PAGE_BUDGET;
|
|
399
|
+
let used = 0;
|
|
400
|
+
for (const message of list) {
|
|
401
|
+
const images = Array.isArray(message?.images) ? message.images : [];
|
|
402
|
+
for (const image of images) {
|
|
403
|
+
if (!image || typeof image !== "object") continue;
|
|
404
|
+
if (typeof image.thumb === "string" && image.thumb !== "") continue;
|
|
405
|
+
if (used >= budget) continue; // 整页预算用尽 → 只发元数据
|
|
406
|
+
const ref = attachmentRefOf(image);
|
|
407
|
+
if (!ref) continue;
|
|
408
|
+
try {
|
|
409
|
+
const bytes = await readAttachmentBytes(attachments, ref, undefined);
|
|
410
|
+
if (!bytes) continue;
|
|
411
|
+
const thumb = await makeThumb(bytes, image.mediaType);
|
|
412
|
+
if (thumb === "") continue;
|
|
413
|
+
const size = thumb.length - THUMB_DATA_URI_PREFIX.length;
|
|
414
|
+
if (used + size > budget) continue; // 这张塞不进去 → 只发元数据
|
|
415
|
+
image.thumb = thumb;
|
|
416
|
+
used += size;
|
|
417
|
+
} catch {
|
|
418
|
+
/* 缩略图失败:只发元数据 */
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
return list;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// ---------------------------------------------------------------------------
|
|
426
|
+
// v1.0.6:工作步骤(§5.7)/ 模式与权限(§5.8)——纯函数映射,便于单测
|
|
427
|
+
// ---------------------------------------------------------------------------
|
|
428
|
+
|
|
429
|
+
/** 事件里的时间戳(毫秒);非法给 0。 */
|
|
430
|
+
function eventTime(event) {
|
|
431
|
+
const time = Number(event?.time);
|
|
432
|
+
return Number.isSafeInteger(time) && time > 0 ? time : 0;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/** 事件里的持久序号;非法给 -1。 */
|
|
436
|
+
function eventSeq(event) {
|
|
437
|
+
const seq = Number(event?.seq);
|
|
438
|
+
return Number.isSafeInteger(seq) && seq >= 0 ? seq : -1;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/**
|
|
442
|
+
* 契约 §5.2 `tool.call` 事件映射(宿主 session/event 的 tool/call)。
|
|
443
|
+
* data = { turn, step, callId, name, arguments }(arguments 是原始 JSON 字符串)。
|
|
444
|
+
* @returns {{sessionId:string,callId:string,name:string,arguments:string,ts:number}|null}
|
|
445
|
+
*/
|
|
446
|
+
export function mapToolCallEvent(sessionId, event) {
|
|
447
|
+
if (!event || typeof event !== "object" || event.type !== "tool/call") return null;
|
|
448
|
+
const data = event.data;
|
|
449
|
+
if (!data || typeof data !== "object") return null;
|
|
450
|
+
const callId = typeof data.callId === "string" ? data.callId : "";
|
|
451
|
+
if (callId === "") return null;
|
|
452
|
+
const rawArgs = data.arguments;
|
|
453
|
+
const args =
|
|
454
|
+
typeof rawArgs === "string"
|
|
455
|
+
? rawArgs
|
|
456
|
+
: rawArgs === undefined || rawArgs === null
|
|
457
|
+
? ""
|
|
458
|
+
: JSON.stringify(rawArgs);
|
|
459
|
+
return {
|
|
460
|
+
sessionId: String(sessionId ?? ""),
|
|
461
|
+
callId,
|
|
462
|
+
name: typeof data.name === "string" ? data.name : "",
|
|
463
|
+
arguments: args,
|
|
464
|
+
ts: eventTime(event),
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* 契约 §5.2 `tool.result` 事件映射(宿主 session/event 的 tool/result)。
|
|
470
|
+
* data = { turn, step, message:{ role:'tool', toolCallId, isError?, content:[blocks] }, error? }
|
|
471
|
+
* @returns {{sessionId:string,callId:string,status:"ok"|"error",resultText:string,errorText:string,ts:number}|null}
|
|
472
|
+
*/
|
|
473
|
+
export function mapToolResultEvent(sessionId, event) {
|
|
474
|
+
if (!event || typeof event !== "object" || event.type !== "tool/result") return null;
|
|
475
|
+
const data = event.data;
|
|
476
|
+
if (!data || typeof data !== "object") return null;
|
|
477
|
+
const message = data.message && typeof data.message === "object" ? data.message : null;
|
|
478
|
+
const callId = typeof message?.toolCallId === "string" ? message.toolCallId : "";
|
|
479
|
+
if (callId === "") return null;
|
|
480
|
+
const isError = message?.isError === true;
|
|
481
|
+
const resultText = contentText(message?.content);
|
|
482
|
+
const reason = data.error?.reason;
|
|
483
|
+
const errorText =
|
|
484
|
+
reason === undefined || reason === null ? (isError ? resultText : "") : String(reason);
|
|
485
|
+
return {
|
|
486
|
+
sessionId: String(sessionId ?? ""),
|
|
487
|
+
callId,
|
|
488
|
+
status: isError ? "error" : "ok",
|
|
489
|
+
resultText,
|
|
490
|
+
errorText,
|
|
491
|
+
ts: eventTime(event),
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
/**
|
|
496
|
+
* 契约 §5.2 `system.message` 事件映射(宿主 session/event 的
|
|
497
|
+
* system/message 与 developer/message;两者共用一个 topic,用 kind 区分)。
|
|
498
|
+
* message 可能是 {content:[blocks]},也可能是字符串——两种都兜住。
|
|
499
|
+
* @returns {{sessionId:string,kind:"system"|"developer",text:string,ts:number}|null}
|
|
500
|
+
*/
|
|
501
|
+
export function mapSystemMessageEvent(sessionId, event, kind) {
|
|
502
|
+
if (!event || typeof event !== "object") return null;
|
|
503
|
+
if (event.type !== "system/message" && event.type !== "developer/message") return null;
|
|
504
|
+
const data = event.data;
|
|
505
|
+
if (!data || typeof data !== "object") return null;
|
|
506
|
+
const message = data.message !== undefined ? data.message : data;
|
|
507
|
+
let text = "";
|
|
508
|
+
if (typeof message === "string") {
|
|
509
|
+
text = message;
|
|
510
|
+
} else if (message && typeof message === "object") {
|
|
511
|
+
text = contentText(message.content);
|
|
512
|
+
}
|
|
513
|
+
if (text.trim() === "") return null;
|
|
514
|
+
return {
|
|
515
|
+
sessionId: String(sessionId ?? ""),
|
|
516
|
+
kind: kind === "developer" ? "developer" : "system",
|
|
517
|
+
text,
|
|
518
|
+
ts: eventTime(event),
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* 契约 §5.7 StepRecord 提取:session.history 的 page.records → steps[]。
|
|
524
|
+
*
|
|
525
|
+
* 规则:
|
|
526
|
+
* - 只看 type==='tool/call' 与 'tool/result' 的记录;
|
|
527
|
+
* - 按 callId 配对:一次调用合并成一条(call 的字段 + result 的状态/文本);
|
|
528
|
+
* - seq:优先取 tool/call 事件的 seq;只有 tool/result 时取它的 seq;
|
|
529
|
+
* - status:tool/result 的 isError 决定 ok/error;只有 call 没有 result 时 running;
|
|
530
|
+
* - turn/step 取事件 data 里的 turn/step;ts 取事件 time(call 优先)。
|
|
531
|
+
* 任何不认识的形状一律跳过,绝不抛出。
|
|
532
|
+
* @param {any[]} records page.records
|
|
533
|
+
* @returns {object[]} StepRecord[](按 seq 升序)
|
|
534
|
+
*/
|
|
535
|
+
export function mapHistorySteps(records) {
|
|
536
|
+
const list = Array.isArray(records) ? records : [];
|
|
537
|
+
/** @type {Map<string, any>} */
|
|
538
|
+
const byCall = new Map();
|
|
539
|
+
/** @type {any[]} */
|
|
540
|
+
const ordered = [];
|
|
541
|
+
|
|
542
|
+
for (const record of list) {
|
|
543
|
+
const event = record?.event ?? record;
|
|
544
|
+
if (!event || typeof event !== "object") continue;
|
|
545
|
+
const type = event.type;
|
|
546
|
+
if (type !== "tool/call" && type !== "tool/result") continue;
|
|
547
|
+
const data = event.data;
|
|
548
|
+
if (!data || typeof data !== "object") continue;
|
|
549
|
+
const ts = eventTime(event);
|
|
550
|
+
const seq = eventSeq(event);
|
|
551
|
+
const turn = Number.isSafeInteger(Number(data.turn)) ? Number(data.turn) : 0;
|
|
552
|
+
const step = Number.isSafeInteger(Number(data.step)) ? Number(data.step) : 0;
|
|
553
|
+
|
|
554
|
+
if (type === "tool/call") {
|
|
555
|
+
const callId = typeof data.callId === "string" ? data.callId : "";
|
|
556
|
+
if (callId === "") continue;
|
|
557
|
+
const rawArgs = data.arguments;
|
|
558
|
+
const args =
|
|
559
|
+
typeof rawArgs === "string"
|
|
560
|
+
? rawArgs
|
|
561
|
+
: rawArgs === undefined || rawArgs === null
|
|
562
|
+
? ""
|
|
563
|
+
: JSON.stringify(rawArgs);
|
|
564
|
+
let rec = byCall.get(callId);
|
|
565
|
+
if (rec === undefined) {
|
|
566
|
+
rec = {
|
|
567
|
+
seq: seq < 0 ? 0 : seq,
|
|
568
|
+
callId,
|
|
569
|
+
name: "",
|
|
570
|
+
arguments: "",
|
|
571
|
+
status: "running",
|
|
572
|
+
resultText: "",
|
|
573
|
+
errorText: "",
|
|
574
|
+
ts: 0,
|
|
575
|
+
turn: 0,
|
|
576
|
+
step: 0,
|
|
577
|
+
};
|
|
578
|
+
byCall.set(callId, rec);
|
|
579
|
+
ordered.push(rec);
|
|
580
|
+
}
|
|
581
|
+
rec.name = typeof data.name === "string" ? data.name : rec.name;
|
|
582
|
+
rec.arguments = args;
|
|
583
|
+
rec.status = "running";
|
|
584
|
+
if (ts > 0) rec.ts = ts;
|
|
585
|
+
rec.turn = turn;
|
|
586
|
+
rec.step = step;
|
|
587
|
+
// seq 优先取 tool/call 的(result 晚到时不覆盖)
|
|
588
|
+
if (seq >= 0) rec.seq = seq;
|
|
589
|
+
continue;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
// tool/result
|
|
593
|
+
const message = data.message && typeof data.message === "object" ? data.message : null;
|
|
594
|
+
const callId = typeof message?.toolCallId === "string" ? message.toolCallId : "";
|
|
595
|
+
if (callId === "") continue;
|
|
596
|
+
const isError = message?.isError === true;
|
|
597
|
+
const resultText = contentText(message?.content);
|
|
598
|
+
const reason = data.error?.reason;
|
|
599
|
+
const errorText =
|
|
600
|
+
reason === undefined || reason === null ? (isError ? resultText : "") : String(reason);
|
|
601
|
+
let rec = byCall.get(callId);
|
|
602
|
+
if (rec === undefined) {
|
|
603
|
+
rec = {
|
|
604
|
+
seq: seq < 0 ? 0 : seq,
|
|
605
|
+
callId,
|
|
606
|
+
name: "",
|
|
607
|
+
arguments: "",
|
|
608
|
+
status: "ok",
|
|
609
|
+
resultText: "",
|
|
610
|
+
errorText: "",
|
|
611
|
+
ts: 0,
|
|
612
|
+
turn: 0,
|
|
613
|
+
step: 0,
|
|
614
|
+
};
|
|
615
|
+
byCall.set(callId, rec);
|
|
616
|
+
ordered.push(rec);
|
|
617
|
+
}
|
|
618
|
+
rec.status = isError ? "error" : "ok";
|
|
619
|
+
rec.resultText = resultText;
|
|
620
|
+
rec.errorText = errorText;
|
|
621
|
+
if (ts > 0 && rec.ts === 0) rec.ts = ts;
|
|
622
|
+
rec.turn = turn;
|
|
623
|
+
rec.step = step;
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
ordered.sort((a, b) => a.seq - b.seq);
|
|
627
|
+
return ordered;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* 契约 §5.8 模式目录映射:宿主 AgentPreset[] → wire ModeOption[]。
|
|
632
|
+
* broken 的预设也列出(name 回退 id);默认 id 用 svc.defaultId。
|
|
633
|
+
* @param {any[]} rows
|
|
634
|
+
* @param {string} defaultId
|
|
635
|
+
* @returns {{presets:{id:string,name:string,description:string}[],defaultPreset:string}}
|
|
636
|
+
*/
|
|
637
|
+
export function mapAgentPresetOptions(rows, defaultId) {
|
|
638
|
+
const list = Array.isArray(rows) ? rows : [];
|
|
639
|
+
const presets = [];
|
|
640
|
+
for (const row of list) {
|
|
641
|
+
if (!row || typeof row !== "object") continue;
|
|
642
|
+
const id = typeof row.id === "string" ? row.id.trim() : "";
|
|
643
|
+
if (id === "") continue;
|
|
644
|
+
const name = typeof row.name === "string" && row.name !== "" ? row.name : id;
|
|
645
|
+
const description = typeof row.description === "string" ? row.description : "";
|
|
646
|
+
presets.push({ id, name, description });
|
|
647
|
+
}
|
|
648
|
+
return { presets, defaultPreset: typeof defaultId === "string" ? defaultId : "" };
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
/**
|
|
652
|
+
* 契约 §5.8 权限目录映射:宿主 PermissionCatalog → wire PermissionOption[]。
|
|
653
|
+
* 宿主 PresetOption 的标识字段是 `value`(契约附录 B 的 `id` 是 wire 字段名),
|
|
654
|
+
* 两种都兜住;`custom` 只是展示态,永不可选 → 跳过。
|
|
655
|
+
* @param {any} catalog { options, defaultOptions, defaultPreset }
|
|
656
|
+
* @returns {{permissions:{id:string,name:string,description:string}[],defaultPermission:string}}
|
|
657
|
+
*/
|
|
658
|
+
export function mapPermissionOptions(catalog) {
|
|
659
|
+
const options = Array.isArray(catalog?.options) ? catalog.options : [];
|
|
660
|
+
const permissions = [];
|
|
661
|
+
for (const option of options) {
|
|
662
|
+
if (!option || typeof option !== "object") continue;
|
|
663
|
+
const rawId =
|
|
664
|
+
typeof option.id === "string" && option.id !== ""
|
|
665
|
+
? option.id
|
|
666
|
+
: typeof option.value === "string"
|
|
667
|
+
? option.value
|
|
668
|
+
: "";
|
|
669
|
+
const id = rawId.trim();
|
|
670
|
+
if (id === "") continue;
|
|
671
|
+
if (id === "custom") continue; // 展示态,不可选
|
|
672
|
+
const name = typeof option.name === "string" && option.name !== "" ? option.name : id;
|
|
673
|
+
const description = typeof option.description === "string" ? option.description : "";
|
|
674
|
+
permissions.push({ id, name, description });
|
|
675
|
+
}
|
|
676
|
+
const defaultPreset =
|
|
677
|
+
typeof catalog?.defaultPreset === "string"
|
|
678
|
+
? catalog.defaultPreset
|
|
679
|
+
: typeof catalog?.defaultPermission === "string"
|
|
680
|
+
? catalog.defaultPermission
|
|
681
|
+
: "";
|
|
682
|
+
return { permissions, defaultPermission: defaultPreset };
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/** 宿主是否因为 agent preset 拒绝了 create(→ unsupported-agent-preset)。 */
|
|
686
|
+
export function isAgentPresetRejection(e) {
|
|
687
|
+
const code = typeof e?.code === "string" ? e.code : "";
|
|
688
|
+
if (/agent[-_ ]?preset/i.test(code)) return true;
|
|
689
|
+
const text = errText(e);
|
|
690
|
+
return /preset/i.test(text);
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
/**
|
|
694
|
+
* 契约 §5.8 模型目录映射(v1.0.7 + v1.0.8):宿主 modelCatalog() → wire ModelOption[]。
|
|
695
|
+
*
|
|
696
|
+
* 宿主形状(附录 C / dsh-api-session-controller 实装):
|
|
697
|
+
* { default:{provider,model,reasoningEffort?},
|
|
698
|
+
* groups:[{ id:providerId, name, models:[{id:modelId,name,description?,reasoning?}] }],
|
|
699
|
+
* failures:[…] }
|
|
700
|
+
* —— group.id 是 **provider**,models[].id 是 **model 名**。
|
|
701
|
+
* wire 形状:{ id:"provider/model", provider, model, name, description,
|
|
702
|
+
* reasoningEffort?, efforts?:[{id,name,description?}] }
|
|
703
|
+
* - reasoningEffort 取该模型 reasoning.defaultEffort(没有就不产出该字段);
|
|
704
|
+
* - efforts 拍平 reasoning.efforts(**合法思考强度集合**,v1.0.8);
|
|
705
|
+
* 模型没有 reasoning 时**不产出** efforts 字段。
|
|
706
|
+
* @param {any} catalog
|
|
707
|
+
* @returns {{models:object[],defaultModelId:string}}
|
|
708
|
+
*/
|
|
709
|
+
export function modelCatalogToWire(catalog) {
|
|
710
|
+
const groups = Array.isArray(catalog?.groups) ? catalog.groups : [];
|
|
711
|
+
const models = [];
|
|
712
|
+
for (const group of groups) {
|
|
713
|
+
if (!group || typeof group !== "object") continue;
|
|
714
|
+
const provider = typeof group.id === "string" ? group.id : "";
|
|
715
|
+
if (provider === "") continue;
|
|
716
|
+
const entries = Array.isArray(group.models) ? group.models : [];
|
|
717
|
+
for (const entry of entries) {
|
|
718
|
+
if (!entry || typeof entry !== "object") continue;
|
|
719
|
+
const model = typeof entry.id === "string" ? entry.id : "";
|
|
720
|
+
if (model === "") continue;
|
|
721
|
+
const effort =
|
|
722
|
+
typeof entry?.reasoning?.defaultEffort === "string" ? entry.reasoning.defaultEffort : "";
|
|
723
|
+
const option = {
|
|
724
|
+
id: `${provider}/${model}`,
|
|
725
|
+
provider,
|
|
726
|
+
model,
|
|
727
|
+
name: typeof entry.name === "string" && entry.name !== "" ? entry.name : model,
|
|
728
|
+
description: typeof entry.description === "string" ? entry.description : "",
|
|
729
|
+
};
|
|
730
|
+
if (effort !== "") option.reasoningEffort = effort;
|
|
731
|
+
const efforts = mapReasoningEfforts(entry?.reasoning?.efforts);
|
|
732
|
+
if (efforts.length > 0) option.efforts = efforts;
|
|
733
|
+
models.push(option);
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
const def = catalog?.default;
|
|
737
|
+
const defaultModelId =
|
|
738
|
+
def && typeof def === "object" && typeof def.provider === "string" && def.provider !== "" &&
|
|
739
|
+
typeof def.model === "string" && def.model !== ""
|
|
740
|
+
? `${def.provider}/${def.model}`
|
|
741
|
+
: "";
|
|
742
|
+
return { models, defaultModelId };
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
/** 兼容别名(v1.0.7 旧名)。 */
|
|
746
|
+
export const mapModelCatalog = modelCatalogToWire;
|
|
747
|
+
|
|
748
|
+
/**
|
|
749
|
+
* 契约 §5.8(v1.0.8):宿主 reasoning.efforts → wire efforts[]。
|
|
750
|
+
* @param {unknown} rows
|
|
751
|
+
* @returns {{id:string,name:string,description:string}[]}
|
|
752
|
+
*/
|
|
753
|
+
export function mapReasoningEfforts(rows) {
|
|
754
|
+
const list = Array.isArray(rows) ? rows : [];
|
|
755
|
+
const efforts = [];
|
|
756
|
+
for (const row of list) {
|
|
757
|
+
if (!row || typeof row !== "object") continue;
|
|
758
|
+
const id = typeof row.id === "string" ? row.id.trim() : "";
|
|
759
|
+
if (id === "") continue;
|
|
760
|
+
efforts.push({
|
|
761
|
+
id,
|
|
762
|
+
name: typeof row.name === "string" && row.name !== "" ? row.name : id,
|
|
763
|
+
description: typeof row.description === "string" ? row.description : "",
|
|
764
|
+
});
|
|
765
|
+
}
|
|
766
|
+
return efforts;
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
/**
|
|
770
|
+
* 契约 §5.8 ModelSelection:手机提交的 model → 提交给宿主的
|
|
771
|
+
* {provider, model, reasoningEffort?}(id 不可反拆,只认 provider/model)。
|
|
772
|
+
* @param {unknown} raw
|
|
773
|
+
* @returns {{provider:string,model:string,reasoningEffort?:string}|null}
|
|
774
|
+
*/
|
|
775
|
+
export function parseModelSelection(raw) {
|
|
776
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
|
|
777
|
+
const provider = typeof raw.provider === "string" ? raw.provider.trim() : "";
|
|
778
|
+
const model = typeof raw.model === "string" ? raw.model.trim() : "";
|
|
779
|
+
if (provider === "" || model === "") return null;
|
|
780
|
+
const selection = { provider, model };
|
|
781
|
+
if (typeof raw.reasoningEffort === "string" && raw.reasoningEffort.trim() !== "") {
|
|
782
|
+
selection.reasoningEffort = raw.reasoningEffort.trim();
|
|
783
|
+
}
|
|
784
|
+
return selection;
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
/** 兼容别名(v1.0.7 旧名)。 */
|
|
788
|
+
export const normalizeModelSelection = parseModelSelection;
|
|
789
|
+
|
|
790
|
+
/**
|
|
791
|
+
* 契约 §5.8 ModelSelection 归一化:宿主 selection / model/selection 事件 data
|
|
792
|
+
* → wire {provider, model, reasoningEffort?}(无 reasoningEffort 时省略该字段)。
|
|
793
|
+
* @param {unknown} data
|
|
794
|
+
* @returns {{provider:string,model:string,reasoningEffort?:string}|null}
|
|
795
|
+
*/
|
|
796
|
+
export function mapModelSelection(data) {
|
|
797
|
+
return parseModelSelection(data);
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
/**
|
|
801
|
+
* 契约 §5.9 归档:宿主错误的「原样」回传。
|
|
802
|
+
* 优先用宿主的错误码(RemoteError.code,如 "workspace/active-session"),
|
|
803
|
+
* 没有就用调用方给的兜底码;message 一律用宿主原文。
|
|
804
|
+
* @param {unknown} e
|
|
805
|
+
* @param {string} fallbackCode
|
|
806
|
+
* @returns {{code:string,message:string}}
|
|
807
|
+
*/
|
|
808
|
+
export function hostErrorOf(e, fallbackCode) {
|
|
809
|
+
const code = typeof e?.code === "string" && e.code !== "" ? e.code : fallbackCode;
|
|
810
|
+
return { code, message: errText(e) };
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
/** result / error 信封(契约 §5)。 */
|
|
814
|
+
function resultOf(m, value) {
|
|
815
|
+
return msg("result", { id: m.id, ok: true, value });
|
|
816
|
+
}
|
|
817
|
+
function errorOf(m, code, message) {
|
|
818
|
+
return msg("result", { id: m.id, ok: false, error: { code, message } });
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
function errText(e) {
|
|
822
|
+
return e && typeof e.message === "string" ? e.message : String(e);
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
export class HostBridge {
|
|
826
|
+
#ctx;
|
|
827
|
+
#relay; // { send(message, urgent): boolean, clientOnline: boolean, ready: boolean }
|
|
828
|
+
#push; // PushSender
|
|
829
|
+
#cfg;
|
|
830
|
+
#log;
|
|
831
|
+
#pluginVersion;
|
|
832
|
+
#disposed = false; // dispose() 后禁止一切出站与拦截
|
|
833
|
+
#deltaBuf = new Map(); // sessionId -> { text, timer }(正文增量)
|
|
834
|
+
#reasoningBuf = new Map(); // sessionId -> { text, timer }(思考增量,v1.0.7 与正文分流)
|
|
835
|
+
#modelSelections = new Map(); // sessionId -> {provider, model, reasoningEffort?}(v1.0.8 内存态)
|
|
836
|
+
#pending = new Map(); // askId -> { resolve, kind, sessionId, timer, abortHandler, signal }
|
|
837
|
+
#titles = new Map(); // sessionId -> title(turn.end 推送文案用)
|
|
838
|
+
#pushToken = ""; // 手机 push.register 上报的 token(内存态)
|
|
839
|
+
// v1.0.9(§5.10):imageId -> 宿主附件引用(image.fetch 用;插件重启后为空)
|
|
840
|
+
#imageRefs = new Map();
|
|
841
|
+
// present 投递的图片文件:imageId -> { path, mediaType }(image.fetch 读盘用)
|
|
842
|
+
#deliveredImages = new Map();
|
|
843
|
+
// v1.0.9(§5.10):`${imageId}:${maxEdge}` -> 已缩放的大图(避免重复压缩)
|
|
844
|
+
#imageCache = new Map();
|
|
845
|
+
// v1.1.1(§5.2):会话的待执行消息(排队中 / 已插入当前 turn 但尚未消费)
|
|
846
|
+
// sessionId -> [{itemId, text, target, rpcId}]
|
|
847
|
+
// rpcId 只在插件内部用于「被消费时出队」的匹配,**不进 wire**。
|
|
848
|
+
#queues = new Map();
|
|
849
|
+
// v1.1.1(§5.10.2):交付物图片的历史条目 sessionId -> [{seq, ts, imageId, …, path}]
|
|
850
|
+
#deliveredEntries = new Map();
|
|
851
|
+
// v1.1.1(§5.10.2):交付物图片的缩略图缓存 imageId -> data URI(避免每次历史刷新都重压)
|
|
852
|
+
#deliveredThumbs = new Map();
|
|
853
|
+
// v1.1.2(§5.1):运行中的会话(api-session/status 维护)——「繁忙时的发送行为」只在忙时有意义
|
|
854
|
+
#runningSessions = new Set();
|
|
855
|
+
#disposers = [];
|
|
856
|
+
#hostName = "";
|
|
857
|
+
#dshVersion = "";
|
|
858
|
+
|
|
859
|
+
/**
|
|
860
|
+
* @param {{
|
|
861
|
+
* ctx: any,
|
|
862
|
+
* relay: { send:(m:object, urgent?:boolean)=>boolean, clientOnline:boolean, ready:boolean },
|
|
863
|
+
* push: { notify:(req:object)=>Promise<{ok:boolean,reason?:string}>, configured:boolean, unavailableReason?:()=>string },
|
|
864
|
+
* config: any,
|
|
865
|
+
* log: (level:"info"|"warn"|"error", message:string, extra?:object)=>void,
|
|
866
|
+
* }} deps
|
|
867
|
+
*/
|
|
868
|
+
constructor(deps) {
|
|
869
|
+
this.#ctx = deps.ctx;
|
|
870
|
+
this.#relay = deps.relay;
|
|
871
|
+
this.#push = deps.push;
|
|
872
|
+
this.#cfg = deps.config;
|
|
873
|
+
this.#log = deps.log;
|
|
874
|
+
this.#pluginVersion = pluginVersion();
|
|
875
|
+
this.#hostName = hostname();
|
|
876
|
+
this.#dshVersion = dshVersion();
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
// ---- 生命周期 ------------------------------------------------------------
|
|
880
|
+
|
|
881
|
+
/** 注册全部监听;返回卸载函数(由 index.js 挂进 ctx.effect)。 */
|
|
882
|
+
attach() {
|
|
883
|
+
const ctx = this.#ctx;
|
|
884
|
+
|
|
885
|
+
// --- 瀑布答案器(§5.5):prepend 抢在桌面人工答案器之前 ---
|
|
886
|
+
ctx.on("approval/request", (req, next) => this.#onApprovalRequest(req, next), { prepend: true });
|
|
887
|
+
ctx.on("user-questions/request", (req, next) => this.#onQuestionRequest(req, next), { prepend: true });
|
|
888
|
+
|
|
889
|
+
// --- 事件桥接(§5.2)---
|
|
890
|
+
this.#on("api-session/added", (summary) => {
|
|
891
|
+
const s = mapSummary(summary);
|
|
892
|
+
if (s.sessionId) this.#titles.set(s.sessionId, s.title);
|
|
893
|
+
this.#sendEvent("session.added", { session: s });
|
|
894
|
+
});
|
|
895
|
+
this.#on("api-session/removed", (sessionId) => {
|
|
896
|
+
const key = String(sessionId);
|
|
897
|
+
this.#titles.delete(key);
|
|
898
|
+
// 会话没了,它的待执行列表与交付物历史条目也没有意义了(避免内存泄漏)
|
|
899
|
+
this.#queues.delete(key);
|
|
900
|
+
this.#deliveredEntries.delete(key);
|
|
901
|
+
this.#runningSessions.delete(key);
|
|
902
|
+
this.#sendEvent("session.removed", { sessionId: key });
|
|
903
|
+
});
|
|
904
|
+
this.#on("api-session/status", (sessionId, running) => {
|
|
905
|
+
// v1.1.2:记运行态——「繁忙时的发送行为」只在 agent 忙时才有意义(§5.1)
|
|
906
|
+
const key = String(sessionId);
|
|
907
|
+
if (running === true) {
|
|
908
|
+
this.#runningSessions.add(key);
|
|
909
|
+
} else {
|
|
910
|
+
this.#runningSessions.delete(key);
|
|
911
|
+
}
|
|
912
|
+
this.#sendEvent("session.status", { sessionId: key, running: running === true });
|
|
913
|
+
});
|
|
914
|
+
this.#on("api-session/activity", (sessionId, updatedAt) => {
|
|
915
|
+
this.#sendEvent("session.activity", { sessionId: String(sessionId), updatedAt: Number(updatedAt) || 0 });
|
|
916
|
+
});
|
|
917
|
+
|
|
918
|
+
// agent/assistant-stream:文本增量与**思考增量分流**,按 sessionId 合并节流(≤8 条/秒)
|
|
919
|
+
// v1.0.7:chunk.type==='reasoning-delta' → assistant.reasoningDelta(§5.2)
|
|
920
|
+
this.#on("agent/assistant-stream", (payload) => {
|
|
921
|
+
try {
|
|
922
|
+
const frame = payload?.frame;
|
|
923
|
+
if (!frame || frame.type !== "chunk") return;
|
|
924
|
+
const chunk = frame.chunk;
|
|
925
|
+
if (!chunk || typeof chunk.text !== "string" || chunk.text === "") return;
|
|
926
|
+
if (chunk.type !== "text-delta" && chunk.type !== "reasoning-delta") return;
|
|
927
|
+
const sessionId = payload?.agent?.session?.id;
|
|
928
|
+
if (!sessionId) return;
|
|
929
|
+
if (chunk.type === "reasoning-delta") {
|
|
930
|
+
this.#queueReasoning(String(sessionId), chunk.text);
|
|
931
|
+
return;
|
|
932
|
+
}
|
|
933
|
+
this.#queueDelta(String(sessionId), chunk.text);
|
|
934
|
+
} catch (e) {
|
|
935
|
+
this.#log("warn", "assistant-stream bridge error", { error: errText(e) });
|
|
936
|
+
}
|
|
937
|
+
});
|
|
938
|
+
|
|
939
|
+
// agent/status → idle 时 turn.end(running 转换由 api-session/status 覆盖,避免双发)
|
|
940
|
+
this.#on("agent/status", (payload) => {
|
|
941
|
+
try {
|
|
942
|
+
const sessionId = payload?.agent?.session?.id;
|
|
943
|
+
if (!sessionId) return;
|
|
944
|
+
if (payload.status === "idle") {
|
|
945
|
+
this.#flushDelta(String(sessionId));
|
|
946
|
+
this.#flushReasoning(String(sessionId));
|
|
947
|
+
this.#sendEvent("turn.end", { sessionId: String(sessionId), status: "idle" });
|
|
948
|
+
this.#maybeNotifyTurnEnd(String(sessionId));
|
|
949
|
+
}
|
|
950
|
+
} catch (e) {
|
|
951
|
+
this.#log("warn", "agent/status bridge error", { error: errText(e) });
|
|
952
|
+
}
|
|
953
|
+
});
|
|
954
|
+
|
|
955
|
+
this.#on("agent/error", (payload) => {
|
|
956
|
+
try {
|
|
957
|
+
const sessionId = payload?.agent?.session?.id;
|
|
958
|
+
if (!sessionId) return;
|
|
959
|
+
const err = payload.error;
|
|
960
|
+
const message = err && typeof err.message === "string" ? err.message : String(err);
|
|
961
|
+
this.#flushDelta(String(sessionId));
|
|
962
|
+
this.#flushReasoning(String(sessionId));
|
|
963
|
+
this.#sendEvent("turn.end", { sessionId: String(sessionId), status: "error", error: message });
|
|
964
|
+
this.#maybeNotifyTurnEnd(String(sessionId), message);
|
|
965
|
+
} catch (e) {
|
|
966
|
+
this.#log("warn", "agent/error bridge error", { error: errText(e) });
|
|
967
|
+
}
|
|
968
|
+
});
|
|
969
|
+
|
|
970
|
+
// --- v1.0.6(§5.7):会话事件总闸 → tool.call / tool.result / system.message ---
|
|
971
|
+
// 宿主每写入一条会话日志事件就触发(覆盖所有会话,含 subagent)。
|
|
972
|
+
// 按 session.id 寻址即可,**不过滤**子代理;不认识的事件类型直接忽略,
|
|
973
|
+
// 绝不因为形状不认识而抛错(#on 包装器已兜底)。
|
|
974
|
+
this.#on("session/event", (session, event) => {
|
|
975
|
+
const sessionId = String(session?.id ?? "");
|
|
976
|
+
if (sessionId === "") return;
|
|
977
|
+
const type = event?.type;
|
|
978
|
+
if (type === "tool/call") {
|
|
979
|
+
const mapped = mapToolCallEvent(sessionId, event);
|
|
980
|
+
if (mapped !== null) this.#sendEvent("tool.call", mapped);
|
|
981
|
+
return;
|
|
982
|
+
}
|
|
983
|
+
if (type === "tool/result") {
|
|
984
|
+
const mapped = mapToolResultEvent(sessionId, event);
|
|
985
|
+
if (mapped !== null) this.#sendEvent("tool.result", mapped);
|
|
986
|
+
return;
|
|
987
|
+
}
|
|
988
|
+
if (type === "system/message" || type === "developer/message") {
|
|
989
|
+
const kind = type === "developer/message" ? "developer" : "system";
|
|
990
|
+
const mapped = mapSystemMessageEvent(sessionId, event, kind);
|
|
991
|
+
if (mapped !== null) this.#sendEvent("system.message", mapped);
|
|
992
|
+
return;
|
|
993
|
+
}
|
|
994
|
+
if (type === "model/selection") {
|
|
995
|
+
// v1.0.8:会话模型/思考强度变化(桌面端或手机端 selectModel 都会追加)
|
|
996
|
+
const selection = mapModelSelection(event.data);
|
|
997
|
+
if (selection === null) return;
|
|
998
|
+
this.#modelSelections.set(sessionId, selection);
|
|
999
|
+
this.#sendEvent("session.modelChanged", { sessionId, model: selection });
|
|
1000
|
+
return;
|
|
1001
|
+
}
|
|
1002
|
+
if (type === "assistant/message") {
|
|
1003
|
+
// v1.0.9(§5.10):助手消息里的图片 → 广播 assistant.image(带内联缩略图)
|
|
1004
|
+
this.#emitAssistantImages(sessionId, event);
|
|
1005
|
+
return;
|
|
1006
|
+
}
|
|
1007
|
+
if (type === "deliverables/presented") {
|
|
1008
|
+
// present 工具投递的文件:宿主记的是**路径**,不是图片附件块 →
|
|
1009
|
+
// 不桥接的话手机端永远看不到这些图(用户反馈:桌面有、手机没有)。
|
|
1010
|
+
void this.#emitDeliveredImages(sessionId, event);
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
if (type === "agent/inbox/spliced") {
|
|
1014
|
+
// v1.1.1(§5.2):宿主把「排队中 / 已插入当前 turn 但还没消费」的用户消息
|
|
1015
|
+
// 放进 Agent 的 inbox,并用这个事件通知客户端 → 维护待执行列表。
|
|
1016
|
+
this.#handleInboxSpliced(sessionId, event);
|
|
1017
|
+
return;
|
|
1018
|
+
}
|
|
1019
|
+
if (type === "user/message") {
|
|
1020
|
+
// v1.1.1(§5.2):真人输入被消费(进入某个 turn)→ 从待执行列表里摘掉。
|
|
1021
|
+
this.#handleUserMessage(sessionId, event);
|
|
1022
|
+
return;
|
|
1023
|
+
}
|
|
1024
|
+
// 其余事件(turn/*、step/* …)忽略
|
|
1025
|
+
});
|
|
1026
|
+
|
|
1027
|
+
// --- v1.0.7(§5.9):Workspace 归档变化 → 广播归档全集 ---
|
|
1028
|
+
// 归档的权威数据是 workspaceRegistry.archivedSessionIds;注册表写盘后
|
|
1029
|
+
// 宿主发 domain/changed(domain="workspace"、table=""、operation="put"),
|
|
1030
|
+
// 此时读最新集合并广播 session.archives(**全集**,客户端覆盖各行 archived)。
|
|
1031
|
+
this.#on("domain/changed", (change) => {
|
|
1032
|
+
if (change?.domain !== "workspace") return;
|
|
1033
|
+
if (change?.table !== "") return;
|
|
1034
|
+
if (change?.operation !== "put") return;
|
|
1035
|
+
this.#broadcastArchives();
|
|
1036
|
+
});
|
|
1037
|
+
|
|
1038
|
+
return () => this.dispose();
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
/** 广播归档全集(契约 §5.2 session.archives)。没有注册表 → 不发。 */
|
|
1042
|
+
#broadcastArchives() {
|
|
1043
|
+
const ids = this.#archivedSessionIds();
|
|
1044
|
+
if (ids === null) return;
|
|
1045
|
+
this.#sendEvent("session.archives", { archivedSessionIds: ids });
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
// ---- v1.1.1(§5.2):待执行消息(排队中)追踪 ------------------------------
|
|
1049
|
+
|
|
1050
|
+
/**
|
|
1051
|
+
* `agent/inbox/spliced` → 把插入的消息记进该会话的待执行列表。
|
|
1052
|
+
*
|
|
1053
|
+
* 宿主把「排队中 / 已插入当前 turn 但还没消费」的用户消息放在 Agent 的 inbox 里,
|
|
1054
|
+
* 并用这个事件通知客户端。`data.target` 取 'next-step'(插进正在跑的 turn)
|
|
1055
|
+
* 或 'next-turn'(排到下一个 turn);**其它取值一律忽略**(不认识就不猜)。
|
|
1056
|
+
* `data.inserted` 是消息数组(`{id, source:{kind:'user', rpcId?}, content}`)。
|
|
1057
|
+
*/
|
|
1058
|
+
#handleInboxSpliced(sessionId, event) {
|
|
1059
|
+
const data = event?.data;
|
|
1060
|
+
const target = data?.target;
|
|
1061
|
+
if (target !== "next-step" && target !== "next-turn") return;
|
|
1062
|
+
const items = this.#queueOf(sessionId);
|
|
1063
|
+
let changed = false;
|
|
1064
|
+
// 被取消的 splice(outcome:'canceled')会移除若干条待执行消息:宿主不会再为
|
|
1065
|
+
// 它们发 user/message,故这里按目标从**最前面**摘掉(宿主的 claim 也是从前面取)。
|
|
1066
|
+
const removedCount = Number(data?.removedCount);
|
|
1067
|
+
if (data?.outcome === "canceled" && Number.isSafeInteger(removedCount) && removedCount > 0) {
|
|
1068
|
+
if (this.#dropQueuedFront(items, target, removedCount)) changed = true;
|
|
1069
|
+
}
|
|
1070
|
+
const inserted = Array.isArray(data?.inserted) ? data.inserted : [];
|
|
1071
|
+
for (const message of inserted) {
|
|
1072
|
+
const itemId = typeof message?.id === "string" ? message.id : "";
|
|
1073
|
+
if (itemId === "") continue;
|
|
1074
|
+
const text = queueItemText(message?.content);
|
|
1075
|
+
if (text.trim() === "") continue; // 没有文本 → 不是一条可展示的待执行消息
|
|
1076
|
+
if (items.length >= QUEUE_MAX_ITEMS) {
|
|
1077
|
+
this.#log("warn", "session.queue item cap reached", { sessionId, target });
|
|
1078
|
+
break;
|
|
1079
|
+
}
|
|
1080
|
+
items.push({
|
|
1081
|
+
itemId,
|
|
1082
|
+
text,
|
|
1083
|
+
target,
|
|
1084
|
+
rpcId: typeof message?.source?.rpcId === "string" ? message.source.rpcId : "",
|
|
1085
|
+
});
|
|
1086
|
+
changed = true;
|
|
1087
|
+
}
|
|
1088
|
+
if (changed) this.#broadcastQueue(sessionId, target);
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
/**
|
|
1092
|
+
* `user/message`(真人输入)→ 该消息已被消费,从待执行列表里摘掉。
|
|
1093
|
+
*
|
|
1094
|
+
* 宿主用 `source.rpcId` 标记「这条是我发起的请求」(= 我们传给 prompt 的
|
|
1095
|
+
* requestId),与 inbox 里那一条一一对应;命中即出队。
|
|
1096
|
+
*/
|
|
1097
|
+
#handleUserMessage(sessionId, event) {
|
|
1098
|
+
const data = event?.data;
|
|
1099
|
+
if (data?.source?.kind !== "user") return;
|
|
1100
|
+
const rpcId = typeof data?.source?.rpcId === "string" ? data.source.rpcId : "";
|
|
1101
|
+
if (rpcId === "") return;
|
|
1102
|
+
const items = this.#queues.get(sessionId);
|
|
1103
|
+
if (!items || items.length === 0) return;
|
|
1104
|
+
const index = items.findIndex((item) => item.rpcId !== "" && item.rpcId === rpcId);
|
|
1105
|
+
if (index < 0) return;
|
|
1106
|
+
const target = items[index]?.target ?? "";
|
|
1107
|
+
items.splice(index, 1);
|
|
1108
|
+
this.#broadcastQueue(sessionId, target);
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
/** 该会话的待执行列表(不存在则建一个)。一个 session 一个列表,不串台。 */
|
|
1112
|
+
#queueOf(sessionId) {
|
|
1113
|
+
let items = this.#queues.get(sessionId);
|
|
1114
|
+
if (items === undefined) {
|
|
1115
|
+
items = [];
|
|
1116
|
+
this.#queues.set(sessionId, items);
|
|
1117
|
+
}
|
|
1118
|
+
return items;
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
/** 从待执行列表里按目标摘掉最前面的 n 条(宿主取消排队时用)。 */
|
|
1122
|
+
#dropQueuedFront(items, target, count) {
|
|
1123
|
+
let dropped = 0;
|
|
1124
|
+
for (let i = 0; i < items.length && dropped < count; ) {
|
|
1125
|
+
if (items[i].target !== target) {
|
|
1126
|
+
i++;
|
|
1127
|
+
continue;
|
|
1128
|
+
}
|
|
1129
|
+
items.splice(i, 1);
|
|
1130
|
+
dropped += 1;
|
|
1131
|
+
}
|
|
1132
|
+
return dropped > 0;
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
/**
|
|
1136
|
+
* 广播该会话**当前全部**待执行消息(契约 §5.2 session.queue)。
|
|
1137
|
+
* items 为空数组 = 「没有待执行消息」——也要发,客户端靠它清掉排队列表。
|
|
1138
|
+
*/
|
|
1139
|
+
#broadcastQueue(sessionId, target) {
|
|
1140
|
+
const items = this.#queueItemsOf(sessionId);
|
|
1141
|
+
// 日志只打 sessionId / 条数 / target——绝不输出消息正文(可能含敏感内容)
|
|
1142
|
+
this.#log("info", "session.queue", { sessionId, count: items.length, target });
|
|
1143
|
+
this.#sendEvent("session.queue", { sessionId, items });
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
/** 该会话当前待执行消息的 wire 形状(itemId/text/target,不含内部用的 rpcId)。 */
|
|
1147
|
+
#queueItemsOf(sessionId) {
|
|
1148
|
+
return (this.#queues.get(sessionId) ?? []).map((item) => ({
|
|
1149
|
+
itemId: item.itemId,
|
|
1150
|
+
text: item.text,
|
|
1151
|
+
target: item.target,
|
|
1152
|
+
}));
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
/**
|
|
1156
|
+
* 请求 `session.queue`:拉取该会话**当前**的待执行消息。
|
|
1157
|
+
*
|
|
1158
|
+
* 为什么要有「拉」这一路:事件只在**变化时**推。手机端断线重连后,
|
|
1159
|
+
* 若队列在断线期间变过(或断线前就有排队),光靠事件永远补不上
|
|
1160
|
+
* ——用户会看到「排队列表空着,但桌面端明明排着一条」。
|
|
1161
|
+
* 故客户端打开会话时拉一次全量快照(与事件同形状)。
|
|
1162
|
+
*/
|
|
1163
|
+
#rSessionQueue(m) {
|
|
1164
|
+
const p = m.payload ?? {};
|
|
1165
|
+
const sessionId = typeof p.sessionId === "string" ? p.sessionId : "";
|
|
1166
|
+
if (sessionId === "") {
|
|
1167
|
+
this.#reply(m, errorOf(m, "bad-params", "sessionId required"));
|
|
1168
|
+
return;
|
|
1169
|
+
}
|
|
1170
|
+
this.#reply(m, resultOf(m, { sessionId, items: this.#queueItemsOf(sessionId) }));
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
/** 归档集合(宿主没有 Workspace 注册表 → null,表示「不知道」而不是「空」)。 */
|
|
1174
|
+
#archivedSessionIds() {
|
|
1175
|
+
const reg = this.#workspaceRegistry();
|
|
1176
|
+
if (!reg) return null;
|
|
1177
|
+
try {
|
|
1178
|
+
const ids = reg.archivedSessionIds;
|
|
1179
|
+
if (!Array.isArray(ids)) return null;
|
|
1180
|
+
return ids.map((id) => String(id));
|
|
1181
|
+
} catch (e) {
|
|
1182
|
+
this.#log("warn", "archivedSessionIds read failed", { error: errText(e) });
|
|
1183
|
+
return null;
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
/** Workspace 注册表(宿主没装 dsh-workspace → null)。 */
|
|
1188
|
+
#workspaceRegistry() {
|
|
1189
|
+
return this.#service("workspaceRegistry");
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
/** 事件监听包装:emit 监听必须永不抛出。 */
|
|
1193
|
+
#on(name, handler) {
|
|
1194
|
+
const wrapped = (...args) => {
|
|
1195
|
+
try {
|
|
1196
|
+
handler(...args);
|
|
1197
|
+
} catch (e) {
|
|
1198
|
+
this.#log("warn", "event listener error", { event: name, error: errText(e) });
|
|
1199
|
+
}
|
|
1200
|
+
};
|
|
1201
|
+
this.#ctx.on(name, wrapped);
|
|
1202
|
+
this.#disposers.push(() => {
|
|
1203
|
+
try {
|
|
1204
|
+
this.#ctx.off?.(name, wrapped);
|
|
1205
|
+
} catch {
|
|
1206
|
+
/* ctx 生命周期自行回收 */
|
|
1207
|
+
}
|
|
1208
|
+
});
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
/** 释放全部资源(定时器/待答项/监听)。 */
|
|
1212
|
+
dispose() {
|
|
1213
|
+
this.#disposed = true;
|
|
1214
|
+
for (const b of this.#deltaBuf.values()) {
|
|
1215
|
+
if (b.timer !== null) clearTimeout(b.timer);
|
|
1216
|
+
}
|
|
1217
|
+
this.#deltaBuf.clear();
|
|
1218
|
+
for (const b of this.#reasoningBuf.values()) {
|
|
1219
|
+
if (b.timer !== null) clearTimeout(b.timer);
|
|
1220
|
+
}
|
|
1221
|
+
this.#reasoningBuf.clear();
|
|
1222
|
+
for (const entry of this.#pending.values()) {
|
|
1223
|
+
if (entry.timer !== null) clearTimeout(entry.timer);
|
|
1224
|
+
if (entry.signal && entry.abortHandler) {
|
|
1225
|
+
try {
|
|
1226
|
+
entry.signal.removeEventListener("abort", entry.abortHandler);
|
|
1227
|
+
} catch {
|
|
1228
|
+
/* ignore */
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
// 插件卸载:待答项一律以超时语义放行(next() 已在其 promise 里挂好)
|
|
1232
|
+
entry.resolve({ settled: "timeout" });
|
|
1233
|
+
}
|
|
1234
|
+
this.#pending.clear();
|
|
1235
|
+
for (const off of this.#disposers) {
|
|
1236
|
+
try {
|
|
1237
|
+
off();
|
|
1238
|
+
} catch {
|
|
1239
|
+
/* ignore */
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
this.#disposers = [];
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
// ---- 出站事件 ------------------------------------------------------------
|
|
1246
|
+
|
|
1247
|
+
/**
|
|
1248
|
+
* 发一条 §5.2 事件;链路未就绪返回 false(中继另有离线缓存)。
|
|
1249
|
+
* @returns {boolean} 帧是否交给了链路
|
|
1250
|
+
*/
|
|
1251
|
+
#sendEvent(topic, data, urgent = false) {
|
|
1252
|
+
try {
|
|
1253
|
+
return this.#relay.send(msg("event", { topic, data }), urgent) === true;
|
|
1254
|
+
} catch (e) {
|
|
1255
|
+
this.#log("warn", "event send failed", { topic, error: errText(e) });
|
|
1256
|
+
return false;
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1260
|
+
/** 推送通道状态(契约 §5.2 push.state)。 */
|
|
1261
|
+
sendPushState() {
|
|
1262
|
+
const cfg = this.#cfg.push;
|
|
1263
|
+
const configured = this.#push.configured === true;
|
|
1264
|
+
const data = configured
|
|
1265
|
+
? { enabled: true }
|
|
1266
|
+
: { enabled: false, reason: this.#push.unavailableReason ? this.#push.unavailableReason() : "not configured" };
|
|
1267
|
+
this.#sendEvent("push.state", data);
|
|
1268
|
+
void cfg;
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
// ---- v1.0.9:会话消息里的图片(契约 §5.10)-------------------------------
|
|
1272
|
+
|
|
1273
|
+
/**
|
|
1274
|
+
* 记下 imageId → 宿主附件引用(image.fetch 要用原始字节)。
|
|
1275
|
+
* 插件重启后这张表是空的——此时 image.fetch 回明确错误(不是崩溃)。
|
|
1276
|
+
* @param {object[]} images ImageRef[]
|
|
1277
|
+
*/
|
|
1278
|
+
#rememberImages(images) {
|
|
1279
|
+
for (const image of Array.isArray(images) ? images : []) {
|
|
1280
|
+
const imageId = typeof image?.imageId === "string" ? image.imageId : "";
|
|
1281
|
+
if (imageId === "") continue;
|
|
1282
|
+
const ref = attachmentRefOf(image);
|
|
1283
|
+
if (ref) this.#imageRefs.set(imageId, ref);
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
/**
|
|
1288
|
+
* assistant/message 事件里的图片 → 广播 `assistant.image`(契约 §5.2/§5.10)。
|
|
1289
|
+
*
|
|
1290
|
+
* 缩略图必须**内联**(客户端立刻显示),所以这里要读字节 + 压缩(异步);
|
|
1291
|
+
* 压缩失败/附件读不到 → thumb 留空,只发元数据(客户端画占位框)。
|
|
1292
|
+
* @param {string} sessionId
|
|
1293
|
+
* @param {any} event 宿主会话事件
|
|
1294
|
+
*/
|
|
1295
|
+
#emitAssistantImages(sessionId, event) {
|
|
1296
|
+
try {
|
|
1297
|
+
// 与历史同口径:只收 append 表面事件(replace 是模型可见的影子副本)
|
|
1298
|
+
if (event?.surfaceOp !== "append") return;
|
|
1299
|
+
const refs = imageBlocksOf(event?.data?.message?.content);
|
|
1300
|
+
if (refs.length === 0) return;
|
|
1301
|
+
void this.#sendAssistantImages(sessionId, refs);
|
|
1302
|
+
} catch (e) {
|
|
1303
|
+
this.#log("warn", "assistant image bridge error", { sessionId, error: errText(e) });
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
/**
|
|
1308
|
+
* 逐张生成缩略图并广播 assistant.image。
|
|
1309
|
+
* @param {string} sessionId
|
|
1310
|
+
* @param {object[]} refs 宿主附件引用
|
|
1311
|
+
*/ async #sendAssistantImages(sessionId, refs) {
|
|
1312
|
+
const attachments = attachmentsOf(this.#ctx);
|
|
1313
|
+
for (const ref of refs) {
|
|
1314
|
+
const image = imageRefMeta(ref);
|
|
1315
|
+
if (image.imageId === "") continue;
|
|
1316
|
+
this.#imageRefs.set(image.imageId, ref);
|
|
1317
|
+
try {
|
|
1318
|
+
const bytes = await readAttachmentBytes(attachments, ref, undefined);
|
|
1319
|
+
if (bytes) image.thumb = await makeThumb(bytes, image.mediaType);
|
|
1320
|
+
} catch (e) {
|
|
1321
|
+
// 只发元数据(thumb 留空)——图片失败不影响消息流
|
|
1322
|
+
this.#log("warn", "assistant image thumb failed", { sessionId, imageId: image.imageId, error: errText(e) });
|
|
1323
|
+
}
|
|
1324
|
+
// 注意:日志里**绝不**输出 data URI / base64(可能含敏感图片内容)
|
|
1325
|
+
this.#log("info", "assistant.image", {
|
|
1326
|
+
sessionId,
|
|
1327
|
+
imageId: image.imageId,
|
|
1328
|
+
mediaType: image.mediaType,
|
|
1329
|
+
width: image.width,
|
|
1330
|
+
height: image.height,
|
|
1331
|
+
bytes: image.bytes,
|
|
1332
|
+
thumbBytes: image.thumb.length,
|
|
1333
|
+
});
|
|
1334
|
+
this.#sendEvent("assistant.image", { sessionId, image });
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
/**
|
|
1339
|
+
* present 投递的文件(deliverables/presented)里的**图片** → assistant.image。
|
|
1340
|
+
*
|
|
1341
|
+
* 宿主对「present 出来的文件」只记路径(没有附件引用、没有尺寸),
|
|
1342
|
+
* 所以图片块那条路(imageBlocksOf)永远看不到它们 → 手机端一片空白。
|
|
1343
|
+
* 这里自己认类型、读字节、量尺寸、压缩略图,按 §5.10 同一套通道发出去。
|
|
1344
|
+
*
|
|
1345
|
+
* 非图片文件(.md/.zip/…)跳过:文件卡片是另一条通道,不在本轮范围。
|
|
1346
|
+
* @param {string} sessionId
|
|
1347
|
+
* @param {any} event 宿主会话事件(data.files = [{path, name?, description?}])
|
|
1348
|
+
*/
|
|
1349
|
+
async #emitDeliveredImages(sessionId, event) {
|
|
1350
|
+
try {
|
|
1351
|
+
const files = Array.isArray(event?.data?.files) ? event.data.files : [];
|
|
1352
|
+
for (const file of files) {
|
|
1353
|
+
const path = typeof file?.path === "string" ? file.path.trim() : "";
|
|
1354
|
+
if (path === "") continue;
|
|
1355
|
+
const mediaType = mediaTypeOfPath(path);
|
|
1356
|
+
if (mediaType === "") continue; // 非图片 → 跳过
|
|
1357
|
+
const bytes = await this.#readDeliveredFile(path);
|
|
1358
|
+
if (bytes === null) continue;
|
|
1359
|
+
const meta = await imageMetaOf(bytes);
|
|
1360
|
+
const imageId = deliveredImageId(path, event?.data?.turn);
|
|
1361
|
+
this.#deliveredImages.set(imageId, { path, mediaType });
|
|
1362
|
+
const image = {
|
|
1363
|
+
imageId,
|
|
1364
|
+
mediaType,
|
|
1365
|
+
width: meta.width,
|
|
1366
|
+
height: meta.height,
|
|
1367
|
+
bytes: bytes.length,
|
|
1368
|
+
// v1.1.1(契约 §5.10.1):交付物图片的 ImageRef 带 source:"deliverable"
|
|
1369
|
+
// (附件来源的图片**不带**这个字段——旧客户端按缺省 "attachment" 处理)。
|
|
1370
|
+
source: "deliverable",
|
|
1371
|
+
thumb: await makeThumb(bytes, mediaType),
|
|
1372
|
+
};
|
|
1373
|
+
// v1.1.1(契约 §5.10.2):记进本会话的交付物历史条目——否则 turn 结束
|
|
1374
|
+
// 刷新历史时,那条挂着图片的 assistant 消息被宿主的持久副本替换 →
|
|
1375
|
+
// 图片「一闪而过然后消失」。
|
|
1376
|
+
this.#rememberDeliveredImage(sessionId, {
|
|
1377
|
+
seq: Math.max(0, eventSeq(event)),
|
|
1378
|
+
ts: eventTime(event),
|
|
1379
|
+
imageId,
|
|
1380
|
+
mediaType,
|
|
1381
|
+
width: meta.width,
|
|
1382
|
+
height: meta.height,
|
|
1383
|
+
bytes: bytes.length,
|
|
1384
|
+
path,
|
|
1385
|
+
});
|
|
1386
|
+
// 日志绝不输出路径/字节内容(路径可能含敏感目录名,base64 更不能落日志)
|
|
1387
|
+
this.#log("info", "delivered image bridged", {
|
|
1388
|
+
sessionId,
|
|
1389
|
+
imageId,
|
|
1390
|
+
mediaType,
|
|
1391
|
+
width: image.width,
|
|
1392
|
+
height: image.height,
|
|
1393
|
+
bytes: image.bytes,
|
|
1394
|
+
thumbBytes: image.thumb.length,
|
|
1395
|
+
});
|
|
1396
|
+
this.#sendEvent("assistant.image", { sessionId, image });
|
|
1397
|
+
}
|
|
1398
|
+
} catch (e) {
|
|
1399
|
+
this.#log("warn", "delivered image bridge error", { sessionId, error: errText(e) });
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
|
|
1403
|
+
/**
|
|
1404
|
+
* 读 present 投递的文件字节(超限 / 读不到 → null,绝不抛)。
|
|
1405
|
+
* @param {string} path 绝对路径
|
|
1406
|
+
* @returns {Promise<Buffer|null>}
|
|
1407
|
+
*/
|
|
1408
|
+
async #readDeliveredFile(path) {
|
|
1409
|
+
try {
|
|
1410
|
+
const bytes = await readFile(path);
|
|
1411
|
+
if (!bytes || bytes.length === 0) return null;
|
|
1412
|
+
if (bytes.length > DELIVERED_MAX_BYTES) return null; // 太大不桥接(避免内存/带宽事故)
|
|
1413
|
+
return bytes;
|
|
1414
|
+
} catch {
|
|
1415
|
+
return null;
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
// ---- v1.1.1(契约 §5.10.2):交付物图片在历史里的位置 ------------------------
|
|
1420
|
+
|
|
1421
|
+
/**
|
|
1422
|
+
* 记下本会话交付过的一张图片(历史回包要靠它补出独立图片消息)。
|
|
1423
|
+
* 同一 imageId 重复 present(同一文件同一 turn)→ 幂等,不重复入列。
|
|
1424
|
+
* @param {string} sessionId
|
|
1425
|
+
* @param {object} entry {seq, ts, imageId, mediaType, width, height, bytes, path}
|
|
1426
|
+
*/
|
|
1427
|
+
#rememberDeliveredImage(sessionId, entry) {
|
|
1428
|
+
let entries = this.#deliveredEntries.get(sessionId);
|
|
1429
|
+
if (entries === undefined) {
|
|
1430
|
+
entries = [];
|
|
1431
|
+
this.#deliveredEntries.set(sessionId, entries);
|
|
1432
|
+
}
|
|
1433
|
+
if (entries.some((item) => item.imageId === entry.imageId)) return;
|
|
1434
|
+
entries.push(entry);
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1437
|
+
/**
|
|
1438
|
+
* 交付物图片 → **独立**的历史消息(契约 §5.10.2)。
|
|
1439
|
+
*
|
|
1440
|
+
* 交付物图片**不挂**在 assistant 气泡上:那条气泡在 turn 结束后的历史刷新里
|
|
1441
|
+
* 会被宿主的持久副本替换(副本里没有交付物图片)→ 图片闪一下就没了。
|
|
1442
|
+
* 故这里补一条正文为空串的独立消息,缩略图内联(读不到文件则 thumb 留空,
|
|
1443
|
+
* 只发元数据)。整页缩略图有总预算,超了后续图片只发元数据——但**消息本身保留**
|
|
1444
|
+
* (客户端至少知道有这么一张图)。
|
|
1445
|
+
* @param {string} sessionId
|
|
1446
|
+
* @returns {Promise<object[]>} ChatMessage[]
|
|
1447
|
+
*/
|
|
1448
|
+
async #deliveredHistoryMessages(sessionId) {
|
|
1449
|
+
const entries = this.#deliveredEntries.get(sessionId);
|
|
1450
|
+
if (!entries || entries.length === 0) return [];
|
|
1451
|
+
const out = [];
|
|
1452
|
+
let used = 0;
|
|
1453
|
+
for (const entry of entries) {
|
|
1454
|
+
let thumb = await this.#deliveredThumb(entry);
|
|
1455
|
+
if (thumb !== "") {
|
|
1456
|
+
const size = thumb.length - THUMB_DATA_URI_PREFIX.length;
|
|
1457
|
+
if (used + size > THUMB_PAGE_BUDGET) thumb = "";
|
|
1458
|
+
else used += size;
|
|
1459
|
+
}
|
|
1460
|
+
out.push({
|
|
1461
|
+
id: `d${entry.imageId}`,
|
|
1462
|
+
role: "assistant",
|
|
1463
|
+
text: "",
|
|
1464
|
+
ts: entry.ts,
|
|
1465
|
+
seq: entry.seq,
|
|
1466
|
+
images: [
|
|
1467
|
+
{
|
|
1468
|
+
imageId: entry.imageId,
|
|
1469
|
+
mediaType: entry.mediaType,
|
|
1470
|
+
width: entry.width,
|
|
1471
|
+
height: entry.height,
|
|
1472
|
+
bytes: entry.bytes,
|
|
1473
|
+
source: "deliverable",
|
|
1474
|
+
thumb,
|
|
1475
|
+
},
|
|
1476
|
+
],
|
|
1477
|
+
});
|
|
1478
|
+
}
|
|
1479
|
+
return out;
|
|
1480
|
+
}
|
|
1481
|
+
|
|
1482
|
+
/** 交付物图片的缩略图(读盘 → 压缩);读不到就只发元数据(thumb 留空)。 */
|
|
1483
|
+
async #deliveredThumb(entry) {
|
|
1484
|
+
const cached = this.#deliveredThumbs.get(entry.imageId);
|
|
1485
|
+
if (cached !== undefined) return cached;
|
|
1486
|
+
let thumb = "";
|
|
1487
|
+
const bytes = await this.#readDeliveredFile(entry.path);
|
|
1488
|
+
if (bytes !== null) {
|
|
1489
|
+
try {
|
|
1490
|
+
thumb = await makeThumb(bytes, entry.mediaType);
|
|
1491
|
+
} catch {
|
|
1492
|
+
thumb = "";
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
this.#deliveredThumbs.set(entry.imageId, thumb);
|
|
1496
|
+
this.#pruneDeliveredThumbs();
|
|
1497
|
+
return thumb;
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
/** 交付物缩略图缓存上限(避免长期运行把内存吃满)。 */
|
|
1501
|
+
#pruneDeliveredThumbs() {
|
|
1502
|
+
const limit = 64;
|
|
1503
|
+
while (this.#deliveredThumbs.size > limit) {
|
|
1504
|
+
const oldest = this.#deliveredThumbs.keys().next();
|
|
1505
|
+
if (oldest.done) break;
|
|
1506
|
+
this.#deliveredThumbs.delete(oldest.value);
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
/**
|
|
1511
|
+
* 契约 §5.1 image.fetch:拉取大图(等比缩放 + JPEG q85,base64 ≤ 1MiB 预算)。
|
|
1512
|
+
*
|
|
1513
|
+
* 失败**不影响**会话其余功能(图片可选,不阻塞消息流):一切失败都回 error。
|
|
1514
|
+
* @param {object} m 入站信封
|
|
1515
|
+
*/
|
|
1516
|
+
async #rImageFetch(m) {
|
|
1517
|
+
const p = m.payload ?? {};
|
|
1518
|
+
const imageId = typeof p.imageId === "string" ? p.imageId.trim() : "";
|
|
1519
|
+
if (imageId === "") {
|
|
1520
|
+
this.#reply(m, errorOf(m, "bad-params", "imageId required"));
|
|
1521
|
+
return;
|
|
1522
|
+
}
|
|
1523
|
+
const maxEdge = clampMaxEdge(p.maxEdge);
|
|
1524
|
+
const ref = this.#imageRefs.get(imageId);
|
|
1525
|
+
const delivered = ref ? null : this.#deliveredImages.get(imageId);
|
|
1526
|
+
if (!ref && !delivered) {
|
|
1527
|
+
// 插件重启后缓存为空(或该图不在本次会话里)——回明确文案,不崩
|
|
1528
|
+
this.#reply(
|
|
1529
|
+
m,
|
|
1530
|
+
errorOf(
|
|
1531
|
+
m,
|
|
1532
|
+
"image-not-found",
|
|
1533
|
+
"图片不可用,请重新加载会话后再试(插件重启后图片缓存已清空)。",
|
|
1534
|
+
),
|
|
1535
|
+
);
|
|
1536
|
+
return;
|
|
1537
|
+
}
|
|
1538
|
+
const cacheKey = `${imageId}:${maxEdge}`;
|
|
1539
|
+
const cached = this.#imageCache.get(cacheKey);
|
|
1540
|
+
if (cached !== undefined) {
|
|
1541
|
+
this.#reply(m, resultOf(m, cached));
|
|
1542
|
+
return;
|
|
1543
|
+
}
|
|
1544
|
+
try {
|
|
1545
|
+
// 两条来源:宿主附件(读附件服务)/ present 投递的文件(直接读盘)
|
|
1546
|
+
let bytes = null;
|
|
1547
|
+
let mediaType = "";
|
|
1548
|
+
if (delivered) {
|
|
1549
|
+
bytes = await this.#readDeliveredFile(delivered.path);
|
|
1550
|
+
mediaType = delivered.mediaType;
|
|
1551
|
+
} else {
|
|
1552
|
+
const attachments = attachmentsOf(this.#ctx);
|
|
1553
|
+
if (!attachments) {
|
|
1554
|
+
this.#reply(m, errorOf(m, "service-unavailable", "attachments service unavailable"));
|
|
1555
|
+
return;
|
|
1556
|
+
}
|
|
1557
|
+
bytes = await readAttachmentBytes(attachments, ref, this.#signal(30_000));
|
|
1558
|
+
mediaType = typeof ref?.mediaType === "string" ? ref.mediaType : "";
|
|
1559
|
+
}
|
|
1560
|
+
if (!bytes) {
|
|
1561
|
+
this.#reply(m, errorOf(m, "image-read-failed", "无法读取该图片的原始字节。"));
|
|
1562
|
+
return;
|
|
1563
|
+
}
|
|
1564
|
+
const out = await makeLarge(bytes, mediaType, maxEdge);
|
|
1565
|
+
const value = {
|
|
1566
|
+
imageId,
|
|
1567
|
+
mediaType: out.mediaType,
|
|
1568
|
+
width: out.width,
|
|
1569
|
+
height: out.height,
|
|
1570
|
+
data: out.data,
|
|
1571
|
+
};
|
|
1572
|
+
// 帧预算守卫:中继 1MiB 是 ws 单帧上限(超了断链)——大图回包必须自己守住
|
|
1573
|
+
if (JSON.stringify(value).length > REPLY_PLAIN_MAX_BYTES) {
|
|
1574
|
+
this.#reply(
|
|
1575
|
+
m,
|
|
1576
|
+
errorOf(m, "image-too-large", "原图过大,仅可看缩略图(请以更小的尺寸重试)。"),
|
|
1577
|
+
);
|
|
1578
|
+
return;
|
|
1579
|
+
}
|
|
1580
|
+
this.#imageCache.set(cacheKey, value);
|
|
1581
|
+
this.#pruneImageCache();
|
|
1582
|
+
// 日志只打 imageId/尺寸/字节数——**绝不**输出 data URI / base64
|
|
1583
|
+
this.#log("info", "image.fetch served", {
|
|
1584
|
+
imageId,
|
|
1585
|
+
maxEdge,
|
|
1586
|
+
width: out.width,
|
|
1587
|
+
height: out.height,
|
|
1588
|
+
sourceBytes: bytes.length,
|
|
1589
|
+
dataBytes: out.data.length,
|
|
1590
|
+
});
|
|
1591
|
+
this.#reply(m, resultOf(m, value));
|
|
1592
|
+
} catch (e) {
|
|
1593
|
+
this.#log("warn", "image.fetch failed", { imageId, maxEdge, error: errText(e) });
|
|
1594
|
+
this.#reply(m, errorOf(m, "image-encode-failed", errText(e)));
|
|
1595
|
+
}
|
|
1596
|
+
}
|
|
1597
|
+
|
|
1598
|
+
/** 大图缓存上限(避免长期运行把内存吃满)。 */
|
|
1599
|
+
#pruneImageCache() {
|
|
1600
|
+
const limit = 32;
|
|
1601
|
+
while (this.#imageCache.size > limit) {
|
|
1602
|
+
const oldest = this.#imageCache.keys().next();
|
|
1603
|
+
if (oldest.done) break;
|
|
1604
|
+
this.#imageCache.delete(oldest.value);
|
|
1605
|
+
}
|
|
1606
|
+
}
|
|
1607
|
+
|
|
1608
|
+
// ---- assistant.delta 节流 -------------------------------------------------
|
|
1609
|
+
|
|
1610
|
+
#queueDelta(sessionId, text) {
|
|
1611
|
+
let b = this.#deltaBuf.get(sessionId);
|
|
1612
|
+
if (b === undefined) {
|
|
1613
|
+
b = { text: "", timer: null };
|
|
1614
|
+
this.#deltaBuf.set(sessionId, b);
|
|
1615
|
+
}
|
|
1616
|
+
b.text += text;
|
|
1617
|
+
if (b.text.length > 65_536) b.text = b.text.slice(-65_536); // 内存上限
|
|
1618
|
+
if (b.timer === null) {
|
|
1619
|
+
b.timer = setTimeout(() => this.#flushDelta(sessionId), Math.ceil(1000 / ASSISTANT_THROTTLE_PER_SEC));
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
|
|
1623
|
+
#flushDelta(sessionId) {
|
|
1624
|
+
const b = this.#deltaBuf.get(sessionId);
|
|
1625
|
+
if (b === undefined) return;
|
|
1626
|
+
if (b.timer !== null) {
|
|
1627
|
+
clearTimeout(b.timer);
|
|
1628
|
+
b.timer = null;
|
|
1629
|
+
}
|
|
1630
|
+
const text = b.text;
|
|
1631
|
+
b.text = "";
|
|
1632
|
+
if (text !== "") this.#sendEvent("assistant.delta", { sessionId, text });
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1635
|
+
// ---- assistant.reasoningDelta 节流(v1.0.7,与正文同口径 ≤8 条/秒)--------
|
|
1636
|
+
|
|
1637
|
+
#queueReasoning(sessionId, text) {
|
|
1638
|
+
let b = this.#reasoningBuf.get(sessionId);
|
|
1639
|
+
if (b === undefined) {
|
|
1640
|
+
b = { text: "", timer: null };
|
|
1641
|
+
this.#reasoningBuf.set(sessionId, b);
|
|
1642
|
+
}
|
|
1643
|
+
b.text += text;
|
|
1644
|
+
if (b.text.length > 65_536) b.text = b.text.slice(-65_536); // 内存上限
|
|
1645
|
+
if (b.timer === null) {
|
|
1646
|
+
b.timer = setTimeout(() => this.#flushReasoning(sessionId), Math.ceil(1000 / ASSISTANT_THROTTLE_PER_SEC));
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1649
|
+
|
|
1650
|
+
#flushReasoning(sessionId) {
|
|
1651
|
+
const b = this.#reasoningBuf.get(sessionId);
|
|
1652
|
+
if (b === undefined) return;
|
|
1653
|
+
if (b.timer !== null) {
|
|
1654
|
+
clearTimeout(b.timer);
|
|
1655
|
+
b.timer = null;
|
|
1656
|
+
}
|
|
1657
|
+
const text = b.text;
|
|
1658
|
+
b.text = "";
|
|
1659
|
+
if (text !== "") this.#sendEvent("assistant.reasoningDelta", { sessionId, text });
|
|
1660
|
+
}
|
|
1661
|
+
|
|
1662
|
+
// ---- 业务请求分发(§5.1)---------------------------------------------------
|
|
1663
|
+
|
|
1664
|
+
/**
|
|
1665
|
+
* 分发一条已解密、已消毒的入站业务消息;异步,内部全量兜底。
|
|
1666
|
+
* @param {object} m
|
|
1667
|
+
*/
|
|
1668
|
+
async dispatch(m) {
|
|
1669
|
+
try {
|
|
1670
|
+
switch (m.type) {
|
|
1671
|
+
case "hello":
|
|
1672
|
+
return this.#rHello(m);
|
|
1673
|
+
case "ping":
|
|
1674
|
+
return this.#reply(m, resultOf(m, { pong: Date.now() }));
|
|
1675
|
+
case "session.list":
|
|
1676
|
+
return await this.#rSessionList(m);
|
|
1677
|
+
case "session.history":
|
|
1678
|
+
return await this.#rSessionHistory(m);
|
|
1679
|
+
case "session.subagents":
|
|
1680
|
+
return await this.#rSessionSubagents(m);
|
|
1681
|
+
case "session.subagentPrompt":
|
|
1682
|
+
return await this.#rSubagentPrompt(m);
|
|
1683
|
+
case "session.subagentCancel":
|
|
1684
|
+
return await this.#rSubagentCancel(m);
|
|
1685
|
+
case "session.create":
|
|
1686
|
+
return await this.#rSessionCreate(m);
|
|
1687
|
+
case "session.capabilities":
|
|
1688
|
+
return await this.#rSessionCapabilities(m);
|
|
1689
|
+
case "session.selectModel":
|
|
1690
|
+
return await this.#rSessionSelectModel(m);
|
|
1691
|
+
case "session.model":
|
|
1692
|
+
return this.#rSessionModel(m);
|
|
1693
|
+
case "session.queue":
|
|
1694
|
+
return this.#rSessionQueue(m);
|
|
1695
|
+
case "session.archive":
|
|
1696
|
+
return await this.#rSessionArchive(m);
|
|
1697
|
+
case "session.unarchive":
|
|
1698
|
+
return await this.#rSessionUnarchive(m);
|
|
1699
|
+
case "session.prompt":
|
|
1700
|
+
return await this.#rSessionPrompt(m);
|
|
1701
|
+
case "session.cancel":
|
|
1702
|
+
return await this.#rSessionCancel(m);
|
|
1703
|
+
case "session.rename":
|
|
1704
|
+
return await this.#rSessionRename(m);
|
|
1705
|
+
case "image.fetch":
|
|
1706
|
+
// v1.0.9(§5.10):拉取大图(缩略图已内联,这里按需给原图)
|
|
1707
|
+
return await this.#rImageFetch(m);
|
|
1708
|
+
case "approval.answer":
|
|
1709
|
+
return this.#rApprovalAnswer(m);
|
|
1710
|
+
case "question.answer":
|
|
1711
|
+
return this.#rQuestionAnswer(m);
|
|
1712
|
+
case "push.register":
|
|
1713
|
+
return this.#rPushRegister(m);
|
|
1714
|
+
default:
|
|
1715
|
+
return this.#reply(m, errorOf(m, "bad-type", "unknown type: " + m.type));
|
|
1716
|
+
}
|
|
1717
|
+
} catch (e) {
|
|
1718
|
+
this.#log("error", "dispatch failed", { type: m.type, error: errText(e) });
|
|
1719
|
+
try {
|
|
1720
|
+
this.#reply(m, errorOf(m, "internal", errText(e)));
|
|
1721
|
+
} catch {
|
|
1722
|
+
/* 链路已断 */
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
|
|
1727
|
+
/** 入站信封消毒入口(relay onMessage 调用)。 */
|
|
1728
|
+
onPlainMessage(plain) {
|
|
1729
|
+
const m = sanitizeEnvelope(plain);
|
|
1730
|
+
if (m === null) {
|
|
1731
|
+
this.#log("warn", "dropped malformed envelope");
|
|
1732
|
+
return;
|
|
1733
|
+
}
|
|
1734
|
+
void this.dispatch(m);
|
|
1735
|
+
}
|
|
1736
|
+
|
|
1737
|
+
#reply(m, envelope) {
|
|
1738
|
+
this.#relay.send(envelope, false);
|
|
1739
|
+
}
|
|
1740
|
+
|
|
1741
|
+
/** sessionController(缺失时回 service-unavailable,不抛)。 */
|
|
1742
|
+
#sc() {
|
|
1743
|
+
const sc = this.#ctx.get("sessionController");
|
|
1744
|
+
if (!sc) throw new Error("sessionController unavailable");
|
|
1745
|
+
return sc;
|
|
1746
|
+
}
|
|
1747
|
+
|
|
1748
|
+
/**
|
|
1749
|
+
* 取一个宿主服务(agentPresets / permissionPresets …)。
|
|
1750
|
+
* ctx.get 对不存在的服务会抛(不同宿主版本行为不一致),故 try/catch + 判空,
|
|
1751
|
+
* 再兜一层 ctx[name] 直取。取不到一律返回 null(能力目录降级为空)。
|
|
1752
|
+
*/
|
|
1753
|
+
#service(name) {
|
|
1754
|
+
try {
|
|
1755
|
+
const svc = this.#ctx.get(name);
|
|
1756
|
+
if (svc) return svc;
|
|
1757
|
+
} catch {
|
|
1758
|
+
/* 服务未注册 */
|
|
1759
|
+
}
|
|
1760
|
+
try {
|
|
1761
|
+
const svc = this.#ctx[name];
|
|
1762
|
+
return svc ?? null;
|
|
1763
|
+
} catch {
|
|
1764
|
+
return null;
|
|
1765
|
+
}
|
|
1766
|
+
}
|
|
1767
|
+
|
|
1768
|
+
/** 带超时的 AbortSignal(Remote 方法都收 signal)。 */
|
|
1769
|
+
#signal(ms = 15_000) {
|
|
1770
|
+
const ac = new AbortController();
|
|
1771
|
+
const t = setTimeout(() => ac.abort(), ms);
|
|
1772
|
+
// 不 unref:abort 超时必须真正触发。abort 事件里 clearTimeout,
|
|
1773
|
+
// 所以定时器不会阻止进程退出,也不泄漏。
|
|
1774
|
+
ac.signal.addEventListener("abort", () => clearTimeout(t), { once: true });
|
|
1775
|
+
return ac.signal;
|
|
1776
|
+
}
|
|
1777
|
+
|
|
1778
|
+
#rHello(m) {
|
|
1779
|
+
const p = m.payload ?? {};
|
|
1780
|
+
if (typeof p.pushToken === "string" && p.pushToken !== "") this.#pushToken = p.pushToken;
|
|
1781
|
+
this.#reply(
|
|
1782
|
+
m,
|
|
1783
|
+
resultOf(m, {
|
|
1784
|
+
hostName: this.#hostName,
|
|
1785
|
+
dshVersion: this.#dshVersion,
|
|
1786
|
+
pluginVersion: this.#pluginVersion,
|
|
1787
|
+
}),
|
|
1788
|
+
);
|
|
1789
|
+
// 每次连接(含重连)同步一次推送通道状态(契约 §5.2 push.state)
|
|
1790
|
+
this.sendPushState();
|
|
1791
|
+
}
|
|
1792
|
+
|
|
1793
|
+
async #rSessionList(m) {
|
|
1794
|
+
try {
|
|
1795
|
+
const value = await this.#sc().list({}, this.#signal());
|
|
1796
|
+
// v1.0.7(§5.9):归档标记来自 Workspace 注册表(不是本机伪造状态)。
|
|
1797
|
+
// 宿主没有注册表 → 不产出 archived 字段(客户端按 false 处理)。
|
|
1798
|
+
const archivedIds = this.#archivedSessionIds();
|
|
1799
|
+
const sessions = [];
|
|
1800
|
+
for (const item of value?.items ?? []) {
|
|
1801
|
+
const s = mapSummary(item, archivedIds ?? undefined);
|
|
1802
|
+
if (s.sessionId) {
|
|
1803
|
+
if (s.title) this.#titles.set(s.sessionId, s.title);
|
|
1804
|
+
sessions.push(s);
|
|
1805
|
+
}
|
|
1806
|
+
}
|
|
1807
|
+
this.#reply(m, resultOf(m, { sessions }));
|
|
1808
|
+
} catch (e) {
|
|
1809
|
+
this.#reply(m, errorOf(m, "session-list-failed", errText(e)));
|
|
1810
|
+
}
|
|
1811
|
+
}
|
|
1812
|
+
|
|
1813
|
+
/** 契约 §5.1 session.history:向后翻页的历史消息页(v1.0.4)。
|
|
1814
|
+
* throughSeq(宿主实证)必须是日志中真实存在的末尾 seq——直接传
|
|
1815
|
+
* MAX_SAFE_INTEGER 会被宿主 bad-request 拒绝(past cursor),-1 只用于空日志;
|
|
1816
|
+
* 故先 inspect 冷读拿日志尾 seq 作为切点,再 page 取消息对齐的一页。
|
|
1817
|
+
* 向前翻页:客户端回传上一页的 oldestSeq 作 beforeSeq(开区间)。 */
|
|
1818
|
+
async #rSessionHistory(m) {
|
|
1819
|
+
const p = m.payload ?? {};
|
|
1820
|
+
const sessionId = typeof p.sessionId === "string" ? p.sessionId : "";
|
|
1821
|
+
if (sessionId === "") {
|
|
1822
|
+
this.#reply(m, errorOf(m, "bad-params", "sessionId required"));
|
|
1823
|
+
return;
|
|
1824
|
+
}
|
|
1825
|
+
let maxMessages = Number.isSafeInteger(p.maxMessages) ? p.maxMessages : HISTORY_DEFAULT_MAX;
|
|
1826
|
+
if (maxMessages <= 0) maxMessages = HISTORY_DEFAULT_MAX;
|
|
1827
|
+
if (maxMessages > HISTORY_MAX_LIMIT) maxMessages = HISTORY_MAX_LIMIT;
|
|
1828
|
+
const beforeSeq =
|
|
1829
|
+
Number.isSafeInteger(p.beforeSeq) && p.beforeSeq >= 0 ? p.beforeSeq : undefined;
|
|
1830
|
+
const signal = this.#signal(30_000);
|
|
1831
|
+
try {
|
|
1832
|
+
const sc = this.#sc();
|
|
1833
|
+
// v1.1.1(§5.10.2):交付物图片作为**独立**的历史消息(两条回包路径都要带上)
|
|
1834
|
+
const delivered = await this.#deliveredHistoryMessages(sessionId);
|
|
1835
|
+
let cursor = -1;
|
|
1836
|
+
let address = { kind: "session", sessionId };
|
|
1837
|
+
try {
|
|
1838
|
+
const inspected = await sc.inspect(sessionId, signal);
|
|
1839
|
+
const events = inspected?.events;
|
|
1840
|
+
if (Array.isArray(events) && events.length > 0) {
|
|
1841
|
+
const lastSeq = Number(events[events.length - 1]?.seq);
|
|
1842
|
+
if (Number.isSafeInteger(lastSeq) && lastSeq >= 0) cursor = lastSeq;
|
|
1843
|
+
}
|
|
1844
|
+
// subagent 会话必须走 durable subagent 地址(宿主校验:kind:'session' 会被拒)
|
|
1845
|
+
const header = inspected?.meta;
|
|
1846
|
+
const parent = typeof header?.parentSession === "string" ? header.parentSession : "";
|
|
1847
|
+
if (header?.origin === "subagent" && parent !== "") {
|
|
1848
|
+
address = { kind: "subagent", parentSessionId: parent, childSessionId: sessionId, mode: "unknown" };
|
|
1849
|
+
}
|
|
1850
|
+
} catch (e) {
|
|
1851
|
+
// inspect 失败(会话不存在等)→ 直接把错误回给手机端
|
|
1852
|
+
throw e;
|
|
1853
|
+
}
|
|
1854
|
+
if (cursor < 0) {
|
|
1855
|
+
// 空会话(无任何事件):直接回空页,不折腾 page
|
|
1856
|
+
// (交付物图片仍要带上——它们不在宿主的会话日志里)
|
|
1857
|
+
this.#reply(m, resultOf(m, { messages: delivered, steps: [], hasMore: false, oldestSeq: 0 }));
|
|
1858
|
+
return;
|
|
1859
|
+
}
|
|
1860
|
+
const request = { address, throughSeq: cursor, maxMessages };
|
|
1861
|
+
if (beforeSeq !== undefined) request.beforeSeq = beforeSeq;
|
|
1862
|
+
const page = await sc.page(request, signal);
|
|
1863
|
+
const messages = [];
|
|
1864
|
+
let oldestSeq = Number.MAX_SAFE_INTEGER;
|
|
1865
|
+
let oldestEventSeq = Number.MAX_SAFE_INTEGER;
|
|
1866
|
+
for (const record of page?.records ?? []) {
|
|
1867
|
+
const rawSeq = Number(record?.event?.seq);
|
|
1868
|
+
if (Number.isSafeInteger(rawSeq) && rawSeq >= 0 && rawSeq < oldestEventSeq) {
|
|
1869
|
+
oldestEventSeq = rawSeq;
|
|
1870
|
+
}
|
|
1871
|
+
// v1.0.7:一条事件可能产出「思考 + 正文」两条(mapHistoryMessages)
|
|
1872
|
+
for (const mapped of mapHistoryMessages(sessionId, record)) {
|
|
1873
|
+
messages.push(mapped);
|
|
1874
|
+
// v1.0.9(§5.10):记下 imageId → 附件引用(image.fetch 要用原始字节)
|
|
1875
|
+
this.#rememberImages(mapped.images);
|
|
1876
|
+
if (mapped.seq < oldestSeq) oldestSeq = mapped.seq;
|
|
1877
|
+
}
|
|
1878
|
+
}
|
|
1879
|
+
if (oldestSeq === Number.MAX_SAFE_INTEGER) {
|
|
1880
|
+
// 本页无可聊消息(全被过滤)→ 用页内最老事件 seq 续翻,避免卡页
|
|
1881
|
+
oldestSeq = oldestEventSeq === Number.MAX_SAFE_INTEGER ? 0 : oldestEventSeq;
|
|
1882
|
+
}
|
|
1883
|
+
// v1.0.9(§5.10):缩略图必须内联(客户端立刻显示)——这里补齐
|
|
1884
|
+
await attachThumbs(messages, this.#ctx);
|
|
1885
|
+
// v1.1.1(§5.10.2):交付物图片作为**独立**的历史消息追加进去
|
|
1886
|
+
// (宿主的持久副本里没有它们 → 不补的话图片「一闪而过然后消失」)。
|
|
1887
|
+
messages.push(...delivered);
|
|
1888
|
+
// v1.0.6(§5.7):工作步骤(工具调用)——旧客户端只读 messages,不受影响
|
|
1889
|
+
const steps = mapHistorySteps(page?.records ?? []);
|
|
1890
|
+
// v1.0.9:帧预算守卫——中继的 1MiB 是 **ws 单帧**上限,超了 ws 直接断链
|
|
1891
|
+
//(不是丢一帧)。先剥缩略图、再丢 images[];实在装不下(只剩文字就超了)
|
|
1892
|
+
// → 回 error,宁可这一页失败也不能把整条链路顶爆。
|
|
1893
|
+
const value = { messages, steps, hasMore: page?.hasMore === true, oldestSeq };
|
|
1894
|
+
const fit = fitReplyBudget(value);
|
|
1895
|
+
if (fit.strippedThumbs > 0 || fit.strippedImages > 0) {
|
|
1896
|
+
this.#log("warn", "history reply trimmed to fit the relay frame budget", {
|
|
1897
|
+
sessionId,
|
|
1898
|
+
strippedThumbs: fit.strippedThumbs,
|
|
1899
|
+
strippedImages: fit.strippedImages,
|
|
1900
|
+
bytes: fit.bytes,
|
|
1901
|
+
});
|
|
1902
|
+
}
|
|
1903
|
+
if (fit.overflow) {
|
|
1904
|
+
this.#reply(
|
|
1905
|
+
m,
|
|
1906
|
+
errorOf(
|
|
1907
|
+
m,
|
|
1908
|
+
"history-too-large",
|
|
1909
|
+
"这一页会话内容过大,无法在一帧内传输(请缩小每页条数后重试)。",
|
|
1910
|
+
),
|
|
1911
|
+
);
|
|
1912
|
+
return;
|
|
1913
|
+
}
|
|
1914
|
+
this.#reply(m, resultOf(m, fit.value));
|
|
1915
|
+
} catch (e) {
|
|
1916
|
+
this.#reply(m, errorOf(m, "session-history-failed", errText(e)));
|
|
1917
|
+
}
|
|
1918
|
+
}
|
|
1919
|
+
|
|
1920
|
+
/** 契约 §5.1 session.subagents(v1.0.5):父会话直接子代理目录。
|
|
1921
|
+
* 数据组合:父会话 subagentCatalog 持久投影(mode/label/createdAt/顺序,
|
|
1922
|
+
* 经 sessionController.projections 冷读,无 Agent 激活)+ list 全量行
|
|
1923
|
+
* (running / hasChildren 血缘推断)。投影缺失/冷会话 → 空目录(不报错)。 */
|
|
1924
|
+
async #rSessionSubagents(m) {
|
|
1925
|
+
const p = m.payload ?? {};
|
|
1926
|
+
const sessionId = typeof p.sessionId === "string" ? p.sessionId : "";
|
|
1927
|
+
if (sessionId === "") {
|
|
1928
|
+
this.#reply(m, errorOf(m, "bad-params", "sessionId required"));
|
|
1929
|
+
return;
|
|
1930
|
+
}
|
|
1931
|
+
try {
|
|
1932
|
+
const sc = this.#sc();
|
|
1933
|
+
const signal = this.#signal(20_000);
|
|
1934
|
+
let entries = [];
|
|
1935
|
+
try {
|
|
1936
|
+
const projections = await sc.projections({ sessionId }, signal);
|
|
1937
|
+
const values = projections?.values;
|
|
1938
|
+
const catalog = values?.subagentCatalog;
|
|
1939
|
+
if (Array.isArray(catalog)) entries = catalog;
|
|
1940
|
+
} catch {
|
|
1941
|
+
entries = []; // 无投影/冷会话 → 空目录
|
|
1942
|
+
}
|
|
1943
|
+
let rowsById = null;
|
|
1944
|
+
let allRows = [];
|
|
1945
|
+
if (entries.length > 0) {
|
|
1946
|
+
try {
|
|
1947
|
+
const listed = await sc.list({}, signal);
|
|
1948
|
+
rowsById = new Map();
|
|
1949
|
+
for (const raw of listed?.items ?? []) {
|
|
1950
|
+
const s = mapSummary(raw);
|
|
1951
|
+
if (!s.sessionId) continue;
|
|
1952
|
+
rowsById.set(s.sessionId, s);
|
|
1953
|
+
allRows.push(s);
|
|
1954
|
+
}
|
|
1955
|
+
} catch {
|
|
1956
|
+
rowsById = null; // list 失败 → running/hasChildren 退化默认值
|
|
1957
|
+
allRows = [];
|
|
1958
|
+
}
|
|
1959
|
+
}
|
|
1960
|
+
const subagents = [];
|
|
1961
|
+
for (const e of entries) {
|
|
1962
|
+
const id = typeof e?.id === "string" ? e.id : "";
|
|
1963
|
+
if (id === "") continue;
|
|
1964
|
+
const mode = e?.mode === "one-shot" ? "one-shot" : "continuable";
|
|
1965
|
+
const row = rowsById !== null ? rowsById.get(id) : undefined;
|
|
1966
|
+
let hasChildren = false;
|
|
1967
|
+
if (row !== undefined) {
|
|
1968
|
+
for (const r of allRows) {
|
|
1969
|
+
if (r.parentSessionId === id) {
|
|
1970
|
+
hasChildren = true;
|
|
1971
|
+
break;
|
|
1972
|
+
}
|
|
1973
|
+
}
|
|
1974
|
+
}
|
|
1975
|
+
subagents.push({
|
|
1976
|
+
sessionId: id,
|
|
1977
|
+
label: typeof e?.label === "string" ? e.label : "",
|
|
1978
|
+
mode,
|
|
1979
|
+
running: row ? row.running === true : false,
|
|
1980
|
+
hasChildren,
|
|
1981
|
+
createdAt: Number.isSafeInteger(e?.createdAt) ? e.createdAt : 0,
|
|
1982
|
+
});
|
|
1983
|
+
}
|
|
1984
|
+
this.#reply(m, resultOf(m, { subagents }));
|
|
1985
|
+
} catch (e) {
|
|
1986
|
+
this.#reply(m, errorOf(m, "session-subagents-failed", errText(e)));
|
|
1987
|
+
}
|
|
1988
|
+
}
|
|
1989
|
+
|
|
1990
|
+
/** 契约 §5.1 session.subagentPrompt(v1.0.5):向 continuable 子代理发消息。
|
|
1991
|
+
* 走宿主 subagents 服务 prompt(delivery:'queue');one-shot/不存在会被
|
|
1992
|
+
* 宿主拒绝 → 包成 unsupported 错误回给手机(不是 500)。 */
|
|
1993
|
+
async #rSubagentPrompt(m) {
|
|
1994
|
+
const p = m.payload ?? {};
|
|
1995
|
+
const parentSessionId = typeof p.parentSessionId === "string" ? p.parentSessionId : "";
|
|
1996
|
+
const childSessionId = typeof p.childSessionId === "string" ? p.childSessionId : "";
|
|
1997
|
+
const text = typeof p.text === "string" ? p.text : "";
|
|
1998
|
+
if (parentSessionId === "" || childSessionId === "" || text === "") {
|
|
1999
|
+
this.#reply(m, errorOf(m, "bad-params", "parentSessionId/childSessionId/text required"));
|
|
2000
|
+
return;
|
|
2001
|
+
}
|
|
2002
|
+
let svc = null;
|
|
2003
|
+
try {
|
|
2004
|
+
svc = this.#ctx.get("subagents");
|
|
2005
|
+
} catch {
|
|
2006
|
+
svc = null;
|
|
2007
|
+
}
|
|
2008
|
+
if (!svc || typeof svc.prompt !== "function") {
|
|
2009
|
+
this.#reply(m, errorOf(m, "service-unavailable", "subagents service unavailable"));
|
|
2010
|
+
return;
|
|
2011
|
+
}
|
|
2012
|
+
try {
|
|
2013
|
+
const req = {
|
|
2014
|
+
requestId: crypto.randomUUID(),
|
|
2015
|
+
parentSessionId,
|
|
2016
|
+
childSessionId,
|
|
2017
|
+
mode: "continuable",
|
|
2018
|
+
delivery: "queue",
|
|
2019
|
+
content: [{ type: "text", text }],
|
|
2020
|
+
};
|
|
2021
|
+
const receipt = await svc.prompt(req, this.#signal(15_000));
|
|
2022
|
+
this.#log("info", "subagent prompt accepted", { childSessionId });
|
|
2023
|
+
this.#reply(m, resultOf(m, { accepted: true }));
|
|
2024
|
+
void receipt;
|
|
2025
|
+
} catch (e) {
|
|
2026
|
+
const msg = errText(e);
|
|
2027
|
+
const unsupported = /one-shot|not continuable|unsupported/i.test(msg);
|
|
2028
|
+
this.#reply(m, errorOf(m, unsupported ? "unsupported" : "subagent-prompt-failed", msg));
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
2031
|
+
|
|
2032
|
+
/** 契约 §5.1 session.subagentCancel(v1.0.5):取消 continuable 子代理当前 turn。
|
|
2033
|
+
* interruptByParent 是 fire-and-return(accepted=信号已受理非已停止);
|
|
2034
|
+
* 任何失败回 accepted:false + 原因(尽力而为,手机 UI 自行提示)。 */
|
|
2035
|
+
async #rSubagentCancel(m) {
|
|
2036
|
+
const p = m.payload ?? {};
|
|
2037
|
+
const parentSessionId = typeof p.parentSessionId === "string" ? p.parentSessionId : "";
|
|
2038
|
+
const childSessionId = typeof p.childSessionId === "string" ? p.childSessionId : "";
|
|
2039
|
+
if (parentSessionId === "" || childSessionId === "") {
|
|
2040
|
+
this.#reply(m, errorOf(m, "bad-params", "parentSessionId/childSessionId required"));
|
|
2041
|
+
return;
|
|
2042
|
+
}
|
|
2043
|
+
let svc = null;
|
|
2044
|
+
try {
|
|
2045
|
+
svc = this.#ctx.get("subagents");
|
|
2046
|
+
} catch {
|
|
2047
|
+
svc = null;
|
|
2048
|
+
}
|
|
2049
|
+
if (!svc || typeof svc.interruptByParent !== "function") {
|
|
2050
|
+
this.#reply(m, errorOf(m, "service-unavailable", "subagents service unavailable"));
|
|
2051
|
+
return;
|
|
2052
|
+
}
|
|
2053
|
+
try {
|
|
2054
|
+
await svc.interruptByParent(parentSessionId, childSessionId, "continuable");
|
|
2055
|
+
this.#reply(m, resultOf(m, { accepted: true }));
|
|
2056
|
+
} catch (e) {
|
|
2057
|
+
this.#reply(m, resultOf(m, { accepted: false, message: errText(e) }));
|
|
2058
|
+
}
|
|
2059
|
+
}
|
|
2060
|
+
|
|
2061
|
+
async #rSessionCreate(m) {
|
|
2062
|
+
const p = m.payload ?? {};
|
|
2063
|
+
const agentPreset = typeof p.agentPreset === "string" ? p.agentPreset.trim() : "";
|
|
2064
|
+
const permission = typeof p.permission === "string" ? p.permission.trim() : "";
|
|
2065
|
+
// v1.0.7:model={provider,model,reasoningEffort?}(id 不可反拆,只认 provider/model)
|
|
2066
|
+
const model = normalizeModelSelection(p.model);
|
|
2067
|
+
if (p.model !== undefined && p.model !== null && model === null) {
|
|
2068
|
+
this.#log("warn", "session.create got an invalid model selection; ignored", {
|
|
2069
|
+
model: typeof p.model === "object" ? Object.keys(p.model) : typeof p.model,
|
|
2070
|
+
});
|
|
2071
|
+
}
|
|
2072
|
+
try {
|
|
2073
|
+
const sc = this.#sc();
|
|
2074
|
+
const req = {};
|
|
2075
|
+
if (typeof p.cwd === "string" && p.cwd !== "") req.cwd = p.cwd;
|
|
2076
|
+
if (agentPreset !== "") req.agentPreset = agentPreset;
|
|
2077
|
+
let value;
|
|
2078
|
+
try {
|
|
2079
|
+
value = await sc.create(req);
|
|
2080
|
+
} catch (e) {
|
|
2081
|
+
// 宿主拒绝该模式(preset 不存在等)→ 回 unsupported-agent-preset,
|
|
2082
|
+
// 手机端会回退成「不带选项」重试(契约 §5.8)。
|
|
2083
|
+
if (agentPreset !== "" && isAgentPresetRejection(e)) {
|
|
2084
|
+
this.#log("warn", "host rejected agent preset; phone should retry without it", {
|
|
2085
|
+
agentPreset,
|
|
2086
|
+
});
|
|
2087
|
+
this.#reply(m, errorOf(m, "unsupported-agent-preset", errText(e)));
|
|
2088
|
+
return;
|
|
2089
|
+
}
|
|
2090
|
+
throw e;
|
|
2091
|
+
}
|
|
2092
|
+
const sessionId = value?.sessionId;
|
|
2093
|
+
if (typeof sessionId !== "string" || sessionId === "") {
|
|
2094
|
+
this.#reply(m, errorOf(m, "session-create-failed", "no sessionId returned"));
|
|
2095
|
+
return;
|
|
2096
|
+
}
|
|
2097
|
+
if (typeof p.title === "string" && p.title.trim() !== "") {
|
|
2098
|
+
try {
|
|
2099
|
+
await sc.rename({ sessionId, title: p.title.trim() });
|
|
2100
|
+
} catch (e) {
|
|
2101
|
+
this.#log("warn", "rename after create failed", { error: errText(e) });
|
|
2102
|
+
}
|
|
2103
|
+
}
|
|
2104
|
+
// 权限档位:创建成功后写入(宿主语义:写进「首次发布」前的种子)。
|
|
2105
|
+
// 失败只 warn,不阻断创建(会话照常返回 sessionId)。
|
|
2106
|
+
if (permission !== "") await this.#applyPermissionPreset(sessionId, permission);
|
|
2107
|
+
// v1.0.7(§5.8):模型选择——创建成功后、首条 prompt 前 selectModel。
|
|
2108
|
+
// **失败绝不能回 error**(会话已创建,回 error 会让手机重复创建):
|
|
2109
|
+
// 仍回 sessionId,附 modelError 让客户端提示「已用默认模型」。
|
|
2110
|
+
let modelOut = null;
|
|
2111
|
+
let modelError = "";
|
|
2112
|
+
if (model !== null) {
|
|
2113
|
+
try {
|
|
2114
|
+
const selected = await sc.selectModel({ sessionId, ...model });
|
|
2115
|
+
modelOut = selected?.selected ?? null;
|
|
2116
|
+
} catch (e) {
|
|
2117
|
+
modelError = errText(e);
|
|
2118
|
+
this.#log("warn", "selectModel failed; session created with default model", {
|
|
2119
|
+
sessionId,
|
|
2120
|
+
error: modelError,
|
|
2121
|
+
});
|
|
2122
|
+
}
|
|
2123
|
+
}
|
|
2124
|
+
const out = { sessionId };
|
|
2125
|
+
const echoed =
|
|
2126
|
+
typeof value?.agentPreset === "string" && value.agentPreset !== ""
|
|
2127
|
+
? value.agentPreset
|
|
2128
|
+
: agentPreset;
|
|
2129
|
+
if (echoed !== "") out.agentPreset = echoed;
|
|
2130
|
+
if (modelOut !== null) out.model = modelOut;
|
|
2131
|
+
if (modelError !== "") out.modelError = modelError;
|
|
2132
|
+
this.#reply(m, resultOf(m, out));
|
|
2133
|
+
} catch (e) {
|
|
2134
|
+
this.#reply(m, errorOf(m, "session-create-failed", errText(e)));
|
|
2135
|
+
}
|
|
2136
|
+
}
|
|
2137
|
+
|
|
2138
|
+
/** 契约 §5.8/§5.9 session.capabilities:模式、权限、模型目录 + 归档能力标记。
|
|
2139
|
+
* 宿主没有对应能力 → 对应数组为空 / archiveSupported=false,不得报错。 */
|
|
2140
|
+
async #rSessionCapabilities(m) {
|
|
2141
|
+
const presets = await this.#loadAgentPresets();
|
|
2142
|
+
const permissions = await this.#loadPermissionPresets();
|
|
2143
|
+
const models = await this.#loadModelCatalog();
|
|
2144
|
+
this.#reply(
|
|
2145
|
+
m,
|
|
2146
|
+
resultOf(m, {
|
|
2147
|
+
presets: presets.presets,
|
|
2148
|
+
permissions: permissions.permissions,
|
|
2149
|
+
defaultPreset: presets.defaultPreset,
|
|
2150
|
+
defaultPermission: permissions.defaultPermission,
|
|
2151
|
+
models: models.models,
|
|
2152
|
+
defaultModelId: models.defaultModelId,
|
|
2153
|
+
archiveSupported: this.#archiveSupported(),
|
|
2154
|
+
// v1.1.2:宿主「繁忙时的发送行为」设置(排队发送/插话发送)。
|
|
2155
|
+
// 客户端**只读不选**——发消息走哪种行为由宿主的设置决定(用户明确要求)。
|
|
2156
|
+
busyEnter: this.#busyEnterMode(),
|
|
2157
|
+
}),
|
|
2158
|
+
);
|
|
2159
|
+
}
|
|
2160
|
+
|
|
2161
|
+
/**
|
|
2162
|
+
* 宿主「繁忙时的发送行为」设置(契约 §5.1 v1.1.2)。
|
|
2163
|
+
*
|
|
2164
|
+
* DSH 桌面端的 composer 也读同一个设置(`ui-conversation` 命名空间的 `busyEnter` 字段,
|
|
2165
|
+
* 落在宿主 user-settings 文档里;缺省 'queue')。手机端**不提供切换**——
|
|
2166
|
+
* 「插话还是排队」是宿主的设置,不是手机端的选项(用户明确要求:跟随 DSH 的设置)。
|
|
2167
|
+
*
|
|
2168
|
+
* **每次都现读**(不缓存):用户刚在 DSH 设置里改过,下一条手机消息就该跟随新行为。
|
|
2169
|
+
* 读设置的时机只有「发提示词」与「回 capabilities」——都是低频,缓存反而会引入滞后。
|
|
2170
|
+
*
|
|
2171
|
+
* 读不到(服务缺失/命名空间不在/字段非法)→ 退回 'queue'(最保守:消息不会丢)。
|
|
2172
|
+
*/
|
|
2173
|
+
#busyEnterMode() {
|
|
2174
|
+
try {
|
|
2175
|
+
const settings = this.#service("settings");
|
|
2176
|
+
if (settings && typeof settings.describe === "function") {
|
|
2177
|
+
const rows = settings.describe({ redactSecrets: true });
|
|
2178
|
+
const row = (Array.isArray(rows) ? rows : []).find((r) => r?.ns === BUSY_ENTER_NAMESPACE);
|
|
2179
|
+
const raw = row?.user?.busyEnter ?? row?.value?.busyEnter;
|
|
2180
|
+
if (raw === "steer" || raw === "queue") {
|
|
2181
|
+
return raw;
|
|
2182
|
+
}
|
|
2183
|
+
}
|
|
2184
|
+
} catch (e) {
|
|
2185
|
+
// 宿主没有设置服务 / 读失败 → 保守用 queue
|
|
2186
|
+
this.#log("warn", "busyEnter read failed", { error: errText(e) });
|
|
2187
|
+
}
|
|
2188
|
+
return "queue";
|
|
2189
|
+
}
|
|
2190
|
+
|
|
2191
|
+
/**
|
|
2192
|
+
* 这次提示词用哪种投递行为('queue' | 'steer')。
|
|
2193
|
+
* 跟宿主设置走:agent 忙时用设置值;空闲时总是 queue(= 立即执行,没有「繁忙」可言)。
|
|
2194
|
+
*/
|
|
2195
|
+
#resolvePromptMode(sessionId) {
|
|
2196
|
+
if (!this.#isSessionRunning(sessionId)) {
|
|
2197
|
+
return "queue";
|
|
2198
|
+
}
|
|
2199
|
+
return this.#busyEnterMode();
|
|
2200
|
+
}
|
|
2201
|
+
|
|
2202
|
+
/** 该会话当前是否在跑(api-session/status 维护的内存态)。 */
|
|
2203
|
+
#isSessionRunning(sessionId) {
|
|
2204
|
+
return this.#runningSessions.has(String(sessionId));
|
|
2205
|
+
}
|
|
2206
|
+
|
|
2207
|
+
/** 归档能力(§5.9):宿主有 Workspace 注册表**且**有归档方法才为 true。 */
|
|
2208
|
+
#archiveSupported() {
|
|
2209
|
+
const reg = this.#workspaceRegistry();
|
|
2210
|
+
if (!reg) return false;
|
|
2211
|
+
return typeof reg.archiveSession === "function" && typeof reg.unarchiveSession === "function";
|
|
2212
|
+
}
|
|
2213
|
+
|
|
2214
|
+
/** 模型目录(宿主 sessionController.modelCatalog())。失败/无方法 → 空目录。 */
|
|
2215
|
+
async #loadModelCatalog() {
|
|
2216
|
+
let sc = null;
|
|
2217
|
+
try {
|
|
2218
|
+
sc = this.#sc();
|
|
2219
|
+
} catch {
|
|
2220
|
+
return { models: [], defaultModelId: "" };
|
|
2221
|
+
}
|
|
2222
|
+
if (typeof sc.modelCatalog !== "function") return { models: [], defaultModelId: "" };
|
|
2223
|
+
let catalog = null;
|
|
2224
|
+
try {
|
|
2225
|
+
catalog = await sc.modelCatalog();
|
|
2226
|
+
} catch (e) {
|
|
2227
|
+
this.#log("warn", "model catalog failed; capabilities degrade to empty", { error: errText(e) });
|
|
2228
|
+
return { models: [], defaultModelId: "" };
|
|
2229
|
+
}
|
|
2230
|
+
return modelCatalogToWire(catalog);
|
|
2231
|
+
}
|
|
2232
|
+
|
|
2233
|
+
/** 契约 §5.1/§5.8(v1.0.8)session.selectModel:对**已存在会话**切换模型/思考强度。
|
|
2234
|
+
* 无效 selection → result.error;宿主拒绝 → 原文带出(不假成功);
|
|
2235
|
+
* 成功 → 回宿主归一化后的 {model}。 */
|
|
2236
|
+
async #rSessionSelectModel(m) {
|
|
2237
|
+
const p = m.payload ?? {};
|
|
2238
|
+
const sessionId = typeof p.sessionId === "string" ? p.sessionId : "";
|
|
2239
|
+
if (sessionId === "") {
|
|
2240
|
+
this.#reply(m, errorOf(m, "bad-params", "sessionId required"));
|
|
2241
|
+
return;
|
|
2242
|
+
}
|
|
2243
|
+
const selection = parseModelSelection(p.model);
|
|
2244
|
+
if (selection === null) {
|
|
2245
|
+
this.#reply(m, errorOf(m, "bad-params", "invalid model selection (provider/model required)"));
|
|
2246
|
+
return;
|
|
2247
|
+
}
|
|
2248
|
+
let sc = null;
|
|
2249
|
+
try {
|
|
2250
|
+
sc = this.#sc();
|
|
2251
|
+
} catch (e) {
|
|
2252
|
+
this.#reply(m, errorOf(m, "service-unavailable", errText(e)));
|
|
2253
|
+
return;
|
|
2254
|
+
}
|
|
2255
|
+
if (typeof sc.selectModel !== "function") {
|
|
2256
|
+
this.#reply(m, errorOf(m, "service-unavailable", "sessionController.selectModel unavailable"));
|
|
2257
|
+
return;
|
|
2258
|
+
}
|
|
2259
|
+
try {
|
|
2260
|
+
const value = await sc.selectModel({ sessionId, ...selection });
|
|
2261
|
+
const model = mapModelSelection(value?.selected) ?? selection;
|
|
2262
|
+
this.#reply(m, resultOf(m, { model }));
|
|
2263
|
+
} catch (e) {
|
|
2264
|
+
const err = hostErrorOf(e, "session-select-model-failed");
|
|
2265
|
+
this.#log("warn", "selectModel failed", { sessionId, code: err.code });
|
|
2266
|
+
this.#reply(m, errorOf(m, err.code, err.message));
|
|
2267
|
+
}
|
|
2268
|
+
}
|
|
2269
|
+
|
|
2270
|
+
/** 契约 §5.1/§5.8(v1.0.8)session.model:查询会话当前模型/思考强度。
|
|
2271
|
+
* 数据源是 model/selection 会话事件维护的**内存态**——插件重启后无记录 → null
|
|
2272
|
+
* (**不得臆造**;客户端回退展示目录默认)。 */
|
|
2273
|
+
#rSessionModel(m) {
|
|
2274
|
+
const p = m.payload ?? {};
|
|
2275
|
+
const sessionId = typeof p.sessionId === "string" ? p.sessionId : "";
|
|
2276
|
+
if (sessionId === "") {
|
|
2277
|
+
this.#reply(m, errorOf(m, "bad-params", "sessionId required"));
|
|
2278
|
+
return;
|
|
2279
|
+
}
|
|
2280
|
+
const model = this.#modelSelections.get(sessionId) ?? null;
|
|
2281
|
+
this.#reply(m, resultOf(m, { model }));
|
|
2282
|
+
}
|
|
2283
|
+
|
|
2284
|
+
/** 模式目录(宿主 Agent preset 目录)。服务缺失/抛错 → 空目录。 */
|
|
2285
|
+
async #loadAgentPresets() {
|
|
2286
|
+
const svc = this.#service("agentPresets");
|
|
2287
|
+
if (!svc || typeof svc.list !== "function") return { presets: [], defaultPreset: "" };
|
|
2288
|
+
let rows;
|
|
2289
|
+
try {
|
|
2290
|
+
rows = await svc.list();
|
|
2291
|
+
} catch (e) {
|
|
2292
|
+
this.#log("warn", "agent preset list failed; capabilities degrade to empty", {
|
|
2293
|
+
error: errText(e),
|
|
2294
|
+
});
|
|
2295
|
+
return { presets: [], defaultPreset: "" };
|
|
2296
|
+
}
|
|
2297
|
+
const list = Array.isArray(rows) ? rows : Array.isArray(rows?.presets) ? rows.presets : [];
|
|
2298
|
+
let defaultId = "";
|
|
2299
|
+
try {
|
|
2300
|
+
defaultId = typeof svc.defaultId === "string" ? svc.defaultId : "";
|
|
2301
|
+
} catch {
|
|
2302
|
+
defaultId = "";
|
|
2303
|
+
}
|
|
2304
|
+
return mapAgentPresetOptions(list, defaultId);
|
|
2305
|
+
}
|
|
2306
|
+
|
|
2307
|
+
/** 权限目录(宿主 permission preset 目录)。服务缺失/抛错 → 空目录。 */
|
|
2308
|
+
async #loadPermissionPresets() {
|
|
2309
|
+
const svc = this.#service("permissionPresets");
|
|
2310
|
+
if (!svc || typeof svc.catalog !== "function") return { permissions: [], defaultPermission: "" };
|
|
2311
|
+
let catalog;
|
|
2312
|
+
try {
|
|
2313
|
+
catalog = await svc.catalog();
|
|
2314
|
+
} catch (e) {
|
|
2315
|
+
this.#log("warn", "permission preset catalog failed; capabilities degrade to empty", {
|
|
2316
|
+
error: errText(e),
|
|
2317
|
+
});
|
|
2318
|
+
return { permissions: [], defaultPermission: "" };
|
|
2319
|
+
}
|
|
2320
|
+
return mapPermissionOptions(catalog);
|
|
2321
|
+
}
|
|
2322
|
+
|
|
2323
|
+
/** 把权限档位写进一个已创建的会话(契约 §5.8)。
|
|
2324
|
+
* 宿主版本没有 resolveAgent / 没有 permissionPresets 服务 → 只 warn,不阻断。 */
|
|
2325
|
+
async #applyPermissionPreset(sessionId, permission) {
|
|
2326
|
+
const svc = this.#service("permissionPresets");
|
|
2327
|
+
if (!svc || typeof svc.set !== "function") {
|
|
2328
|
+
this.#log("warn", "permissionPresets service unavailable; permission not applied", {
|
|
2329
|
+
sessionId,
|
|
2330
|
+
});
|
|
2331
|
+
return;
|
|
2332
|
+
}
|
|
2333
|
+
let sc = null;
|
|
2334
|
+
try {
|
|
2335
|
+
sc = this.#sc();
|
|
2336
|
+
} catch (e) {
|
|
2337
|
+
this.#log("warn", "sessionController unavailable; permission not applied", {
|
|
2338
|
+
sessionId,
|
|
2339
|
+
error: errText(e),
|
|
2340
|
+
});
|
|
2341
|
+
return;
|
|
2342
|
+
}
|
|
2343
|
+
if (typeof sc.resolveAgent !== "function") {
|
|
2344
|
+
this.#log("warn", "sessionController.resolveAgent unavailable; permission not applied", {
|
|
2345
|
+
sessionId,
|
|
2346
|
+
});
|
|
2347
|
+
return;
|
|
2348
|
+
}
|
|
2349
|
+
let agentRes = null;
|
|
2350
|
+
try {
|
|
2351
|
+
agentRes = await sc.resolveAgent(sessionId);
|
|
2352
|
+
} catch (e) {
|
|
2353
|
+
this.#log("warn", "resolveAgent failed; permission not applied", {
|
|
2354
|
+
sessionId,
|
|
2355
|
+
error: errText(e),
|
|
2356
|
+
});
|
|
2357
|
+
return;
|
|
2358
|
+
}
|
|
2359
|
+
// 宿主两种形状都兜住:{ agent } | { error }(旧版)与直接返回 Agent 的新版
|
|
2360
|
+
const agent = agentRes?.agent ?? agentRes;
|
|
2361
|
+
const session = agent?.session;
|
|
2362
|
+
if (!session) {
|
|
2363
|
+
this.#log("warn", "resolveAgent returned no session; permission not applied", { sessionId });
|
|
2364
|
+
return;
|
|
2365
|
+
}
|
|
2366
|
+
try {
|
|
2367
|
+
svc.set(session, permission);
|
|
2368
|
+
} catch (e) {
|
|
2369
|
+
this.#log("warn", "permission preset set failed; session kept", {
|
|
2370
|
+
sessionId,
|
|
2371
|
+
error: errText(e),
|
|
2372
|
+
});
|
|
2373
|
+
}
|
|
2374
|
+
}
|
|
2375
|
+
|
|
2376
|
+
/** 契约 §5.1/§5.9 session.archive:写入 Workspace 真实归档集合。
|
|
2377
|
+
* 宿主错误**原样**回给客户端(不得在本机假成功);归档广播由
|
|
2378
|
+
* domain/changed 驱动(#broadcastArchives)。 */
|
|
2379
|
+
async #rSessionArchive(m) {
|
|
2380
|
+
const p = m.payload ?? {};
|
|
2381
|
+
const sessionId = typeof p.sessionId === "string" ? p.sessionId : "";
|
|
2382
|
+
if (sessionId === "") {
|
|
2383
|
+
this.#reply(m, errorOf(m, "bad-params", "sessionId required"));
|
|
2384
|
+
return;
|
|
2385
|
+
}
|
|
2386
|
+
const reg = this.#workspaceRegistry();
|
|
2387
|
+
if (!reg || typeof reg.archiveSession !== "function") {
|
|
2388
|
+
this.#reply(m, errorOf(m, "service-unavailable", "workspace registry unavailable"));
|
|
2389
|
+
return;
|
|
2390
|
+
}
|
|
2391
|
+
const stopActivity = p.stopActivity === true;
|
|
2392
|
+
try {
|
|
2393
|
+
await reg.archiveSession(sessionId, { stopActivity });
|
|
2394
|
+
this.#reply(m, resultOf(m, { sessionId, archived: true }));
|
|
2395
|
+
} catch (e) {
|
|
2396
|
+
const err = hostErrorOf(e, "session-archive-failed");
|
|
2397
|
+
this.#log("warn", "archive failed", { sessionId, code: err.code });
|
|
2398
|
+
this.#reply(m, errorOf(m, err.code, err.message));
|
|
2399
|
+
}
|
|
2400
|
+
}
|
|
2401
|
+
|
|
2402
|
+
/** 契约 §5.1/§5.9 session.unarchive:从 Workspace 归档集合恢复(幂等)。 */
|
|
2403
|
+
async #rSessionUnarchive(m) {
|
|
2404
|
+
const p = m.payload ?? {};
|
|
2405
|
+
const sessionId = typeof p.sessionId === "string" ? p.sessionId : "";
|
|
2406
|
+
if (sessionId === "") {
|
|
2407
|
+
this.#reply(m, errorOf(m, "bad-params", "sessionId required"));
|
|
2408
|
+
return;
|
|
2409
|
+
}
|
|
2410
|
+
const reg = this.#workspaceRegistry();
|
|
2411
|
+
if (!reg || typeof reg.unarchiveSession !== "function") {
|
|
2412
|
+
this.#reply(m, errorOf(m, "service-unavailable", "workspace registry unavailable"));
|
|
2413
|
+
return;
|
|
2414
|
+
}
|
|
2415
|
+
try {
|
|
2416
|
+
await reg.unarchiveSession(sessionId);
|
|
2417
|
+
this.#reply(m, resultOf(m, { sessionId, archived: false }));
|
|
2418
|
+
} catch (e) {
|
|
2419
|
+
const err = hostErrorOf(e, "session-unarchive-failed");
|
|
2420
|
+
this.#log("warn", "unarchive failed", { sessionId, code: err.code });
|
|
2421
|
+
this.#reply(m, errorOf(m, err.code, err.message));
|
|
2422
|
+
}
|
|
2423
|
+
}
|
|
2424
|
+
|
|
2425
|
+
async #rSessionPrompt(m) {
|
|
2426
|
+
const p = m.payload ?? {};
|
|
2427
|
+
const sessionId = typeof p.sessionId === "string" ? p.sessionId : "";
|
|
2428
|
+
const text = typeof p.text === "string" ? p.text : "";
|
|
2429
|
+
if (sessionId === "" || text.trim() === "") {
|
|
2430
|
+
this.#reply(m, errorOf(m, "bad-params", "sessionId and non-empty text required"));
|
|
2431
|
+
return;
|
|
2432
|
+
}
|
|
2433
|
+
// v1.1.2(契约 §5.1):**投递行为由宿主设置决定**,客户端不参与选择。
|
|
2434
|
+
// DSH 桌面端 composer 读的是同一处设置(ui-conversation.busyEnter:
|
|
2435
|
+
// 「排队发送」/「插话发送」),手机端只跟随——用户明确要求「不应该手机上设置」。
|
|
2436
|
+
// 客户端若仍带 mode(旧客户端),**忽略**它,不报错也不改变行为。
|
|
2437
|
+
const mode = this.#resolvePromptMode(sessionId);
|
|
2438
|
+
const requestId = randomUUID();
|
|
2439
|
+
const send = async (delivery) =>
|
|
2440
|
+
this.#sc().prompt(
|
|
2441
|
+
{
|
|
2442
|
+
requestId,
|
|
2443
|
+
sessionId,
|
|
2444
|
+
mode: delivery,
|
|
2445
|
+
content: [{ type: "text", text }],
|
|
2446
|
+
},
|
|
2447
|
+
this.#signal(30_000),
|
|
2448
|
+
);
|
|
2449
|
+
try {
|
|
2450
|
+
const value = await send(mode);
|
|
2451
|
+
this.#reply(m, resultOf(m, { accepted: value?.accepted === true, mode }));
|
|
2452
|
+
} catch (e) {
|
|
2453
|
+
// 宿主拒绝插话(session/steer-unavailable:当前 turn 不再接受插入)时
|
|
2454
|
+
// **自动退回排队**——桌面端此时是把 steer 动作置灰,手机不能把用户的消息弄丢。
|
|
2455
|
+
const err = hostErrorOf(e, "prompt-failed");
|
|
2456
|
+
if (mode === "steer" && err.code === "session/steer-unavailable") {
|
|
2457
|
+
this.#log("warn", "steer unavailable, falling back to queue", { sessionId });
|
|
2458
|
+
try {
|
|
2459
|
+
const value = await send("queue");
|
|
2460
|
+
this.#reply(m, resultOf(m, { accepted: value?.accepted === true, mode: "queue" }));
|
|
2461
|
+
return;
|
|
2462
|
+
} catch (e2) {
|
|
2463
|
+
const err2 = hostErrorOf(e2, "prompt-failed");
|
|
2464
|
+
this.#log("warn", "prompt failed", { sessionId, mode: "queue", code: err2.code });
|
|
2465
|
+
this.#reply(m, errorOf(m, err2.code, err2.message));
|
|
2466
|
+
return;
|
|
2467
|
+
}
|
|
2468
|
+
}
|
|
2469
|
+
// 其余宿主错误**原样**回客户端(不得吞掉)
|
|
2470
|
+
this.#log("warn", "prompt failed", { sessionId, mode, code: err.code });
|
|
2471
|
+
this.#reply(m, errorOf(m, err.code, err.message));
|
|
2472
|
+
}
|
|
2473
|
+
}
|
|
2474
|
+
|
|
2475
|
+
async #rSessionCancel(m) {
|
|
2476
|
+
const p = m.payload ?? {};
|
|
2477
|
+
const sessionId = typeof p.sessionId === "string" ? p.sessionId : "";
|
|
2478
|
+
if (sessionId === "") {
|
|
2479
|
+
this.#reply(m, errorOf(m, "bad-params", "sessionId required"));
|
|
2480
|
+
return;
|
|
2481
|
+
}
|
|
2482
|
+
try {
|
|
2483
|
+
const value = await this.#sc().cancel({ sessionId });
|
|
2484
|
+
this.#reply(m, resultOf(m, { cancelled: value?.accepted === true }));
|
|
2485
|
+
} catch (e) {
|
|
2486
|
+
this.#reply(m, errorOf(m, "cancel-failed", errText(e)));
|
|
2487
|
+
}
|
|
2488
|
+
}
|
|
2489
|
+
|
|
2490
|
+
async #rSessionRename(m) {
|
|
2491
|
+
const p = m.payload ?? {};
|
|
2492
|
+
const sessionId = typeof p.sessionId === "string" ? p.sessionId : "";
|
|
2493
|
+
const title = typeof p.title === "string" ? p.title : "";
|
|
2494
|
+
if (sessionId === "" || title.trim() === "") {
|
|
2495
|
+
this.#reply(m, errorOf(m, "bad-params", "sessionId and non-empty title required"));
|
|
2496
|
+
return;
|
|
2497
|
+
}
|
|
2498
|
+
try {
|
|
2499
|
+
const value = await this.#sc().rename({ sessionId, title: title.trim() });
|
|
2500
|
+
const accepted = typeof value?.title === "string" ? value.title : title.trim();
|
|
2501
|
+
this.#titles.set(sessionId, accepted);
|
|
2502
|
+
this.#reply(m, resultOf(m, { title: accepted }));
|
|
2503
|
+
} catch (e) {
|
|
2504
|
+
this.#reply(m, errorOf(m, "rename-failed", errText(e)));
|
|
2505
|
+
}
|
|
2506
|
+
}
|
|
2507
|
+
|
|
2508
|
+
#rApprovalAnswer(m) {
|
|
2509
|
+
const p = m.payload ?? {};
|
|
2510
|
+
const askId = typeof p.askId === "string" ? p.askId : "";
|
|
2511
|
+
const decision = p.decision;
|
|
2512
|
+
if (decision !== "approved" && decision !== "rejected") {
|
|
2513
|
+
this.#reply(m, errorOf(m, "bad-decision", 'decision must be "approved" or "rejected"'));
|
|
2514
|
+
return;
|
|
2515
|
+
}
|
|
2516
|
+
const entry = askId === "" ? undefined : this.#pending.get(askId);
|
|
2517
|
+
if (entry === undefined || entry.kind !== "approval") {
|
|
2518
|
+
// 未命中 = 超时后迟到 / 未知 askId(契约 §5.1:applied:false)
|
|
2519
|
+
this.#reply(m, resultOf(m, { applied: false }));
|
|
2520
|
+
return;
|
|
2521
|
+
}
|
|
2522
|
+
this.#settle(entry, "phone", { decision });
|
|
2523
|
+
this.#reply(m, resultOf(m, { applied: true }));
|
|
2524
|
+
}
|
|
2525
|
+
|
|
2526
|
+
#rQuestionAnswer(m) {
|
|
2527
|
+
const p = m.payload ?? {};
|
|
2528
|
+
const askId = typeof p.askId === "string" ? p.askId : "";
|
|
2529
|
+
const entry = askId === "" ? undefined : this.#pending.get(askId);
|
|
2530
|
+
if (entry === undefined || entry.kind !== "question") {
|
|
2531
|
+
this.#reply(m, resultOf(m, { applied: false }));
|
|
2532
|
+
return;
|
|
2533
|
+
}
|
|
2534
|
+
const answers = p.answers;
|
|
2535
|
+
if (answers === null || typeof answers !== "object" || Array.isArray(answers)) {
|
|
2536
|
+
this.#reply(m, errorOf(m, "bad-answers", "answers must be an object of questionId -> label(s)"));
|
|
2537
|
+
return;
|
|
2538
|
+
}
|
|
2539
|
+
this.#settle(entry, "phone", { answers, freeText: typeof p.freeText === "string" ? p.freeText : "" });
|
|
2540
|
+
this.#reply(m, resultOf(m, { applied: true }));
|
|
2541
|
+
}
|
|
2542
|
+
|
|
2543
|
+
#rPushRegister(m) {
|
|
2544
|
+
const p = m.payload ?? {};
|
|
2545
|
+
const token = typeof p.pushToken === "string" ? p.pushToken : "";
|
|
2546
|
+
const platform = typeof p.platform === "string" ? p.platform : "";
|
|
2547
|
+
if (token === "") {
|
|
2548
|
+
this.#reply(m, errorOf(m, "bad-params", "pushToken required"));
|
|
2549
|
+
return;
|
|
2550
|
+
}
|
|
2551
|
+
if (platform !== "" && platform !== "harmonyos") {
|
|
2552
|
+
this.#reply(m, errorOf(m, "bad-platform", 'platform must be "harmonyos"'));
|
|
2553
|
+
return;
|
|
2554
|
+
}
|
|
2555
|
+
this.#pushToken = token;
|
|
2556
|
+
this.#reply(m, resultOf(m, { registered: true }));
|
|
2557
|
+
this.sendPushState();
|
|
2558
|
+
}
|
|
2559
|
+
|
|
2560
|
+
// ---- 瀑布答案器(§5.5)-----------------------------------------------------
|
|
2561
|
+
|
|
2562
|
+
/** 手机在线且开关打开才拦截;否则 next() 原样放行。 */
|
|
2563
|
+
#shouldIntercept(kind) {
|
|
2564
|
+
try {
|
|
2565
|
+
if (this.#disposed) return false;
|
|
2566
|
+
if (this.#cfg.enabled !== true) return false;
|
|
2567
|
+
if (kind === "approval" && this.#cfg.interceptApprovals !== true) return false;
|
|
2568
|
+
if (kind === "question" && this.#cfg.interceptQuestions !== true) return false;
|
|
2569
|
+
return this.#relay.clientOnline === true;
|
|
2570
|
+
} catch {
|
|
2571
|
+
return false;
|
|
2572
|
+
}
|
|
2573
|
+
}
|
|
2574
|
+
|
|
2575
|
+
/**
|
|
2576
|
+
* approval/request 拦截器。契约 §5.5:
|
|
2577
|
+
* 拦截 → 推 approval.request + Push → 等 approval.answer(默认 120s);
|
|
2578
|
+
* 超时/出错/取消 → return next()(绝不 fail-closed);迟到回答回 applied:false。
|
|
2579
|
+
*/
|
|
2580
|
+
async #onApprovalRequest(req, next) {
|
|
2581
|
+
if (!this.#shouldIntercept("approval")) return next();
|
|
2582
|
+
const askId = randomUUID();
|
|
2583
|
+
const sessionId = String(req?.agent?.session?.id ?? "");
|
|
2584
|
+
const timeoutMs = Number(this.#cfg.approvalTimeoutMs) || 120_000;
|
|
2585
|
+
const sent = this.#sendEvent(
|
|
2586
|
+
"approval.request",
|
|
2587
|
+
{
|
|
2588
|
+
askId,
|
|
2589
|
+
sessionId,
|
|
2590
|
+
toolName: String(req?.toolName ?? "unknown"),
|
|
2591
|
+
reason: typeof req?.reason === "string" ? req.reason : "",
|
|
2592
|
+
argsPreview: this.#argsPreviewOf(req?.agent, req?.callId),
|
|
2593
|
+
timeoutMs,
|
|
2594
|
+
},
|
|
2595
|
+
true, // urgent:离线时优先补发(契约 §4)
|
|
2596
|
+
);
|
|
2597
|
+
if (!sent) {
|
|
2598
|
+
// 帧没进链路(socket 刚断)→ 白等 120s 没意义,直接放行桌面答案器
|
|
2599
|
+
return next();
|
|
2600
|
+
}
|
|
2601
|
+
this.#notifyKind("approval", sessionId, askId, {
|
|
2602
|
+
title: "需要审批",
|
|
2603
|
+
body: `${req?.toolName ?? "tool"}:${(typeof req?.reason === "string" && req.reason) || "请求提权"}`.slice(0, 200),
|
|
2604
|
+
});
|
|
2605
|
+
|
|
2606
|
+
const outcome = await this.#waitForAnswer({
|
|
2607
|
+
askId,
|
|
2608
|
+
kind: "approval",
|
|
2609
|
+
sessionId,
|
|
2610
|
+
signal: req?.signal,
|
|
2611
|
+
timeoutMs,
|
|
2612
|
+
});
|
|
2613
|
+
if (outcome.settled === "phone") {
|
|
2614
|
+
const decision = outcome.decision === "approved" ? "approved" : "rejected";
|
|
2615
|
+
this.#sendEvent("approval.resolved", { askId, decision, source: "phone" });
|
|
2616
|
+
return decision === "approved" ? "allowed-once" : "rejected";
|
|
2617
|
+
}
|
|
2618
|
+
// timeout / abort / 插件卸载 → 放行桌面答案器(契约 §5.5 硬性要求)
|
|
2619
|
+
this.#sendEvent("approval.resolved", { askId, decision: "pending", source: "timeout" });
|
|
2620
|
+
let final = "unavailable";
|
|
2621
|
+
try {
|
|
2622
|
+
final = await next();
|
|
2623
|
+
} catch (e) {
|
|
2624
|
+
// 桌面链条自身故障:向上传播,由核心决定(我们已尽放行义务)
|
|
2625
|
+
this.#log("warn", "next() after approval timeout failed", { error: errText(e) });
|
|
2626
|
+
throw e;
|
|
2627
|
+
}
|
|
2628
|
+
this.#sendEvent("approval.resolved", {
|
|
2629
|
+
askId,
|
|
2630
|
+
decision: final === "allowed-once" ? "approved" : "rejected",
|
|
2631
|
+
source: "desktop",
|
|
2632
|
+
});
|
|
2633
|
+
return final;
|
|
2634
|
+
}
|
|
2635
|
+
|
|
2636
|
+
/** user-questions/request 拦截器(同 §5.5 语义,答案是 AskUserQuestionAnswer)。 */
|
|
2637
|
+
async #onQuestionRequest(req, next) {
|
|
2638
|
+
if (!this.#shouldIntercept("question")) return next();
|
|
2639
|
+
const askId = randomUUID();
|
|
2640
|
+
const sessionId = String(req?.agent?.session?.id ?? "");
|
|
2641
|
+
const timeoutMs = Number(this.#cfg.approvalTimeoutMs) || 120_000;
|
|
2642
|
+
const questions = (Array.isArray(req?.questions) ? req.questions : []).map((q) => ({
|
|
2643
|
+
id: String(q?.id ?? ""),
|
|
2644
|
+
question: String(q?.question ?? ""),
|
|
2645
|
+
multiSelect: q?.multiSelect === true,
|
|
2646
|
+
options: (Array.isArray(q?.options) ? q.options : []).map((o) => ({
|
|
2647
|
+
label: String(o?.label ?? ""),
|
|
2648
|
+
description: typeof o?.description === "string" ? o.description : "",
|
|
2649
|
+
})),
|
|
2650
|
+
}));
|
|
2651
|
+
if (questions.length === 0 || questions.some((q) => q.id === "")) return next(); // 形状不对,放行
|
|
2652
|
+
const sent = this.#sendEvent(
|
|
2653
|
+
"question.request",
|
|
2654
|
+
{
|
|
2655
|
+
askId,
|
|
2656
|
+
sessionId,
|
|
2657
|
+
questions,
|
|
2658
|
+
timeoutMs,
|
|
2659
|
+
multiSelect: questions.some((q) => q.multiSelect),
|
|
2660
|
+
},
|
|
2661
|
+
true,
|
|
2662
|
+
);
|
|
2663
|
+
if (!sent) {
|
|
2664
|
+
// 帧没进链路 → 不白等,直接放行桌面答案器
|
|
2665
|
+
return next();
|
|
2666
|
+
}
|
|
2667
|
+
this.#notifyKind("question", sessionId, askId, {
|
|
2668
|
+
title: "需要回答",
|
|
2669
|
+
body: questions[0]?.question?.slice(0, 160) || "助手向你提问",
|
|
2670
|
+
});
|
|
2671
|
+
|
|
2672
|
+
const outcome = await this.#waitForAnswer({
|
|
2673
|
+
askId,
|
|
2674
|
+
kind: "question",
|
|
2675
|
+
sessionId,
|
|
2676
|
+
signal: req?.signal,
|
|
2677
|
+
timeoutMs,
|
|
2678
|
+
});
|
|
2679
|
+
if (outcome.settled === "phone") {
|
|
2680
|
+
this.#sendEvent("question.resolved", { askId, source: "phone" });
|
|
2681
|
+
return toAskUserQuestionAnswer(questions, outcome.answers, outcome.freeText);
|
|
2682
|
+
}
|
|
2683
|
+
this.#sendEvent("question.resolved", { askId, source: "timeout" });
|
|
2684
|
+
try {
|
|
2685
|
+
return await next();
|
|
2686
|
+
} catch (e) {
|
|
2687
|
+
this.#log("warn", "next() after question timeout failed", { error: errText(e) });
|
|
2688
|
+
throw e;
|
|
2689
|
+
}
|
|
2690
|
+
}
|
|
2691
|
+
|
|
2692
|
+
/**
|
|
2693
|
+
* 等待手机应答:Promise 竞速 [answer, timeout, abort]。
|
|
2694
|
+
* settle 后从 #pending 移除——迟到的手机回答回 applied:false(§5.5)。
|
|
2695
|
+
* @returns {Promise<{settled:"phone", ...}|{settled:"timeout"}>}
|
|
2696
|
+
*/
|
|
2697
|
+
#waitForAnswer({ askId, kind, sessionId, signal, timeoutMs }) {
|
|
2698
|
+
return new Promise((resolve) => {
|
|
2699
|
+
const entry = {
|
|
2700
|
+
kind,
|
|
2701
|
+
sessionId,
|
|
2702
|
+
resolve,
|
|
2703
|
+
timer: null,
|
|
2704
|
+
signal,
|
|
2705
|
+
abortHandler: null,
|
|
2706
|
+
};
|
|
2707
|
+
const finish = (result) => {
|
|
2708
|
+
if (this.#pending.get(askId) !== entry) return;
|
|
2709
|
+
this.#pending.delete(askId);
|
|
2710
|
+
if (entry.timer !== null) clearTimeout(entry.timer);
|
|
2711
|
+
if (signal && entry.abortHandler) {
|
|
2712
|
+
try {
|
|
2713
|
+
signal.removeEventListener("abort", entry.abortHandler);
|
|
2714
|
+
} catch {
|
|
2715
|
+
/* ignore */
|
|
2716
|
+
}
|
|
2717
|
+
}
|
|
2718
|
+
resolve(result);
|
|
2719
|
+
};
|
|
2720
|
+
// 先登记再武装定时器/abort:finish 的幂等守卫要求 entry 已在 #pending,
|
|
2721
|
+
// 否则「注册时已 abort」的路径会早退且永不 resolve(死锁任务)。
|
|
2722
|
+
this.#pending.set(askId, entry);
|
|
2723
|
+
entry.timer = setTimeout(() => finish({ settled: "timeout" }), timeoutMs);
|
|
2724
|
+
// 不 unref:超时放行是 fail-open 的触发器,必须真正触发。finish 里
|
|
2725
|
+
// 已 clearTimeout,故不会阻止进程退出、也不泄漏。
|
|
2726
|
+
if (signal) {
|
|
2727
|
+
if (signal.aborted) {
|
|
2728
|
+
finish({ settled: "timeout" });
|
|
2729
|
+
return;
|
|
2730
|
+
}
|
|
2731
|
+
entry.abortHandler = () => finish({ settled: "timeout" });
|
|
2732
|
+
try {
|
|
2733
|
+
signal.addEventListener("abort", entry.abortHandler, { once: true });
|
|
2734
|
+
} catch {
|
|
2735
|
+
/* ignore */
|
|
2736
|
+
}
|
|
2737
|
+
}
|
|
2738
|
+
});
|
|
2739
|
+
}
|
|
2740
|
+
|
|
2741
|
+
#settle(entryRef, source, extra) {
|
|
2742
|
+
// entry 由 #pending 持有;这里按 askId 摘除并 resolve
|
|
2743
|
+
for (const [askId, entry] of this.#pending) {
|
|
2744
|
+
if (entry === entryRef) {
|
|
2745
|
+
this.#pending.delete(askId);
|
|
2746
|
+
if (entry.timer !== null) clearTimeout(entry.timer);
|
|
2747
|
+
if (entry.signal && entry.abortHandler) {
|
|
2748
|
+
try {
|
|
2749
|
+
entry.signal.removeEventListener("abort", entry.abortHandler);
|
|
2750
|
+
} catch {
|
|
2751
|
+
/* ignore */
|
|
2752
|
+
}
|
|
2753
|
+
}
|
|
2754
|
+
entry.resolve({ settled: source, ...extra });
|
|
2755
|
+
return true;
|
|
2756
|
+
}
|
|
2757
|
+
}
|
|
2758
|
+
return false;
|
|
2759
|
+
}
|
|
2760
|
+
|
|
2761
|
+
/** 审批参数预览:从会话日志按 callId 倒查 tool/call 的 arguments(截断)。 */
|
|
2762
|
+
#argsPreviewOf(agent, callId) {
|
|
2763
|
+
if (!callId) return "";
|
|
2764
|
+
try {
|
|
2765
|
+
const session = agent?.session;
|
|
2766
|
+
if (!session) return "";
|
|
2767
|
+
const events =
|
|
2768
|
+
typeof session.snapshotEvents === "function"
|
|
2769
|
+
? session.snapshotEvents()
|
|
2770
|
+
: Array.isArray(session.events)
|
|
2771
|
+
? session.events
|
|
2772
|
+
: [];
|
|
2773
|
+
for (let i = events.length - 1; i >= 0; i--) {
|
|
2774
|
+
const e = events[i];
|
|
2775
|
+
if (e && e.type === "tool/call" && e.data && e.data.callId === callId) {
|
|
2776
|
+
const raw = typeof e.data.arguments === "string" ? e.data.arguments : JSON.stringify(e.data.arguments ?? "");
|
|
2777
|
+
return raw.length > 400 ? raw.slice(0, 400) + "…[truncated]" : raw;
|
|
2778
|
+
}
|
|
2779
|
+
}
|
|
2780
|
+
} catch {
|
|
2781
|
+
/* 预览尽力而为,失败给空串 */
|
|
2782
|
+
}
|
|
2783
|
+
return "";
|
|
2784
|
+
}
|
|
2785
|
+
|
|
2786
|
+
// ---- Push(§6,任何异常不打断主流程)---------------------------------------
|
|
2787
|
+
|
|
2788
|
+
#notifyKind(kind, sessionId, askId, { title, body }) {
|
|
2789
|
+
const push = this.#push;
|
|
2790
|
+
if (!push || push.configured !== true) return;
|
|
2791
|
+
if (!this.#pushToken) return;
|
|
2792
|
+
Promise.resolve()
|
|
2793
|
+
.then(() =>
|
|
2794
|
+
push.notify({
|
|
2795
|
+
pushToken: this.#pushToken,
|
|
2796
|
+
title,
|
|
2797
|
+
body,
|
|
2798
|
+
kind,
|
|
2799
|
+
sessionId,
|
|
2800
|
+
askId,
|
|
2801
|
+
}),
|
|
2802
|
+
)
|
|
2803
|
+
.then((r) => {
|
|
2804
|
+
if (r && r.ok === false && r.reason) {
|
|
2805
|
+
this.#log("info", "push not delivered", { reason: r.reason });
|
|
2806
|
+
}
|
|
2807
|
+
})
|
|
2808
|
+
.catch((e) => {
|
|
2809
|
+
this.#log("warn", "push notify threw", { error: errText(e) });
|
|
2810
|
+
});
|
|
2811
|
+
}
|
|
2812
|
+
|
|
2813
|
+
#maybeNotifyTurnEnd(sessionId, errorMessage) {
|
|
2814
|
+
try {
|
|
2815
|
+
if (this.#cfg.push?.notifyTurnEnd !== true) return;
|
|
2816
|
+
if (!this.#push || this.#push.configured !== true) return;
|
|
2817
|
+
if (!this.#pushToken) return;
|
|
2818
|
+
const title = this.#titles.get(sessionId) || "会话 " + sessionId.slice(0, 12);
|
|
2819
|
+
this.#notifyKind("turn-end", sessionId, undefined, {
|
|
2820
|
+
title: errorMessage ? "任务出错" : "任务完成",
|
|
2821
|
+
body: errorMessage ? `${title}:${errorMessage}`.slice(0, 200) : `${title} 已完成`.slice(0, 200),
|
|
2822
|
+
});
|
|
2823
|
+
} catch (e) {
|
|
2824
|
+
this.#log("warn", "turn.end push error", { error: errText(e) });
|
|
2825
|
+
}
|
|
2826
|
+
}
|
|
2827
|
+
}
|
|
2828
|
+
|
|
2829
|
+
/**
|
|
2830
|
+
* 手机 question.answer 的 answers(§5.4:qid -> label | label[])
|
|
2831
|
+
* → Host AskUserQuestionAnswer({answers:[{id, selected, custom?}]})。
|
|
2832
|
+
* freeText 挂到第一个作答项(宿主按 custom 字段消费)。
|
|
2833
|
+
*/
|
|
2834
|
+
export function toAskUserQuestionAnswer(questions, answers, freeText) {
|
|
2835
|
+
const items = [];
|
|
2836
|
+
for (const q of questions) {
|
|
2837
|
+
const v = answers?.[q.id];
|
|
2838
|
+
if (v === undefined) continue;
|
|
2839
|
+
const selected = Array.isArray(v) ? v.map((x) => String(x)) : [String(v)];
|
|
2840
|
+
items.push({ id: q.id, selected });
|
|
2841
|
+
}
|
|
2842
|
+
if (items.length === 0 && typeof freeText === "string" && freeText !== "" && questions.length > 0) {
|
|
2843
|
+
items.push({ id: questions[0].id, selected: [], custom: freeText });
|
|
2844
|
+
} else if (typeof freeText === "string" && freeText !== "" && items.length > 0) {
|
|
2845
|
+
items[0].custom = freeText;
|
|
2846
|
+
}
|
|
2847
|
+
return { answers: items };
|
|
2848
|
+
}
|