agent-bridge-service 0.2.2 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +112 -140
  2. package/README.md +508 -35
  3. package/README.zh-CN.md +443 -33
  4. package/assets/agent-icons/agy.svg +27 -0
  5. package/dist/adapters/acp-auth.js +51 -0
  6. package/dist/adapters/acp-codebuddy.js +507 -0
  7. package/dist/adapters/agent-adapters.js +466 -46
  8. package/dist/adapters/claude-stream.js +159 -0
  9. package/dist/adapters/codex-app-server.js +310 -0
  10. package/dist/adapters/host-env.js +48 -0
  11. package/dist/adapters/mcp-elicitation.js +148 -0
  12. package/dist/adapters/mcp-host.js +70 -0
  13. package/dist/adapters/step-parsers.js +583 -0
  14. package/dist/app/bootstrap.js +163 -74
  15. package/dist/app/claude-resident.js +204 -0
  16. package/dist/app/conversation.js +639 -0
  17. package/dist/app/service-gate.js +1 -1
  18. package/dist/app/session.js +425 -14
  19. package/dist/app/task-dispatch.js +883 -7
  20. package/dist/app/task-registry.js +168 -0
  21. package/dist/cli/dispatch.js +4 -0
  22. package/dist/cli/flags.js +11 -0
  23. package/dist/cli/help.js +25 -7
  24. package/dist/cli/panel.js +334 -0
  25. package/dist/cli/render.js +2 -0
  26. package/dist/commands/approvals.js +80 -0
  27. package/dist/commands/connect.js +122 -4
  28. package/dist/commands/daemon-service.js +81 -0
  29. package/dist/commands/daemon.js +269 -6
  30. package/dist/commands/logout.js +13 -10
  31. package/dist/commands/serve.js +98 -12
  32. package/dist/commands/sessions.js +106 -0
  33. package/dist/core/ansi.js +5 -0
  34. package/dist/core/artifact-extract.js +158 -0
  35. package/dist/core/artifact-transfer.js +583 -0
  36. package/dist/core/device-identity.js +22 -0
  37. package/dist/core/emitter.js +50 -8
  38. package/dist/core/errors.js +43 -0
  39. package/dist/core/form-schema.js +72 -0
  40. package/dist/core/interaction-broker.js +440 -0
  41. package/dist/core/interaction-url.js +63 -0
  42. package/dist/core/partial-messages.js +99 -0
  43. package/dist/core/permission-ledger.js +146 -0
  44. package/dist/core/permission-policy.js +88 -0
  45. package/dist/core/port-fallback.js +22 -0
  46. package/dist/core/redact.js +13 -0
  47. package/dist/core/scan.js +12 -7
  48. package/dist/core/session-store.js +1632 -0
  49. package/dist/core/task-supervisor.js +955 -30
  50. package/dist/infra/atomic-file.js +111 -0
  51. package/dist/infra/audit.js +7 -0
  52. package/dist/infra/auth.js +167 -42
  53. package/dist/infra/config.js +511 -72
  54. package/dist/infra/device-identity-store.js +87 -0
  55. package/dist/infra/jwt.js +149 -0
  56. package/dist/infra/profile-lock.js +295 -0
  57. package/dist/infra/proxy-env.js +60 -0
  58. package/dist/infra/service-token.js +25 -4
  59. package/dist/protocol.js +298 -2
  60. package/dist/transport/a2a-mapping.js +206 -0
  61. package/dist/transport/acp-gateway-mapping.js +186 -0
  62. package/dist/transport/bridge-client.js +31 -22
  63. package/dist/transport/control-plane-page.js +820 -0
  64. package/dist/transport/control-plane-sessions-page.js +90 -0
  65. package/dist/transport/control-plane.js +923 -71
  66. package/dist/transport/gateway.js +1005 -0
  67. package/dist/transport/office-preview.js +154 -0
  68. package/package.json +6 -3
  69. package/assets/agent-icons/gemini.svg +0 -1
@@ -0,0 +1,583 @@
1
+ /**
2
+ * Inbound artifact upload (1.0, first slice).
3
+ *
4
+ * Flow: start → ready → chunk/ack … → complete → task_artifact + result.
5
+ * Contents go to a tenant-partitioned content-addressed store; SQLite stores metadata only.
6
+ */
7
+ import { createHash, randomUUID } from 'node:crypto';
8
+ import { closeSync, mkdirSync, openSync, readSync, renameSync, rmSync, statSync, writeSync, } from 'node:fs';
9
+ import { dirname, join } from 'node:path';
10
+ const DEFAULT_CHUNK_SIZE = 256 * 1024;
11
+ const MAX_CHUNK_SIZE = 1024 * 1024;
12
+ export class ArtifactTransferError extends Error {
13
+ code;
14
+ constructor(code, message) {
15
+ super(message);
16
+ this.code = code;
17
+ this.name = 'ArtifactTransferError';
18
+ }
19
+ }
20
+ export class ArtifactTransferManager {
21
+ deps;
22
+ transfers = new Map();
23
+ byOperation = new Map();
24
+ downloads = new Map();
25
+ root;
26
+ constructor(deps) {
27
+ this.deps = deps;
28
+ this.root = deps.rootDir;
29
+ }
30
+ tenant() {
31
+ return this.deps.tenantId ?? 'default';
32
+ }
33
+ sha256Bytes(data) {
34
+ return createHash('sha256').update(data).digest('hex');
35
+ }
36
+ sha256File(path) {
37
+ const fd = openSync(path, 'r');
38
+ const hash = createHash('sha256');
39
+ const buffer = Buffer.allocUnsafe(MAX_CHUNK_SIZE);
40
+ try {
41
+ while (true) {
42
+ const bytesRead = readSync(fd, buffer, 0, buffer.length, null);
43
+ if (bytesRead === 0)
44
+ break;
45
+ hash.update(buffer.subarray(0, bytesRead));
46
+ }
47
+ }
48
+ finally {
49
+ closeSync(fd);
50
+ }
51
+ return hash.digest('hex');
52
+ }
53
+ readRange(fd, length, offset) {
54
+ const bytes = Buffer.alloc(length);
55
+ let total = 0;
56
+ while (total < length) {
57
+ const read = readSync(fd, bytes, total, length - total, offset + total);
58
+ if (read === 0)
59
+ break;
60
+ total += read;
61
+ }
62
+ return { bytes, bytesRead: total };
63
+ }
64
+ closeDownload(transfer) {
65
+ if (transfer.fd === undefined)
66
+ return;
67
+ const fd = transfer.fd;
68
+ transfer.fd = undefined;
69
+ closeSync(fd);
70
+ }
71
+ startUpload(input) {
72
+ const key = `${input.sessionId}:${input.operationId}`;
73
+ const existingId = this.byOperation.get(key);
74
+ if (existingId) {
75
+ const existing = this.transfers.get(existingId);
76
+ if (existing) {
77
+ return {
78
+ transferId: existing.transferId,
79
+ artifactId: existing.artifactId,
80
+ nextOffset: existing.nextOffset,
81
+ chunkSize: existing.chunkSize,
82
+ };
83
+ }
84
+ }
85
+ const persisted = this.deps.store.getTransferByOperation(input.sessionId, input.operationId, this.tenant());
86
+ if (persisted?.state === 'committed') {
87
+ return {
88
+ transferId: persisted.transferId,
89
+ artifactId: persisted.artifactId,
90
+ nextOffset: persisted.nextOffset,
91
+ chunkSize: persisted.chunkSize,
92
+ };
93
+ }
94
+ if (persisted?.state === 'aborted') {
95
+ throw new ArtifactTransferError('transfer_aborted', '该 operationId 的传输已中止');
96
+ }
97
+ if (persisted?.state === 'uploading' && persisted.tempPath) {
98
+ const restored = {
99
+ transferId: persisted.transferId,
100
+ operationId: persisted.operationId,
101
+ sessionId: persisted.sessionId,
102
+ artifactId: persisted.artifactId,
103
+ name: persisted.name,
104
+ mimeType: persisted.mimeType,
105
+ size: persisted.size,
106
+ sha256: persisted.sha256,
107
+ chunkSize: persisted.chunkSize,
108
+ nextOffset: persisted.nextOffset,
109
+ tempPath: persisted.tempPath,
110
+ };
111
+ this.transfers.set(restored.transferId, restored);
112
+ this.byOperation.set(key, restored.transferId);
113
+ return {
114
+ transferId: restored.transferId,
115
+ artifactId: restored.artifactId,
116
+ nextOffset: restored.nextOffset,
117
+ chunkSize: restored.chunkSize,
118
+ };
119
+ }
120
+ if (!this.deps.store.getSession(input.sessionId)) {
121
+ throw new ArtifactTransferError('session_not_found', `会话不存在:${input.sessionId}`);
122
+ }
123
+ const chunkSize = Math.min(MAX_CHUNK_SIZE, Math.max(1, Math.floor(input.chunkSize ?? DEFAULT_CHUNK_SIZE)));
124
+ const transferId = `tr_${randomUUID().replace(/-/g, '').slice(0, 20)}`;
125
+ const artifactId = `art_${randomUUID().replace(/-/g, '').slice(0, 20)}`;
126
+ const tempDir = join(this.root, '.tmp');
127
+ mkdirSync(tempDir, { recursive: true });
128
+ const tempPath = join(tempDir, transferId);
129
+ closeSync(openSync(tempPath, 'w'));
130
+ const transfer = {
131
+ transferId,
132
+ operationId: input.operationId,
133
+ sessionId: input.sessionId,
134
+ artifactId,
135
+ name: input.name,
136
+ mimeType: input.mimeType,
137
+ size: input.size,
138
+ sha256: input.sha256.toLowerCase(),
139
+ chunkSize,
140
+ nextOffset: 0,
141
+ tempPath,
142
+ };
143
+ this.transfers.set(transferId, transfer);
144
+ this.byOperation.set(key, transferId);
145
+ this.deps.store.saveTransfer({
146
+ tenantId: this.tenant(),
147
+ transferId,
148
+ sessionId: input.sessionId,
149
+ operationId: input.operationId,
150
+ artifactId,
151
+ direction: 'upload',
152
+ name: input.name,
153
+ mimeType: input.mimeType,
154
+ size: input.size,
155
+ sha256: transfer.sha256,
156
+ chunkSize,
157
+ nextOffset: 0,
158
+ tempPath,
159
+ state: 'uploading',
160
+ });
161
+ return { transferId, artifactId, nextOffset: 0, chunkSize };
162
+ }
163
+ writeChunk(input) {
164
+ let transfer = this.transfers.get(input.transferId);
165
+ if (!transfer) {
166
+ const persisted = this.deps.store.getTransfer(input.transferId, this.tenant());
167
+ if (persisted?.state === 'uploading' &&
168
+ persisted.tempPath &&
169
+ statSync(persisted.tempPath, { throwIfNoEntry: false })) {
170
+ transfer = {
171
+ transferId: persisted.transferId,
172
+ operationId: persisted.operationId,
173
+ sessionId: persisted.sessionId,
174
+ artifactId: persisted.artifactId,
175
+ name: persisted.name,
176
+ mimeType: persisted.mimeType,
177
+ size: persisted.size,
178
+ sha256: persisted.sha256,
179
+ chunkSize: persisted.chunkSize,
180
+ nextOffset: persisted.nextOffset,
181
+ tempPath: persisted.tempPath,
182
+ };
183
+ this.transfers.set(transfer.transferId, transfer);
184
+ this.byOperation.set(`${transfer.sessionId}:${transfer.operationId}`, transfer.transferId);
185
+ }
186
+ }
187
+ if (!transfer)
188
+ throw new ArtifactTransferError('transfer_not_found', '传输不存在或已结束');
189
+ if (!Number.isSafeInteger(input.offset) || input.offset < 0) {
190
+ throw new ArtifactTransferError('invalid_offset', 'chunk offset 必须是非负安全整数');
191
+ }
192
+ if (!/^[0-9a-fA-F]{64}$/.test(input.chunkSha256)) {
193
+ throw new ArtifactTransferError('invalid_hash', 'chunk SHA-256 必须是 64 位十六进制字符串');
194
+ }
195
+ const maxChunkSize = Math.min(transfer.chunkSize, MAX_CHUNK_SIZE);
196
+ if (input.data.length > 4 * Math.ceil(maxChunkSize / 3)) {
197
+ throw new ArtifactTransferError('chunk_too_large', 'chunk 超过协商大小');
198
+ }
199
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(input.data)) {
200
+ throw new ArtifactTransferError('invalid_base64', 'chunk data 必须是规范 base64');
201
+ }
202
+ const bytes = Buffer.from(input.data, 'base64');
203
+ if (bytes.toString('base64') !== input.data) {
204
+ throw new ArtifactTransferError('invalid_base64', 'chunk data 必须是规范 base64');
205
+ }
206
+ if (bytes.length > maxChunkSize) {
207
+ throw new ArtifactTransferError('chunk_too_large', 'chunk 超过协商大小');
208
+ }
209
+ if (this.sha256Bytes(bytes) !== input.chunkSha256.toLowerCase()) {
210
+ throw new ArtifactTransferError('chunk_hash_mismatch', 'chunk SHA-256 不匹配');
211
+ }
212
+ if (input.offset < transfer.nextOffset) {
213
+ if (bytes.length > transfer.nextOffset - input.offset) {
214
+ throw new ArtifactTransferError('conflict', '重放 chunk 与已确认内容不一致');
215
+ }
216
+ const fd = openSync(transfer.tempPath, 'r');
217
+ let persisted;
218
+ try {
219
+ persisted = this.readRange(fd, bytes.length, input.offset);
220
+ }
221
+ finally {
222
+ closeSync(fd);
223
+ }
224
+ if (persisted.bytesRead !== bytes.length || !persisted.bytes.equals(bytes)) {
225
+ throw new ArtifactTransferError('conflict', '重放 chunk 与已确认内容不一致');
226
+ }
227
+ return { nextOffset: transfer.nextOffset };
228
+ }
229
+ if (input.offset > transfer.nextOffset) {
230
+ throw new ArtifactTransferError('out_of_order', `chunk offset ${input.offset} != expected ${transfer.nextOffset}`);
231
+ }
232
+ if (input.offset > transfer.size || bytes.length > transfer.size - input.offset) {
233
+ throw new ArtifactTransferError('size_exceeded', 'chunk 超出声明的文件大小');
234
+ }
235
+ const fd = openSync(transfer.tempPath, 'r+');
236
+ try {
237
+ writeSync(fd, bytes, 0, bytes.length, transfer.nextOffset);
238
+ }
239
+ finally {
240
+ closeSync(fd);
241
+ }
242
+ const nextOffset = transfer.nextOffset + bytes.length;
243
+ this.deps.store.updateTransferOffset(transfer.transferId, nextOffset, this.tenant());
244
+ transfer.nextOffset = nextOffset;
245
+ return { nextOffset };
246
+ }
247
+ transferStatus(transferId) {
248
+ const transfer = this.deps.store.getTransfer(transferId, this.tenant());
249
+ if (!transfer)
250
+ throw new ArtifactTransferError('transfer_not_found', '传输不存在');
251
+ return {
252
+ transferId: transfer.transferId,
253
+ direction: transfer.direction,
254
+ state: transfer.state,
255
+ nextOffset: transfer.nextOffset,
256
+ chunkSize: transfer.chunkSize,
257
+ artifactId: transfer.artifactId,
258
+ };
259
+ }
260
+ abortTransfer(transferId, reason) {
261
+ const persisted = this.deps.store.getTransfer(transferId, this.tenant());
262
+ if (!persisted || persisted.state !== 'uploading') {
263
+ if (persisted?.state === 'aborted')
264
+ return this.transferStatus(transferId);
265
+ throw new ArtifactTransferError('transfer_not_found', '传输不存在或已结束');
266
+ }
267
+ if (persisted.direction === 'upload') {
268
+ if (persisted.tempPath)
269
+ rmSync(persisted.tempPath, { force: true });
270
+ this.transfers.delete(transferId);
271
+ this.byOperation.delete(`${persisted.sessionId}:${persisted.operationId}`);
272
+ }
273
+ else {
274
+ const active = this.downloads.get(transferId);
275
+ if (active)
276
+ this.closeDownload(active);
277
+ this.downloads.delete(transferId);
278
+ }
279
+ this.deps.store.saveTransfer({ ...persisted, state: 'aborted' });
280
+ const status = this.transferStatus(transferId);
281
+ this.deps.emit({
282
+ type: 'artifact_transfer_status',
283
+ ...status,
284
+ reason,
285
+ });
286
+ return status;
287
+ }
288
+ /**
289
+ * 回收超时未完成的上传:只删临时文件与 transfer 记录,已提交 artifact 不受影响。
290
+ */
291
+ cleanupStaleTransfers(olderThanMs = 24 * 60 * 60 * 1000, now = Date.now()) {
292
+ const cutoff = now - olderThanMs;
293
+ let removed = 0;
294
+ for (const transfer of this.deps.store.listTransfers('uploading', this.tenant())) {
295
+ if (Date.parse(transfer.updatedAt) > cutoff)
296
+ continue;
297
+ if (transfer.tempPath)
298
+ rmSync(transfer.tempPath, { force: true });
299
+ this.deps.store.deleteTransfer(transfer.transferId, this.tenant());
300
+ this.transfers.delete(transfer.transferId);
301
+ this.byOperation.delete(`${transfer.sessionId}:${transfer.operationId}`);
302
+ removed += 1;
303
+ }
304
+ return removed;
305
+ }
306
+ /**
307
+ * 显式 artifact TTL 清理(不自动执行)。同一 CAS 文件仍被其他 artifact 引用时保留文件。
308
+ */
309
+ cleanupArtifacts(input) {
310
+ const cutoff = (input.now ?? Date.now()) - input.olderThanMs;
311
+ const all = this.deps.store.listAllArtifacts(this.tenant());
312
+ const expired = all.filter((artifact) => Date.parse(artifact.createdAt) <= cutoff);
313
+ if (expired.length === 0)
314
+ return { scanned: all.length, deleted: 0, filesRemoved: 0 };
315
+ const expiredKeys = new Set(expired.map((artifact) => artifact.storageKey));
316
+ if (!input.dryRun) {
317
+ for (const artifact of expired) {
318
+ this.deps.store.deleteArtifact(artifact.artifactId, this.tenant());
319
+ }
320
+ }
321
+ const remaining = input.dryRun
322
+ ? all.filter((artifact) => !expiredKeys.has(artifact.storageKey))
323
+ : this.deps.store.listAllArtifacts(this.tenant());
324
+ const remainingKeys = new Set(remaining.map((artifact) => artifact.storageKey));
325
+ let filesRemoved = 0;
326
+ for (const key of expiredKeys) {
327
+ if (remainingKeys.has(key))
328
+ continue;
329
+ filesRemoved += 1;
330
+ if (!input.dryRun)
331
+ rmSync(join(this.root, key), { force: true });
332
+ }
333
+ return { scanned: all.length, deleted: expired.length, filesRemoved };
334
+ }
335
+ artifactPath(sessionId, artifactId) {
336
+ const artifact = this.deps.store.getArtifact(artifactId, this.tenant());
337
+ if (!artifact || artifact.sessionId !== sessionId)
338
+ return undefined;
339
+ const path = join(this.root, artifact.storageKey);
340
+ if (!statSync(path, { throwIfNoEntry: false }))
341
+ return undefined;
342
+ return {
343
+ path,
344
+ artifact: { name: artifact.name, mimeType: artifact.mimeType, size: artifact.size },
345
+ };
346
+ }
347
+ startDownload(input) {
348
+ const persisted = this.deps.store.getTransferByOperation(input.sessionId, input.operationId, this.tenant());
349
+ const artifact = this.deps.store.getArtifact(input.artifactId);
350
+ if (!artifact || artifact.sessionId !== input.sessionId) {
351
+ throw new ArtifactTransferError('artifact_not_found', `附件不存在:${input.artifactId}`);
352
+ }
353
+ const path = join(this.root, artifact.storageKey);
354
+ if (!statSync(path, { throwIfNoEntry: false })) {
355
+ throw new ArtifactTransferError('artifact_missing', '附件内容不在 CAS 中');
356
+ }
357
+ const transferId = persisted?.state === 'uploading' &&
358
+ persisted.direction === 'download' &&
359
+ persisted.artifactId === input.artifactId
360
+ ? persisted.transferId
361
+ : `dt_${randomUUID().replace(/-/g, '').slice(0, 20)}`;
362
+ const active = this.downloads.get(transferId);
363
+ if (active) {
364
+ this.closeDownload(active);
365
+ this.downloads.delete(transferId);
366
+ }
367
+ const chunkSize = Math.min(MAX_CHUNK_SIZE, Math.max(1, Math.floor(persisted?.chunkSize ?? input.chunkSize ?? DEFAULT_CHUNK_SIZE)));
368
+ const transfer = {
369
+ transferId,
370
+ artifactId: artifact.artifactId,
371
+ sessionId: input.sessionId,
372
+ operationId: input.operationId,
373
+ path,
374
+ size: artifact.size,
375
+ sha256: artifact.sha256,
376
+ chunkSize,
377
+ offset: persisted?.state === 'uploading' && persisted.direction === 'download'
378
+ ? Math.min(persisted.nextOffset, artifact.size)
379
+ : 0,
380
+ lastLength: 0,
381
+ fd: openSync(path, 'r'),
382
+ };
383
+ this.downloads.set(transferId, transfer);
384
+ try {
385
+ this.deps.store.saveTransfer({
386
+ tenantId: this.tenant(),
387
+ transferId,
388
+ sessionId: input.sessionId,
389
+ operationId: input.operationId,
390
+ artifactId: artifact.artifactId,
391
+ direction: 'download',
392
+ name: artifact.name,
393
+ mimeType: artifact.mimeType,
394
+ size: artifact.size,
395
+ sha256: artifact.sha256,
396
+ chunkSize,
397
+ nextOffset: transfer.offset,
398
+ state: 'uploading',
399
+ });
400
+ this.deps.emit({
401
+ type: 'artifact_download_ready',
402
+ transferId,
403
+ artifactId: artifact.artifactId,
404
+ nextOffset: transfer.offset,
405
+ size: artifact.size,
406
+ sha256: artifact.sha256,
407
+ chunkSize,
408
+ });
409
+ if (transfer.offset >= artifact.size) {
410
+ this.closeDownload(transfer);
411
+ this.downloads.delete(transferId);
412
+ this.deps.store.deleteTransfer(transferId, this.tenant());
413
+ this.deps.emit({ type: 'artifact_download_result', transferId, status: 'completed' });
414
+ }
415
+ else {
416
+ this.sendNextDownloadChunk(transfer);
417
+ }
418
+ return { transferId, size: artifact.size, sha256: artifact.sha256, chunkSize };
419
+ }
420
+ catch (error) {
421
+ try {
422
+ this.closeDownload(transfer);
423
+ }
424
+ finally {
425
+ this.downloads.delete(transferId);
426
+ }
427
+ throw error;
428
+ }
429
+ }
430
+ ackDownload(input) {
431
+ const transfer = this.downloads.get(input.transferId);
432
+ if (!transfer)
433
+ throw new ArtifactTransferError('transfer_not_found', '下载传输不存在或已结束');
434
+ const expected = transfer.offset + transfer.lastLength;
435
+ if (input.nextOffset !== expected) {
436
+ try {
437
+ this.closeDownload(transfer);
438
+ }
439
+ finally {
440
+ this.downloads.delete(transfer.transferId);
441
+ }
442
+ throw new ArtifactTransferError('out_of_order', `chunk ack offset ${input.nextOffset} != expected ${expected}`);
443
+ }
444
+ try {
445
+ this.deps.store.updateTransferOffset(transfer.transferId, input.nextOffset, this.tenant());
446
+ transfer.offset = input.nextOffset;
447
+ if (transfer.offset >= transfer.size) {
448
+ this.closeDownload(transfer);
449
+ this.downloads.delete(transfer.transferId);
450
+ this.deps.store.deleteTransfer(transfer.transferId, this.tenant());
451
+ this.deps.emit({
452
+ type: 'artifact_download_result',
453
+ transferId: transfer.transferId,
454
+ status: 'completed',
455
+ });
456
+ return;
457
+ }
458
+ this.sendNextDownloadChunk(transfer);
459
+ }
460
+ catch (error) {
461
+ try {
462
+ this.closeDownload(transfer);
463
+ }
464
+ finally {
465
+ this.downloads.delete(transfer.transferId);
466
+ }
467
+ throw error;
468
+ }
469
+ }
470
+ sendNextDownloadChunk(transfer) {
471
+ try {
472
+ if (transfer.fd === undefined)
473
+ throw new ArtifactTransferError('artifact_read_failed', '附件文件句柄已关闭');
474
+ const length = Math.min(transfer.chunkSize, transfer.size - transfer.offset);
475
+ const { bytes: chunk, bytesRead } = this.readRange(transfer.fd, length, transfer.offset);
476
+ if (bytesRead !== length)
477
+ throw new ArtifactTransferError('artifact_read_failed', '附件读取长度不足');
478
+ transfer.lastLength = bytesRead;
479
+ this.deps.emit({
480
+ type: 'artifact_download_chunk',
481
+ transferId: transfer.transferId,
482
+ offset: transfer.offset,
483
+ data: chunk.toString('base64'),
484
+ chunkSha256: this.sha256Bytes(chunk),
485
+ });
486
+ }
487
+ catch (error) {
488
+ try {
489
+ this.closeDownload(transfer);
490
+ }
491
+ finally {
492
+ this.downloads.delete(transfer.transferId);
493
+ }
494
+ throw error;
495
+ }
496
+ }
497
+ completeUpload(input) {
498
+ const persisted = this.deps.store.getTransfer(input.transferId, this.tenant());
499
+ if (persisted?.state === 'committed') {
500
+ if (input.size !== persisted.size || input.sha256.toLowerCase() !== persisted.sha256) {
501
+ throw new ArtifactTransferError('conflict', 'committed 重放参数与原传输不一致');
502
+ }
503
+ const artifact = this.deps.store.getArtifact(persisted.artifactId, this.tenant());
504
+ const event = this.deps.store.getArtifactEvent(persisted.sessionId, persisted.artifactId, this.tenant());
505
+ return {
506
+ committed: true,
507
+ artifactId: artifact?.artifactId ?? persisted.artifactId,
508
+ eventSeq: event?.eventSeq,
509
+ sha256: persisted.sha256,
510
+ };
511
+ }
512
+ let transfer = this.transfers.get(input.transferId);
513
+ if (!transfer && persisted?.state === 'uploading' && persisted.direction === 'upload' && persisted.tempPath) {
514
+ transfer = {
515
+ transferId: persisted.transferId,
516
+ operationId: persisted.operationId,
517
+ sessionId: persisted.sessionId,
518
+ artifactId: persisted.artifactId,
519
+ name: persisted.name,
520
+ mimeType: persisted.mimeType,
521
+ size: persisted.size,
522
+ sha256: persisted.sha256,
523
+ chunkSize: persisted.chunkSize,
524
+ nextOffset: persisted.nextOffset,
525
+ tempPath: persisted.tempPath,
526
+ };
527
+ this.transfers.set(transfer.transferId, transfer);
528
+ this.byOperation.set(`${transfer.sessionId}:${transfer.operationId}`, transfer.transferId);
529
+ }
530
+ if (!transfer)
531
+ throw new ArtifactTransferError('transfer_not_found', '传输不存在或已结束');
532
+ if (input.size !== transfer.size || transfer.nextOffset !== transfer.size) {
533
+ throw new ArtifactTransferError('size_mismatch', '文件大小与声明不一致');
534
+ }
535
+ const storageKey = `${this.tenant()}/sha256/${transfer.sha256.slice(0, 2)}/${transfer.sha256}`;
536
+ const target = join(this.root, storageKey);
537
+ const tempExists = Boolean(statSync(transfer.tempPath, { throwIfNoEntry: false }));
538
+ const targetExists = Boolean(statSync(target, { throwIfNoEntry: false }));
539
+ if (!tempExists && !targetExists) {
540
+ throw new ArtifactTransferError('artifact_missing', '上传临时文件与 CAS 内容均不存在');
541
+ }
542
+ // rename 后崩溃也可恢复:从已存在的 CAS 文件重新流式校验,再补 DB 事务。
543
+ const actual = this.sha256File(targetExists ? target : transfer.tempPath);
544
+ if (actual !== transfer.sha256 || input.sha256.toLowerCase() !== actual) {
545
+ throw new ArtifactTransferError('file_hash_mismatch', '整文件 SHA-256 不匹配');
546
+ }
547
+ mkdirSync(dirname(target), { recursive: true });
548
+ if (!targetExists)
549
+ renameSync(transfer.tempPath, target);
550
+ else if (tempExists)
551
+ rmSync(transfer.tempPath, { force: true });
552
+ const { artifact, event } = this.deps.store.commitArtifact({
553
+ tenantId: this.tenant(),
554
+ artifactId: transfer.artifactId,
555
+ sessionId: transfer.sessionId,
556
+ name: transfer.name,
557
+ mimeType: transfer.mimeType,
558
+ size: transfer.size,
559
+ sha256: actual,
560
+ kind: 'attachment',
561
+ storageKey,
562
+ }, transfer.transferId);
563
+ this.transfers.delete(transfer.transferId);
564
+ this.byOperation.delete(`${transfer.sessionId}:${transfer.operationId}`);
565
+ try {
566
+ this.deps.emit({
567
+ type: 'task_artifact',
568
+ taskId: transfer.sessionId,
569
+ artifactId: artifact.artifactId,
570
+ name: artifact.name,
571
+ mimeType: artifact.mimeType,
572
+ size: artifact.size,
573
+ sha256: artifact.sha256,
574
+ kind: artifact.kind,
575
+ eventSeq: event.eventSeq,
576
+ });
577
+ }
578
+ catch {
579
+ // DB/CAS 已 committed;发送失败由快照/重试恢复,不能把结果翻转成 failed。
580
+ }
581
+ return { committed: true, artifactId: artifact.artifactId, eventSeq: event.eventSeq, sha256: artifact.sha256 };
582
+ }
583
+ }
@@ -0,0 +1,22 @@
1
+ export const DEVICE_ID_PATTERN = /^bd_(?:[0-9a-f]{32}|[0-9a-f]{12})$/;
2
+ export function assertDeviceId(value) {
3
+ if (typeof value !== 'string' || !DEVICE_ID_PATTERN.test(value)) {
4
+ throw new Error('设备 ID 格式无效:应为 bd_ 加 32 或 12 位小写十六进制字符。');
5
+ }
6
+ return value;
7
+ }
8
+ export function resolveDeviceIdCandidate(candidates) {
9
+ let resolved;
10
+ let resolvedSource;
11
+ for (const candidate of candidates) {
12
+ if (candidate.value === undefined)
13
+ continue;
14
+ const deviceId = assertDeviceId(candidate.value);
15
+ if (resolved !== undefined && resolved !== deviceId) {
16
+ throw new Error(`本地设备身份冲突:${resolvedSource ?? '已有身份'}与${candidate.source}不一致;请核对后重试。`);
17
+ }
18
+ resolved = deviceId;
19
+ resolvedSource = candidate.source;
20
+ }
21
+ return resolved;
22
+ }