@linxin666/dsh-client-ui-task-board 0.4.12 → 0.4.14

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 (61) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +9 -3
  3. package/README.zh.md +9 -3
  4. package/lib/client.js +1476 -478
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +1280 -65
  7. package/lib/types/client/board/AttachmentField.d.ts +70 -0
  8. package/lib/types/client/board/model-options.d.ts +21 -1
  9. package/lib/types/client/board/source-group.d.ts +27 -0
  10. package/lib/types/client/host-api.d.ts +25 -0
  11. package/lib/types/client/locales.d.ts +17 -0
  12. package/lib/types/client/pending-verify.d.ts +47 -0
  13. package/lib/types/client/service.d.ts +4 -1
  14. package/lib/types/core/attachment.d.ts +132 -0
  15. package/lib/types/core/controller.d.ts +26 -2
  16. package/lib/types/core/extension.d.ts +82 -0
  17. package/lib/types/core/session-reuse.d.ts +7 -1
  18. package/lib/types/core/tasks.d.ts +38 -1
  19. package/lib/types/core/use-cases/task-update.d.ts +21 -0
  20. package/lib/types/core/wire-projection.d.ts +35 -0
  21. package/lib/types/host/attachments.d.ts +250 -0
  22. package/lib/types/host/extension-registry.d.ts +40 -0
  23. package/lib/types/host-ledger.d.ts +16 -0
  24. package/lib/types/host-routes.d.ts +14 -0
  25. package/lib/types/host-runner.d.ts +53 -1
  26. package/lib/types/host-service.d.ts +59 -0
  27. package/lib/types/index.d.ts +23 -0
  28. package/lib/types/protocol.d.ts +39 -6
  29. package/locale/en.json +6 -0
  30. package/locale/zh.json +6 -0
  31. package/package.json +6 -2
  32. package/src/client/TaskBoardSettingsCard.tsx +11 -1
  33. package/src/client/board/AttachmentField.tsx +383 -0
  34. package/src/client/board/EditTaskModal.tsx +63 -0
  35. package/src/client/board/NewTaskModal.tsx +76 -4
  36. package/src/client/board/TaskBoard.tsx +47 -10
  37. package/src/client/board/TaskDetail.tsx +30 -2
  38. package/src/client/board/model-options.ts +32 -2
  39. package/src/client/board/source-group.ts +94 -0
  40. package/src/client/board.module.css +83 -0
  41. package/src/client/host-api.ts +70 -0
  42. package/src/client/index.ts +11 -0
  43. package/src/client/locales.ts +34 -0
  44. package/src/client/pending-verify.ts +90 -0
  45. package/src/client/service.ts +24 -0
  46. package/src/core/attachment.ts +287 -0
  47. package/src/core/controller.ts +47 -1
  48. package/src/core/extension.ts +86 -0
  49. package/src/core/session-reuse.ts +7 -1
  50. package/src/core/store.ts +10 -1
  51. package/src/core/tasks.ts +49 -0
  52. package/src/core/use-cases/task-update.ts +27 -2
  53. package/src/core/wire-projection.ts +81 -0
  54. package/src/host/attachments.ts +650 -0
  55. package/src/host/extension-registry.ts +150 -5
  56. package/src/host-ledger.ts +32 -4
  57. package/src/host-routes.ts +168 -13
  58. package/src/host-runner.ts +124 -4
  59. package/src/host-service.ts +165 -12
  60. package/src/index.ts +47 -0
  61. package/src/protocol.ts +57 -9
@@ -8,6 +8,16 @@ import { MISSING_WORKSPACE_REASON, mostRecentWorkspaceId } from './core/workspac
8
8
  import { declaredRoute, normalizeReasoningEffort, resolveReasoningEffort, type ReasoningRoute } from './core/reasoning-effort.ts'
9
9
  import type { ModelCatalogView } from './core/verification.ts'
10
10
  import type { ExecutionSummary, TaskPermission, TaskRecord } from './core/tasks.ts'
11
+ import type { TaskAttachment } from './core/attachment.ts'
12
+ import {
13
+ assertRouteAcceptsImages,
14
+ attachmentPromptPreamble,
15
+ resolveExecutionAttachments,
16
+ type ExecutionFilePart,
17
+ type ModelInfoResolver,
18
+ type ResolvedAttachments,
19
+ type TaskBoardAttachmentStore,
20
+ } from './host/attachments.ts'
11
21
  import { executionSummaryOf } from './core/execution-summary.ts'
12
22
 
13
23
  /**
@@ -227,6 +237,20 @@ export interface PromptContext {
227
237
  * run's own terms instead of guessing from the Host clock (issue #1722).
228
238
  */
229
239
  schedule?: { triggeredAt: number; timeZone: string; mode: 'cron' | 'once'; cron?: string }
240
+ /**
241
+ * Rework provenance: the instructions a reviewer sent the previous run back
242
+ * with. Present exactly when this execution continues the card's own session
243
+ * to redo work, so the agent reads why it is being asked again instead of
244
+ * seeing the card body a second time with no explanation.
245
+ */
246
+ rework?: { instructions: string }
247
+ /**
248
+ * The card's attached files, resolved to readable host paths for THIS
249
+ * execution. Present exactly when the card carries files: the section is a
250
+ * preamble of its own, separate from the handover references, so the two
251
+ * kinds of reference stay distinguishable to the reading agent.
252
+ */
253
+ files?: readonly ExecutionFilePart[]
230
254
  }
231
255
 
232
256
  /**
@@ -262,6 +286,19 @@ function schedulePromptPreamble(context: PromptContext): string | undefined {
262
286
  return `本次执行由任务看板的定时规则自动触发:触发时间 ${stamp}(UTC),规则时区 ${schedule.timeZone},cron 表达式 ${schedule.cron}。需要判断「今天」「现在」或计算时间窗口时,以该时区的触发时间为准。`
263
287
  }
264
288
 
289
+ /**
290
+ * The rework section: this execution continues the card's own conversation
291
+ * because a reviewer sent the previous attempt back. It states both halves the
292
+ * agent must not guess — that the earlier work is the starting point, and what
293
+ * the reviewer actually wants changed — and marks the instruction block with a
294
+ * delimiter pair, so reviewer text cannot pass for board text.
295
+ */
296
+ function reworkPromptPreamble(context: PromptContext): string | undefined {
297
+ const rework = context.rework
298
+ if (rework === undefined) return undefined
299
+ return `本次执行是同一会话上的返工:上一轮的结果被人工审阅打回,请在已完成的工作上继续修改,不要从头重做。返工意见 开始\n${escapeProvenanceDelimiter(rework.instructions)}\n返工意见 结束`
300
+ }
301
+
265
302
  /**
266
303
  * Build the execution prompt for one task.
267
304
  * @param task - the task being launched.
@@ -278,10 +315,16 @@ export function promptText(task: TaskRecord, context: PromptContext = {}): strin
278
315
  // output location), the handover preamble is a per-card note, the scheduled
279
316
  // section states why this run exists, and the task body is the instruction.
280
317
  const tagPreamble = tagPromptPreamble(task)
318
+ // The attachment section names the readable paths of the card's files. It
319
+ // is a section of its own, never folded into the handover preamble.
320
+ const attachmentSection = context.files === undefined ? undefined : attachmentPromptPreamble(context.files)
281
321
  const handoverSection = handoverPreamble
282
322
  const schedulePreamble = schedulePromptPreamble(context)
283
323
  const runPreamble = dispatchPromptPreamble(context)
284
- const preambles = [tagPreamble, handoverSection, schedulePreamble, runPreamble]
324
+ // The rework section sits last: it is the most specific instruction of this
325
+ // run and therefore the one read immediately before the card body.
326
+ const reworkSection = reworkPromptPreamble(context)
327
+ const preambles = [tagPreamble, attachmentSection, handoverSection, schedulePreamble, runPreamble, reworkSection]
285
328
  .filter((part): part is string => part !== undefined)
286
329
  const preamble = preambles.length === 0 ? undefined : preambles.join('\n\n')
287
330
  const freeze = task.freeze
@@ -373,6 +416,19 @@ function invokeWireArgs(namespace: string, method: string, request: Record<strin
373
416
  return { request }
374
417
  }
375
418
 
419
+ /**
420
+ * The optional runtime faces an execution needs beyond the session gateway:
421
+ * the official attachment storage and the model-info reader the image
422
+ * preflight uses. Both are read live, so a deployment that mounts them after
423
+ * the board still gains the capability.
424
+ */
425
+ export interface TaskBoardRuntimeFaces {
426
+ /** The official attachment storage, or undefined when the deployment has none. */
427
+ attachments?: () => TaskBoardAttachmentStore | undefined
428
+ /** The model-info reader, or undefined when the deployment serves no model information. */
429
+ llm?: () => ModelInfoResolver | undefined
430
+ }
431
+
376
432
  export class HostExecutionRunner {
377
433
  /**
378
434
  * Newest event sequence per session whose COMPLETE history walk (reaching
@@ -396,6 +452,7 @@ export class HostExecutionRunner {
396
452
  private readonly workspaceRegistry?: TaskBoardWorkspaceRegistry,
397
453
  unavailableRetry?: { attempts?: number; backoffMs?: number },
398
454
  ownerPeer?: GatewayPeer,
455
+ private readonly faces: TaskBoardRuntimeFaces = {},
399
456
  ) {
400
457
  this.unavailableAttempts = unavailableRetry?.attempts ?? SERVICE_UNAVAILABLE_ATTEMPTS
401
458
  this.unavailableBackoffMs = unavailableRetry?.backoffMs ?? SERVICE_UNAVAILABLE_BACKOFF_MS
@@ -543,6 +600,26 @@ export class HostExecutionRunner {
543
600
  return sessionId
544
601
  }
545
602
 
603
+ /**
604
+ * Queue one follow-up user message into an existing execution session.
605
+ *
606
+ * This is the same `session/prompt` call a launch makes, with none of the
607
+ * launch pins: a follow-up continues a conversation the board already
608
+ * composed, so it must not re-assert the permission, rename the session, or
609
+ * switch the model. The message is queued behind whatever that session is
610
+ * doing, which is what lets a caller reach a run that is still working.
611
+ * @param sessionId - the session the card's execution recorded.
612
+ * @param text - the message to deliver, already validated by the caller.
613
+ */
614
+ async followUp(sessionId: string, text: string): Promise<void> {
615
+ await this.invoke('session', 'prompt', {
616
+ sessionId,
617
+ requestId: 'task-board-follow-up-' + crypto.randomUUID(),
618
+ mode: 'queue' as const,
619
+ content: [{ type: 'text' as const, text }],
620
+ })
621
+ }
622
+
546
623
  /**
547
624
  * Fail closed when a reused session records a different Agent preset than
548
625
  * the one this task pins.
@@ -646,7 +723,17 @@ export class HostExecutionRunner {
646
723
  // never chose one must not gain a model-selection call it did not have.
647
724
  const requestedEffort = normalizeReasoningEffort(task.reasoningEffort)
648
725
  const pinned = HostExecutionRunner.pinnedRoute(task.model)
649
- const route = pinned ?? (requestedEffort === undefined ? undefined : await this.sessionRoute(sessionId, catalog))
726
+ // The card's attachments, resolved afresh for THIS execution: the
727
+ // recorded metadata is never trusted on its own, and a file whose host
728
+ // path is missing or unreadable fails the run instead of being silently
729
+ // dropped.
730
+ const attachments = task.attachments ?? []
731
+ const carriesImages = attachments.some(attachment => attachment.kind === 'image')
732
+ // The route the execution runs at: the card's own pin, or the session's
733
+ // current selection. It is needed for the effort decision AND for the
734
+ // image preflight, which must judge the route the run really uses — a
735
+ // reused session is judged by its CURRENT route, not by the card's pin.
736
+ const route = pinned ?? (requestedEffort === undefined && !carriesImages ? undefined : await this.sessionRoute(sessionId, catalog))
650
737
  if (route !== undefined) {
651
738
  const routeLabel = `${route.provider === undefined ? '' : route.provider + '/'}${route.model}`
652
739
  const decision = resolveReasoningEffort(requestedEffort, catalog, route)
@@ -659,6 +746,15 @@ export class HostExecutionRunner {
659
746
  const declared = declaredRoute(catalog, route)
660
747
  const provider = declared?.provider ?? route.provider
661
748
  const modelId = declared?.model ?? route.model
749
+ // The image preflight runs BEFORE the prompt: a route that declares its
750
+ // input modalities and does not accept an image refuses the run here,
751
+ // so no session is ever prompted with an image it cannot read. A route
752
+ // that declares no modalities is unknown, and an unknown route is
753
+ // allowed — the official model catalog publishes no modality
754
+ // information and must not be used to answer this question.
755
+ if (carriesImages && provider !== undefined && modelId !== undefined) {
756
+ await assertRouteAcceptsImages(this.faces.llm?.(), provider, modelId)
757
+ }
662
758
  try {
663
759
  await this.invoke('session', 'selectModel', {
664
760
  sessionId,
@@ -679,16 +775,40 @@ export class HostExecutionRunner {
679
775
  console.warn(`[dsh-task-board] failed to select model "${provider === undefined ? modelId : provider + '/' + modelId}" for session ${sessionId}, falling back to default:`, modelError)
680
776
  }
681
777
  }
778
+ // The attachments are resolved AFTER the preflight and BEFORE the prompt:
779
+ // an image becomes an image part of the prompt (after the text part), and
780
+ // a file becomes a readable path in a preamble section of its own.
781
+ const resolved = await this.resolveAttachments(attachments)
782
+ const promptContext: PromptContext = resolved.files.length === 0 ? context : { ...context, files: resolved.files }
682
783
  await this.invoke('session', 'prompt', {
683
784
  sessionId,
684
785
  requestId: 'task-board-' + crypto.randomUUID(),
685
786
  mode: 'queue' as const,
686
- content: [{ type: 'text' as const, text: promptText(task, context) }],
787
+ content: [
788
+ { type: 'text' as const, text: promptText(task, promptContext) },
789
+ ...resolved.images,
790
+ ],
687
791
  })
688
- const armed = await this.armGoal(sessionId, task, context, goalEnabled)
792
+ const armed = await this.armGoal(sessionId, task, promptContext, goalEnabled)
689
793
  onGoalArmed?.(armed)
690
794
  }
691
795
 
796
+ /**
797
+ * Resolve a card's attachments for one execution.
798
+ *
799
+ * A card without attachments resolves to nothing, even in a deployment that
800
+ * serves no attachment storage at all. A card WITH attachments cannot run
801
+ * without the storage: the run fails with a readable reason instead of
802
+ * silently dropping the attachment and running the card as if it carried
803
+ * none.
804
+ */
805
+ private async resolveAttachments(attachments: readonly TaskAttachment[]): Promise<ResolvedAttachments> {
806
+ if (attachments.length === 0) return { images: [], files: [] }
807
+ const store = this.faces.attachments?.()
808
+ if (store === undefined) throw new Error('this deployment serves no attachment storage')
809
+ return await resolveExecutionAttachments(store, attachments)
810
+ }
811
+
692
812
  /**
693
813
  * Read the host's model catalog: the default route an unconfigured session
694
814
  * starts at, and each provider's models with the reasoning metadata its
@@ -11,12 +11,20 @@ import { LIANGSHEN_PRESET_ID } from './core/subtask.ts'
11
11
  import { workspaceOwningSession } from './core/workspace-target.ts'
12
12
  import { PowerInhibitor } from './power-inhibitor.ts'
13
13
  import { TASK_BOARD_SCHEMA_VERSION, type TaskBoardAction, type TaskBoardEventPayload, type TaskBoardSnapshot } from './protocol.ts'
14
+ import { projectSnapshotForWire } from './core/wire-projection.ts'
14
15
  import type { CardDefaults } from './core/card-defaults.ts'
15
16
  import { TaskBoardExtensionRegistry } from './host/extension-registry.ts'
16
17
  import type { TaskBoardExtension } from './core/extension.ts'
17
18
  import { isTaskPermission, normalizeTargetId, type ExecutionOutcome, type ExecutionSummary, type ScheduleMode, type TaskRecord, type TaskStatus } from './core/tasks.ts'
18
19
  import { passedAttempt, resolveContract, verificationNeverInvoked, verificationOnlyInvalid, verificationRequired, withAcceptanceDetailCleared, type ExecutionVerification, type ModelCatalogView, type VerificationContract, type VerificationSettings } from './core/verification.ts'
19
20
  import type { TaskPermission } from './core/handover.ts'
21
+ import type { TaskAttachment } from './core/attachment.ts'
22
+ import {
23
+ publishedAttachmentLimits,
24
+ verifyAttachments,
25
+ type ModelInfoResolver,
26
+ type TaskBoardAttachmentStore,
27
+ } from './host/attachments.ts'
20
28
 
21
29
  /** Ceiling for the roster-poll failure backoff: a broken session tree is retried at most once a minute. */
22
30
  const POLL_FAILURE_MAX_BACKOFF_MS = 60_000
@@ -48,6 +56,14 @@ const UNREADABLE_SETTLE_POLLS = 24
48
56
  */
49
57
  const ABANDONED_LAUNCH_REASON = 'host stopped before this execution started'
50
58
 
59
+ /**
60
+ * Why a rework could not launch: it redoes work in the card's own
61
+ * conversation, so a session the Host cannot continue means there is nothing to
62
+ * send the reviewer's instructions into. Starting a fresh conversation instead
63
+ * would hand those instructions to an agent that never saw the work.
64
+ */
65
+ const REWORK_SESSION_REASON = 'rework: the card\'s previous execution session is not present and idle in the host session roster, so there is no conversation to send the rework instructions into'
66
+
51
67
  /**
52
68
  * The acceptance contract one run group freezes, read once for the whole group.
53
69
  *
@@ -194,6 +210,7 @@ const ACTION_KINDS: Readonly<Record<TaskBoardAction['kind'], true>> = {
194
210
  'set-schedule': true,
195
211
  run: true,
196
212
  rerun: true,
213
+ rework: true,
197
214
  'confirm-permission': true,
198
215
  'set-parent': true,
199
216
  'rename-tag': true,
@@ -201,10 +218,24 @@ const ACTION_KINDS: Readonly<Record<TaskBoardAction['kind'], true>> = {
201
218
  'extension-action': true,
202
219
  }
203
220
 
221
+ /**
222
+ * The attachments an action carries, or undefined when it carries none.
223
+ *
224
+ * Only a create and an update can carry attachments: an import refuses them
225
+ * outright, and every other action kind has no attachment surface at all.
226
+ */
227
+ function attachmentsOfAction(action: Exclude<TaskBoardAction, { kind: 'extension-action' }>): TaskAttachment[] | undefined {
228
+ if (action.kind === 'create') return action.input.attachments
229
+ if (action.kind === 'update') return action.patch.attachments ?? undefined
230
+ return undefined
231
+ }
232
+
204
233
  export class TaskBoardHostService {
205
234
  readonly ledger: HostTaskLedger
206
235
  readonly runner: HostExecutionRunner
207
236
  readonly power: PowerInhibitor
237
+ /** The official attachment storage, read live so a late mount is honoured. */
238
+ private readonly attachmentStore: () => TaskBoardAttachmentStore | undefined
208
239
  private readonly listeners = new Set<() => void>()
209
240
  /** The one recurring timer: the session-roster poll. */
210
241
  private pollTimer: (() => void) | undefined
@@ -327,6 +358,18 @@ export class TaskBoardHostService {
327
358
  * no readable usage ledger. Defaults to the family usage ledger reader.
328
359
  */
329
360
  spendUsedToday?: (now: number) => number | undefined
361
+ /**
362
+ * The official attachment storage, read at request time. Absent means the
363
+ * deployment stores no attachments: every attachment action is then
364
+ * refused and the board publishes no attachment limits.
365
+ */
366
+ attachments?: () => TaskBoardAttachmentStore | undefined
367
+ /**
368
+ * The model-info reader the image preflight uses. Absent means the
369
+ * deployment serves no model information, and a route whose modalities are
370
+ * unknown is allowed.
371
+ */
372
+ modelInfo?: () => ModelInfoResolver | undefined
330
373
  } = {}) {
331
374
  this.ledger = options.ledger ?? new HostTaskLedger(undefined, undefined, {
332
375
  sessionDefaultPermission: options.sessionDefaultPermission,
@@ -335,7 +378,11 @@ export class TaskBoardHostService {
335
378
  spendBudgetTokens: options.spendBudgetTokens,
336
379
  spendUsedToday: options.spendUsedToday,
337
380
  })
338
- this.runner = new HostExecutionRunner(gateway, options.commandDispatcher, options.workspaceRegistry, undefined, options.ownerPeer)
381
+ this.attachmentStore = options.attachments ?? (() => undefined)
382
+ this.runner = new HostExecutionRunner(gateway, options.commandDispatcher, options.workspaceRegistry, undefined, options.ownerPeer, {
383
+ attachments: this.attachmentStore,
384
+ llm: options.modelInfo,
385
+ })
339
386
  this.workspaceRegistry = options.workspaceRegistry
340
387
  this.timers = options.timers ?? PROCESS_TIMERS
341
388
  this.power = options.power ?? new PowerInhibitor()
@@ -353,6 +400,15 @@ export class TaskBoardHostService {
353
400
  // Capability writes go through the board's own action path, so every
354
401
  // board gate (content freeze, running lock, permission gate) still holds.
355
402
  apply: (action, initiator) => this.applyBoardAction(crypto.randomUUID(), action, initiator),
403
+ // Delivery into a run the board already owns is the runner's session wire
404
+ // call, never a second execution path.
405
+ followUp: (sessionId, text) => this.runner.followUp(sessionId, text),
406
+ // A rework is a run request like any other: it opens its execution through
407
+ // the same action path, so the running lock, the permission confirmation,
408
+ // the acceptance contract and the spend cap all apply to it.
409
+ rework: (taskId, instructions, initiator) => {
410
+ this.applyBoardAction(crypto.randomUUID(), { kind: 'rework', taskId, instructions }, initiator)
411
+ },
356
412
  now: this.now,
357
413
  })
358
414
  installStreamErrorGuards()
@@ -433,11 +489,20 @@ export class TaskBoardHostService {
433
489
  this.emit()
434
490
  }
435
491
 
492
+ /**
493
+ * The board's published snapshot.
494
+ *
495
+ * Every read path serializes this object — the HTTP `state` answer, the
496
+ * `action` answer through {@link apply}, and the remote bridge's
497
+ * `board.snapshot` — so a provider's integration credentials are stripped
498
+ * once, here, instead of at each exit. The ledger keeps them verbatim for the
499
+ * provider's own in-process read.
500
+ */
436
501
  snapshot(): TaskBoardSnapshot {
437
502
  const state = this.ledger.state()
438
503
  const published = this.extensions.published()
439
504
  const cardDefaults = cardDefaultsOf(this.cardDefaults())
440
- return {
505
+ return projectSnapshotForWire({
441
506
  schemaVersion: TASK_BOARD_SCHEMA_VERSION,
442
507
  revision: state.revision,
443
508
  tasks: state.tasks,
@@ -453,8 +518,11 @@ export class TaskBoardHostService {
453
518
  // is: the create dialog prefills from them, and each creating session
454
519
  // re-reads them for the create it submits.
455
520
  ...(cardDefaults === undefined ? {} : { cardDefaults }),
521
+ // The attachment limits travel with the snapshot so the browser can
522
+ // refuse an oversized selection before it uploads anything.
523
+ ...(this.attachmentStore() === undefined ? {} : { attachmentLimits: publishedAttachmentLimits(this.attachmentStore()) }),
456
524
  ...(Object.keys(published).length === 0 ? {} : { extensions: published }),
457
- }
525
+ })
458
526
  }
459
527
 
460
528
  /**
@@ -527,6 +595,43 @@ export class TaskBoardHostService {
527
595
  return { ...action, input: { ...input, workspaceId } }
528
596
  }
529
597
 
598
+ /**
599
+ * Apply an action whose attachments the Host proved against the official
600
+ * storage first.
601
+ *
602
+ * This is the board's trust boundary for attachment metadata: the browser
603
+ * asserts the size, the type and the digest of every object it uploaded, and
604
+ * the Host reads the stored objects back (an image is compared, a file is
605
+ * streamed and its digest recomputed) before the ledger commits the claim.
606
+ * An attachment the storage cannot prove is refused, so a spoofed client
607
+ * claim never becomes a stored fact.
608
+ */
609
+ async applyVerified(requestId: string, action: TaskBoardAction, initiator?: string): Promise<TaskBoardSnapshot> {
610
+ if (!this.active) throw new Error('task board is disabled')
611
+ // A provider action never carries attachments: it is routed through the
612
+ // registry exactly like every other extension call.
613
+ if (action.kind === 'extension-action') return await this.apply(requestId, action, initiator)
614
+ await this.verifyActionAttachments(action)
615
+ return projectSnapshotForWire(this.applyBoardAction(requestId, action, initiator, true))
616
+ }
617
+
618
+ /**
619
+ * Prove every attachment of an action against the official storage.
620
+ *
621
+ * An action without attachments is untouched: the board keeps working in a
622
+ * deployment that serves no attachment storage at all.
623
+ */
624
+ private async verifyActionAttachments(action: Exclude<TaskBoardAction, { kind: 'extension-action' }>): Promise<void> {
625
+ const attachments = attachmentsOfAction(action)
626
+ if (attachments === undefined || attachments.length === 0) return
627
+ const store = this.attachmentStore()
628
+ if (store === undefined) throw new Error('this deployment serves no attachment storage')
629
+ // The failure keeps its CLASS: a storage that is unavailable must reach
630
+ // the caller as "the storage is unavailable" (503), not as a generic
631
+ // rejected action (400).
632
+ await verifyAttachments(store, attachments)
633
+ }
634
+
530
635
  apply(requestId: string, action: Extract<TaskBoardAction, { kind: 'extension-action' }>, initiator?: string): Promise<TaskBoardSnapshot>
531
636
  apply(requestId: string, action: Exclude<TaskBoardAction, { kind: 'extension-action' }>, initiator?: string): TaskBoardSnapshot
532
637
  apply(requestId: string, action: TaskBoardAction, initiator?: string): TaskBoardSnapshot | Promise<TaskBoardSnapshot>
@@ -547,7 +652,10 @@ export class TaskBoardHostService {
547
652
  if (action.kind === 'extension-action') {
548
653
  return this.handleExtensionAction(action)
549
654
  }
550
- return this.applyBoardAction(requestId, action, initiator)
655
+ // The answer to a write is a read like any other — it crosses the same wire
656
+ // (the HTTP action route and the remote bridge's board.apply) — so it leaves
657
+ // through the same projection as snapshot().
658
+ return projectSnapshotForWire(this.applyBoardAction(requestId, action, initiator))
551
659
  }
552
660
 
553
661
  /**
@@ -555,9 +663,16 @@ export class TaskBoardHostService {
555
663
  * calls and the same-origin wire both land here, so the two surfaces can
556
664
  * never disagree about a card.
557
665
  */
558
- private applyBoardAction(requestId: string, action: Exclude<TaskBoardAction, { kind: 'extension-action' }>, initiator?: string): TaskBoardSnapshot {
666
+ private applyBoardAction(requestId: string, action: Exclude<TaskBoardAction, { kind: 'extension-action' }>, initiator?: string, attachmentVerified = false): TaskBoardSnapshot {
667
+ // Attachments reach the ledger only through the VERIFIED action path: the
668
+ // in-process capability face, the agent tools and the legacy import never
669
+ // carry them, and an action that does is refused here rather than
670
+ // committed without the storage proof.
671
+ if (!attachmentVerified && attachmentsOfAction(action) !== undefined) {
672
+ throw new Error('attachments must be applied through the verified attachment action route')
673
+ }
559
674
  const before = this.statusMap()
560
- if (action.kind === 'run' || action.kind === 'rerun') this.assertSpendCap()
675
+ if (action.kind === 'run' || action.kind === 'rerun' || action.kind === 'rework') this.assertSpendCap()
561
676
  const result = this.ledger.applyRequest(requestId, this.withInheritedWorkspace(action, initiator), initiator)
562
677
  if (result.runs !== undefined) this.dispatchRuns(result.runs)
563
678
  // A committed write that can move a rule moves the nearest trigger;
@@ -657,13 +772,24 @@ export class TaskBoardHostService {
657
772
  // never rewritten by it.
658
773
  const forcedPreset = this.ledger.hasOutstandingDescendants(opened.task.id) ? LIANGSHEN_PRESET_ID : undefined
659
774
  const descendants = forcedPreset === undefined ? [] : this.ledger.outstandingDescendants(opened.task.id)
775
+ // The rework this execution carries, when it carries one: it decides both
776
+ // the session this run continues in and the section the prompt states.
777
+ const rework = opened.execution.rework
660
778
  // A forced preset is not the card's own composition, so continuing a
661
779
  // session composed from another preset would be refused anyway: mint a
662
- // fresh one and run the tree the way this execution requires.
663
- const reuseSessionId = forcedPreset === undefined ? await this.reuseSessionFor(opened.task) : undefined
780
+ // fresh one and run the tree the way this execution requires. A rework
781
+ // has no such freedom — its whole point is the conversation the reviewer
782
+ // read — so it fails instead of quietly opening a new one.
783
+ let reuseSessionId: string | undefined
784
+ if (rework === undefined) {
785
+ reuseSessionId = forcedPreset === undefined ? await this.reuseSessionFor(opened.task) : undefined
786
+ } else {
787
+ if (forcedPreset !== undefined) throw new Error(REWORK_SESSION_REASON)
788
+ reuseSessionId = await this.reworkSessionFor(opened.task)
789
+ }
664
790
  // A cron-triggered run additionally states its own firing instant and
665
791
  // rule zone, so a scheduled job can resolve "today" without guessing.
666
- const promptContext = descendants.length === 0 && schedule === undefined ? undefined : {
792
+ const contextParts = {
667
793
  ...(descendants.length === 0 ? {} : {
668
794
  descendants: descendants.map(descendant => ({
669
795
  id: descendant.id,
@@ -672,7 +798,9 @@ export class TaskBoardHostService {
672
798
  })),
673
799
  }),
674
800
  ...(schedule === undefined ? {} : { schedule }),
801
+ ...(rework === undefined ? {} : { rework }),
675
802
  }
803
+ const promptContext = Object.keys(contextParts).length === 0 ? undefined : contextParts
676
804
  // Freeze this execution's acceptance contract BEFORE the session is
677
805
  // prompted: a settings change made while the run is in flight must not
678
806
  // retrofit the rule that will judge it. A card that opted out resolves the
@@ -860,10 +988,13 @@ export class TaskBoardHostService {
860
988
  * reads no roster at all, and a read that fails mints a fresh conversation
861
989
  * exactly as an unknown roster always did.
862
990
  * @param task - the task about to run.
991
+ * @param force - continue the settled session regardless of the card's own
992
+ * opt-in (a rework), which the reuse rule accepts without waiving any of its
993
+ * evidence conditions.
863
994
  * @returns the session id to continue in, or undefined for a fresh session.
864
995
  */
865
- private async reuseSessionFor(task: TaskRecord): Promise<string | undefined> {
866
- if (task.reuseSession !== true) return undefined
996
+ private async reuseSessionFor(task: TaskRecord, force?: boolean): Promise<string | undefined> {
997
+ if (task.reuseSession !== true && force !== true) return undefined
867
998
  let running: Awaited<ReturnType<HostExecutionRunner['listRunning']>>
868
999
  try {
869
1000
  running = await this.runner.listRunning()
@@ -875,7 +1006,29 @@ export class TaskBoardHostService {
875
1006
  return undefined
876
1007
  }
877
1008
  if (!running.known) return undefined
878
- return reusableSessionId(task, new Set(running.items.filter(item => !item.running).map(item => item.sessionId)))
1009
+ return reusableSessionId(
1010
+ task,
1011
+ new Set(running.items.filter(item => !item.running).map(item => item.sessionId)),
1012
+ force === true ? { force: true } : {},
1013
+ )
1014
+ }
1015
+
1016
+ /**
1017
+ * The session a rework continues, or the refusal that says why it cannot.
1018
+ *
1019
+ * A rework exists for one conversation — the one the reviewer read before
1020
+ * sending the work back — so the evidence that this Host still reaches it is
1021
+ * required, exactly as it is for a card that opted into reuse. What a rework
1022
+ * does NOT get is the fresh-conversation fallback: launching there would hand
1023
+ * the reviewer's instructions to an agent that never saw the work, so the run
1024
+ * fails with a readable reason instead.
1025
+ * @param task - the card being reworked.
1026
+ * @returns the session id this rework continues in.
1027
+ */
1028
+ private async reworkSessionFor(task: TaskRecord): Promise<string> {
1029
+ const sessionId = await this.reuseSessionFor(task, true)
1030
+ if (sessionId === undefined) throw new Error(REWORK_SESSION_REASON)
1031
+ return sessionId
879
1032
  }
880
1033
 
881
1034
  /** Reuse the session list this poll already fetched: one list RPC per tick, not 1 + E. */
package/src/index.ts CHANGED
@@ -40,6 +40,7 @@ import type { CardDefaults } from './core/card-defaults.ts'
40
40
  import { buildTaskBoardTools, TASK_BOARD_TOOL_NAMES } from './host/agent-tools.ts'
41
41
  import { PLUGIN_TOOL_SECTION_ORDERS, visibleToolText } from './tool-surface.ts'
42
42
  import { makeTaskBoardRoutes, type TaskBoardConnectionTrust } from './host-routes.ts'
43
+ import type { ModelInfoResolver, TaskBoardAttachmentStore } from './host/attachments.ts'
43
44
  import { TASK_BOARD_SERVICE_NAME, type TaskBoardExtension } from './core/extension.ts'
44
45
  import type { TaskBoardAction } from './protocol.ts'
45
46
  import { mountOnce } from './mount-once.ts'
@@ -511,6 +512,49 @@ export function resolveLlmRuntime(ctx: Context): LlmRuntime | undefined {
511
512
  }
512
513
  }
513
514
 
515
+ /**
516
+ * Resolve the optional attachment storage.
517
+ *
518
+ * The board does not inject the service: a deployment without one must still
519
+ * mount the board, and every attachment surface then answers with a typed
520
+ * "storage unavailable" failure instead of the plugin failing to load.
521
+ * @param ctx - the plugin context.
522
+ * @returns the attachment storage, or undefined when this deployment serves none.
523
+ */
524
+ export function resolveAttachmentStore(ctx: Context): TaskBoardAttachmentStore | undefined {
525
+ try {
526
+ const store = ctx.get('attachments') as TaskBoardAttachmentStore | undefined
527
+ return store !== undefined && typeof store.saveImage === 'function' ? store : undefined
528
+ } catch {
529
+ return undefined
530
+ }
531
+ }
532
+
533
+ /**
534
+ * The model-info reader the image preflight uses.
535
+ *
536
+ * It asks the OFFICIAL model service about one exact route. The model catalog
537
+ * the board already publishes carries no modality information and must not be
538
+ * used to answer that question: only the model's own declared input
539
+ * modalities can refuse an image route, and a route whose modalities cannot be
540
+ * read is UNKNOWN and therefore allowed.
541
+ * @param ctx - the plugin context.
542
+ * @returns the reader, or undefined when the deployment serves no model service.
543
+ */
544
+ export function resolveModelInfoReader(ctx: Context): ModelInfoResolver | undefined {
545
+ return async (provider: string, model: string): Promise<{ inputModalities?: readonly string[] } | undefined> => {
546
+ const llm = resolveLlmRuntime(ctx)
547
+ if (llm === undefined) return undefined
548
+ try {
549
+ const info = await llm.resolveModelInfo(provider, model)
550
+ return { ...(info.inputModalities === undefined ? {} : { inputModalities: info.inputModalities }) }
551
+ } catch (error) {
552
+ console.warn('[dsh-task-board] could not resolve the model info of ' + provider + '/' + model + '; the image preflight allows the route', error)
553
+ return undefined
554
+ }
555
+ }
556
+ }
557
+
514
558
  /**
515
559
  * The subset of `sessionController` the board uses to wake a cold persisted
516
560
  * session before running a slash command on it (issue #1861).
@@ -681,6 +725,8 @@ function applyImpl(ctx: Context, config?: Config): void {
681
725
  cardDefaults,
682
726
  verificationSettings,
683
727
  verificationCatalog,
728
+ attachments: () => resolveAttachmentStore(ctx),
729
+ modelInfo: () => resolveModelInfoReader(ctx),
684
730
  timers: resolveHostTimers(ctx),
685
731
  commandDispatcher: {
686
732
  async execute(sessionId, line, signal) {
@@ -811,6 +857,7 @@ function applyImpl(ctx: Context, config?: Config): void {
811
857
  ...resolveProxyAccess(config),
812
858
  connection: () => resolveConnectionTrust(ctx),
813
859
  }, {
860
+ attachments: () => resolveAttachmentStore(ctx),
814
861
  parseTask: async (request, signal) => {
815
862
  const llm = resolveLlmRuntime(ctx)
816
863
  if (llm === undefined) throw new TaskParseError('no-model', 'this deployment serves no llm service')