@duke-dsh-plugins/dsh-remote-control 1.1.8 → 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.
@@ -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
+ }
@@ -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
- * "[图片]" 会出现重复的假文字。file 块仍保留占位符(文件没有独立渲染通道)。
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),不占位;reasoning / tool-call 等:跳过
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
- * 正文会把 file 块渲染成 "[文件]" 占位符,而排队列表要的是**用户实际打的字**。
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
- if (text.trim() !== "" || images.length > 0) {
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;
@@ -788,6 +803,32 @@ export function mapModelSelection(data) {
788
803
  return parseModelSelection(data);
789
804
  }
790
805
 
806
+ /**
807
+ * 契约 §5.1:会话历史读取地址(宿主 0.2.2+ 的 durable address)。
808
+ *
809
+ * 宿主对**普通会话**与**子代理会话**用两种地址:
810
+ * - 普通会话:{kind:'session', sessionId}
811
+ * - 子代理:{kind:'subagent', parentSessionId, childSessionId, mode:'unknown'}
812
+ * (子代理会话用 kind:'session' 会被宿主拒为 session/agent-busy)
813
+ *
814
+ * mode 固定 'unknown':宿主在 mode==='unknown' 时跳过 mode 比对,
815
+ * 免得我们还得额外读一次子代理目录去确认 one-shot/continuable。
816
+ * @param {string} sessionId
817
+ * @param {string} [parentSessionId] 子代理的父会话 id(普通会话留空)
818
+ * @returns {{kind:string,sessionId?:string,parentSessionId?:string,childSessionId?:string,mode?:string}}
819
+ */
820
+ export function historyAddress(sessionId, parentSessionId = "") {
821
+ if (parentSessionId !== "") {
822
+ return {
823
+ kind: "subagent",
824
+ parentSessionId,
825
+ childSessionId: sessionId,
826
+ mode: "unknown",
827
+ };
828
+ }
829
+ return { kind: "session", sessionId };
830
+ }
831
+
791
832
  /**
792
833
  * 契约 §5.9 归档:宿主错误的「原样」回传。
793
834
  * 优先用宿主的错误码(RemoteError.code,如 "workspace/active-session"),
@@ -880,6 +921,8 @@ export class HostBridge {
880
921
  #deliveredThumbs = new Map();
881
922
  // v1.1.2(§5.1):运行中的会话(api-session/status 维护)——「繁忙时的发送行为」只在忙时有意义
882
923
  #runningSessions = new Set();
924
+ // v1.2.0(§5.11):手机端附件分块上传登记表(内存态;未提交缓冲 + 已提交 receipt)
925
+ #uploads = new UploadRegistry();
883
926
  #disposers = [];
884
927
  #hostName = "";
885
928
  #dshVersion = "";
@@ -1860,6 +1903,14 @@ export class HostBridge {
1860
1903
  return await this.#rSessionUnarchive(m);
1861
1904
  case "session.prompt":
1862
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);
1863
1914
  case "session.cancel":
1864
1915
  return await this.#rSessionCancel(m);
1865
1916
  case "session.rename":
@@ -1973,9 +2024,14 @@ export class HostBridge {
1973
2024
  }
1974
2025
 
1975
2026
  /** 契约 §5.1 session.history:向后翻页的历史消息页(v1.0.4)。
1976
- * throughSeq(宿主实证)必须是日志中真实存在的末尾 seq——直接传
1977
- * MAX_SAFE_INTEGER 会被宿主 bad-request 拒绝(past cursor),-1 只用于空日志;
1978
- * 故先 inspect 冷读拿日志尾 seq 作为切点,再 page 取消息对齐的一页。
2027
+ *
2028
+ * 宿主 API 分代(DSH 0.2.2-rc.1 起换了历史入口):
2029
+ * - 新宿主:sessionController.events({address, throughSeq?, beforeSeq?, maxMessages?})。
2030
+ * **省略 throughSeq 即取当前日志末尾**(宿主自己算 observation.cursor),
2031
+ * 所以不再需要先 inspect() 拿尾 seq——旧宿主那套 inspect()+page() 在新宿主上
2032
+ * 会直接抛 "sc.inspect is not a function",手机端表现为「历史消息加载不了」。
2033
+ * - 旧宿主:只有 inspect()(拿日志尾 seq + subagent 身份)与 page(),保留原路径。
2034
+ *
1979
2035
  * 向前翻页:客户端回传上一页的 oldestSeq 作 beforeSeq(开区间)。 */
1980
2036
  async #rSessionHistory(m) {
1981
2037
  const p = m.payload ?? {};
@@ -1994,34 +2050,7 @@ export class HostBridge {
1994
2050
  const sc = this.#sc();
1995
2051
  // v1.1.1(§5.10.2):交付物图片作为**独立**的历史消息(两条回包路径都要带上)
1996
2052
  const delivered = await this.#deliveredHistoryMessages(sessionId);
1997
- let cursor = -1;
1998
- let address = { kind: "session", sessionId };
1999
- try {
2000
- const inspected = await sc.inspect(sessionId, signal);
2001
- const events = inspected?.events;
2002
- if (Array.isArray(events) && events.length > 0) {
2003
- const lastSeq = Number(events[events.length - 1]?.seq);
2004
- if (Number.isSafeInteger(lastSeq) && lastSeq >= 0) cursor = lastSeq;
2005
- }
2006
- // subagent 会话必须走 durable subagent 地址(宿主校验:kind:'session' 会被拒)
2007
- const header = inspected?.meta;
2008
- const parent = typeof header?.parentSession === "string" ? header.parentSession : "";
2009
- if (header?.origin === "subagent" && parent !== "") {
2010
- address = { kind: "subagent", parentSessionId: parent, childSessionId: sessionId, mode: "unknown" };
2011
- }
2012
- } catch (e) {
2013
- // inspect 失败(会话不存在等)→ 直接把错误回给手机端
2014
- throw e;
2015
- }
2016
- if (cursor < 0) {
2017
- // 空会话(无任何事件):直接回空页,不折腾 page
2018
- // (交付物图片仍要带上——它们不在宿主的会话日志里)
2019
- this.#reply(m, resultOf(m, { messages: delivered, steps: [], hasMore: false, oldestSeq: 0 }));
2020
- return;
2021
- }
2022
- const request = { address, throughSeq: cursor, maxMessages };
2023
- if (beforeSeq !== undefined) request.beforeSeq = beforeSeq;
2024
- const page = await sc.page(request, signal);
2053
+ const page = await this.#readHistoryPage(sc, sessionId, maxMessages, beforeSeq, signal);
2025
2054
  const messages = [];
2026
2055
  let oldestSeq = Number.MAX_SAFE_INTEGER;
2027
2056
  let oldestEventSeq = Number.MAX_SAFE_INTEGER;
@@ -2079,6 +2108,137 @@ export class HostBridge {
2079
2108
  }
2080
2109
  }
2081
2110
 
2111
+ /**
2112
+ * 读一页会话历史(宿主 API 分代适配层)。
2113
+ *
2114
+ * 新宿主(DSH 0.2.2-rc.1+):走 events()。
2115
+ * - **不传 throughSeq**:宿主会自己取当前日志末尾作为切点
2116
+ * (resolveHistoryRequest 允许省略;history() 用 observation.cursor,
2117
+ * 它就是日志最后一条事件的 seq —— 与旧路径 inspect() 算出的 cursor 等价)。
2118
+ * - 向前翻页只传 beforeSeq(开区间),宿主自己与末尾取交集。
2119
+ * 旧宿主(0.2.1 及更早):先 inspect() 冷读拿日志尾 seq(throughSeq 必须是真实
2120
+ * 存在的 seq,传 MAX_SAFE_INTEGER 会被 bad-request 拒为 past cursor),再 page()。
2121
+ *
2122
+ * 版本判据(实测 0.2.1-rc.5 无 events()、有 inspect();0.2.2-rc.1 有 events()、
2123
+ * 无 inspect()):**以 events() 的存在与否分流**,不靠版本号猜。
2124
+ *
2125
+ * @param {any} sc sessionController
2126
+ * @param {string} sessionId
2127
+ * @param {number} maxMessages
2128
+ * @param {number|undefined} beforeSeq
2129
+ * @param {AbortSignal} signal
2130
+ * @returns {Promise<{records:any[],hasMore:boolean}>}
2131
+ */
2132
+ async #readHistoryPage(sc, sessionId, maxMessages, beforeSeq, signal) {
2133
+ if (typeof sc.events === "function") {
2134
+ const address = await this.#historyAddress(sc, sessionId, signal);
2135
+ const request = { address, maxMessages };
2136
+ if (beforeSeq !== undefined) request.beforeSeq = beforeSeq;
2137
+ const page = await sc.events(request, signal);
2138
+ return { records: page?.records ?? [], hasMore: page?.hasMore === true };
2139
+ }
2140
+ // 旧宿主:inspect + page。
2141
+ const inspected = await sc.inspect(sessionId, signal);
2142
+ const events = inspected?.events;
2143
+ let cursor = -1;
2144
+ let address = historyAddress(sessionId);
2145
+ if (Array.isArray(events) && events.length > 0) {
2146
+ const lastSeq = Number(events[events.length - 1]?.seq);
2147
+ if (Number.isSafeInteger(lastSeq) && lastSeq >= 0) cursor = lastSeq;
2148
+ }
2149
+ // subagent 会话必须走 durable subagent 地址(宿主校验:kind:'session' 会被拒)
2150
+ const header = inspected?.meta;
2151
+ const parent = typeof header?.parentSession === "string" ? header.parentSession : "";
2152
+ if (header?.origin === "subagent" && parent !== "") {
2153
+ address = historyAddress(sessionId, parent);
2154
+ }
2155
+ if (cursor < 0) {
2156
+ // 空会话(无任何事件):直接回空页,不折腾 page
2157
+ // (交付物图片仍要带上——它们不在宿主的会话日志里)
2158
+ return { records: [], hasMore: false };
2159
+ }
2160
+ const request = { address, throughSeq: cursor, maxMessages };
2161
+ if (beforeSeq !== undefined) request.beforeSeq = beforeSeq;
2162
+ const page = await sc.page(request, signal);
2163
+ return { records: page?.records ?? [], hasMore: page?.hasMore === true };
2164
+ }
2165
+
2166
+ /**
2167
+ * 解析会话历史的宿主地址(新宿主路径)。
2168
+ *
2169
+ * 子代理会话必须用 durable subagent 地址;它的父会话 id 从**冷读**的
2170
+ * sessionController.list() 里取(list 不激活 Agent)。
2171
+ * list() 拿不到(例如会话已不在可见列表里)→ 退回普通会话地址,
2172
+ * 由宿主自己判定(子代理用 kind:'session' 会被拒为 session/agent-busy,
2173
+ * 错误原样回给手机端,不静默吞掉)。
2174
+ * @param {any} sc sessionController
2175
+ * @param {string} sessionId
2176
+ * @param {AbortSignal} signal
2177
+ * @returns {Promise<{kind:string,sessionId?:string,parentSessionId?:string,childSessionId?:string,mode?:string}>}
2178
+ */
2179
+ async #historyAddress(sc, sessionId, signal) {
2180
+ try {
2181
+ const listed = await sc.list({}, signal);
2182
+ for (const raw of listed?.items ?? []) {
2183
+ if (String(raw?.sessionId ?? "") !== sessionId) continue;
2184
+ const parent = typeof raw?.parentSessionId === "string" ? raw.parentSessionId : "";
2185
+ if (raw?.origin === "subagent" && parent !== "") {
2186
+ return historyAddress(sessionId, parent);
2187
+ }
2188
+ return historyAddress(sessionId);
2189
+ }
2190
+ } catch (e) {
2191
+ this.#log("warn", "history address lookup failed; using plain session address", {
2192
+ sessionId,
2193
+ error: errText(e),
2194
+ });
2195
+ }
2196
+ return historyAddress(sessionId);
2197
+ }
2198
+
2199
+ /**
2200
+ * 冷读判定一个会话是不是子代理(**绝不激活 Agent**)。
2201
+ *
2202
+ * 新宿主没有 inspect() 了 → 用 list() 的 origin/parentSessionId 字段
2203
+ * (宿主 listFields(header) 直接带出这两个字段,与旧宿主 inspect().meta 同源)。
2204
+ * 旧宿主仍走 inspect()(更快,且不必列举全部会话)。
2205
+ *
2206
+ * 用途:权限查询的 live 降级前必须先判身份——子代理绝不能为了显示权限
2207
+ * 而 resolveAgent 激活它(v1.1.7 规则)。
2208
+ * @param {any} sc sessionController
2209
+ * @param {string} sessionId
2210
+ * @param {AbortSignal} signal
2211
+ * @returns {Promise<boolean>}
2212
+ */
2213
+ async #isSubagentSession(sc, sessionId, signal) {
2214
+ try {
2215
+ if (typeof sc.inspect === "function") {
2216
+ const inspected = await sc.inspect(sessionId, signal);
2217
+ const meta = inspected?.meta;
2218
+ return (
2219
+ meta?.origin === "subagent" ||
2220
+ (typeof meta?.parentSession === "string" && meta.parentSession !== "") ||
2221
+ (typeof meta?.parentSessionId === "string" && meta.parentSessionId !== "")
2222
+ );
2223
+ }
2224
+ const listed = await sc.list({}, signal);
2225
+ for (const raw of listed?.items ?? []) {
2226
+ if (String(raw?.sessionId ?? "") !== sessionId) continue;
2227
+ if (raw?.origin === "subagent") return true;
2228
+ return typeof raw?.parentSessionId === "string" && raw.parentSessionId !== "";
2229
+ }
2230
+ return false;
2231
+ } catch (e) {
2232
+ this.#log("warn", "subagent identity cold read unavailable", {
2233
+ sessionId,
2234
+ error: errText(e),
2235
+ });
2236
+ // 判不出来 → 按“不是子代理”处理(宿主对普通会话的权限查询是安全的);
2237
+ // 真子代理会走 resolveAgent 路径,但那是宿主的既有行为,不是我们引入的。
2238
+ return false;
2239
+ }
2240
+ }
2241
+
2082
2242
  /** 契约 §5.1 session.subagents(v1.0.5):父会话直接子代理目录。
2083
2243
  * 数据组合:父会话 subagentCatalog 持久投影(mode/label/createdAt/顺序,
2084
2244
  * 经 sessionController.projections 冷读,无 Agent 激活)+ list 全量行
@@ -2157,6 +2317,11 @@ export class HostBridge {
2157
2317
  const parentSessionId = typeof p.parentSessionId === "string" ? p.parentSessionId : "";
2158
2318
  const childSessionId = typeof p.childSessionId === "string" ? p.childSessionId : "";
2159
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
+ }
2160
2325
  if (parentSessionId === "" || childSessionId === "" || text === "") {
2161
2326
  this.#reply(m, errorOf(m, "bad-params", "parentSessionId/childSessionId/text required"));
2162
2327
  return;
@@ -2340,21 +2505,22 @@ export class HostBridge {
2340
2505
  const presets = await this.#loadAgentPresets();
2341
2506
  const permissions = await this.#loadPermissionPresets();
2342
2507
  const models = await this.#loadModelCatalog();
2343
- this.#reply(
2344
- m,
2345
- resultOf(m, {
2346
- presets: presets.presets,
2347
- permissions: permissions.permissions,
2348
- defaultPreset: presets.defaultPreset,
2349
- defaultPermission: permissions.defaultPermission,
2350
- models: models.models,
2351
- defaultModelId: models.defaultModelId,
2352
- archiveSupported: this.#archiveSupported(),
2353
- // v1.1.2:宿主「繁忙时的发送行为」设置(排队发送/插话发送)。
2354
- // 客户端**只读不选**——发消息走哪种行为由宿主的设置决定(用户明确要求)。
2355
- busyEnter: this.#busyEnterMode(),
2356
- }),
2357
- );
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));
2358
2524
  }
2359
2525
 
2360
2526
  /**
@@ -2611,24 +2777,13 @@ export class HostBridge {
2611
2777
  }
2612
2778
 
2613
2779
  // 旧宿主没有 permissions 投影时,live Session 的 current() 仍是有效值权威来源。
2614
- // 但 subagent 查询绝不能为了兜底而激活 Agent:先用 inspect 冷读身份,命中即只回内存态。
2780
+ // 但 subagent 查询绝不能为了兜底而激活 Agent:先冷读身份,命中即只回内存态。
2781
+ // 新宿主(0.2.2-rc.1+)没有 inspect() 了 → 冷读改走 list() 的 origin/parentSessionId
2782
+ // (同样不激活 Agent),否则会误把子代理 resolveAgent 起来(违反 v1.1.7)。
2615
2783
  try {
2616
2784
  const svc = this.#service("permissionPresets");
2617
2785
  const sc = this.#sc();
2618
- let coldSubagent = false;
2619
- if (typeof sc.inspect === "function") {
2620
- try {
2621
- const inspected = await sc.inspect(sessionId, this.#signal(10_000));
2622
- const meta = inspected?.meta;
2623
- coldSubagent = meta?.origin === "subagent" ||
2624
- (typeof meta?.parentSessionId === "string" && meta.parentSessionId !== "");
2625
- } catch (e) {
2626
- this.#log("warn", "permission subagent identity inspect unavailable", {
2627
- sessionId,
2628
- error: errText(e),
2629
- });
2630
- }
2631
- }
2786
+ const coldSubagent = await this.#isSubagentSession(sc, sessionId, this.#signal(10_000));
2632
2787
  if (!coldSubagent && svc && typeof svc.current === "function" && typeof sc.resolveAgent === "function") {
2633
2788
  const agentRes = await sc.resolveAgent(sessionId);
2634
2789
  const session = agentRes?.agent?.session ?? agentRes?.session ?? null;
@@ -2795,8 +2950,15 @@ export class HostBridge {
2795
2950
  const p = m.payload ?? {};
2796
2951
  const sessionId = typeof p.sessionId === "string" ? p.sessionId : "";
2797
2952
  const text = typeof p.text === "string" ? p.text : "";
2798
- if (sessionId === "" || text.trim() === "") {
2799
- this.#reply(m, errorOf(m, "bad-params", "sessionId and non-empty text required"));
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"));
2800
2962
  return;
2801
2963
  }
2802
2964
  // v1.1.2(契约 §5.1):**投递行为由宿主设置决定**,客户端不参与选择。
@@ -2805,19 +2967,38 @@ export class HostBridge {
2805
2967
  // 客户端若仍带 mode(旧客户端),**忽略**它,不报错也不改变行为。
2806
2968
  const mode = this.#resolvePromptMode(sessionId);
2807
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
+ }
2808
2984
  const send = async (delivery) =>
2809
2985
  this.#sc().prompt(
2810
2986
  {
2811
2987
  requestId,
2812
2988
  sessionId,
2813
2989
  mode: delivery,
2814
- content: [{ type: "text", text }],
2990
+ content,
2815
2991
  },
2816
2992
  this.#signal(30_000),
2817
2993
  );
2818
2994
  try {
2819
2995
  const value = await send(mode);
2820
- this.#reply(m, resultOf(m, { accepted: value?.accepted === true, mode }));
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 }));
2821
3002
  } catch (e) {
2822
3003
  // 宿主拒绝插话(session/steer-unavailable:当前 turn 不再接受插入)时
2823
3004
  // **自动退回排队**——桌面端此时是把 steer 动作置灰,手机不能把用户的消息弄丢。
@@ -2826,7 +3007,9 @@ export class HostBridge {
2826
3007
  this.#log("warn", "steer unavailable, falling back to queue", { sessionId });
2827
3008
  try {
2828
3009
  const value = await send("queue");
2829
- this.#reply(m, resultOf(m, { accepted: value?.accepted === true, mode: "queue" }));
3010
+ const accepted = value?.accepted === true;
3011
+ if (accepted) this.#uploads.markConsumed(uploadIds);
3012
+ this.#reply(m, resultOf(m, { accepted, mode: "queue" }));
2830
3013
  return;
2831
3014
  } catch (e2) {
2832
3015
  const err2 = hostErrorOf(e2, "prompt-failed");
@@ -2835,12 +3018,173 @@ export class HostBridge {
2835
3018
  return;
2836
3019
  }
2837
3020
  }
2838
- // 其余宿主错误**原样**回客户端(不得吞掉)
3021
+ // 其余宿主错误**原样**回客户端(不得吞掉)——附件校验失败(如模型不支持
3022
+ // 图片输入、单图超限)也走这里,客户端据此提示;uploadId 仍可重试。
2839
3023
  this.#log("warn", "prompt failed", { sessionId, mode, code: err.code });
2840
3024
  this.#reply(m, errorOf(m, err.code, err.message));
2841
3025
  }
2842
3026
  }
2843
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
+
2844
3188
  async #rSessionCancel(m) {
2845
3189
  const p = m.payload ?? {};
2846
3190
  const sessionId = typeof p.sessionId === "string" ? p.sessionId : "";
package/market/index.json CHANGED
@@ -69,6 +69,26 @@
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
+ },
82
+ {
83
+ "version": "1.1.9",
84
+ "publishTimestamp": 1793924339,
85
+ "source": {
86
+ "type": "npm"
87
+ },
88
+ "engines": {
89
+ "dsh": "^0.1.5-rc.3 || ^0.2.0-rc.1 || ^0.2.1-rc.0"
90
+ }
91
+ },
72
92
  {
73
93
  "version": "1.1.8",
74
94
  "publishTimestamp": 1793807705,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@duke-dsh-plugins/dsh-remote-control",
3
- "version": "1.1.8",
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",