@duke-dsh-plugins/dsh-remote-control 1.1.9 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/attachments.mjs +641 -0
- package/lib/host-bridge.mjs +249 -29
- package/market/index.json +10 -0
- package/package.json +1 -1
|
@@ -0,0 +1,641 @@
|
|
|
1
|
+
// lib/attachments.mjs —— 用户提示词的附件(契约 §5.11,v1.2.0)。
|
|
2
|
+
//
|
|
3
|
+
// 手机端输入框与 DSH 桌面端 composer 一样支持图片/文件附件。中继单帧上限
|
|
4
|
+
// 1MiB(密文帧),原图/大文件不能塞进一条 `session.prompt`,所以走**分块上传**:
|
|
5
|
+
//
|
|
6
|
+
// begin {sessionId,kind,name?,mediaType?,bytes} → {uploadId,chunkBytes}
|
|
7
|
+
// chunk {uploadId,index,data} → {received}
|
|
8
|
+
// commit{uploadId} → {attachment}
|
|
9
|
+
// prompt {sessionId,text,uploads:[uploadId…]} → 插件换宿主 receipt 再 prompt
|
|
10
|
+
//
|
|
11
|
+
// 本模块只做**纯状态机 + 校验 + wire 映射**(不碰 ctx、不读盘、不写盘),
|
|
12
|
+
// 便于 scripts/verify-attachments.mjs 直接单测。真正的附件落盘由 host-bridge
|
|
13
|
+
// 调宿主 `ctx.fileUploads.uploadImageStream / uploadStream` 完成(见附录 D):
|
|
14
|
+
// 宿主 receipt 是 prompt 准入时唯一认可的附件凭据(直接塞 attachment ref 会被
|
|
15
|
+
// 宿主拒为 FILE_NOT_STAGED)。
|
|
16
|
+
import { randomBytes } from "node:crypto";
|
|
17
|
+
|
|
18
|
+
/** 附件种类(wire 取值)。 */
|
|
19
|
+
export const ATTACHMENT_KIND_IMAGE = "image";
|
|
20
|
+
export const ATTACHMENT_KIND_FILE = "file";
|
|
21
|
+
|
|
22
|
+
/** 宿主接受的图片媒体类型(dsh-attachment 的 ImageMediaType,§5.11.1)。 */
|
|
23
|
+
export const ATTACHMENT_IMAGE_TYPES = Object.freeze([
|
|
24
|
+
"image/png",
|
|
25
|
+
"image/jpeg",
|
|
26
|
+
"image/webp",
|
|
27
|
+
"image/gif",
|
|
28
|
+
]);
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 契约 §5.11.1 的固定上限(插件侧实现常量;wire 上由 session.capabilities 暴露)。
|
|
32
|
+
* 这些是**手机端单条消息**的保守上限,不是宿主部署上限(宿主另有自己的准入)。
|
|
33
|
+
*/
|
|
34
|
+
export const ATTACHMENT_LIMITS = Object.freeze({
|
|
35
|
+
maxCount: 9,
|
|
36
|
+
maxItemBytes: 20 * 1024 * 1024,
|
|
37
|
+
maxMessageBytes: 40 * 1024 * 1024,
|
|
38
|
+
chunkBytes: 256 * 1024,
|
|
39
|
+
imageMediaTypes: ATTACHMENT_IMAGE_TYPES,
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
/** 未提交上传的存活时间(契约 §5.11.2:begin 后 5 分钟内必须 commit)。 */
|
|
43
|
+
export const UPLOAD_TTL_MS = 5 * 60 * 1000;
|
|
44
|
+
|
|
45
|
+
/** 已提交附件的可用时间(契约 §5.11.2:commit 后 60 分钟内可用于一次 prompt)。 */
|
|
46
|
+
export const STAGED_TTL_MS = 60 * 60 * 1000;
|
|
47
|
+
|
|
48
|
+
/** 同时未提交的上传上限(契约 §5.11.2:第 5 个回 attachment-too-many)。 */
|
|
49
|
+
export const MAX_PENDING_UPLOADS = 4;
|
|
50
|
+
|
|
51
|
+
/** 已消费 uploadId 的墓碑上限(用于区分「用过了」与「没收到过」,避免无限增长)。 */
|
|
52
|
+
const CONSUMED_TOMBSTONE_MAX = 256;
|
|
53
|
+
|
|
54
|
+
/** 附件文件名净化后的最大长度(字符)。 */
|
|
55
|
+
const MAX_NAME_LENGTH = 180;
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 附件处理的稳定错误(host-bridge 直接映射成 result.error.code)。
|
|
59
|
+
* @param {string} code 契约 §5.11.5 的错误码
|
|
60
|
+
* @param {string} message 面向用户的中文原因
|
|
61
|
+
*/
|
|
62
|
+
export class AttachmentWireError extends Error {
|
|
63
|
+
/**
|
|
64
|
+
* @param {string} code
|
|
65
|
+
* @param {string} message
|
|
66
|
+
*/
|
|
67
|
+
constructor(code, message) {
|
|
68
|
+
super(message);
|
|
69
|
+
this.name = "AttachmentWireError";
|
|
70
|
+
this.code = code;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** 契约 §5.11.1 能力目录(插件支持时固定输出;不支持时 host-bridge 省略该字段)。 */
|
|
75
|
+
export function attachmentCapabilities() {
|
|
76
|
+
return {
|
|
77
|
+
supported: true,
|
|
78
|
+
maxCount: ATTACHMENT_LIMITS.maxCount,
|
|
79
|
+
maxItemBytes: ATTACHMENT_LIMITS.maxItemBytes,
|
|
80
|
+
maxMessageBytes: ATTACHMENT_LIMITS.maxMessageBytes,
|
|
81
|
+
chunkBytes: ATTACHMENT_LIMITS.chunkBytes,
|
|
82
|
+
imageMediaTypes: [...ATTACHMENT_IMAGE_TYPES],
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* 是否为宿主接受的图片类型(大小写敏感,wire 规定小写)。
|
|
88
|
+
* @param {unknown} mediaType
|
|
89
|
+
* @returns {boolean}
|
|
90
|
+
*/
|
|
91
|
+
export function isImageMediaType(mediaType) {
|
|
92
|
+
return typeof mediaType === "string" && ATTACHMENT_IMAGE_TYPES.includes(mediaType);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* 净化显示文件名:去路径、去控制字符、限长;空/非法 → 空串(由调用方决定是否拒绝)。
|
|
97
|
+
* 附件服务自己还会再净化一次(它不接受路径),这里只保证不把路径带进 wire/日志。
|
|
98
|
+
* @param {unknown} name
|
|
99
|
+
* @returns {string}
|
|
100
|
+
*/
|
|
101
|
+
export function sanitizeAttachmentName(name) {
|
|
102
|
+
if (typeof name !== "string") return "";
|
|
103
|
+
let out = "";
|
|
104
|
+
for (const ch of name.replace(/\\/g, "/").split("/").pop() ?? "") {
|
|
105
|
+
const code = ch.codePointAt(0) ?? 0;
|
|
106
|
+
if (code < 0x20 || code === 0x7f) continue; // 控制字符
|
|
107
|
+
out += ch;
|
|
108
|
+
if (out.length >= MAX_NAME_LENGTH) break;
|
|
109
|
+
}
|
|
110
|
+
return out.trim();
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* 生成 uploadId(24 位十六进制;只用于插件内存索引,不落盘、不进日志)。
|
|
115
|
+
* @returns {string}
|
|
116
|
+
*/
|
|
117
|
+
export function newUploadId() {
|
|
118
|
+
return `up_${randomBytes(12).toString("hex")}`;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* 校验并解码一个 chunk 的 canonical base64。
|
|
123
|
+
*
|
|
124
|
+
* 契约要求 `data` 是**标准 base64(canonical)**:解码后重编码必须逐字相同
|
|
125
|
+
* (否则同一个字节串有多个合法写法,分块校验会失去确定性)。
|
|
126
|
+
* @param {unknown} data
|
|
127
|
+
* @param {number} maxBytes 单块明文上限(最后一小块可短)
|
|
128
|
+
* @returns {Buffer} 解码后的明文块
|
|
129
|
+
* @throws {AttachmentWireError} 非字符串 / 非 canonical / 空块 / 超长
|
|
130
|
+
*/
|
|
131
|
+
export function decodeChunkData(data, maxBytes = ATTACHMENT_LIMITS.chunkBytes) {
|
|
132
|
+
if (typeof data !== "string") {
|
|
133
|
+
throw new AttachmentWireError("attachment-bad-params", "chunk data 必须是 base64 字符串");
|
|
134
|
+
}
|
|
135
|
+
if (data.length === 0) {
|
|
136
|
+
throw new AttachmentWireError("attachment-chunk-mismatch", "空分块(附件字节数 > 0)");
|
|
137
|
+
}
|
|
138
|
+
const bytes = Buffer.from(data, "base64");
|
|
139
|
+
if (bytes.toString("base64") !== data) {
|
|
140
|
+
throw new AttachmentWireError("attachment-bad-params", "chunk data 必须是标准 base64(canonical)");
|
|
141
|
+
}
|
|
142
|
+
if (bytes.length === 0) {
|
|
143
|
+
throw new AttachmentWireError("attachment-chunk-mismatch", "空分块(附件字节数 > 0)");
|
|
144
|
+
}
|
|
145
|
+
if (bytes.length > maxBytes) {
|
|
146
|
+
throw new AttachmentWireError("attachment-chunk-mismatch", "分块超过 chunkBytes 上限");
|
|
147
|
+
}
|
|
148
|
+
return bytes;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* 校验 `attachment.upload.begin` 的 payload(纯函数)。
|
|
153
|
+
* @param {any} payload 业务信封 payload
|
|
154
|
+
* @param {{maxItemBytes?:number, imageMediaTypes?:readonly string[]}} [limits]
|
|
155
|
+
* @returns {{sessionId:string,kind:string,name:string,mediaType:string,bytes:number}}
|
|
156
|
+
* @throws {AttachmentWireError}
|
|
157
|
+
*/
|
|
158
|
+
export function parseUploadBegin(payload, limits = ATTACHMENT_LIMITS) {
|
|
159
|
+
const p = payload ?? {};
|
|
160
|
+
const sessionId = typeof p.sessionId === "string" ? p.sessionId.trim() : "";
|
|
161
|
+
if (sessionId === "") {
|
|
162
|
+
throw new AttachmentWireError("attachment-bad-params", "sessionId required");
|
|
163
|
+
}
|
|
164
|
+
const kind = p.kind;
|
|
165
|
+
if (kind !== ATTACHMENT_KIND_IMAGE && kind !== ATTACHMENT_KIND_FILE) {
|
|
166
|
+
throw new AttachmentWireError("attachment-bad-params", 'kind must be "image" or "file"');
|
|
167
|
+
}
|
|
168
|
+
const bytes = p.bytes;
|
|
169
|
+
if (!Number.isSafeInteger(bytes) || bytes < 0) {
|
|
170
|
+
throw new AttachmentWireError("attachment-bad-params", "bytes must be a non-negative safe integer");
|
|
171
|
+
}
|
|
172
|
+
const maxItemBytes = Number.isSafeInteger(limits?.maxItemBytes)
|
|
173
|
+
? limits.maxItemBytes
|
|
174
|
+
: ATTACHMENT_LIMITS.maxItemBytes;
|
|
175
|
+
if (bytes > maxItemBytes) {
|
|
176
|
+
throw new AttachmentWireError(
|
|
177
|
+
"attachment-too-large",
|
|
178
|
+
`附件过大(${bytes} 字节,上限 ${maxItemBytes} 字节)`,
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
const name = sanitizeAttachmentName(p.name);
|
|
182
|
+
let mediaType = "";
|
|
183
|
+
if (kind === ATTACHMENT_KIND_IMAGE) {
|
|
184
|
+
const accepted = Array.isArray(limits?.imageMediaTypes)
|
|
185
|
+
? limits.imageMediaTypes
|
|
186
|
+
: ATTACHMENT_IMAGE_TYPES;
|
|
187
|
+
if (typeof p.mediaType !== "string" || !accepted.includes(p.mediaType)) {
|
|
188
|
+
throw new AttachmentWireError(
|
|
189
|
+
"attachment-bad-params",
|
|
190
|
+
`图片 mediaType 必须是 ${accepted.join(" / ")} 之一`,
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
mediaType = p.mediaType;
|
|
194
|
+
if (bytes === 0) {
|
|
195
|
+
throw new AttachmentWireError("attachment-bad-params", "图片附件不能是空文件");
|
|
196
|
+
}
|
|
197
|
+
} else if (name === "") {
|
|
198
|
+
// 文件必须有显示名(宿主用它做存储别名与模型末端的提示行)
|
|
199
|
+
throw new AttachmentWireError("attachment-bad-params", "文件附件必须带 name");
|
|
200
|
+
}
|
|
201
|
+
return { sessionId, kind, name, mediaType, bytes };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* 分块总数(bytes=0 → 0;否则 ceil)。
|
|
206
|
+
* @param {number} bytes
|
|
207
|
+
* @param {number} [chunkBytes]
|
|
208
|
+
* @returns {number}
|
|
209
|
+
*/
|
|
210
|
+
export function chunkCountOf(bytes, chunkBytes = ATTACHMENT_LIMITS.chunkBytes) {
|
|
211
|
+
if (!Number.isSafeInteger(bytes) || bytes <= 0) return 0;
|
|
212
|
+
if (!Number.isSafeInteger(chunkBytes) || chunkBytes <= 0) return 0;
|
|
213
|
+
return Math.ceil(bytes / chunkBytes);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* 一个 uploadId 当前已收字节数(供 `received` 回包 / 校验)。
|
|
218
|
+
* @param {{received:number}} record
|
|
219
|
+
* @returns {number}
|
|
220
|
+
*/
|
|
221
|
+
export function receivedOf(record) {
|
|
222
|
+
return Number.isSafeInteger(record?.received) ? record.received : 0;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* commit 成功后附件 → wire UploadedAttachment(契约 §5.11.2)。
|
|
227
|
+
* @param {{kind:string,name?:string,mediaType?:string,bytes:number,width?:number,height?:number,
|
|
228
|
+
* attachment?:any,requestedName?:string}} record
|
|
229
|
+
* @returns {{kind:string,name?:string,mediaType?:string,bytes:number,width?:number,height?:number}}
|
|
230
|
+
*/
|
|
231
|
+
export function uploadedAttachmentOf(record) {
|
|
232
|
+
const attachment = record?.attachment ?? {};
|
|
233
|
+
const bytes =
|
|
234
|
+
Number.isSafeInteger(attachment.bytes) && attachment.bytes >= 0
|
|
235
|
+
? attachment.bytes
|
|
236
|
+
: Number.isSafeInteger(record?.bytes)
|
|
237
|
+
? record.bytes
|
|
238
|
+
: 0;
|
|
239
|
+
/** @type {{kind:string,name?:string,mediaType?:string,bytes:number,width?:number,height?:number}} */
|
|
240
|
+
const out = { kind: record?.kind === ATTACHMENT_KIND_IMAGE ? ATTACHMENT_KIND_IMAGE : ATTACHMENT_KIND_FILE };
|
|
241
|
+
const name =
|
|
242
|
+
sanitizeAttachmentName(attachment.name) ||
|
|
243
|
+
sanitizeAttachmentName(record?.requestedName) ||
|
|
244
|
+
sanitizeAttachmentName(record?.name);
|
|
245
|
+
if (name !== "") out.name = name;
|
|
246
|
+
if (out.kind === ATTACHMENT_KIND_IMAGE) {
|
|
247
|
+
const mediaType = typeof attachment.mediaType === "string" ? attachment.mediaType : record?.mediaType;
|
|
248
|
+
if (typeof mediaType === "string" && mediaType !== "") out.mediaType = mediaType;
|
|
249
|
+
out.width = Number.isSafeInteger(attachment.width) && attachment.width > 0 ? attachment.width : 0;
|
|
250
|
+
out.height = Number.isSafeInteger(attachment.height) && attachment.height > 0 ? attachment.height : 0;
|
|
251
|
+
}
|
|
252
|
+
out.bytes = bytes;
|
|
253
|
+
return out;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* 校验 prompt 的 `uploads` 列表(纯函数):类型、条数、总字节、去重。
|
|
258
|
+
* 上传记录的可用性(存在/会话匹配/未消费/未过期)由 registry 负责——本函数只守 wire。
|
|
259
|
+
* @param {any} uploads
|
|
260
|
+
* @param {{maxCount?:number, maxMessageBytes?:number}} [limits]
|
|
261
|
+
* @returns {string[]} 去重后的 uploadId 列表(保留首次出现顺序)
|
|
262
|
+
* @throws {AttachmentWireError}
|
|
263
|
+
*/
|
|
264
|
+
export function parseUploadIds(uploads, limits = ATTACHMENT_LIMITS) {
|
|
265
|
+
if (uploads === undefined || uploads === null) return [];
|
|
266
|
+
if (!Array.isArray(uploads)) {
|
|
267
|
+
throw new AttachmentWireError("attachment-bad-params", "uploads must be an array of uploadId");
|
|
268
|
+
}
|
|
269
|
+
const maxCount = Number.isSafeInteger(limits?.maxCount) ? limits.maxCount : ATTACHMENT_LIMITS.maxCount;
|
|
270
|
+
if (uploads.length > maxCount) {
|
|
271
|
+
throw new AttachmentWireError("attachment-too-many", `单条消息最多 ${maxCount} 个附件`);
|
|
272
|
+
}
|
|
273
|
+
const out = [];
|
|
274
|
+
for (const id of uploads) {
|
|
275
|
+
if (typeof id !== "string" || id.trim() === "") {
|
|
276
|
+
throw new AttachmentWireError("attachment-bad-params", "uploads 含非法 uploadId");
|
|
277
|
+
}
|
|
278
|
+
if (!out.includes(id)) out.push(id);
|
|
279
|
+
}
|
|
280
|
+
return out;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* 附件上传登记表(内存):未提交缓冲 + 已提交 staged receipt + 已消费墓碑。
|
|
285
|
+
*
|
|
286
|
+
* 生命周期(契约 §5.11.2):
|
|
287
|
+
* - `receiving`:begin 后收 chunk;5 分钟未 commit 即过期;
|
|
288
|
+
* - `committing`:已进入宿主落盘(期间不再收 chunk);宿主失败可退回 `receiving`;
|
|
289
|
+
* - `staged`:commit 成功,60 分钟内可用于**一次** prompt;
|
|
290
|
+
* - `consumed`:prompt 已被宿主接受(墓碑只用于给出准确错误码)。
|
|
291
|
+
*
|
|
292
|
+
* 线程模型:Node 单线程;方法都是同步的,唯一 await 在 host-bridge 调宿主时。
|
|
293
|
+
*/
|
|
294
|
+
export class UploadRegistry {
|
|
295
|
+
/** @type {Map<string, any>} */
|
|
296
|
+
#receiving = new Map();
|
|
297
|
+
/** @type {Map<string, any>} */
|
|
298
|
+
#staged = new Map();
|
|
299
|
+
/** @type {Map<string, number>} consumed uploadId → 消费时间 */
|
|
300
|
+
#consumed = new Map();
|
|
301
|
+
#now;
|
|
302
|
+
#limits;
|
|
303
|
+
#pendingTtlMs;
|
|
304
|
+
#stagedTtlMs;
|
|
305
|
+
#maxPending;
|
|
306
|
+
#seq = 0;
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* @param {{now?:()=>number, limits?:any, pendingTtlMs?:number, stagedTtlMs?:number,
|
|
310
|
+
* maxPending?:number}} [options]
|
|
311
|
+
*/
|
|
312
|
+
constructor(options = {}) {
|
|
313
|
+
this.#now = typeof options.now === "function" ? options.now : () => Date.now();
|
|
314
|
+
this.#limits = options.limits ?? ATTACHMENT_LIMITS;
|
|
315
|
+
this.#pendingTtlMs = Number.isSafeInteger(options.pendingTtlMs)
|
|
316
|
+
? options.pendingTtlMs
|
|
317
|
+
: UPLOAD_TTL_MS;
|
|
318
|
+
this.#stagedTtlMs = Number.isSafeInteger(options.stagedTtlMs) ? options.stagedTtlMs : STAGED_TTL_MS;
|
|
319
|
+
this.#maxPending = Number.isSafeInteger(options.maxPending) ? options.maxPending : MAX_PENDING_UPLOADS;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** 当前未提交 + 已提交(未消费)的条数(诊断/测试用)。 */
|
|
323
|
+
get size() {
|
|
324
|
+
return this.#receiving.size + this.#staged.size;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* begin:登记一次上传。
|
|
329
|
+
* @param {any} payload
|
|
330
|
+
* @returns {{uploadId:string, chunkBytes:number}}
|
|
331
|
+
*/
|
|
332
|
+
begin(payload) {
|
|
333
|
+
this.prune();
|
|
334
|
+
const parsed = parseUploadBegin(payload, this.#limits);
|
|
335
|
+
if (this.#receiving.size >= this.#maxPending) {
|
|
336
|
+
throw new AttachmentWireError(
|
|
337
|
+
"attachment-too-many",
|
|
338
|
+
`已有 ${this.#receiving.size} 个未完成上传(上限 ${this.#maxPending})`,
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
const uploadId = newUploadId();
|
|
342
|
+
this.#receiving.set(uploadId, {
|
|
343
|
+
uploadId,
|
|
344
|
+
sessionId: parsed.sessionId,
|
|
345
|
+
kind: parsed.kind,
|
|
346
|
+
name: parsed.name,
|
|
347
|
+
mediaType: parsed.mediaType,
|
|
348
|
+
bytes: parsed.bytes,
|
|
349
|
+
received: 0,
|
|
350
|
+
chunks: [],
|
|
351
|
+
state: "receiving",
|
|
352
|
+
beganAt: this.#now(),
|
|
353
|
+
seq: ++this.#seq,
|
|
354
|
+
});
|
|
355
|
+
return { uploadId, chunkBytes: this.#limits.chunkBytes ?? ATTACHMENT_LIMITS.chunkBytes };
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* 收一个分块:index 必须连续、长度不得超过 begin.bytes、每块只发一次。
|
|
360
|
+
* @param {any} payload `{uploadId,index,data}`
|
|
361
|
+
* @returns {{received:number}}
|
|
362
|
+
*/
|
|
363
|
+
chunk(payload) {
|
|
364
|
+
this.prune();
|
|
365
|
+
const p = payload ?? {};
|
|
366
|
+
const uploadId = typeof p.uploadId === "string" ? p.uploadId : "";
|
|
367
|
+
const record = this.#receivingRecord(uploadId);
|
|
368
|
+
if (record.state !== "receiving") {
|
|
369
|
+
throw new AttachmentWireError("attachment-upload-consumed", "该上传正在提交,不能再追加分块");
|
|
370
|
+
}
|
|
371
|
+
if (!Number.isSafeInteger(p.index) || p.index < 0) {
|
|
372
|
+
throw new AttachmentWireError("attachment-bad-params", "index must be a non-negative safe integer");
|
|
373
|
+
}
|
|
374
|
+
if (p.index !== record.chunks.length) {
|
|
375
|
+
throw new AttachmentWireError(
|
|
376
|
+
"attachment-chunk-mismatch",
|
|
377
|
+
`分块序号不连续(期望 ${record.chunks.length},收到 ${p.index})`,
|
|
378
|
+
);
|
|
379
|
+
}
|
|
380
|
+
if (record.received >= record.bytes) {
|
|
381
|
+
throw new AttachmentWireError("attachment-chunk-mismatch", "附件已收满,不能继续追加分块");
|
|
382
|
+
}
|
|
383
|
+
const remaining = record.bytes - record.received;
|
|
384
|
+
const maxChunk = Math.min(
|
|
385
|
+
this.#limits.chunkBytes ?? ATTACHMENT_LIMITS.chunkBytes,
|
|
386
|
+
remaining,
|
|
387
|
+
);
|
|
388
|
+
const bytes = decodeChunkData(p.data, maxChunk);
|
|
389
|
+
record.chunks.push(bytes);
|
|
390
|
+
record.received += bytes.length;
|
|
391
|
+
return { received: record.received };
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* 进入提交:把上传从「收块」切到「落盘」。宿主失败时必须调 `failCommit` 退回。
|
|
396
|
+
* @param {unknown} uploadId
|
|
397
|
+
* @returns {any} 上传记录(含 chunks 与 bytes)
|
|
398
|
+
* @throws {AttachmentWireError} 未知/过期/未收满
|
|
399
|
+
*/
|
|
400
|
+
beginCommit(uploadId) {
|
|
401
|
+
this.prune();
|
|
402
|
+
const record = this.#receivingRecord(uploadId);
|
|
403
|
+
if (record.state !== "receiving") {
|
|
404
|
+
throw new AttachmentWireError("attachment-upload-consumed", "该上传正在提交,请勿重复 commit");
|
|
405
|
+
}
|
|
406
|
+
if (record.received !== record.bytes) {
|
|
407
|
+
throw new AttachmentWireError(
|
|
408
|
+
"attachment-chunk-mismatch",
|
|
409
|
+
`附件未收完(已收 ${record.received}/${record.bytes} 字节)`,
|
|
410
|
+
);
|
|
411
|
+
}
|
|
412
|
+
record.state = "committing";
|
|
413
|
+
return record;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* 提交失败:把记录退回 receiving(保留缓冲,允许客户端重试 commit)。
|
|
418
|
+
* @param {unknown} uploadId
|
|
419
|
+
*/
|
|
420
|
+
failCommit(uploadId) {
|
|
421
|
+
const record = this.#receiving.get(typeof uploadId === "string" ? uploadId : "");
|
|
422
|
+
if (record !== undefined && record.state === "committing") {
|
|
423
|
+
record.state = "receiving";
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* 提交成功:转入 staged(保存宿主 receipt,供后续 prompt 使用)。
|
|
429
|
+
* @param {unknown} uploadId
|
|
430
|
+
* @param {{receiptId:string, attachment:any}} input
|
|
431
|
+
* @returns {any} staged 记录
|
|
432
|
+
*/
|
|
433
|
+
completeCommit(uploadId, input) {
|
|
434
|
+
const id = typeof uploadId === "string" ? uploadId : "";
|
|
435
|
+
const record = this.#receiving.get(id);
|
|
436
|
+
if (record === undefined) {
|
|
437
|
+
throw new AttachmentWireError("attachment-upload-not-found", "上传不存在或已过期");
|
|
438
|
+
}
|
|
439
|
+
const receiptId = typeof input?.receiptId === "string" ? input.receiptId : "";
|
|
440
|
+
if (receiptId === "") {
|
|
441
|
+
// 宿主没给 receipt,这条上传没法用于 prompt —— 不能假装成功
|
|
442
|
+
this.failCommit(id);
|
|
443
|
+
throw new AttachmentWireError("attachment-upload-failed", "宿主未返回附件凭据");
|
|
444
|
+
}
|
|
445
|
+
this.#receiving.delete(id);
|
|
446
|
+
const staged = {
|
|
447
|
+
uploadId: id,
|
|
448
|
+
sessionId: record.sessionId,
|
|
449
|
+
kind: record.kind,
|
|
450
|
+
name: record.name,
|
|
451
|
+
mediaType: record.mediaType,
|
|
452
|
+
bytes: record.bytes,
|
|
453
|
+
receiptId,
|
|
454
|
+
attachment: input?.attachment ?? {},
|
|
455
|
+
state: "staged",
|
|
456
|
+
committedAt: this.#now(),
|
|
457
|
+
seq: record.seq,
|
|
458
|
+
};
|
|
459
|
+
this.#staged.set(id, staged);
|
|
460
|
+
return staged;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* 放弃上传(幂等):只对未提交记录生效;已 staged 的返回 false(宿主附件不可删除)。
|
|
465
|
+
* @param {unknown} uploadId
|
|
466
|
+
* @returns {boolean}
|
|
467
|
+
*/
|
|
468
|
+
abort(uploadId) {
|
|
469
|
+
const id = typeof uploadId === "string" ? uploadId : "";
|
|
470
|
+
const record = this.#receiving.get(id);
|
|
471
|
+
// 正在落盘的附件不能撤(宿主可能已经写入存储);只有还在收块的才能放弃。
|
|
472
|
+
if (record === undefined || record.state !== "receiving") return false;
|
|
473
|
+
this.#receiving.delete(id);
|
|
474
|
+
return true;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* 提示词前解析 uploads:全集校验(会话绑定 / 未消费 / 未过期 / 条数与总字节)。
|
|
479
|
+
* 不在这里标记消费——宿主接受 prompt 后才调 `markConsumed`。
|
|
480
|
+
* @param {string} sessionId
|
|
481
|
+
* @param {unknown} uploadIds
|
|
482
|
+
* @returns {{uploadId:string, receiptId:string, kind:string, bytes:number, seq:number}[]}
|
|
483
|
+
*/
|
|
484
|
+
promptUploads(sessionId, uploadIds) {
|
|
485
|
+
this.prune();
|
|
486
|
+
const ids = parseUploadIds(uploadIds, this.#limits);
|
|
487
|
+
const out = [];
|
|
488
|
+
let total = 0;
|
|
489
|
+
for (const id of ids) {
|
|
490
|
+
if (this.#consumed.has(id)) {
|
|
491
|
+
throw new AttachmentWireError("attachment-upload-consumed", "该附件已用于上一条消息");
|
|
492
|
+
}
|
|
493
|
+
const staged = this.#staged.get(id);
|
|
494
|
+
if (staged === undefined) {
|
|
495
|
+
throw new AttachmentWireError("attachment-upload-not-found", "附件上传记录不存在或已过期");
|
|
496
|
+
}
|
|
497
|
+
if (staged.sessionId !== sessionId) {
|
|
498
|
+
throw new AttachmentWireError("attachment-upload-not-found", "附件不属于该会话");
|
|
499
|
+
}
|
|
500
|
+
total += staged.bytes;
|
|
501
|
+
out.push({
|
|
502
|
+
uploadId: id,
|
|
503
|
+
receiptId: staged.receiptId,
|
|
504
|
+
kind: staged.kind,
|
|
505
|
+
bytes: staged.bytes,
|
|
506
|
+
seq: staged.seq,
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
const maxMessageBytes = Number.isSafeInteger(this.#limits.maxMessageBytes)
|
|
510
|
+
? this.#limits.maxMessageBytes
|
|
511
|
+
: ATTACHMENT_LIMITS.maxMessageBytes;
|
|
512
|
+
if (total > maxMessageBytes) {
|
|
513
|
+
throw new AttachmentWireError(
|
|
514
|
+
"attachment-too-large",
|
|
515
|
+
`附件总大小超限(${total} 字节,上限 ${maxMessageBytes} 字节)`,
|
|
516
|
+
);
|
|
517
|
+
}
|
|
518
|
+
return out;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/**
|
|
522
|
+
* 宿主要求 prompt 成功接受后调用:staged → consumed 墓碑。
|
|
523
|
+
* @param {readonly string[]} uploadIds
|
|
524
|
+
*/
|
|
525
|
+
markConsumed(uploadIds) {
|
|
526
|
+
if (!Array.isArray(uploadIds)) return;
|
|
527
|
+
const now = this.#now();
|
|
528
|
+
for (const id of uploadIds) {
|
|
529
|
+
if (typeof id !== "string" || id === "") continue;
|
|
530
|
+
this.#staged.delete(id);
|
|
531
|
+
this.#consumed.set(id, now);
|
|
532
|
+
}
|
|
533
|
+
// 墓碑裁剪(按插入序淘汰最旧)
|
|
534
|
+
while (this.#consumed.size > CONSUMED_TOMBSTONE_MAX) {
|
|
535
|
+
const oldest = this.#consumed.keys().next();
|
|
536
|
+
if (oldest.done === true) break;
|
|
537
|
+
this.#consumed.delete(oldest.value);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/** 清理过期记录(begin 后 5 分钟 / commit 后 60 分钟)。 */
|
|
542
|
+
prune() {
|
|
543
|
+
const now = this.#now();
|
|
544
|
+
for (const [id, record] of this.#receiving) {
|
|
545
|
+
const beganAt = Number.isSafeInteger(record.beganAt) ? record.beganAt : now;
|
|
546
|
+
if (now - beganAt > this.#pendingTtlMs) this.#receiving.delete(id);
|
|
547
|
+
}
|
|
548
|
+
for (const [id, record] of this.#staged) {
|
|
549
|
+
const committedAt = Number.isSafeInteger(record.committedAt) ? record.committedAt : now;
|
|
550
|
+
if (now - committedAt > this.#stagedTtlMs) this.#staged.delete(id);
|
|
551
|
+
}
|
|
552
|
+
for (const [id, at] of this.#consumed) {
|
|
553
|
+
if (now - at > this.#stagedTtlMs) this.#consumed.delete(id);
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* 取一个未提交记录;不存在/过期 → `attachment-upload-not-found`。
|
|
559
|
+
* @param {unknown} uploadId
|
|
560
|
+
* @returns {any}
|
|
561
|
+
*/
|
|
562
|
+
#receivingRecord(uploadId) {
|
|
563
|
+
const id = typeof uploadId === "string" ? uploadId : "";
|
|
564
|
+
if (id === "") {
|
|
565
|
+
throw new AttachmentWireError("attachment-bad-params", "uploadId required");
|
|
566
|
+
}
|
|
567
|
+
const record = this.#receiving.get(id);
|
|
568
|
+
if (record === undefined) {
|
|
569
|
+
throw new AttachmentWireError("attachment-upload-not-found", "上传不存在或已过期");
|
|
570
|
+
}
|
|
571
|
+
return record;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
// ---------------------------------------------------------------------------
|
|
576
|
+
// 历史消息里的文件块(契约 §5.11.4)
|
|
577
|
+
// ---------------------------------------------------------------------------
|
|
578
|
+
|
|
579
|
+
/**
|
|
580
|
+
* 从 ContentBlock[] 里取文件附件(与 imageBlocksOf 同口径:只认结构,不读字节)。
|
|
581
|
+
*
|
|
582
|
+
* 宿主 `FileBlock = { type:'file', attachment:{ attachmentId, name, bytes } }`;
|
|
583
|
+
* 其他形态(缺 attachment/缺 name)跳过,绝不抛。
|
|
584
|
+
* @param {unknown} content ContentBlock[]
|
|
585
|
+
* @returns {any[]} FileAttachmentRef[]
|
|
586
|
+
*/
|
|
587
|
+
export function fileBlocksOf(content) {
|
|
588
|
+
if (!Array.isArray(content)) return [];
|
|
589
|
+
const out = [];
|
|
590
|
+
for (const block of content) {
|
|
591
|
+
if (!block || typeof block !== "object" || block.type !== "file") continue;
|
|
592
|
+
const attachment = block.attachment;
|
|
593
|
+
if (!attachment || typeof attachment !== "object") continue;
|
|
594
|
+
if (typeof attachment.attachmentId !== "string" || attachment.attachmentId === "") continue;
|
|
595
|
+
if (typeof attachment.name !== "string" || attachment.name === "") continue;
|
|
596
|
+
out.push(attachment);
|
|
597
|
+
}
|
|
598
|
+
return out;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/**
|
|
602
|
+
* FileAttachmentRef → wire `FileRef`(契约 §5.11.4)。
|
|
603
|
+
* `fileId` = 宿主附件 id(内容摘要),手机端只用于去重,不做下载。
|
|
604
|
+
* @param {any} ref
|
|
605
|
+
* @returns {{fileId:string,name:string,bytes:number}|null}
|
|
606
|
+
*/
|
|
607
|
+
export function fileRefMeta(ref) {
|
|
608
|
+
if (!ref || typeof ref !== "object") return null;
|
|
609
|
+
const fileId = typeof ref.attachmentId === "string" ? ref.attachmentId : "";
|
|
610
|
+
const name = sanitizeAttachmentName(ref.name);
|
|
611
|
+
if (fileId === "" || name === "") return null;
|
|
612
|
+
const bytes = Number.isSafeInteger(ref.bytes) && ref.bytes >= 0 ? ref.bytes : 0;
|
|
613
|
+
return { fileId, name, bytes };
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
/**
|
|
617
|
+
* 消息里的文件块 → wire `files[]`(跳过非法项;空数组不产出字段)。
|
|
618
|
+
* @param {unknown} content ContentBlock[]
|
|
619
|
+
* @returns {{fileId:string,name:string,bytes:number}[]}
|
|
620
|
+
*/
|
|
621
|
+
export function fileRefsOfContent(content) {
|
|
622
|
+
const out = [];
|
|
623
|
+
for (const ref of fileBlocksOf(content)) {
|
|
624
|
+
const wire = fileRefMeta(ref);
|
|
625
|
+
if (wire !== null) out.push(wire);
|
|
626
|
+
}
|
|
627
|
+
return out;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* 附件大小的人类可读文本(契约:客户端可以自己格式化;插件不用它渲染,只给日志/测试)。
|
|
632
|
+
* @param {number} bytes
|
|
633
|
+
* @returns {string}
|
|
634
|
+
*/
|
|
635
|
+
export function formatAttachmentBytes(bytes) {
|
|
636
|
+
const n = Number.isSafeInteger(bytes) && bytes >= 0 ? bytes : 0;
|
|
637
|
+
if (n < 1024) return `${n} B`;
|
|
638
|
+
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
|
|
639
|
+
if (n < 1024 * 1024 * 1024) return `${(n / (1024 * 1024)).toFixed(1)} MB`;
|
|
640
|
+
return `${(n / (1024 * 1024 * 1024)).toFixed(1)} GB`;
|
|
641
|
+
}
|
package/lib/host-bridge.mjs
CHANGED
|
@@ -45,6 +45,14 @@ import {
|
|
|
45
45
|
makeThumb,
|
|
46
46
|
mediaTypeOfPath,
|
|
47
47
|
} from "./images.mjs";
|
|
48
|
+
import {
|
|
49
|
+
ATTACHMENT_KIND_IMAGE,
|
|
50
|
+
AttachmentWireError,
|
|
51
|
+
UploadRegistry,
|
|
52
|
+
attachmentCapabilities,
|
|
53
|
+
fileRefsOfContent,
|
|
54
|
+
uploadedAttachmentOf,
|
|
55
|
+
} from "./attachments.mjs";
|
|
48
56
|
|
|
49
57
|
/**
|
|
50
58
|
* present 投递文件的字节上限(超过就不桥接:内存与带宽都不值得)。
|
|
@@ -182,10 +190,12 @@ export function contentText(blocks) {
|
|
|
182
190
|
}
|
|
183
191
|
|
|
184
192
|
/**
|
|
185
|
-
* 会话消息正文文本(契约 §5.10
|
|
193
|
+
* 会话消息正文文本(契约 §5.10 / §5.11.4):**图片与文件块都不占位**。
|
|
186
194
|
*
|
|
187
|
-
* 图片在 ChatMessage.images[]
|
|
188
|
-
*
|
|
195
|
+
* 图片在 ChatMessage.images[] 里单独渲染(客户端画缩略图气泡),
|
|
196
|
+
* 文件在 ChatMessage.files[] 里单独渲染(文件卡片);正文里再写一遍
|
|
197
|
+
* "[图片]"/"[文件]" 会出现重复的假文字。v1.2.0 起 file 块也不再添加占位符
|
|
198
|
+
* (旧客户端会少一行占位文本,属可接受降级)。
|
|
189
199
|
* @param {unknown} blocks ContentBlock[]
|
|
190
200
|
* @returns {string}
|
|
191
201
|
*/
|
|
@@ -196,10 +206,9 @@ export function messageText(blocks) {
|
|
|
196
206
|
if (!block || typeof block !== "object") continue;
|
|
197
207
|
if (block.type === "text" && typeof block.text === "string") {
|
|
198
208
|
text += block.text;
|
|
199
|
-
} else if (block.type === "file") {
|
|
200
|
-
text += "[文件]";
|
|
201
209
|
}
|
|
202
|
-
// image:单独渲染(§5.10
|
|
210
|
+
// image:单独渲染(§5.10);file:单独渲染(§5.11.4);
|
|
211
|
+
// reasoning / tool-call 等:跳过
|
|
203
212
|
}
|
|
204
213
|
return text;
|
|
205
214
|
}
|
|
@@ -208,7 +217,8 @@ export function messageText(blocks) {
|
|
|
208
217
|
* 契约 §5.2 `session.queue`:待执行消息的文本口径。
|
|
209
218
|
*
|
|
210
219
|
* 只取 content 里 `type==='text'` 的块拼接——与正文口径(messageText)刻意不同:
|
|
211
|
-
*
|
|
220
|
+
* 正文会把图片/文件块独立渲染(不占位),而排队列表要的是**用户实际打的字**
|
|
221
|
+
* (附件-only 消息没有文本,不进队列展示;消息本身照常投递)。
|
|
212
222
|
* @param {unknown} content ContentBlock[]
|
|
213
223
|
* @returns {string}
|
|
214
224
|
*/
|
|
@@ -257,6 +267,8 @@ export function reasoningText(blocks) {
|
|
|
257
267
|
* - v1.0.9(§5.10):消息里有 image 块时,ChatMessage 追加 `images: ImageRef[]`
|
|
258
268
|
* (只带元数据,thumb 由上层 attachThumbs 补);**纯图片消息(无正文)也要成条**,
|
|
259
269
|
* 否则手机端永远看不到这张图;
|
|
270
|
+
* - v1.2.0(§5.11.4):消息里有 file 块时,ChatMessage 追加 `files: FileRef[]`
|
|
271
|
+
* (fileId/name/bytes,手机端渲染文件卡片,不下载);**纯文件消息也要成条**;
|
|
260
272
|
* - 没有任何内容的消息跳过(不产生空泡);
|
|
261
273
|
* - 任何不认识的形态返回 [](跳过),绝不抛出。
|
|
262
274
|
* @returns {object[]} ChatMessage[]
|
|
@@ -297,9 +309,12 @@ export function mapHistoryMessages(sessionId, record) {
|
|
|
297
309
|
const text = messageText(content);
|
|
298
310
|
// v1.0.9(§5.10):图片单独成字段,**不带缩略图**(纯函数读不到附件字节)
|
|
299
311
|
const images = imageBlocksOf(content).map((ref) => imageRefMeta(ref));
|
|
300
|
-
|
|
312
|
+
// v1.2.0(§5.11.4):文件块单独成字段(只有名称/大小,不需要读字节)
|
|
313
|
+
const files = fileRefsOfContent(content);
|
|
314
|
+
if (text.trim() !== "" || images.length > 0 || files.length > 0) {
|
|
301
315
|
const message = { id: `${sessionId}:${seq}`, role, text, ts, seq };
|
|
302
316
|
if (images.length > 0) message.images = images;
|
|
317
|
+
if (files.length > 0) message.files = files;
|
|
303
318
|
out.push(message);
|
|
304
319
|
}
|
|
305
320
|
return out;
|
|
@@ -906,6 +921,8 @@ export class HostBridge {
|
|
|
906
921
|
#deliveredThumbs = new Map();
|
|
907
922
|
// v1.1.2(§5.1):运行中的会话(api-session/status 维护)——「繁忙时的发送行为」只在忙时有意义
|
|
908
923
|
#runningSessions = new Set();
|
|
924
|
+
// v1.2.0(§5.11):手机端附件分块上传登记表(内存态;未提交缓冲 + 已提交 receipt)
|
|
925
|
+
#uploads = new UploadRegistry();
|
|
909
926
|
#disposers = [];
|
|
910
927
|
#hostName = "";
|
|
911
928
|
#dshVersion = "";
|
|
@@ -1886,6 +1903,14 @@ export class HostBridge {
|
|
|
1886
1903
|
return await this.#rSessionUnarchive(m);
|
|
1887
1904
|
case "session.prompt":
|
|
1888
1905
|
return await this.#rSessionPrompt(m);
|
|
1906
|
+
case "attachment.upload.begin":
|
|
1907
|
+
return await this.#rAttachmentUploadBegin(m);
|
|
1908
|
+
case "attachment.upload.chunk":
|
|
1909
|
+
return await this.#rAttachmentUploadChunk(m);
|
|
1910
|
+
case "attachment.upload.commit":
|
|
1911
|
+
return await this.#rAttachmentUploadCommit(m);
|
|
1912
|
+
case "attachment.upload.abort":
|
|
1913
|
+
return await this.#rAttachmentUploadAbort(m);
|
|
1889
1914
|
case "session.cancel":
|
|
1890
1915
|
return await this.#rSessionCancel(m);
|
|
1891
1916
|
case "session.rename":
|
|
@@ -2292,6 +2317,11 @@ export class HostBridge {
|
|
|
2292
2317
|
const parentSessionId = typeof p.parentSessionId === "string" ? p.parentSessionId : "";
|
|
2293
2318
|
const childSessionId = typeof p.childSessionId === "string" ? p.childSessionId : "";
|
|
2294
2319
|
const text = typeof p.text === "string" ? p.text : "";
|
|
2320
|
+
// v1.2.0(§5.11.1):附件只对根会话开放;subagent 的输入不接收 uploads(不静默丢)。
|
|
2321
|
+
if (Array.isArray(p.uploads) && p.uploads.length > 0) {
|
|
2322
|
+
this.#reply(m, errorOf(m, "attachment-unsupported", "subagent 不支持附件"));
|
|
2323
|
+
return;
|
|
2324
|
+
}
|
|
2295
2325
|
if (parentSessionId === "" || childSessionId === "" || text === "") {
|
|
2296
2326
|
this.#reply(m, errorOf(m, "bad-params", "parentSessionId/childSessionId/text required"));
|
|
2297
2327
|
return;
|
|
@@ -2475,21 +2505,22 @@ export class HostBridge {
|
|
|
2475
2505
|
const presets = await this.#loadAgentPresets();
|
|
2476
2506
|
const permissions = await this.#loadPermissionPresets();
|
|
2477
2507
|
const models = await this.#loadModelCatalog();
|
|
2478
|
-
|
|
2479
|
-
|
|
2480
|
-
|
|
2481
|
-
|
|
2482
|
-
|
|
2483
|
-
|
|
2484
|
-
|
|
2485
|
-
|
|
2486
|
-
|
|
2487
|
-
|
|
2488
|
-
|
|
2489
|
-
|
|
2490
|
-
|
|
2491
|
-
|
|
2492
|
-
);
|
|
2508
|
+
const capabilities = {
|
|
2509
|
+
presets: presets.presets,
|
|
2510
|
+
permissions: permissions.permissions,
|
|
2511
|
+
defaultPreset: presets.defaultPreset,
|
|
2512
|
+
defaultPermission: permissions.defaultPermission,
|
|
2513
|
+
models: models.models,
|
|
2514
|
+
defaultModelId: models.defaultModelId,
|
|
2515
|
+
archiveSupported: this.#archiveSupported(),
|
|
2516
|
+
// v1.1.2:宿主「繁忙时的发送行为」设置(排队发送/插话发送)。
|
|
2517
|
+
// 客户端**只读不选**——发消息走哪种行为由宿主的设置决定(用户明确要求)。
|
|
2518
|
+
busyEnter: this.#busyEnterMode(),
|
|
2519
|
+
};
|
|
2520
|
+
// v1.2.0(§5.11.1):宿主具备附件服务(attachments + fileUploads)才声明附件能力;
|
|
2521
|
+
// 否则**省略该字段**,客户端隐藏附件入口(旧插件也没有该字段)。
|
|
2522
|
+
if (this.#attachmentHostReady()) capabilities.attachments = attachmentCapabilities();
|
|
2523
|
+
this.#reply(m, resultOf(m, capabilities));
|
|
2493
2524
|
}
|
|
2494
2525
|
|
|
2495
2526
|
/**
|
|
@@ -2919,8 +2950,15 @@ export class HostBridge {
|
|
|
2919
2950
|
const p = m.payload ?? {};
|
|
2920
2951
|
const sessionId = typeof p.sessionId === "string" ? p.sessionId : "";
|
|
2921
2952
|
const text = typeof p.text === "string" ? p.text : "";
|
|
2922
|
-
|
|
2923
|
-
|
|
2953
|
+
const rawUploads = p.uploads;
|
|
2954
|
+
// v1.2.0(§5.11.3):text 与 uploads 至少一项非空——附件可以单独发送。
|
|
2955
|
+
if (sessionId === "") {
|
|
2956
|
+
this.#reply(m, errorOf(m, "bad-params", "sessionId required"));
|
|
2957
|
+
return;
|
|
2958
|
+
}
|
|
2959
|
+
const hasUploads = Array.isArray(rawUploads) && rawUploads.length > 0;
|
|
2960
|
+
if (text.trim() === "" && !hasUploads) {
|
|
2961
|
+
this.#reply(m, errorOf(m, "bad-params", "text or uploads required"));
|
|
2924
2962
|
return;
|
|
2925
2963
|
}
|
|
2926
2964
|
// v1.1.2(契约 §5.1):**投递行为由宿主设置决定**,客户端不参与选择。
|
|
@@ -2929,19 +2967,38 @@ export class HostBridge {
|
|
|
2929
2967
|
// 客户端若仍带 mode(旧客户端),**忽略**它,不报错也不改变行为。
|
|
2930
2968
|
const mode = this.#resolvePromptMode(sessionId);
|
|
2931
2969
|
const requestId = randomUUID();
|
|
2970
|
+
// v1.2.0(§5.11.3):把 uploadId 换成宿主 receipt(图片/文件都走 file receipt
|
|
2971
|
+
// 通道;宿主在 prompt 准入时解成附件块)。未知/过期/跨会话/已消费 → 明确错误。
|
|
2972
|
+
let content;
|
|
2973
|
+
let uploadIds = [];
|
|
2974
|
+
try {
|
|
2975
|
+
const staged = this.#uploads.promptUploads(sessionId, rawUploads);
|
|
2976
|
+
content = [];
|
|
2977
|
+
if (text.trim() !== "") content.push({ type: "text", text });
|
|
2978
|
+
for (const item of staged) content.push({ type: "file", receiptId: item.receiptId });
|
|
2979
|
+
uploadIds = staged.map((item) => item.uploadId);
|
|
2980
|
+
} catch (e) {
|
|
2981
|
+
this.#replyAttachmentError(m, e);
|
|
2982
|
+
return;
|
|
2983
|
+
}
|
|
2932
2984
|
const send = async (delivery) =>
|
|
2933
2985
|
this.#sc().prompt(
|
|
2934
2986
|
{
|
|
2935
2987
|
requestId,
|
|
2936
2988
|
sessionId,
|
|
2937
2989
|
mode: delivery,
|
|
2938
|
-
content
|
|
2990
|
+
content,
|
|
2939
2991
|
},
|
|
2940
2992
|
this.#signal(30_000),
|
|
2941
2993
|
);
|
|
2942
2994
|
try {
|
|
2943
2995
|
const value = await send(mode);
|
|
2944
|
-
|
|
2996
|
+
const accepted = value?.accepted === true;
|
|
2997
|
+
// 宿主已接受 → 这批 receipt 被 bindPrompt 消费;墓碑保证同一 uploadId
|
|
2998
|
+
// 不能被第二条消息复用(重复用自己的附件 → attachment-upload-consumed)。
|
|
2999
|
+
// 未真正接受时不消费,让客户端可以重试。
|
|
3000
|
+
if (accepted) this.#uploads.markConsumed(uploadIds);
|
|
3001
|
+
this.#reply(m, resultOf(m, { accepted, mode }));
|
|
2945
3002
|
} catch (e) {
|
|
2946
3003
|
// 宿主拒绝插话(session/steer-unavailable:当前 turn 不再接受插入)时
|
|
2947
3004
|
// **自动退回排队**——桌面端此时是把 steer 动作置灰,手机不能把用户的消息弄丢。
|
|
@@ -2950,7 +3007,9 @@ export class HostBridge {
|
|
|
2950
3007
|
this.#log("warn", "steer unavailable, falling back to queue", { sessionId });
|
|
2951
3008
|
try {
|
|
2952
3009
|
const value = await send("queue");
|
|
2953
|
-
|
|
3010
|
+
const accepted = value?.accepted === true;
|
|
3011
|
+
if (accepted) this.#uploads.markConsumed(uploadIds);
|
|
3012
|
+
this.#reply(m, resultOf(m, { accepted, mode: "queue" }));
|
|
2954
3013
|
return;
|
|
2955
3014
|
} catch (e2) {
|
|
2956
3015
|
const err2 = hostErrorOf(e2, "prompt-failed");
|
|
@@ -2959,12 +3018,173 @@ export class HostBridge {
|
|
|
2959
3018
|
return;
|
|
2960
3019
|
}
|
|
2961
3020
|
}
|
|
2962
|
-
//
|
|
3021
|
+
// 其余宿主错误**原样**回客户端(不得吞掉)——附件校验失败(如模型不支持
|
|
3022
|
+
// 图片输入、单图超限)也走这里,客户端据此提示;uploadId 仍可重试。
|
|
2963
3023
|
this.#log("warn", "prompt failed", { sessionId, mode, code: err.code });
|
|
2964
3024
|
this.#reply(m, errorOf(m, err.code, err.message));
|
|
2965
3025
|
}
|
|
2966
3026
|
}
|
|
2967
3027
|
|
|
3028
|
+
// ---- v1.2.0(§5.11):附件分块上传 ---------------------------------------
|
|
3029
|
+
|
|
3030
|
+
/** 附件服务的宿主能力判断:两个服务都在才支持(§5.11.1 supported)。 */
|
|
3031
|
+
#attachmentHostReady() {
|
|
3032
|
+
const fileUploads = this.#service("fileUploads");
|
|
3033
|
+
if (!fileUploads) return false;
|
|
3034
|
+
if (typeof fileUploads.uploadImageStream !== "function") return false;
|
|
3035
|
+
if (typeof fileUploads.uploadStream !== "function") return false;
|
|
3036
|
+
return this.#service("attachments") !== null;
|
|
3037
|
+
}
|
|
3038
|
+
|
|
3039
|
+
/** 统一回附件错误(AttachmentWireError 用契约错误码;宿主错误原样透传)。 */
|
|
3040
|
+
#replyAttachmentError(m, e) {
|
|
3041
|
+
if (e instanceof AttachmentWireError) {
|
|
3042
|
+
this.#reply(m, errorOf(m, e.code, e.message));
|
|
3043
|
+
return;
|
|
3044
|
+
}
|
|
3045
|
+
const err = hostErrorOf(e, "attachment-upload-failed");
|
|
3046
|
+
this.#log("warn", "attachment operation failed", { code: err.code });
|
|
3047
|
+
this.#reply(m, errorOf(m, err.code, err.message));
|
|
3048
|
+
}
|
|
3049
|
+
|
|
3050
|
+
async #rAttachmentUploadBegin(m) {
|
|
3051
|
+
if (!this.#attachmentHostReady()) {
|
|
3052
|
+
this.#reply(m, errorOf(m, "attachment-unsupported", "当前宿主未提供附件上传服务"));
|
|
3053
|
+
return;
|
|
3054
|
+
}
|
|
3055
|
+
try {
|
|
3056
|
+
const begun = this.#uploads.begin(m.payload ?? {});
|
|
3057
|
+
this.#reply(m, resultOf(m, begun));
|
|
3058
|
+
} catch (e) {
|
|
3059
|
+
this.#replyAttachmentError(m, e);
|
|
3060
|
+
}
|
|
3061
|
+
}
|
|
3062
|
+
|
|
3063
|
+
async #rAttachmentUploadChunk(m) {
|
|
3064
|
+
try {
|
|
3065
|
+
const p = m.payload ?? {};
|
|
3066
|
+
const result = this.#uploads.chunk(p);
|
|
3067
|
+
this.#reply(m, resultOf(m, result));
|
|
3068
|
+
} catch (e) {
|
|
3069
|
+
this.#replyAttachmentError(m, e);
|
|
3070
|
+
}
|
|
3071
|
+
}
|
|
3072
|
+
|
|
3073
|
+
/**
|
|
3074
|
+
* 提交:把内存缓冲写进宿主附件存储。
|
|
3075
|
+
*
|
|
3076
|
+
* 为什么走 `ctx.fileUploads`(而不是直接 `attachments.saveFile`):
|
|
3077
|
+
* 宿主 prompt 只认 receipt——`resolvePromptFileReceipts()` 会把 content 里的
|
|
3078
|
+
* `{type:'file',receiptId}` 解回 staged 的图片/文件块;直接塞 attachment ref 会被
|
|
3079
|
+
* 拒为 `FILE_NOT_STAGED`(附录 D)。图片与文件都用同一条 receipt 通道(桌面端
|
|
3080
|
+
* composer 的图片上传也是这么做的:图片 receipt 在 prompt 里以 file part 提交)。
|
|
3081
|
+
*/
|
|
3082
|
+
async #rAttachmentUploadCommit(m) {
|
|
3083
|
+
const p = m.payload ?? {};
|
|
3084
|
+
const uploadId = typeof p.uploadId === "string" ? p.uploadId : "";
|
|
3085
|
+
let record;
|
|
3086
|
+
try {
|
|
3087
|
+
record = this.#uploads.beginCommit(uploadId);
|
|
3088
|
+
} catch (e) {
|
|
3089
|
+
this.#replyAttachmentError(m, e);
|
|
3090
|
+
return;
|
|
3091
|
+
}
|
|
3092
|
+
const svc = this.#service("fileUploads");
|
|
3093
|
+
if (!svc) {
|
|
3094
|
+
this.#uploads.failCommit(uploadId);
|
|
3095
|
+
this.#reply(m, errorOf(m, "attachment-unsupported", "当前宿主未提供附件上传服务"));
|
|
3096
|
+
return;
|
|
3097
|
+
}
|
|
3098
|
+
const chunks = record.chunks;
|
|
3099
|
+
const iterate = async function* () {
|
|
3100
|
+
for (const chunk of chunks) yield new Uint8Array(chunk);
|
|
3101
|
+
};
|
|
3102
|
+
// 宿主归一化/落盘可能较慢(sharp 压缩大图),给 120s;**完成后必须清定时器**
|
|
3103
|
+
// ——否则每个 commit 都会留下一个 2 分钟的空定时器(测试进程也被吊住)。
|
|
3104
|
+
const ac = new AbortController();
|
|
3105
|
+
const timer = setTimeout(() => ac.abort(), 120_000);
|
|
3106
|
+
try {
|
|
3107
|
+
let result;
|
|
3108
|
+
if (record.kind === ATTACHMENT_KIND_IMAGE) {
|
|
3109
|
+
result = await svc.uploadImageStream({
|
|
3110
|
+
sessionId: record.sessionId,
|
|
3111
|
+
data: iterate(),
|
|
3112
|
+
mediaType: record.mediaType,
|
|
3113
|
+
...(record.name !== "" ? { name: record.name } : {}),
|
|
3114
|
+
signal: ac.signal,
|
|
3115
|
+
});
|
|
3116
|
+
if (!result || typeof result.receiptId !== "string" || !result.image) {
|
|
3117
|
+
throw new Error("宿主未返回图片附件凭据");
|
|
3118
|
+
}
|
|
3119
|
+
this.#uploads.completeCommit(uploadId, {
|
|
3120
|
+
receiptId: result.receiptId,
|
|
3121
|
+
attachment: result.image,
|
|
3122
|
+
kind: record.kind,
|
|
3123
|
+
mediaType: record.mediaType,
|
|
3124
|
+
requestedName: record.name,
|
|
3125
|
+
bytes: record.bytes,
|
|
3126
|
+
});
|
|
3127
|
+
const attachment = uploadedAttachmentOf({
|
|
3128
|
+
kind: record.kind,
|
|
3129
|
+
mediaType: record.mediaType,
|
|
3130
|
+
requestedName: record.name,
|
|
3131
|
+
bytes: record.bytes,
|
|
3132
|
+
attachment: result.image,
|
|
3133
|
+
});
|
|
3134
|
+
// 日志只打 kind/字节数/尺寸——**绝不**打文件名或字节内容
|
|
3135
|
+
this.#log("info", "attachment committed", {
|
|
3136
|
+
uploadId: uploadId.slice(0, 10),
|
|
3137
|
+
kind: "image",
|
|
3138
|
+
bytes: attachment.bytes,
|
|
3139
|
+
});
|
|
3140
|
+
this.#reply(m, resultOf(m, { uploadId, attachment }));
|
|
3141
|
+
return;
|
|
3142
|
+
}
|
|
3143
|
+
result = await svc.uploadStream({
|
|
3144
|
+
sessionId: record.sessionId,
|
|
3145
|
+
data: iterate(),
|
|
3146
|
+
...(record.name !== "" ? { name: record.name } : {}),
|
|
3147
|
+
signal: ac.signal,
|
|
3148
|
+
});
|
|
3149
|
+
if (!result || typeof result.receiptId !== "string" || !result.file) {
|
|
3150
|
+
throw new Error("宿主未返回文件附件凭据");
|
|
3151
|
+
}
|
|
3152
|
+
this.#uploads.completeCommit(uploadId, {
|
|
3153
|
+
receiptId: result.receiptId,
|
|
3154
|
+
attachment: result.file,
|
|
3155
|
+
kind: record.kind,
|
|
3156
|
+
mediaType: record.mediaType,
|
|
3157
|
+
requestedName: record.name,
|
|
3158
|
+
bytes: record.bytes,
|
|
3159
|
+
});
|
|
3160
|
+
const attachment = uploadedAttachmentOf({
|
|
3161
|
+
kind: record.kind,
|
|
3162
|
+
requestedName: record.name,
|
|
3163
|
+
bytes: record.bytes,
|
|
3164
|
+
attachment: result.file,
|
|
3165
|
+
});
|
|
3166
|
+
this.#log("info", "attachment committed", {
|
|
3167
|
+
uploadId: uploadId.slice(0, 10),
|
|
3168
|
+
kind: "file",
|
|
3169
|
+
bytes: attachment.bytes,
|
|
3170
|
+
});
|
|
3171
|
+
this.#reply(m, resultOf(m, { uploadId, attachment }));
|
|
3172
|
+
} catch (e) {
|
|
3173
|
+
// 宿主失败 → 退回 receiving(缓冲还在),客户端可重试 commit
|
|
3174
|
+
this.#uploads.failCommit(uploadId);
|
|
3175
|
+
this.#replyAttachmentError(m, e);
|
|
3176
|
+
} finally {
|
|
3177
|
+
clearTimeout(timer);
|
|
3178
|
+
}
|
|
3179
|
+
}
|
|
3180
|
+
|
|
3181
|
+
async #rAttachmentUploadAbort(m) {
|
|
3182
|
+
const p = m.payload ?? {};
|
|
3183
|
+
const uploadId = typeof p.uploadId === "string" ? p.uploadId : "";
|
|
3184
|
+
const aborted = uploadId === "" ? false : this.#uploads.abort(uploadId);
|
|
3185
|
+
this.#reply(m, resultOf(m, { aborted }));
|
|
3186
|
+
}
|
|
3187
|
+
|
|
2968
3188
|
async #rSessionCancel(m) {
|
|
2969
3189
|
const p = m.payload ?? {};
|
|
2970
3190
|
const sessionId = typeof p.sessionId === "string" ? p.sessionId : "";
|
package/market/index.json
CHANGED
|
@@ -69,6 +69,16 @@
|
|
|
69
69
|
"sortKeys": {}
|
|
70
70
|
},
|
|
71
71
|
"versions": [
|
|
72
|
+
{
|
|
73
|
+
"version": "1.2.0",
|
|
74
|
+
"publishTimestamp": 1793981953,
|
|
75
|
+
"source": {
|
|
76
|
+
"type": "npm"
|
|
77
|
+
},
|
|
78
|
+
"engines": {
|
|
79
|
+
"dsh": "^0.1.5-rc.3 || ^0.2.0-rc.1 || ^0.2.1-rc.0"
|
|
80
|
+
}
|
|
81
|
+
},
|
|
72
82
|
{
|
|
73
83
|
"version": "1.1.9",
|
|
74
84
|
"publishTimestamp": 1793924339,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@duke-dsh-plugins/dsh-remote-control",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"description": "Remote-control bridge for DeepSeek Harness: pairs a HarmonyOS phone app with the desktop Host over an end-to-end-encrypted public relay (WebSocket). Lets the phone list/create/switch sessions, send prompts, watch streamed replies, cancel turns, and answer approval and ask-user-question requests from anywhere; pushes Huawei Push Kit notifications (gracefully disabled when AGC is unconfigured) for approvals, questions, and turn completion. The pairing QR lives in the DSH settings panel (\"DSH Pocket\"). Fail-open by design: any relay timeout or fault hands the request back to the desktop answerer.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "index.js",
|