@fish-under-sea/dsh-client-ui-task-board-fish 1.0.2 → 2.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 (125) hide show
  1. package/NOTICE +1 -1
  2. package/README.en.md +6 -4
  3. package/README.md +6 -4
  4. package/README.zh.md +6 -4
  5. package/icon.png +0 -0
  6. package/lib/client.js +4428 -1508
  7. package/lib/client.js.map +1 -1
  8. package/lib/index.js +2670 -496
  9. package/lib/types/client/CardDefaultPresetField.d.ts +35 -0
  10. package/lib/types/client/PluginSettingsCard.d.ts +130 -19
  11. package/lib/types/client/RangeBubble.d.ts +46 -0
  12. package/lib/types/client/SegmentGroup.d.ts +28 -0
  13. package/lib/types/client/TaskBoardSettingsCard.d.ts +63 -0
  14. package/lib/types/client/board/AttachmentField.d.ts +70 -0
  15. package/lib/types/client/board/ExecutionLog.d.ts +24 -0
  16. package/lib/types/client/board/ReasoningEffortField.d.ts +25 -0
  17. package/lib/types/client/board/TaskForm.d.ts +4 -0
  18. package/lib/types/client/board/VerificationReport.d.ts +2 -15
  19. package/lib/types/client/board/model-options.d.ts +87 -0
  20. package/lib/types/client/board/preset-label.d.ts +21 -0
  21. package/lib/types/client/board/preset-roster.d.ts +45 -0
  22. package/lib/types/client/board/source-group.d.ts +27 -0
  23. package/lib/types/client/body-mutations.d.ts +45 -0
  24. package/lib/types/client/host-api.d.ts +25 -0
  25. package/lib/types/client/locales.d.ts +87 -9
  26. package/lib/types/client/pending-verify.d.ts +47 -0
  27. package/lib/types/client/plugin-card-seat.d.ts +3 -1
  28. package/lib/types/client/service.d.ts +4 -1
  29. package/lib/types/client/settings-form.d.ts +73 -51
  30. package/lib/types/core/attachment.d.ts +132 -0
  31. package/lib/types/core/card-defaults.d.ts +78 -0
  32. package/lib/types/core/controller.d.ts +57 -8
  33. package/lib/types/core/execution-summary.d.ts +52 -0
  34. package/lib/types/core/extension.d.ts +116 -0
  35. package/lib/types/core/launch-width.d.ts +31 -0
  36. package/lib/types/core/reasoning-effort.d.ts +57 -0
  37. package/lib/types/core/session-reuse.d.ts +7 -1
  38. package/lib/types/core/spend-budget.d.ts +28 -0
  39. package/lib/types/core/subtask.d.ts +100 -37
  40. package/lib/types/core/tasks.d.ts +94 -10
  41. package/lib/types/core/use-cases/task-create.d.ts +10 -5
  42. package/lib/types/core/use-cases/task-tag.d.ts +36 -0
  43. package/lib/types/core/use-cases/task-update.d.ts +22 -1
  44. package/lib/types/core/wire-projection.d.ts +35 -0
  45. package/lib/types/core/workspace-target.d.ts +23 -3
  46. package/lib/types/host/attachments.d.ts +250 -0
  47. package/lib/types/host/extension-registry.d.ts +40 -0
  48. package/lib/types/host/launch-admission.d.ts +71 -0
  49. package/lib/types/host-ledger.d.ts +114 -47
  50. package/lib/types/host-routes.d.ts +63 -0
  51. package/lib/types/host-runner.d.ts +164 -18
  52. package/lib/types/host-service.d.ts +182 -46
  53. package/lib/types/host-spend.d.ts +52 -0
  54. package/lib/types/index.d.ts +173 -54
  55. package/lib/types/loopback.d.ts +41 -1
  56. package/lib/types/protocol.d.ts +52 -11
  57. package/lib/types/tool-surface.d.ts +1 -0
  58. package/locale/en.json +6 -0
  59. package/locale/zh.json +6 -0
  60. package/package.json +36 -29
  61. package/src/client/CardDefaultPresetField.tsx +101 -0
  62. package/src/client/PluginSettingsCard.tsx +385 -111
  63. package/src/client/RangeBubble.tsx +164 -0
  64. package/src/client/SegmentGroup.tsx +93 -0
  65. package/src/client/TaskBoardSettingsCard.tsx +332 -37
  66. package/src/client/board/AttachmentField.tsx +383 -0
  67. package/src/client/board/EditTaskModal.tsx +63 -0
  68. package/src/client/board/ExecutionLog.tsx +154 -0
  69. package/src/client/board/LinkSubtaskModal.tsx +1 -1
  70. package/src/client/board/NewTaskModal.tsx +154 -45
  71. package/src/client/board/ReasoningEffortField.tsx +50 -0
  72. package/src/client/board/TagManagerModal.tsx +151 -2
  73. package/src/client/board/TaskBoard.tsx +47 -10
  74. package/src/client/board/TaskCard.tsx +45 -23
  75. package/src/client/board/TaskDetail.tsx +468 -258
  76. package/src/client/board/TaskForm.tsx +19 -4
  77. package/src/client/board/VerificationReport.tsx +143 -104
  78. package/src/client/board/model-options.ts +208 -0
  79. package/src/client/board/preset-label.ts +32 -0
  80. package/src/client/board/preset-roster.ts +58 -0
  81. package/src/client/board/source-group.ts +94 -0
  82. package/src/client/board/task-markdown.module.css +11 -8
  83. package/src/client/board-settings.module.css +35 -7
  84. package/src/client/board.module.css +1044 -105
  85. package/src/client/body-mutations.ts +133 -0
  86. package/src/client/host-api.ts +70 -0
  87. package/src/client/index.ts +109 -95
  88. package/src/client/locales.ts +205 -48
  89. package/src/client/pending-verify.ts +90 -0
  90. package/src/client/plugin-card-seat.ts +8 -2
  91. package/src/client/service.ts +24 -0
  92. package/src/client/settings-card.module.css +466 -89
  93. package/src/client/settings-entry-form.ts +0 -1
  94. package/src/client/settings-form.ts +102 -60
  95. package/src/core/attachment.ts +287 -0
  96. package/src/core/card-defaults.ts +132 -0
  97. package/src/core/controller.ts +90 -11
  98. package/src/core/execution-summary.ts +96 -0
  99. package/src/core/extension.ts +120 -0
  100. package/src/core/launch-width.ts +38 -0
  101. package/src/core/reasoning-effort.ts +92 -0
  102. package/src/core/session-reuse.ts +7 -1
  103. package/src/core/spend-budget.ts +35 -0
  104. package/src/core/store.ts +19 -1
  105. package/src/core/subtask.ts +144 -68
  106. package/src/core/tasks.ts +117 -10
  107. package/src/core/use-cases/task-create.ts +27 -16
  108. package/src/core/use-cases/task-tag.ts +56 -0
  109. package/src/core/use-cases/task-update.ts +33 -5
  110. package/src/core/wire-projection.ts +81 -0
  111. package/src/core/workspace-target.ts +27 -3
  112. package/src/host/agent-tools.ts +33 -21
  113. package/src/host/attachments.ts +650 -0
  114. package/src/host/extension-registry.ts +150 -5
  115. package/src/host/launch-admission.ts +139 -0
  116. package/src/host-ledger.ts +248 -117
  117. package/src/host-routes.ts +233 -15
  118. package/src/host-runner.ts +395 -61
  119. package/src/host-service.ts +512 -139
  120. package/src/host-spend.ts +105 -0
  121. package/src/index.ts +312 -92
  122. package/src/loopback.ts +57 -1
  123. package/src/protocol.ts +83 -18
  124. package/src/tool-surface.ts +1 -0
  125. package/icon.svg +0 -3
@@ -1,11 +1,24 @@
1
- import type { TypertGateway } from '@deepseek-ai/dsh-api-gateway'
2
- import type { PeerScope } from '@deepseek-ai/dsh-client-connection'
1
+ import { Context } from '@deepseek-ai/cordis'
2
+ import type { InvokeRemoteRequest, TypertGateway } from '@deepseek-ai/dsh-api-gateway'
3
3
  import type { SessionAddress, SessionHistoryRecord, SessionListValue, SessionPage, SessionSummary } from '@deepseek-ai/dsh-api-session-controller/types'
4
4
  import type { CommandResult } from '@deepseek-ai/dsh-commands/types'
5
5
  import type { Workspace } from '@deepseek-ai/dsh-workspace/types'
6
- import { teammateName } from './core/subtask.ts'
7
- import { mostRecentWorkspaceId } from './core/workspace-target.ts'
8
- import type { TaskPermission, TaskRecord } from './core/tasks.ts'
6
+ import { LEGACY_AGENT_TEAMS_REASON, LIANGSHEN_PRESET_ID } from './core/subtask.ts'
7
+ import { MISSING_WORKSPACE_REASON, mostRecentWorkspaceId } from './core/workspace-target.ts'
8
+ import { declaredRoute, normalizeReasoningEffort, resolveReasoningEffort, type ReasoningRoute } from './core/reasoning-effort.ts'
9
+ import type { ModelCatalogView } from './core/verification.ts'
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'
21
+ import { executionSummaryOf } from './core/execution-summary.ts'
9
22
 
10
23
  /**
11
24
  * Host services needed to validate a task's workspace before creating a
@@ -15,14 +28,69 @@ export interface TaskBoardWorkspaceRegistry {
15
28
  list(): readonly Workspace[]
16
29
  }
17
30
 
31
+ /**
32
+ * The peer every gateway request names: derived from the public
33
+ * `InvokeRemoteRequest` type so this package needs no direct dependency on
34
+ * `@deepseek-ai/dsh-typert-protocol` for the shape.
35
+ */
36
+ export type GatewayPeer = InvokeRemoteRequest['peer']
37
+
18
38
  interface GatewayRequest {
19
39
  namespace: string
20
40
  method: string
21
41
  args: Record<string, unknown>
22
- peer?: PeerScope
42
+ peer: GatewayPeer
23
43
  signal?: AbortSignal
24
44
  }
25
45
 
46
+ /**
47
+ * Mint the in-process owner peer this plugin's Host calls speak for.
48
+ *
49
+ * The 0.2.1 gateway made `peer` mandatory on every request, and the
50
+ * authorization layer reads only `peer.principal`: a principal of
51
+ * `{ kind: 'owner' }` is how host-local code states that the call IS the local
52
+ * user driving their own Host, so the gateway answers it directly instead of
53
+ * running a remote-access decision (only non-owner principals are judged).
54
+ * That is exactly the task board's position — it creates, renames, prompts,
55
+ * and reads sessions as the Host itself, which before 0.2.1 was the implicit
56
+ * privilege of every in-process caller. The board claims owner explicitly, and
57
+ * only ever inside its own Host process: no wire field can set a principal,
58
+ * and this plugin never forwards a browser-supplied one.
59
+ *
60
+ * `interactions` stays `'none'`: the board only invokes methods and opens the
61
+ * short `session/follow` stream. The gateway's interactions check gates
62
+ * exactly the forwarded-event endpoints (opening an event stream, answering a
63
+ * waterfall), which this caller never touches; an `'answer'` peer would
64
+ * additionally receive forwarded Host events, a capability the board neither
65
+ * needs nor wants.
66
+ *
67
+ * The peer's signal aborts once `ctx` disposes, so streams opened for it end
68
+ * with the plugin fiber, and `dispose()` is idempotent with racing calls
69
+ * sharing one completion. The id carries no credential — the protocol fixes
70
+ * `principal` as the only identity persisted in a session log — so a fresh
71
+ * unique id per mount is sufficient.
72
+ */
73
+ export function createOwnerPeer(ctx: Context): GatewayPeer {
74
+ const controller = new AbortController()
75
+ let completion: Promise<void> | undefined
76
+ const peer: GatewayPeer = {
77
+ id: `task-board-owner:${crypto.randomUUID()}` as GatewayPeer['id'],
78
+ ctx,
79
+ principal: { kind: 'owner' },
80
+ signal: controller.signal,
81
+ interactions: 'none',
82
+ dispose() {
83
+ if (completion === undefined) {
84
+ controller.abort()
85
+ completion = Promise.resolve()
86
+ }
87
+ return completion
88
+ },
89
+ }
90
+ ctx.effect(() => () => { void peer.dispose() }, 'task-board owner peer')
91
+ return peer
92
+ }
93
+
26
94
  interface SessionGateway {
27
95
  invoke(request: GatewayRequest): Promise<unknown>
28
96
  stream?(request: GatewayRequest): Promise<AsyncIterable<unknown>>
@@ -112,9 +180,9 @@ export type ExecutionInspection =
112
180
  * forever.
113
181
  */
114
182
  | { outcome: 'pending'; unreadable?: true; reason?: string }
115
- | { outcome: 'succeeded' }
116
- | { outcome: 'failed'; error: string }
117
- | { outcome: 'cancelled'; error: string }
183
+ | { outcome: 'succeeded'; summary?: ExecutionSummary }
184
+ | { outcome: 'failed'; error: string; summary?: ExecutionSummary }
185
+ | { outcome: 'cancelled'; error: string; summary?: ExecutionSummary }
118
186
 
119
187
  /** A post-create launch failure that still identifies the session to the ledger. */
120
188
  export class SessionLaunchError extends Error {
@@ -144,22 +212,24 @@ function escapeProvenanceDelimiter(value: string): string {
144
212
  * first, the provenance wrap then encloses the instruction. Plain tasks (no
145
213
  * freeze) keep the bare handover preamble + prompt.
146
214
  */
147
- /** One other execution member of a run, as named in the launched task's prompt. */
148
- export interface PromptPeer {
149
- /** Task id of the member. */
215
+ /** One unfinished subtask the launched card's own agent has to dispatch. */
216
+ export interface PromptDescendant {
217
+ /** Task id of the subtask card. */
150
218
  id: string
151
- /** Member title. */
219
+ /** Subtask title. */
152
220
  title: string
153
- /** Teammate name when this member runs as a teammate. */
154
- name?: string
221
+ /** Its column, so the run can tell a fresh card from one already failed before. */
222
+ status: string
155
223
  }
156
224
 
157
225
  /** Execution-shape context appended to the launched task's prompt. */
158
226
  export interface PromptContext {
159
- /** The other members this run opens, excluding the launched task itself. */
160
- peers?: readonly PromptPeer[]
161
- /** True when those members run as teammates inside this session (Team Lead). */
162
- team?: boolean
227
+ /**
228
+ * The card's outstanding descendants. Present exactly when this run is an
229
+ * autonomous dispatch: the Host opens no session for them, so this session
230
+ * reads them and dispatches subagents itself.
231
+ */
232
+ descendants?: readonly PromptDescendant[]
163
233
  /**
164
234
  * Scheduled-run provenance: the instant the rule actually fired, its kind,
165
235
  * and the IANA zone its wall clock was read in. Present only for a
@@ -167,22 +237,35 @@ export interface PromptContext {
167
237
  * run's own terms instead of guessing from the Host clock (issue #1722).
168
238
  */
169
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[]
170
254
  }
171
255
 
172
256
  /**
173
- * The execution-shape section: what else this run opens. A plain cascade opens
174
- * one independent session per member; a team run starts every other member as a
175
- * teammate inside THIS session, so the prompt names the Team tools instead.
257
+ * The dispatch section: this run is the card's own session, and the card still
258
+ * has unfinished subtasks. The Host opens no session for them, so the prompt
259
+ * states what the session must do itself — read each card, dispatch subagents
260
+ * in dependency order, and write the conclusions back before finishing. A card
261
+ * with no outstanding descendant gets no section at all.
176
262
  */
177
- function peerPromptPreamble(context: PromptContext): string | undefined {
178
- const peers = context.peers ?? []
179
- if (peers.length === 0) return undefined
180
- if (context.team === true) {
181
- const lines = peers.map(peer => `- ${escapeProvenanceDelimiter(peer.title)}(teammate: ${peer.name ?? teammateName(peer.title, peer.id, peer.id)})`)
182
- return `本任务是 Agent Team 的 Lead:本次运行不额外开启独立会话,以下 ${peers.length} 个子任务成员已在本会话中作为 teammate 启动。用 list_agents / send_message / wait_agent 协调它们,用任务看板工具读写它们在看板上的卡片:\n${lines.join('\n')}`
183
- }
184
- const lines = peers.map(peer => `- ${escapeProvenanceDelimiter(peer.title)}(任务 ${peer.id})`)
185
- return `本次运行同时并发开启 ${peers.length} 个独立 DSH 会话执行下列子任务成员(可用 task_board_* 工具查看它们的进度):\n${lines.join('\n')}`
263
+ function dispatchPromptPreamble(context: PromptContext): string | undefined {
264
+ const descendants = context.descendants ?? []
265
+ if (descendants.length === 0) return undefined
266
+ const lines = descendants.map(descendant =>
267
+ `- ${escapeProvenanceDelimiter(descendant.title)}(任务 ${descendant.id},状态 ${descendant.status})`)
268
+ return `本卡还有 ${descendants.length} 个未完成的子任务,本次执行不会为它们额外开启会话,由你在本会话内自行派发:\n${lines.join('\n')}\n先用 task_board_get 读取每张子卡的内容与执行目标,再用 subagent 按依赖顺序派发(互不依赖的可以并发),完工前用 task_board_manage({action:'record-external-outcome', result, initiatedBy, summary}) 一次性回填各子卡的结论。`
186
269
  }
187
270
 
188
271
  /**
@@ -203,6 +286,19 @@ function schedulePromptPreamble(context: PromptContext): string | undefined {
203
286
  return `本次执行由任务看板的定时规则自动触发:触发时间 ${stamp}(UTC),规则时区 ${schedule.timeZone},cron 表达式 ${schedule.cron}。需要判断「今天」「现在」或计算时间窗口时,以该时区的触发时间为准。`
204
287
  }
205
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
+
206
302
  /**
207
303
  * Build the execution prompt for one task.
208
304
  * @param task - the task being launched.
@@ -219,10 +315,16 @@ export function promptText(task: TaskRecord, context: PromptContext = {}): strin
219
315
  // output location), the handover preamble is a per-card note, the scheduled
220
316
  // section states why this run exists, and the task body is the instruction.
221
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)
222
321
  const handoverSection = handoverPreamble
223
322
  const schedulePreamble = schedulePromptPreamble(context)
224
- const runPreamble = peerPromptPreamble(context)
225
- const preambles = [tagPreamble, handoverSection, schedulePreamble, runPreamble]
323
+ const runPreamble = dispatchPromptPreamble(context)
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]
226
328
  .filter((part): part is string => part !== undefined)
227
329
  const preamble = preambles.length === 0 ? undefined : preambles.join('\n\n')
228
330
  const freeze = task.freeze
@@ -314,11 +416,43 @@ function invokeWireArgs(namespace: string, method: string, request: Record<strin
314
416
  return { request }
315
417
  }
316
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
+ * Whether this deployment runs the legacy Agent Teams runtime, read live
432
+ * from the agent tool registry. Absent, or answering false, means the
433
+ * deployment is not PROVEN legacy: the dispatcher preset is then forced as
434
+ * before. Only a positive answer refuses the run, so a deployment whose
435
+ * registry cannot be read keeps its current behaviour instead of losing the
436
+ * ability to dispatch a subtask tree.
437
+ */
438
+ legacyAgentTeams?: () => boolean
439
+ }
440
+
317
441
  export class HostExecutionRunner {
318
- /** Newest scanned event sequence per session with no matching execution end. */
442
+ /**
443
+ * Newest event sequence per session whose COMPLETE history walk (reaching
444
+ * the execution boundary) found no matching execution end. A later walk may
445
+ * trust everything at or below it and examine only newer records.
446
+ */
319
447
  private readonly scanMemos = new Map<string, number>()
320
448
  private readonly unavailableAttempts: number
321
449
  private readonly unavailableBackoffMs: number
450
+ /**
451
+ * The peer every request speaks for. Production passes the peer bound to the
452
+ * plugin fiber; a bare runner (unit tests around fake gateways) gets one
453
+ * bound to a fresh root context instead.
454
+ */
455
+ private readonly ownerPeer: GatewayPeer
322
456
  private unsupportedSessionListWarned = false
323
457
 
324
458
  constructor(
@@ -326,21 +460,21 @@ export class HostExecutionRunner {
326
460
  private readonly commands?: SessionCommandDispatcher,
327
461
  private readonly workspaceRegistry?: TaskBoardWorkspaceRegistry,
328
462
  unavailableRetry?: { attempts?: number; backoffMs?: number },
329
- private readonly operatorPeer?: () => PeerScope | undefined,
463
+ ownerPeer?: GatewayPeer,
464
+ private readonly faces: TaskBoardRuntimeFaces = {},
330
465
  ) {
331
466
  this.unavailableAttempts = unavailableRetry?.attempts ?? SERVICE_UNAVAILABLE_ATTEMPTS
332
467
  this.unavailableBackoffMs = unavailableRetry?.backoffMs ?? SERVICE_UNAVAILABLE_BACKOFF_MS
468
+ this.ownerPeer = ownerPeer ?? createOwnerPeer(new Context())
333
469
  }
334
470
 
335
471
  private invoke(namespace: string, method: string, request: Record<string, unknown>, signal?: AbortSignal): Promise<unknown> {
336
- const peer = this.operatorPeer?.()
337
- return this.gateway.invoke({ namespace, method, args: invokeWireArgs(namespace, method, request), ...(peer === undefined ? {} : { peer }), ...(signal === undefined ? {} : { signal }) })
472
+ return this.gateway.invoke({ namespace, method, args: invokeWireArgs(namespace, method, request), peer: this.ownerPeer, ...(signal === undefined ? {} : { signal }) })
338
473
  }
339
474
 
340
475
  private stream(namespace: string, method: string, request: Record<string, unknown>, signal?: AbortSignal): Promise<AsyncIterable<unknown>> {
341
476
  if (!('stream' in this.gateway) || this.gateway.stream === undefined) throw new Error('gateway stream is unavailable')
342
- const peer = this.operatorPeer?.()
343
- return this.gateway.stream({ namespace, method, args: { request }, ...(peer === undefined ? {} : { peer }), ...(signal === undefined ? {} : { signal }) })
477
+ return this.gateway.stream({ namespace, method, args: { request }, peer: this.ownerPeer, ...(signal === undefined ? {} : { signal }) })
344
478
  }
345
479
 
346
480
  /**
@@ -368,6 +502,14 @@ export class HostExecutionRunner {
368
502
  async launch(task: TaskRecord, options: {
369
503
  reuseSessionId?: string
370
504
  promptContext?: PromptContext
505
+ /**
506
+ * Agent preset this execution is FORCED under, overriding the card's own
507
+ * `mode` pin (and a handover bundle's): the caller decides it from the run's
508
+ * shape (a card with unfinished subtasks runs as the autonomous dispatcher),
509
+ * and the override is never written into the card. A preset the deployment
510
+ * does not register fails the launch before any session exists.
511
+ */
512
+ agentPreset?: string
371
513
  onSession?: (sessionId: string) => void
372
514
  onGoalArmed?: (armed: boolean) => void
373
515
  /**
@@ -382,15 +524,24 @@ export class HostExecutionRunner {
382
524
  * `goalRun` still applies on top of it (both must ASK for a goal).
383
525
  */
384
526
  goalEnabled?: boolean
527
+ /**
528
+ * The host model catalog, read ONCE per execution by the caller. The card's
529
+ * pinned reasoning effort is sent only when this catalog declares it for the
530
+ * route the execution runs at, so one snapshot decides both the acceptance
531
+ * contract and the effort this run freezes. Absent means "no capability
532
+ * evidence": an effort is then not sent at all.
533
+ */
534
+ catalog?: ModelCatalogView
385
535
  } = {}): Promise<string> {
386
536
  // A handover bundle overrides the legacy pin fields: the bundle is the
387
537
  // authoritative execution triplet for a continuation card (issue #5). A
388
538
  // card that pins nothing is resolved to the deployment's most recently used
389
539
  // workspace instead of being left to `session.create`, whose own fallback is
390
540
  // the Host process working directory (the desktop app's profile directory) —
391
- // never the project the user was in when the card was written.
541
+ // never the project the user was in when the card was written. A deployment
542
+ // with no workspace to offer gets a refusal below, not that fallback.
392
543
  const workspaceId = task.handover?.workspaceId ?? task.workspaceId ?? this.recentWorkspaceId()
393
- const mode = task.handover?.mode ?? task.mode
544
+ const mode = options.agentPreset ?? task.handover?.mode ?? task.mode
394
545
  const permission = task.handover?.permission ?? task.permission
395
546
 
396
547
  if (workspaceId !== undefined && this.workspaceRegistry !== undefined) {
@@ -401,8 +552,27 @@ export class HostExecutionRunner {
401
552
  if (mode !== undefined) {
402
553
  const presets = await this.invoke('agentPresets', 'list', {}) as { presets?: readonly { id: string; broken?: string }[] }
403
554
  const preset = presets.presets?.find(item => item.id === mode)
555
+ // A forced preset is the run's shape, not a stored preference: a
556
+ // deployment that does not serve it (the `liangshen` dispatcher preset is
557
+ // shipped by packages/dsh-liangshen) cannot run this card the way its tree
558
+ // requires, so the run fails closed with the reason readable on the card.
559
+ if (preset === undefined && options.agentPreset !== undefined) {
560
+ throw new Error('agent preset not found: ' + mode + ' (a card with unfinished subtasks runs under the '
561
+ + LIANGSHEN_PRESET_ID + ' preset, which this deployment does not serve)')
562
+ }
404
563
  if (preset === undefined) throw new Error('agent preset not found: ' + mode)
405
564
  if (preset.broken !== undefined) throw new Error('agent preset is unavailable: ' + preset.broken)
565
+ // A forced preset is the run's shape, so the deployment must also be
566
+ // able to orchestrate under it: the dispatcher preset's own compatibility
567
+ // gate judges the tool surface at session start and, when the legacy
568
+ // Agent Teams runtime shadows the coordination tools, stops and waits for
569
+ // a human reply. A card with unfinished subtasks may be launched by a
570
+ // schedule, so that reply never comes and the card would sit in running
571
+ // forever (issue #2031). Refuse here instead, with the reason readable on
572
+ // the card, rather than minting a session that can only deadlock.
573
+ if (options.agentPreset !== undefined && this.faces.legacyAgentTeams?.() === true) {
574
+ throw new Error(LEGACY_AGENT_TEAMS_REASON)
575
+ }
406
576
  }
407
577
  // The ledger only ever stores ids minted by this runner (or the roster),
408
578
  // so the brand is reasserted at this boundary instead of re-deriving it.
@@ -422,27 +592,54 @@ export class HostExecutionRunner {
422
592
  // at the gate without its binding.
423
593
  options.onSession?.(reused)
424
594
  await this.assertReusedPreset(reused, mode)
425
- await this.pinAndPrompt(reused, task, permission, options.promptContext, options.onGoalArmed, options.goalEnabled === true)
595
+ await this.pinAndPrompt(reused, task, permission, options.promptContext, options.onGoalArmed, options.goalEnabled === true, options.catalog)
426
596
  } catch (error) {
427
597
  throw new SessionLaunchError(reused, error)
428
598
  }
429
599
  return reused
430
600
  }
601
+ // Nothing names a workspace and the deployment has none to resolve to, so
602
+ // there is no place this run may legitimately start: `session.create` would
603
+ // quietly land it in the Host process working directory (the desktop app's
604
+ // profile directory). Refuse before the session exists, with the reason the
605
+ // board settles the card with and the browser renders in the user's
606
+ // language, so the fix (pick a workspace on the card) is what the user reads.
607
+ if (workspaceId === undefined) throw new Error(MISSING_WORKSPACE_REASON)
431
608
  const created = await this.invoke('session', 'create', {
432
- ...(workspaceId === undefined ? {} : { workspaceId }),
609
+ workspaceId,
433
610
  ...(mode === undefined ? {} : { agentPreset: mode }),
434
611
  }) as { sessionId: ExecutionSessionId }
435
612
  const sessionId = created.sessionId
436
613
  options.onSession?.(sessionId)
437
614
  try {
438
615
  await this.invoke('session', 'rename', { sessionId, title: task.title })
439
- await this.pinAndPrompt(sessionId, task, permission, options.promptContext, options.onGoalArmed, options.goalEnabled === true)
616
+ await this.pinAndPrompt(sessionId, task, permission, options.promptContext, options.onGoalArmed, options.goalEnabled === true, options.catalog)
440
617
  } catch (error) {
441
618
  throw new SessionLaunchError(sessionId, error)
442
619
  }
443
620
  return sessionId
444
621
  }
445
622
 
623
+ /**
624
+ * Queue one follow-up user message into an existing execution session.
625
+ *
626
+ * This is the same `session/prompt` call a launch makes, with none of the
627
+ * launch pins: a follow-up continues a conversation the board already
628
+ * composed, so it must not re-assert the permission, rename the session, or
629
+ * switch the model. The message is queued behind whatever that session is
630
+ * doing, which is what lets a caller reach a run that is still working.
631
+ * @param sessionId - the session the card's execution recorded.
632
+ * @param text - the message to deliver, already validated by the caller.
633
+ */
634
+ async followUp(sessionId: string, text: string): Promise<void> {
635
+ await this.invoke('session', 'prompt', {
636
+ sessionId,
637
+ requestId: 'task-board-follow-up-' + crypto.randomUUID(),
638
+ mode: 'queue' as const,
639
+ content: [{ type: 'text' as const, text }],
640
+ })
641
+ }
642
+
446
643
  /**
447
644
  * Fail closed when a reused session records a different Agent preset than
448
645
  * the one this task pins.
@@ -471,10 +668,59 @@ export class HostExecutionRunner {
471
668
  )
472
669
  }
473
670
 
671
+ /**
672
+ * Split a `provider/model` pin. A pin without a provider keeps only the model
673
+ * id: the provider is the one the host catalog declares for it, resolved at
674
+ * launch because the session wire contract requires a provider.
675
+ */
676
+ private static pinnedRoute(model: string | undefined): ReasoningRoute | undefined {
677
+ const raw = model?.trim()
678
+ if (raw === undefined || raw === '') return undefined
679
+ const slash = raw.indexOf('/')
680
+ if (slash < 0) return { model: raw }
681
+ const provider = raw.slice(0, slash).trim()
682
+ const modelId = raw.slice(slash + 1).trim()
683
+ if (provider === '' || modelId === '') return undefined
684
+ return { provider, model: modelId }
685
+ }
686
+
687
+ /**
688
+ * The route a card that pins no model actually runs at: the session's own
689
+ * recorded selection (the durable fold the GUI reads; `next` is the pending
690
+ * user choice, `lastUsed` what the last request consumed), or — for a session
691
+ * that has selected none yet, which is exactly a session that would start at
692
+ * the deployment default — the host default from the catalog.
693
+ *
694
+ * A route that cannot be READ is undefined and the effort is not sent:
695
+ * falling back to the host default there would silently switch the model of a
696
+ * session this run only meant to continue.
697
+ */
698
+ private async sessionRoute(sessionId: ExecutionSessionId, catalog?: ModelCatalogView): Promise<ReasoningRoute | undefined> {
699
+ let selection: { provider?: unknown; model?: unknown } | null | undefined
700
+ try {
701
+ const projections = await this.invoke('session', 'projections', { sessionId }) as
702
+ | { values?: { modelSelection?: { lastUsed?: { provider?: unknown; model?: unknown } | null; next?: { provider?: unknown; model?: unknown } | null } } }
703
+ | null
704
+ selection = projections?.values?.modelSelection?.next ?? projections?.values?.modelSelection?.lastUsed
705
+ } catch (error) {
706
+ console.warn('[dsh-task-board] session/projections failed while resolving the execution model route', error)
707
+ return undefined
708
+ }
709
+ if (typeof selection?.provider === 'string' && selection.provider !== ''
710
+ && typeof selection.model === 'string' && selection.model !== '') {
711
+ return { provider: selection.provider, model: selection.model }
712
+ }
713
+ return catalog?.default === undefined
714
+ ? undefined
715
+ : { provider: catalog.default.provider, model: catalog.default.model }
716
+ }
717
+
474
718
  /**
475
719
  * Re-assert the pinned execution contract on a session and queue the task
476
720
  * prompt. Shared by the fresh-session and reuse paths so both apply exactly
477
- * the same permission/model pins before the prompt.
721
+ * the same permission/model/effort pins before the prompt. A session that
722
+ * refuses a selection carrying a catalog-confirmed effort throws here, so the
723
+ * prompt is never queued behind a run at the wrong level.
478
724
  */
479
725
  private async pinAndPrompt(
480
726
  sessionId: ExecutionSessionId,
@@ -483,6 +729,7 @@ export class HostExecutionRunner {
483
729
  context: PromptContext = {},
484
730
  onGoalArmed?: (armed: boolean) => void,
485
731
  goalEnabled = false,
732
+ catalog?: ModelCatalogView,
486
733
  ): Promise<void> {
487
734
  if (permission !== undefined) {
488
735
  if (this.commands === undefined) throw new Error('permission command dispatcher is unavailable')
@@ -490,31 +737,98 @@ export class HostExecutionRunner {
490
737
  if (command === undefined) throw new Error('permission command was not acknowledged')
491
738
  if (command.kind !== 'success') throw new Error(command.text ?? 'permission command failed')
492
739
  }
493
- if (task.model !== undefined && task.model.trim() !== '') {
494
- const rawModel = task.model.trim()
495
- const slashIdx = rawModel.indexOf('/')
496
- const provider = slashIdx >= 0 ? rawModel.slice(0, slashIdx).trim() : undefined
497
- const modelId = slashIdx >= 0 ? rawModel.slice(slashIdx + 1).trim() : rawModel
740
+ // The effort is bound to the model route the execution runs at. A card that
741
+ // pins no model of its own runs at the session's route, so that route is
742
+ // resolved first — and only when there is an effort to place: a card that
743
+ // never chose one must not gain a model-selection call it did not have.
744
+ const requestedEffort = normalizeReasoningEffort(task.reasoningEffort)
745
+ const pinned = HostExecutionRunner.pinnedRoute(task.model)
746
+ // The card's attachments, resolved afresh for THIS execution: the
747
+ // recorded metadata is never trusted on its own, and a file whose host
748
+ // path is missing or unreadable fails the run instead of being silently
749
+ // dropped.
750
+ const attachments = task.attachments ?? []
751
+ const carriesImages = attachments.some(attachment => attachment.kind === 'image')
752
+ // The route the execution runs at: the card's own pin, or the session's
753
+ // current selection. It is needed for the effort decision AND for the
754
+ // image preflight, which must judge the route the run really uses — a
755
+ // reused session is judged by its CURRENT route, not by the card's pin.
756
+ const route = pinned ?? (requestedEffort === undefined && !carriesImages ? undefined : await this.sessionRoute(sessionId, catalog))
757
+ if (route !== undefined) {
758
+ const routeLabel = `${route.provider === undefined ? '' : route.provider + '/'}${route.model}`
759
+ const decision = resolveReasoningEffort(requestedEffort, catalog, route)
760
+ if (decision.dropped !== undefined) {
761
+ console.warn(`[dsh-task-board] model route ${routeLabel} does not declare reasoning effort "${decision.dropped}"; session ${sessionId} runs at the model default`)
762
+ }
763
+ // The catalog completes a bare model pin into the provider the session
764
+ // request must name; an undeclared pin keeps its own spelling exactly as
765
+ // before, minus an effort that could not be verified.
766
+ const declared = declaredRoute(catalog, route)
767
+ const provider = declared?.provider ?? route.provider
768
+ const modelId = declared?.model ?? route.model
769
+ // The image preflight runs BEFORE the prompt: a route that declares its
770
+ // input modalities and does not accept an image refuses the run here,
771
+ // so no session is ever prompted with an image it cannot read. A route
772
+ // that declares no modalities is unknown, and an unknown route is
773
+ // allowed — the official model catalog publishes no modality
774
+ // information and must not be used to answer this question.
775
+ if (carriesImages && provider !== undefined && modelId !== undefined) {
776
+ await assertRouteAcceptsImages(this.faces.llm?.(), provider, modelId)
777
+ }
498
778
  try {
499
779
  await this.invoke('session', 'selectModel', {
500
780
  sessionId,
501
- ...(provider ? { provider } : {}),
781
+ ...(provider === undefined ? {} : { provider }),
502
782
  model: modelId,
783
+ ...(decision.effort === undefined ? {} : { reasoningEffort: decision.effort }),
503
784
  })
504
785
  } catch (modelError) {
505
- console.warn(`[dsh-task-board] failed to select model "${task.model}" for session ${sessionId}, falling back to default:`, modelError)
786
+ // An effort the catalog CONFIRMED for this route is a contract, not a
787
+ // preference: if the session refuses the selection, the run fails here,
788
+ // before the prompt, rather than silently executing at the model default
789
+ // the user did not pick. A selection that carries no confirmed effort
790
+ // keeps the best-effort behavior: the card was asked to run, and losing
791
+ // the work over a model switch this run never promised is worse.
792
+ if (decision.effort !== undefined) {
793
+ throw new Error(`session ${sessionId} refused the model selection "${provider === undefined ? modelId : provider + '/' + modelId}" with reasoning effort "${decision.effort}": ` + (modelError instanceof Error ? modelError.message : String(modelError)))
794
+ }
795
+ console.warn(`[dsh-task-board] failed to select model "${provider === undefined ? modelId : provider + '/' + modelId}" for session ${sessionId}, falling back to default:`, modelError)
506
796
  }
507
797
  }
798
+ // The attachments are resolved AFTER the preflight and BEFORE the prompt:
799
+ // an image becomes an image part of the prompt (after the text part), and
800
+ // a file becomes a readable path in a preamble section of its own.
801
+ const resolved = await this.resolveAttachments(attachments)
802
+ const promptContext: PromptContext = resolved.files.length === 0 ? context : { ...context, files: resolved.files }
508
803
  await this.invoke('session', 'prompt', {
509
804
  sessionId,
510
805
  requestId: 'task-board-' + crypto.randomUUID(),
511
806
  mode: 'queue' as const,
512
- content: [{ type: 'text' as const, text: promptText(task, context) }],
807
+ content: [
808
+ { type: 'text' as const, text: promptText(task, promptContext) },
809
+ ...resolved.images,
810
+ ],
513
811
  })
514
- const armed = await this.armGoal(sessionId, task, context, goalEnabled)
812
+ const armed = await this.armGoal(sessionId, task, promptContext, goalEnabled)
515
813
  onGoalArmed?.(armed)
516
814
  }
517
815
 
816
+ /**
817
+ * Resolve a card's attachments for one execution.
818
+ *
819
+ * A card without attachments resolves to nothing, even in a deployment that
820
+ * serves no attachment storage at all. A card WITH attachments cannot run
821
+ * without the storage: the run fails with a readable reason instead of
822
+ * silently dropping the attachment and running the card as if it carried
823
+ * none.
824
+ */
825
+ private async resolveAttachments(attachments: readonly TaskAttachment[]): Promise<ResolvedAttachments> {
826
+ if (attachments.length === 0) return { images: [], files: [] }
827
+ const store = this.faces.attachments?.()
828
+ if (store === undefined) throw new Error('this deployment serves no attachment storage')
829
+ return await resolveExecutionAttachments(store, attachments)
830
+ }
831
+
518
832
  /**
519
833
  * Read the host's model catalog: the default route an unconfigured session
520
834
  * starts at, and each provider's models with the reasoning metadata its
@@ -709,10 +1023,21 @@ export class HostExecutionRunner {
709
1023
  }
710
1024
  const openingEvents = opening.records.map(record => ({ event: recordEvent(record) }))
711
1025
  const newestSeq = openingEvents.reduce<number | undefined>((newest, entry) => newest === undefined ? entry.event.seq : Math.max(newest, entry.event.seq), undefined)
712
- if (newestSeq !== undefined && this.scanMemos.get(sessionId) === newestSeq) return { outcome: 'pending' }
1026
+ const scannedThrough = this.scanMemos.get(sessionId)
1027
+ if (newestSeq !== undefined && scannedThrough === newestSeq) return { outcome: 'pending' }
1028
+ // The memo is not only "nothing changed": it is the seq up to which a
1029
+ // COMPLETE walk already proved this execution has no completed turn. A
1030
+ // session log is append-only, so records at or below it can never acquire
1031
+ // one — this pass only has to examine what arrived after it. Without that,
1032
+ // a working teammate (whose roster entry never stops reporting `running`,
1033
+ // so every poll re-inspects it) re-read its whole history since the run
1034
+ // started once per poll: a 1200-record history cost 12 page RPCs and 1223
1035
+ // materialized records per session per poll, against 0 and 21 here.
1036
+ const oldestOpeningSeq = openingEvents.reduce<number | undefined>((oldest, entry) => oldest === undefined ? entry.event.seq : Math.min(oldest, entry.event.seq), undefined)
1037
+ const coveredThrough = scannedThrough !== undefined && oldestOpeningSeq !== undefined && oldestOpeningSeq <= scannedThrough
713
1038
  const events: Array<{ event: { type: string; seq: number; time: number; data: unknown } }> = [...openingEvents]
714
1039
  let beforeSeq: number | undefined
715
- let reachedExecutionBoundary = !opening.hasMore
1040
+ let reachedExecutionBoundary = !opening.hasMore || coveredThrough
716
1041
  for (let page = 0; page < HISTORY_PAGE_LIMIT && !reachedExecutionBoundary; page += 1) {
717
1042
  let history: SessionPage
718
1043
  try {
@@ -729,11 +1054,13 @@ export class HostExecutionRunner {
729
1054
  const pageEntries = pageEvents(history)
730
1055
  events.push(...pageEntries)
731
1056
  const oldestTime = pageEntries.reduce<number | undefined>((oldest, entry) => oldest === undefined ? entry.event.time : Math.min(oldest, entry.event.time), undefined)
732
- if (!history.hasMore || (oldestTime !== undefined && oldestTime <= startedAt)) {
1057
+ const oldestSeq = pageEntries.reduce<number | undefined>((oldest, entry) => oldest === undefined ? entry.event.seq : Math.min(oldest, entry.event.seq), undefined)
1058
+ if (!history.hasMore
1059
+ || (oldestTime !== undefined && oldestTime <= startedAt)
1060
+ || (scannedThrough !== undefined && oldestSeq !== undefined && oldestSeq <= scannedThrough)) {
733
1061
  reachedExecutionBoundary = true
734
1062
  break
735
1063
  }
736
- const oldestSeq = pageEntries.reduce<number | undefined>((oldest, entry) => oldest === undefined ? entry.event.seq : Math.min(oldest, entry.event.seq), undefined)
737
1064
  if (oldestSeq === undefined || oldestSeq === beforeSeq) return { outcome: 'pending' }
738
1065
  beforeSeq = oldestSeq
739
1066
  }
@@ -748,13 +1075,20 @@ export class HostExecutionRunner {
748
1075
  return { outcome: 'pending' }
749
1076
  }
750
1077
  this.scanMemos.delete(sessionId)
1078
+ // What the run left behind rides the verdict the caller settles with, for a
1079
+ // success and a failure alike: the events are in hand here, and no later
1080
+ // reader can recover them once the session is gone. A run with no assistant
1081
+ // prose carries no field at all, so settling stays a decision about the
1082
+ // verdict alone.
1083
+ const closing = executionSummaryOf(events.map(entry => entry.event), startedAt)
1084
+ const carried = closing === undefined ? {} : { summary: closing }
751
1085
  const reason = nonCompletedTurnEnd(turnEnd.event.data)
752
- if (reason === undefined) return await this.goalVerdict(sessionId) ?? { outcome: 'succeeded' }
1086
+ if (reason === undefined) return { ...(await this.goalVerdict(sessionId) ?? { outcome: 'succeeded' as const }), ...carried }
753
1087
  // `error` keeps its historical wording; every other non-completed reason
754
1088
  // (aborted / blocked / max-tokens / interrupted) now reports instead of
755
1089
  // silently counting as success.
756
1090
  return reason === 'error'
757
- ? { outcome: 'failed', error: 'agent turn ended with an error' }
758
- : { outcome: 'failed', error: 'agent turn ended without completing: ' + reason }
1091
+ ? { outcome: 'failed', error: 'agent turn ended with an error', ...carried }
1092
+ : { outcome: 'failed', error: 'agent turn ended without completing: ' + reason, ...carried }
759
1093
  }
760
1094
  }