@fish-under-sea/dsh-client-ui-task-board-fish 1.0.2 → 1.1.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 (123) hide show
  1. package/NOTICE +1 -1
  2. package/README.en.md +4 -4
  3. package/README.md +4 -4
  4. package/README.zh.md +4 -4
  5. package/lib/client.js +4428 -1508
  6. package/lib/client.js.map +1 -1
  7. package/lib/index.js +2670 -496
  8. package/lib/types/client/CardDefaultPresetField.d.ts +35 -0
  9. package/lib/types/client/PluginSettingsCard.d.ts +130 -19
  10. package/lib/types/client/RangeBubble.d.ts +46 -0
  11. package/lib/types/client/SegmentGroup.d.ts +28 -0
  12. package/lib/types/client/TaskBoardSettingsCard.d.ts +63 -0
  13. package/lib/types/client/board/AttachmentField.d.ts +70 -0
  14. package/lib/types/client/board/ExecutionLog.d.ts +24 -0
  15. package/lib/types/client/board/ReasoningEffortField.d.ts +25 -0
  16. package/lib/types/client/board/TaskForm.d.ts +4 -0
  17. package/lib/types/client/board/VerificationReport.d.ts +2 -15
  18. package/lib/types/client/board/model-options.d.ts +87 -0
  19. package/lib/types/client/board/preset-label.d.ts +21 -0
  20. package/lib/types/client/board/preset-roster.d.ts +45 -0
  21. package/lib/types/client/board/source-group.d.ts +27 -0
  22. package/lib/types/client/body-mutations.d.ts +45 -0
  23. package/lib/types/client/host-api.d.ts +25 -0
  24. package/lib/types/client/locales.d.ts +87 -9
  25. package/lib/types/client/pending-verify.d.ts +47 -0
  26. package/lib/types/client/plugin-card-seat.d.ts +3 -1
  27. package/lib/types/client/service.d.ts +4 -1
  28. package/lib/types/client/settings-form.d.ts +73 -51
  29. package/lib/types/core/attachment.d.ts +132 -0
  30. package/lib/types/core/card-defaults.d.ts +78 -0
  31. package/lib/types/core/controller.d.ts +57 -8
  32. package/lib/types/core/execution-summary.d.ts +52 -0
  33. package/lib/types/core/extension.d.ts +116 -0
  34. package/lib/types/core/launch-width.d.ts +31 -0
  35. package/lib/types/core/reasoning-effort.d.ts +57 -0
  36. package/lib/types/core/session-reuse.d.ts +7 -1
  37. package/lib/types/core/spend-budget.d.ts +28 -0
  38. package/lib/types/core/subtask.d.ts +100 -37
  39. package/lib/types/core/tasks.d.ts +94 -10
  40. package/lib/types/core/use-cases/task-create.d.ts +10 -5
  41. package/lib/types/core/use-cases/task-tag.d.ts +36 -0
  42. package/lib/types/core/use-cases/task-update.d.ts +22 -1
  43. package/lib/types/core/wire-projection.d.ts +35 -0
  44. package/lib/types/core/workspace-target.d.ts +23 -3
  45. package/lib/types/host/attachments.d.ts +250 -0
  46. package/lib/types/host/extension-registry.d.ts +40 -0
  47. package/lib/types/host/launch-admission.d.ts +71 -0
  48. package/lib/types/host-ledger.d.ts +114 -47
  49. package/lib/types/host-routes.d.ts +63 -0
  50. package/lib/types/host-runner.d.ts +164 -18
  51. package/lib/types/host-service.d.ts +182 -46
  52. package/lib/types/host-spend.d.ts +52 -0
  53. package/lib/types/index.d.ts +173 -54
  54. package/lib/types/loopback.d.ts +41 -1
  55. package/lib/types/protocol.d.ts +52 -11
  56. package/lib/types/tool-surface.d.ts +1 -0
  57. package/locale/en.json +6 -0
  58. package/locale/zh.json +6 -0
  59. package/package.json +35 -28
  60. package/src/client/CardDefaultPresetField.tsx +101 -0
  61. package/src/client/PluginSettingsCard.tsx +385 -111
  62. package/src/client/RangeBubble.tsx +164 -0
  63. package/src/client/SegmentGroup.tsx +93 -0
  64. package/src/client/TaskBoardSettingsCard.tsx +332 -37
  65. package/src/client/board/AttachmentField.tsx +383 -0
  66. package/src/client/board/EditTaskModal.tsx +63 -0
  67. package/src/client/board/ExecutionLog.tsx +154 -0
  68. package/src/client/board/LinkSubtaskModal.tsx +1 -1
  69. package/src/client/board/NewTaskModal.tsx +154 -45
  70. package/src/client/board/ReasoningEffortField.tsx +50 -0
  71. package/src/client/board/TagManagerModal.tsx +151 -2
  72. package/src/client/board/TaskBoard.tsx +47 -10
  73. package/src/client/board/TaskCard.tsx +45 -23
  74. package/src/client/board/TaskDetail.tsx +468 -258
  75. package/src/client/board/TaskForm.tsx +19 -4
  76. package/src/client/board/VerificationReport.tsx +143 -104
  77. package/src/client/board/model-options.ts +208 -0
  78. package/src/client/board/preset-label.ts +32 -0
  79. package/src/client/board/preset-roster.ts +58 -0
  80. package/src/client/board/source-group.ts +94 -0
  81. package/src/client/board/task-markdown.module.css +11 -8
  82. package/src/client/board-settings.module.css +35 -7
  83. package/src/client/board.module.css +1044 -105
  84. package/src/client/body-mutations.ts +133 -0
  85. package/src/client/host-api.ts +70 -0
  86. package/src/client/index.ts +109 -95
  87. package/src/client/locales.ts +205 -48
  88. package/src/client/pending-verify.ts +90 -0
  89. package/src/client/plugin-card-seat.ts +8 -2
  90. package/src/client/service.ts +24 -0
  91. package/src/client/settings-card.module.css +466 -89
  92. package/src/client/settings-entry-form.ts +0 -1
  93. package/src/client/settings-form.ts +102 -60
  94. package/src/core/attachment.ts +287 -0
  95. package/src/core/card-defaults.ts +132 -0
  96. package/src/core/controller.ts +90 -11
  97. package/src/core/execution-summary.ts +96 -0
  98. package/src/core/extension.ts +120 -0
  99. package/src/core/launch-width.ts +38 -0
  100. package/src/core/reasoning-effort.ts +92 -0
  101. package/src/core/session-reuse.ts +7 -1
  102. package/src/core/spend-budget.ts +35 -0
  103. package/src/core/store.ts +19 -1
  104. package/src/core/subtask.ts +144 -68
  105. package/src/core/tasks.ts +117 -10
  106. package/src/core/use-cases/task-create.ts +27 -16
  107. package/src/core/use-cases/task-tag.ts +56 -0
  108. package/src/core/use-cases/task-update.ts +33 -5
  109. package/src/core/wire-projection.ts +81 -0
  110. package/src/core/workspace-target.ts +27 -3
  111. package/src/host/agent-tools.ts +33 -21
  112. package/src/host/attachments.ts +650 -0
  113. package/src/host/extension-registry.ts +150 -5
  114. package/src/host/launch-admission.ts +139 -0
  115. package/src/host-ledger.ts +248 -117
  116. package/src/host-routes.ts +233 -15
  117. package/src/host-runner.ts +395 -61
  118. package/src/host-service.ts +512 -139
  119. package/src/host-spend.ts +105 -0
  120. package/src/index.ts +312 -92
  121. package/src/loopback.ts +57 -1
  122. package/src/protocol.ts +83 -18
  123. package/src/tool-surface.ts +1 -0
@@ -0,0 +1,650 @@
1
+ /**
2
+ * Host-side attachment plumbing: the trusted upload path, the verification
3
+ * against the official attachment storage, and the execution-time resolution
4
+ * of a card's attachments into prompt parts.
5
+ *
6
+ * The board keeps METADATA in the ledger; the bytes live in the official
7
+ * storage (`ctx.attachments`). This module is the only place that touches
8
+ * both: it publishes bytes into the storage, proves a recorded claim against
9
+ * it, and reads the objects back for an execution.
10
+ *
11
+ * The official storage has NO deletion API. Removing an attachment or deleting
12
+ * a card therefore removes METADATA only: the stored object stays where it is.
13
+ */
14
+ import { createHash } from 'node:crypto'
15
+ import { accessSync, constants as fsConstants } from 'node:fs'
16
+ import type { IncomingMessage } from 'node:http'
17
+ import type {
18
+ FileAttachmentRef,
19
+ ImageAttachmentRef,
20
+ ImageMediaType,
21
+ StoredImageAttachment,
22
+ } from '@deepseek-ai/dsh-attachment/types'
23
+ import {
24
+ canonicalAttachmentName,
25
+ TASK_ATTACHMENT_IMAGE_MEDIA_TYPES,
26
+ TASK_ATTACHMENT_LIMIT,
27
+ TASK_ATTACHMENT_MAX_BYTES,
28
+ TASK_ATTACHMENT_TOTAL_MAX_BYTES,
29
+ type TaskAttachment,
30
+ type TaskAttachmentKind,
31
+ } from '../core/attachment.ts'
32
+
33
+ /**
34
+ * The official attachment storage, narrowed to the members the board uses.
35
+ *
36
+ * The board declares the face structurally (like the other optional services
37
+ * it resolves) so the Host half needs no value import of the SDK package: the
38
+ * deployment's own attachment service provides it, and a deployment without
39
+ * one simply refuses attachment work.
40
+ */
41
+ export interface TaskBoardAttachmentStore {
42
+ /** Deployment-resolved image policy. */
43
+ readonly imageLimits: {
44
+ maxImageBytes: number
45
+ maxImagesPerMessage: number
46
+ maxMessageImageBytes: number
47
+ maxImagePixels: number
48
+ maxImageDimension: number
49
+ mediaTypes: readonly string[]
50
+ }
51
+ /** Validate one image without persisting it. */
52
+ validateImage(input: { data: Uint8Array; mediaType: string; name?: string }): Promise<void>
53
+ /** Validate and durably commit one image. */
54
+ saveImage(input: { data: Uint8Array; mediaType: string; name?: string }): Promise<ImageAttachmentRef>
55
+ /** Read one image and verify that the bytes still match the reference. */
56
+ readImage(ref: ImageAttachmentRef, signal?: AbortSignal): Promise<StoredImageAttachment>
57
+ /** Durably commit one file byte-for-byte from bounded chunks. */
58
+ saveFileStream(input: { data: AsyncIterable<Uint8Array>; signal?: AbortSignal; name?: string }): Promise<FileAttachmentRef>
59
+ /** Read and verify one verbatim stored file as bounded chunks. */
60
+ readFileStream(ref: FileAttachmentRef, signal?: AbortSignal): AsyncIterable<Uint8Array>
61
+ /** Locate the verbatim stored file object in the Host filesystem. */
62
+ fileHostPath(ref: FileAttachmentRef): string | undefined
63
+ }
64
+
65
+ /** The stable failure classes the attachment routes answer with. */
66
+ export type TaskBoardAttachmentErrorCode =
67
+ | 'invalid-request'
68
+ | 'unsupported-type'
69
+ | 'too-large'
70
+ | 'invalid-image'
71
+ | 'storage-unavailable'
72
+ | 'not-found'
73
+ | 'unreadable'
74
+
75
+ /**
76
+ * One attachment failure, carrying the class the route maps to a status and a
77
+ * message that never contains raw bytes or a host path.
78
+ */
79
+ export class TaskBoardAttachmentError extends Error {
80
+ constructor(readonly code: TaskBoardAttachmentErrorCode, message: string, options?: ErrorOptions) {
81
+ super(message, options)
82
+ this.name = 'TaskBoardAttachmentError'
83
+ }
84
+ }
85
+
86
+ /** The HTTP status one attachment failure class answers with. */
87
+ export function attachmentErrorStatus(code: TaskBoardAttachmentErrorCode): number {
88
+ if (code === 'invalid-request' || code === 'invalid-image' || code === 'unreadable') return 400
89
+ if (code === 'unsupported-type') return 415
90
+ if (code === 'too-large') return 413
91
+ if (code === 'not-found') return 404
92
+ return 503
93
+ }
94
+
95
+ /** Lowercase hex sha256 digest of the exact bytes. */
96
+ export function sha256Hex(bytes: Uint8Array): string {
97
+ return createHash('sha256').update(bytes).digest('hex')
98
+ }
99
+
100
+ /** Whether a value names one of the raster media types the image path accepts. */
101
+ export function isImageMediaType(value: unknown): value is ImageMediaType {
102
+ return typeof value === 'string'
103
+ && (TASK_ATTACHMENT_IMAGE_MEDIA_TYPES as readonly string[]).includes(value.toLowerCase())
104
+ }
105
+
106
+ /**
107
+ * Normalize a client-declared file media type: a well-formed type is kept
108
+ * (lowercased), anything else falls back to the opaque binary type. The type
109
+ * of a verbatim file is a declaration, not something the storage can prove.
110
+ */
111
+ export function normalizeFileMediaType(value: unknown): string {
112
+ if (typeof value !== 'string') return 'application/octet-stream'
113
+ const trimmed = value.trim().toLowerCase()
114
+ if (trimmed === '' || trimmed.length > 255) return 'application/octet-stream'
115
+ return /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(trimmed) ? trimmed : 'application/octet-stream'
116
+ }
117
+
118
+ /**
119
+ * The canonical display name of an upload.
120
+ *
121
+ * The Host publishes the canonical name, and the ledger stores the same
122
+ * string: the wire gate accepts only a name that already IS canonical, so a
123
+ * client cannot rename an object into something the storage never saw. The
124
+ * canonical form is single-line and free of any path part, which is what
125
+ * makes it safe to place in an execution prompt.
126
+ */
127
+ export function sanitizeAttachmentName(value: unknown): string {
128
+ return canonicalAttachmentName(value)
129
+ }
130
+
131
+ /**
132
+ * The per-image byte cap this deployment enforces: the board's own ceiling
133
+ * lowered by the storage's own policy when that policy is stricter.
134
+ */
135
+ export function effectiveImageByteLimit(store: TaskBoardAttachmentStore | undefined): number {
136
+ const deployment = store?.imageLimits?.maxImageBytes
137
+ if (typeof deployment !== 'number' || !Number.isFinite(deployment) || deployment <= 0) return TASK_ATTACHMENT_MAX_BYTES
138
+ return Math.min(TASK_ATTACHMENT_MAX_BYTES, deployment)
139
+ }
140
+
141
+ /**
142
+ * Read a whole request body, refusing it the moment it grows past the cap.
143
+ * The count is the ACTUAL byte length of the stream, not a declared length.
144
+ */
145
+ export async function readRequestBytes(req: IncomingMessage, limit: number): Promise<Uint8Array> {
146
+ const chunks: Buffer[] = []
147
+ let size = 0
148
+ let overflow = false
149
+ for await (const chunk of req) {
150
+ const buffer = chunk as Buffer
151
+ size += buffer.length
152
+ if (size > limit) {
153
+ // The rest of the body is drained rather than abandoned: the caller
154
+ // still answers with a typed refusal, and the memory stays bounded.
155
+ overflow = true
156
+ chunks.length = 0
157
+ continue
158
+ }
159
+ chunks.push(buffer)
160
+ }
161
+ if (overflow) throw new TaskBoardAttachmentError('too-large', `attachment exceeds the ${limit} byte limit`)
162
+ return new Uint8Array(Buffer.concat(chunks))
163
+ }
164
+
165
+ /**
166
+ * A byte stream that measures and digests what it yields.
167
+ *
168
+ * The file path streams the request straight into the official storage: the
169
+ * bytes are never collected in memory, and the count and digest the board
170
+ * records are the ones computed from the bytes that actually went in.
171
+ */
172
+ export class MeasuredStream {
173
+ private readonly hash = createHash('sha256')
174
+ private size = 0
175
+ private finished = false
176
+
177
+ constructor(private readonly limit: number) {}
178
+
179
+ /** The byte length seen so far. */
180
+ get bytes(): number {
181
+ return this.size
182
+ }
183
+
184
+ /** The digest of the bytes seen so far; final once the stream ended. */
185
+ digest(): string {
186
+ return this.hash.digest('hex')
187
+ }
188
+
189
+ /** Whether the whole stream was consumed. */
190
+ get complete(): boolean {
191
+ return this.finished
192
+ }
193
+
194
+ /** The chunks, refusing the stream the moment it grows past the cap. */
195
+ async *chunks(source: AsyncIterable<Uint8Array>): AsyncGenerator<Uint8Array> {
196
+ for await (const chunk of source) {
197
+ this.size += chunk.byteLength
198
+ if (this.size > this.limit) {
199
+ throw new TaskBoardAttachmentError('too-large', `attachment exceeds the ${this.limit} byte limit`)
200
+ }
201
+ this.hash.update(chunk)
202
+ yield chunk
203
+ }
204
+ this.finished = true
205
+ }
206
+ }
207
+
208
+ /**
209
+ * The request body as a byte stream: the file path hands it straight to the
210
+ * official storage, so the bytes are never collected in memory.
211
+ */
212
+ export function requestChunks(req: IncomingMessage): AsyncIterable<Uint8Array> {
213
+ return req as unknown as AsyncIterable<Uint8Array>
214
+ }
215
+
216
+ /**
217
+ * The image reference a recorded attachment stands for. The stored object is
218
+ * addressed by its opaque identifier; the rest of the fields are the board's
219
+ * own record of what the storage holds.
220
+ */
221
+ export function imageRefOf(attachment: TaskAttachment): ImageAttachmentRef {
222
+ // The stored object is addressed by its pixel size, so a record without one
223
+ // cannot address it: the reference is refused rather than completed with a
224
+ // manufactured 0x0.
225
+ if (attachment.width === undefined || attachment.height === undefined) {
226
+ throw new TaskBoardAttachmentError(
227
+ 'unreadable',
228
+ `attachment ${attachment.attachmentId} carries no image dimensions`,
229
+ )
230
+ }
231
+ return {
232
+ attachmentId: attachment.attachmentId as ImageAttachmentRef['attachmentId'],
233
+ mediaType: attachment.mediaType as ImageMediaType,
234
+ bytes: attachment.bytes,
235
+ width: attachment.width,
236
+ height: attachment.height,
237
+ ...(attachment.name === '' ? {} : { name: attachment.name }),
238
+ }
239
+ }
240
+
241
+ /** The file reference a recorded attachment stands for. */
242
+ export function fileRefOf(attachment: TaskAttachment): FileAttachmentRef {
243
+ return {
244
+ attachmentId: attachment.attachmentId as FileAttachmentRef['attachmentId'],
245
+ name: attachment.name,
246
+ bytes: attachment.bytes,
247
+ }
248
+ }
249
+
250
+ /**
251
+ * Publish one image into the official storage and describe it with
252
+ * host-computed metadata.
253
+ *
254
+ * The image is validated before it is stored (the storage checks the decoded
255
+ * bytes against the declared type), and the recorded digest is computed over
256
+ * the NORMALIZED bytes the storage actually kept — not over what the client
257
+ * sent — so the metadata and the object can never disagree.
258
+ */
259
+ export async function storeImage(
260
+ store: TaskBoardAttachmentStore,
261
+ data: Uint8Array,
262
+ name: string,
263
+ mediaType: string,
264
+ ): Promise<TaskAttachment> {
265
+ if (!isImageMediaType(mediaType)) {
266
+ throw new TaskBoardAttachmentError('unsupported-type', `${mediaType} is not an accepted image type`)
267
+ }
268
+ const limit = effectiveImageByteLimit(store)
269
+ if (data.byteLength > limit) {
270
+ throw new TaskBoardAttachmentError('too-large', `image exceeds the ${limit} byte limit`)
271
+ }
272
+ const type = mediaType.toLowerCase() as ImageMediaType
273
+ try {
274
+ await store.validateImage({ data, mediaType: type, name })
275
+ const ref = await store.saveImage({ data, mediaType: type, name })
276
+ const stored = await store.readImage(ref)
277
+ // The stored name is the storage's own: the ledger records it verbatim
278
+ // after canonicalization, so the two can never disagree.
279
+ return {
280
+ kind: 'image',
281
+ attachmentId: String(ref.attachmentId),
282
+ name: canonicalAttachmentName(stored.ref.name ?? name),
283
+ bytes: stored.ref.bytes,
284
+ mediaType: stored.ref.mediaType,
285
+ sha256: sha256Hex(stored.data),
286
+ width: stored.ref.width,
287
+ height: stored.ref.height,
288
+ }
289
+ } catch (error) {
290
+ throw asAttachmentError(error)
291
+ }
292
+ }
293
+
294
+ /**
295
+ * Publish one file into the official storage and describe it with
296
+ * host-computed metadata. The digest is computed from the streamed bytes, so
297
+ * the record and the stored object agree by construction.
298
+ */
299
+ export async function storeFile(
300
+ store: TaskBoardAttachmentStore,
301
+ chunks: AsyncIterable<Uint8Array>,
302
+ name: string,
303
+ mediaType: string,
304
+ signal?: AbortSignal,
305
+ ): Promise<{ attachment: TaskAttachment; bytes: number; sha256: string }> {
306
+ const measured = new MeasuredStream(TASK_ATTACHMENT_MAX_BYTES)
307
+ try {
308
+ const ref = await store.saveFileStream({
309
+ data: measured.chunks(chunks),
310
+ ...(signal === undefined ? {} : { signal }),
311
+ name,
312
+ })
313
+ const sha256 = measured.digest()
314
+ return {
315
+ attachment: {
316
+ kind: 'file',
317
+ attachmentId: String(ref.attachmentId),
318
+ // The storage sanitizes the leaf of the name it was given, but it
319
+ // cannot prove which name a client claimed later: the ledger
320
+ // therefore keeps the CANONICAL form of the stored name, so a rename
321
+ // on the wire stays single-line and safe for the prompt.
322
+ name: canonicalAttachmentName(ref.name || name),
323
+ bytes: ref.bytes,
324
+ mediaType: normalizeFileMediaType(mediaType),
325
+ sha256,
326
+ },
327
+ bytes: measured.bytes,
328
+ sha256,
329
+ }
330
+ } catch (error) {
331
+ throw asAttachmentError(error)
332
+ }
333
+ }
334
+
335
+ /**
336
+ * Map an official attachment failure onto the board's own classes, so a
337
+ * storage fault reads as "the storage is unavailable" and a rejected image
338
+ * reads as "the image is not acceptable" — never as an internal error.
339
+ */
340
+ export function asAttachmentError(error: unknown): TaskBoardAttachmentError {
341
+ if (error instanceof TaskBoardAttachmentError) return error
342
+ const code = (error as { code?: unknown } | null)?.code
343
+ if (typeof code === 'string') {
344
+ if (code === 'IMAGE_TOO_LARGE' || code === 'IMAGES_TOO_LARGE') {
345
+ return new TaskBoardAttachmentError('too-large', 'the attachment exceeds the deployment size limit', { cause: error })
346
+ }
347
+ if (code === 'TOO_MANY_IMAGES') {
348
+ return new TaskBoardAttachmentError('too-large', 'the attachment exceeds the deployment image count limit', { cause: error })
349
+ }
350
+ if (code === 'UNSUPPORTED_IMAGE_TYPE' || code === 'IMAGE_TYPE_MISMATCH') {
351
+ return new TaskBoardAttachmentError('unsupported-type', 'the attachment is not an accepted image type', { cause: error })
352
+ }
353
+ if (code === 'INVALID_IMAGE' || code === 'INVALID_IMAGE_BASE64' || code === 'IMAGE_TOO_MANY_PIXELS' || code === 'IMAGE_DIMENSION_TOO_LARGE') {
354
+ return new TaskBoardAttachmentError('invalid-image', 'the attachment is not a readable image', { cause: error })
355
+ }
356
+ if (code === 'ATTACHMENT_NOT_FOUND') {
357
+ return new TaskBoardAttachmentError('not-found', 'the attachment is not in the storage', { cause: error })
358
+ }
359
+ if (code === 'ATTACHMENT_READ_FAILED' || code === 'ATTACHMENT_CORRUPT') {
360
+ return new TaskBoardAttachmentError('unreadable', 'the stored attachment could not be read back', { cause: error })
361
+ }
362
+ if (code === 'ATTACHMENT_WRITE_FAILED' || code === 'ATTACHMENT_FILES_UNSUPPORTED' || code === 'ATTACHMENT_PROJECTION_UNSUPPORTED') {
363
+ return new TaskBoardAttachmentError('storage-unavailable', 'the attachment storage refused the write', { cause: error })
364
+ }
365
+ }
366
+ return new TaskBoardAttachmentError('storage-unavailable', 'the attachment storage is unavailable', { cause: error })
367
+ }
368
+
369
+ /**
370
+ * Prove every recorded attachment against the official storage: an image is
371
+ * read back and compared, a file is streamed and its digest recomputed.
372
+ *
373
+ * A reference the storage does not know, and a record whose metadata does not
374
+ * match the stored bytes, are both a refusal: the action never reaches the
375
+ * ledger, so a spoofed client claim can never become a stored fact.
376
+ */
377
+ export async function verifyAttachments(
378
+ store: TaskBoardAttachmentStore,
379
+ attachments: readonly TaskAttachment[],
380
+ ): Promise<void> {
381
+ // The official per-message budget is checked FIRST: a card whose images
382
+ // exceed the deployment's own batch limits must never reach the prompt
383
+ // admission, however well each individual object is stored.
384
+ assertImageBatchWithinLimits(store, attachments)
385
+ for (const attachment of attachments) {
386
+ if (attachment.kind === 'image') await verifyImage(store, attachment)
387
+ else await verifyFile(store, attachment)
388
+ }
389
+ }
390
+
391
+ /**
392
+ * The official image batch limits of a deployment: how many images one
393
+ * message may carry and how many bytes they may add up to.
394
+ *
395
+ * The board's own caps (eight attachments, 10 MiB each, 32 MiB per card) stay
396
+ * in force; the deployment's policy can only lower them, and it governs the
397
+ * IMAGES of one card because that is what one prompt carries.
398
+ */
399
+ export function officialImageBatchLimits(store: TaskBoardAttachmentStore | undefined): {
400
+ maxImages: number
401
+ maxImageBytes: number
402
+ maxMessageImageBytes: number
403
+ } {
404
+ const limits = store?.imageLimits
405
+ const maxImages = typeof limits?.maxImagesPerMessage === 'number' && limits.maxImagesPerMessage > 0
406
+ ? Math.min(TASK_ATTACHMENT_LIMIT, limits.maxImagesPerMessage)
407
+ : TASK_ATTACHMENT_LIMIT
408
+ const maxMessageImageBytes = typeof limits?.maxMessageImageBytes === 'number' && limits.maxMessageImageBytes > 0
409
+ ? Math.min(TASK_ATTACHMENT_TOTAL_MAX_BYTES, limits.maxMessageImageBytes)
410
+ : TASK_ATTACHMENT_TOTAL_MAX_BYTES
411
+ return {
412
+ maxImages,
413
+ maxImageBytes: effectiveImageByteLimit(store),
414
+ maxMessageImageBytes,
415
+ }
416
+ }
417
+
418
+ /**
419
+ * Refuse a card whose images exceed the deployment's per-message budget.
420
+ *
421
+ * The check counts only the images: plain files travel as paths and never
422
+ * enter the prompt admission, so they are not part of that budget.
423
+ * @param store - the official attachment storage.
424
+ * @param attachments - the card's attachments.
425
+ */
426
+ export function assertImageBatchWithinLimits(
427
+ store: TaskBoardAttachmentStore | undefined,
428
+ attachments: readonly TaskAttachment[],
429
+ ): void {
430
+ if (store === undefined) return
431
+ const limits = officialImageBatchLimits(store)
432
+ const images = attachments.filter(attachment => attachment.kind === 'image')
433
+ if (images.length > limits.maxImages) {
434
+ throw new TaskBoardAttachmentError(
435
+ 'too-large',
436
+ `the card carries ${images.length} images, the deployment admits ${limits.maxImages} per message`,
437
+ )
438
+ }
439
+ const bytes = images.reduce((sum, attachment) => sum + attachment.bytes, 0)
440
+ if (bytes > limits.maxMessageImageBytes) {
441
+ throw new TaskBoardAttachmentError(
442
+ 'too-large',
443
+ `the card's images total ${bytes} bytes, the deployment admits ${limits.maxMessageImageBytes} per message`,
444
+ )
445
+ }
446
+ for (const image of images) {
447
+ if (image.bytes > limits.maxImageBytes) {
448
+ throw new TaskBoardAttachmentError(
449
+ 'too-large',
450
+ `an image exceeds the deployment limit of ${limits.maxImageBytes} bytes`,
451
+ )
452
+ }
453
+ }
454
+ }
455
+
456
+ /** Read one image back and compare it with the recorded metadata. */
457
+ export async function verifyImage(store: TaskBoardAttachmentStore, attachment: TaskAttachment): Promise<void> {
458
+ let stored: StoredImageAttachment
459
+ try {
460
+ stored = await store.readImage(imageRefOf(attachment))
461
+ } catch (error) {
462
+ throw asAttachmentError(error)
463
+ }
464
+ const digest = sha256Hex(stored.data)
465
+ // The stored name is compared too, WHEN the storage echoes one: the storage
466
+ // owns the display name of an image, so a client that renamed it is refused
467
+ // rather than believed. A storage that keeps no name of its own cannot
468
+ // disprove the claim that way; the bytes and the digest still prove the
469
+ // object, and the canonical name keeps the claim safe for the prompt.
470
+ const storedName = stored.ref.name
471
+ if (stored.ref.bytes !== attachment.bytes
472
+ || stored.ref.mediaType !== attachment.mediaType
473
+ || digest !== attachment.sha256
474
+ || stored.ref.width !== attachment.width
475
+ || stored.ref.height !== attachment.height
476
+ || (storedName !== undefined && canonicalAttachmentName(storedName) !== attachment.name)) {
477
+ throw new TaskBoardAttachmentError('unreadable', `attachment ${attachment.attachmentId} does not match the stored object`)
478
+ }
479
+ }
480
+
481
+ /** Stream one file back and recompute its digest. */
482
+ export async function verifyFile(store: TaskBoardAttachmentStore, attachment: TaskAttachment): Promise<void> {
483
+ const hash = createHash('sha256')
484
+ let bytes = 0
485
+ try {
486
+ for await (const chunk of store.readFileStream(fileRefOf(attachment))) {
487
+ bytes += chunk.byteLength
488
+ hash.update(chunk)
489
+ }
490
+ } catch (error) {
491
+ throw asAttachmentError(error)
492
+ }
493
+ if (bytes !== attachment.bytes || hash.digest('hex') !== attachment.sha256) {
494
+ throw new TaskBoardAttachmentError('unreadable', `attachment ${attachment.attachmentId} does not match the stored object`)
495
+ }
496
+ }
497
+
498
+ /**
499
+ * The limits the board publishes for its attachments: the board's own caps,
500
+ * lowered by the deployment's image policy where that policy is stricter.
501
+ */
502
+ export function publishedAttachmentLimits(store: TaskBoardAttachmentStore | undefined): {
503
+ maxAttachments: number
504
+ maxBytes: number
505
+ maxTotalBytes: number
506
+ maxImages: number
507
+ maxImageBytes: number
508
+ maxMessageImageBytes: number
509
+ } {
510
+ const batch = officialImageBatchLimits(store)
511
+ return {
512
+ maxAttachments: TASK_ATTACHMENT_LIMIT,
513
+ maxBytes: TASK_ATTACHMENT_MAX_BYTES,
514
+ maxTotalBytes: TASK_ATTACHMENT_TOTAL_MAX_BYTES,
515
+ maxImages: batch.maxImages,
516
+ maxImageBytes: batch.maxImageBytes,
517
+ maxMessageImageBytes: batch.maxMessageImageBytes,
518
+ }
519
+ }
520
+
521
+ /** One image resolved for an execution prompt. */
522
+ export interface ExecutionImagePart {
523
+ type: 'image'
524
+ mediaType: string
525
+ data: string
526
+ name?: string
527
+ }
528
+
529
+ /** One file resolved for an execution prompt: its readable host path. */
530
+ export interface ExecutionFilePart {
531
+ name: string
532
+ path: string
533
+ bytes: number
534
+ mediaType: string
535
+ }
536
+
537
+ /** The attachments of a card, resolved for one execution. */
538
+ export interface ResolvedAttachments {
539
+ /** The images, in the order the card lists them. */
540
+ images: ExecutionImagePart[]
541
+ /** The files, in the order the card lists them. */
542
+ files: ExecutionFilePart[]
543
+ }
544
+
545
+ /**
546
+ * Resolve a card's attachments for one execution: images become prompt image
547
+ * parts, files become readable host paths.
548
+ *
549
+ * Every execution resolves the attachments afresh — the recorded metadata is
550
+ * never trusted on its own, and a file whose host path is missing or
551
+ * unreadable fails the run instead of being silently dropped.
552
+ */
553
+ export async function resolveExecutionAttachments(
554
+ store: TaskBoardAttachmentStore,
555
+ attachments: readonly TaskAttachment[],
556
+ ): Promise<ResolvedAttachments> {
557
+ // The deployment's per-message image budget is checked before anything is
558
+ // read: a card over that budget must not reach the prompt admission.
559
+ assertImageBatchWithinLimits(store, attachments)
560
+ const images: ExecutionImagePart[] = []
561
+ const files: ExecutionFilePart[] = []
562
+ for (const attachment of attachments) {
563
+ if (attachment.kind === 'image') {
564
+ let stored: StoredImageAttachment
565
+ try {
566
+ stored = await store.readImage(imageRefOf(attachment))
567
+ } catch (error) {
568
+ throw asAttachmentError(error)
569
+ }
570
+ images.push({
571
+ type: 'image',
572
+ mediaType: stored.ref.mediaType,
573
+ data: Buffer.from(stored.data).toString('base64'),
574
+ name: attachment.name,
575
+ })
576
+ continue
577
+ }
578
+ const ref = fileRefOf(attachment)
579
+ let path: string | undefined
580
+ try {
581
+ path = store.fileHostPath(ref)
582
+ } catch (error) {
583
+ throw asAttachmentError(error)
584
+ }
585
+ if (path === undefined || path === '') {
586
+ throw new TaskBoardAttachmentError(
587
+ 'unreadable',
588
+ `attachment ${attachment.attachmentId} has no readable path in this deployment`,
589
+ )
590
+ }
591
+ try {
592
+ accessSync(path, fsConstants.R_OK)
593
+ } catch (error) {
594
+ throw new TaskBoardAttachmentError(
595
+ 'unreadable',
596
+ `attachment ${attachment.name} is not readable in this deployment`,
597
+ { cause: error },
598
+ )
599
+ }
600
+ files.push({ name: attachment.name, path, bytes: attachment.bytes, mediaType: attachment.mediaType })
601
+ }
602
+ return { images, files }
603
+ }
604
+
605
+ /**
606
+ * The attachment section of an execution prompt: the readable paths of the
607
+ * card's files, marked read-only.
608
+ *
609
+ * It is a section of its own — never folded into the handover preamble — so
610
+ * the two kinds of reference stay distinguishable to the reading agent.
611
+ */
612
+ export function attachmentPromptPreamble(files: readonly ExecutionFilePart[]): string | undefined {
613
+ if (files.length === 0) return undefined
614
+ const lines = files.map(file => `- ${file.name}(${file.path},${file.bytes} 字节,${file.mediaType})`)
615
+ return `附件文件(任务看板附件,只读路径;请直接读取这些文件,不要修改或移动它们):
616
+ ${lines.join('\n')}`
617
+ }
618
+
619
+ /** The model-info reader the image preflight uses. */
620
+ export type ModelInfoResolver = (
621
+ provider: string,
622
+ model: string,
623
+ signal?: AbortSignal,
624
+ ) => Promise<{ inputModalities?: readonly string[] } | undefined>
625
+
626
+ /**
627
+ * Refuse an execution whose route cannot read images.
628
+ *
629
+ * The check uses the ACTUAL route of the session the run is about to use and
630
+ * the model's own declared input modalities. A route that declares no
631
+ * modalities is UNKNOWN, and an unknown route is allowed: the official model
632
+ * catalog publishes no modality information, so it cannot answer this
633
+ * question, and refusing on its silence would block every image run.
634
+ */
635
+ export async function assertRouteAcceptsImages(
636
+ resolveModelInfo: ModelInfoResolver | undefined,
637
+ provider: string,
638
+ model: string,
639
+ ): Promise<void> {
640
+ if (resolveModelInfo === undefined) return
641
+ const info = await resolveModelInfo(provider, model)
642
+ const modalities = info?.inputModalities
643
+ if (!Array.isArray(modalities)) return
644
+ if (!modalities.includes('image')) {
645
+ throw new Error(`the model route ${provider}/${model} does not accept image input`)
646
+ }
647
+ }
648
+
649
+ /** The attachment kinds a card may carry, for the wire gates. */
650
+ export const ATTACHMENT_KINDS: readonly TaskAttachmentKind[] = ['image', 'file']