@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,48 +1,30 @@
1
1
  import type { TypertGateway } from '@deepseek-ai/dsh-api-gateway'
2
- import type { PeerScope } from '@deepseek-ai/dsh-client-connection'
2
+ import { DEFAULT_RUN_LAUNCH_WIDTH, normalizeRunLaunchWidth } from './core/launch-width.ts'
3
+ import { DEFAULT_SPEND_BUDGET_TOKENS, spendCapMessage, spendCapReached } from './core/spend-budget.ts'
4
+ import { usedTokensToday } from './host-spend.ts'
3
5
  import { DEFAULT_SESSION_POLL_SECONDS, normalizeSessionPollSeconds, sessionPollMs } from './core/poll-cadence.ts'
4
6
  import { reusableSessionId } from './core/session-reuse.ts'
7
+ import { LaunchAdmissionQueue, type QueuedLaunch } from './host/launch-admission.ts'
5
8
  import { HostTaskLedger, type OpenedRun, type OpenExecutionReference } from './host-ledger.ts'
6
- import { HostExecutionRunner, SessionLaunchError, promptText, type SessionCommandDispatcher, type SessionSummary, type TaskBoardWorkspaceRegistry } from './host-runner.ts'
7
- import { teammateName } from './core/subtask.ts'
9
+ import { HostExecutionRunner, SessionLaunchError, type GatewayPeer, type SessionCommandDispatcher, type SessionSummary, type TaskBoardWorkspaceRegistry } from './host-runner.ts'
10
+ import { LIANGSHEN_PRESET_ID } from './core/subtask.ts'
8
11
  import { workspaceOwningSession } from './core/workspace-target.ts'
9
12
  import { PowerInhibitor } from './power-inhibitor.ts'
10
13
  import { TASK_BOARD_SCHEMA_VERSION, type TaskBoardAction, type TaskBoardEventPayload, type TaskBoardSnapshot } from './protocol.ts'
14
+ import { projectSnapshotForWire } from './core/wire-projection.ts'
15
+ import type { CardDefaults } from './core/card-defaults.ts'
11
16
  import { TaskBoardExtensionRegistry } from './host/extension-registry.ts'
12
17
  import type { TaskBoardExtension } from './core/extension.ts'
13
- import type { ExecutionOutcome, ScheduleMode, TaskRecord, TaskStatus } from './core/tasks.ts'
18
+ import { isTaskPermission, normalizeTargetId, type ExecutionOutcome, type ExecutionSummary, type ScheduleMode, type TaskRecord, type TaskStatus } from './core/tasks.ts'
14
19
  import { passedAttempt, resolveContract, verificationNeverInvoked, verificationOnlyInvalid, verificationRequired, withAcceptanceDetailCleared, type ExecutionVerification, type ModelCatalogView, type VerificationContract, type VerificationSettings } from './core/verification.ts'
15
20
  import type { TaskPermission } from './core/handover.ts'
16
-
17
- /** One teammate the Host asks the Agent Teams service to spawn for a team run. */
18
- export interface TeamSpawnInput {
19
- /** Session id of the run's Team Lead (the root task's execution session). */
20
- leadSessionId: string
21
- /** Immutable lower-kebab-case teammate name, unique inside the Team. */
22
- name: string
23
- /** Short description of the delegated responsibility. */
24
- description: string
25
- /** The subtask's execution prompt. */
26
- prompt: string
27
- }
28
-
29
- /** Result of one teammate spawn attempt. */
30
- export interface TeamSpawnResult {
31
- /** The teammate's session id when it reached the active edge. */
32
- sessionId?: string
33
- /** Why the spawn failed: a thrown call, or a member that settled as failed. */
34
- error?: string
35
- }
36
-
37
- /**
38
- * The Agent Teams capability the Host needs for team-mode runs. The plugin
39
- * builds it from the optional `agentTeams` service; it is absent when this
40
- * deployment does not serve that service, in which case a team run is refused
41
- * instead of silently degrading into a plain cascade.
42
- */
43
- export interface TaskBoardTeamDispatcher {
44
- spawn(input: TeamSpawnInput): Promise<TeamSpawnResult>
45
- }
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'
46
28
 
47
29
  /** Ceiling for the roster-poll failure backoff: a broken session tree is retried at most once a minute. */
48
30
  const POLL_FAILURE_MAX_BACKOFF_MS = 60_000
@@ -66,6 +48,43 @@ const MAX_TIMER_DELAY_MS = 2_147_483_647
66
48
  */
67
49
  const UNREADABLE_SETTLE_POLLS = 24
68
50
 
51
+ /**
52
+ * Why a member of a run never started: the Host stopped while its launch was
53
+ * still waiting for an admission slot. Recorded rather than left open, so the
54
+ * card leaves the running column instead of waiting for the next Host start's
55
+ * interrupted-start recovery.
56
+ */
57
+ const ABANDONED_LAUNCH_REASON = 'host stopped before this execution started'
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
+
67
+ /**
68
+ * The acceptance contract one run group freezes, read once for the whole group.
69
+ *
70
+ * The board freezes an execution's acceptance contract BEFORE its session is
71
+ * prompted. Admission delays the launch, so reading these per execution would
72
+ * let a settings edit made while later members wait reach some members of one
73
+ * run and not others. Reading them once per run group — at the group's first
74
+ * admission, which is its root's — keeps the whole group on one contract and
75
+ * still freezes it before any member's session is prompted.
76
+ */
77
+ interface FrozenRunContract {
78
+ settings: VerificationSettings
79
+ /** The GLOBAL native-/goal switch, resolved exactly once for the run group. */
80
+ globalGoalEnabled: boolean
81
+ /** The host model catalog the group's contracts resolve their route from. */
82
+ catalog: ModelCatalogView | undefined
83
+ }
84
+
85
+ /** Reads (or returns the already-read) contract of one run group. */
86
+ type RunContractFreezer = () => Promise<FrozenRunContract>
87
+
69
88
  /**
70
89
  * Why an enforced goal execution settled failed while its acceptance DID run:
71
90
  * attempts were recorded and none of them passed. The judge answered about the
@@ -92,7 +111,7 @@ export const NEVER_INVOKED_VERIFICATION_REASON = 'goal 验收未触发:本次
92
111
  export const INVALID_ONLY_VERIFICATION_REASON = 'goal 验收无效:本次执行只记录了无效验收(裁判未能给出与任务要求对应、且可定位到本次证据的否决依据),看板已停止调用裁判。这**不是**有证据的质量判负:验收本身不可用,本次运行因没有匹配的通过记录而结束。请检查验收环境与证据可见性,或用 task_board_manage(action=reset-verification) 清除记录的无效验收后重新完成目标。'
93
112
 
94
113
  /**
95
- * Provenance of one cron-triggered cascade: when the rule fired and the zone
114
+ * Provenance of one cron-triggered run: when the rule fired and the zone
96
115
  * its wall clock was read in. Passed into every launched prompt of that run so
97
116
  * a scheduled job knows its own clock rather than inferring one.
98
117
  */
@@ -143,10 +162,80 @@ const PROCESS_TIMERS: HostTimerFace = {
143
162
  },
144
163
  }
145
164
 
165
+ /**
166
+ * The new-card defaults a snapshot publishes, or undefined when this
167
+ * deployment configures none. A target the board configures nothing for is
168
+ * omitted instead of published blank, so the browser can tell "no default
169
+ * model" from "a blank one" (only a hand-edited settings document can express
170
+ * the latter).
171
+ */
172
+ function cardDefaultsOf(defaults: CardDefaults): TaskBoardSnapshot['cardDefaults'] {
173
+ const mode = normalizeTargetId(defaults.mode)
174
+ const permission = normalizeTargetId(defaults.permission)
175
+ const model = normalizeTargetId(defaults.model)
176
+ const reasoningEffort = normalizeTargetId(defaults.reasoningEffort)
177
+ const published: NonNullable<TaskBoardSnapshot['cardDefaults']> = {
178
+ ...(mode === undefined ? {} : { mode }),
179
+ // The snapshot publishes a permission the board's own vocabulary knows; an
180
+ // out-of-domain value is ignored here exactly as the create path ignores it.
181
+ ...(isTaskPermission(permission) ? { permission } : {}),
182
+ ...(model === undefined ? {} : { model }),
183
+ ...(reasoningEffort === undefined ? {} : { reasoningEffort }),
184
+ }
185
+ return Object.keys(published).length === 0 ? undefined : published
186
+ }
187
+
188
+ /**
189
+ * Every action kind this board accepts, keyed by the kind itself.
190
+ *
191
+ * Written as a total record of `TaskBoardAction['kind']` on purpose: a new member
192
+ * of that union does not compile until it is listed here, so the table cannot
193
+ * drift behind the protocol. `apply()` validates against it because a caller
194
+ * reaching the board through the in-process capability face forwards its action
195
+ * object verbatim, with no envelope parser in front of it — the HTTP route was the
196
+ * only entrance before that face existed, and its parser is what used to turn an
197
+ * unknown kind into a refusal.
198
+ */
199
+ const ACTION_KINDS: Readonly<Record<TaskBoardAction['kind'], true>> = {
200
+ import: true,
201
+ create: true,
202
+ update: true,
203
+ delete: true,
204
+ move: true,
205
+ archive: true,
206
+ restore: true,
207
+ settle: true,
208
+ 'reset-verification': true,
209
+ 'record-external-outcome': true,
210
+ 'set-schedule': true,
211
+ run: true,
212
+ rerun: true,
213
+ rework: true,
214
+ 'confirm-permission': true,
215
+ 'set-parent': true,
216
+ 'rename-tag': true,
217
+ 'delete-tag': true,
218
+ 'extension-action': true,
219
+ }
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
+
146
233
  export class TaskBoardHostService {
147
234
  readonly ledger: HostTaskLedger
148
235
  readonly runner: HostExecutionRunner
149
236
  readonly power: PowerInhibitor
237
+ /** The official attachment storage, read live so a late mount is honoured. */
238
+ private readonly attachmentStore: () => TaskBoardAttachmentStore | undefined
150
239
  private readonly listeners = new Set<() => void>()
151
240
  /** The one recurring timer: the session-roster poll. */
152
241
  private pollTimer: (() => void) | undefined
@@ -163,6 +252,12 @@ export class TaskBoardHostService {
163
252
  private disposed = false
164
253
  private pollInFlight = false
165
254
  private active = true
255
+ /**
256
+ * Admission control for the session-creating half of a run: one board action
257
+ * opens a whole subtree, and this is what keeps the Host from asking DSH for
258
+ * every member's session at once (see {@link LaunchAdmissionQueue}).
259
+ */
260
+ private readonly launches: LaunchAdmissionQueue
166
261
  /**
167
262
  * Consecutive unreadable-history polls per open execution (see
168
263
  * {@link noteUnreadableInspection}). Cleared as soon as an inspection
@@ -172,10 +267,24 @@ export class TaskBoardHostService {
172
267
  private preventIdleSleep = false
173
268
  private readonly verificationSettings: () => VerificationSettings
174
269
  private readonly verificationCatalog: () => Promise<ModelCatalogView | undefined>
175
- private readonly team: TaskBoardTeamDispatcher | undefined
176
270
  private readonly timers: HostTimerFace
177
271
  /** Live reader of the global native-/goal switch; frozen per execution. */
178
272
  private readonly goalRunEnabled: () => boolean
273
+ /** Live reader of the deployment's new-card defaults (published and applied per create). */
274
+ private readonly cardDefaults: () => CardDefaults
275
+ /**
276
+ * Live reader of the run-launch admission width: how many launches may be in
277
+ * flight at once. Read at every admission, so a settings edit bounds the next
278
+ * launch without remounting the row. Absent means the default.
279
+ */
280
+ private readonly runLaunchWidth: () => number
281
+ /**
282
+ * Live reader of the daily token cap; 0 means no gate. Read at each run
283
+ * action, so closing or raising the cap binds the next action.
284
+ */
285
+ private readonly spendBudgetTokens: () => number
286
+ /** Today's measured spend: absent measurement reads as "cannot see", never as zero. */
287
+ private readonly spendUsedToday: (now: number) => number | undefined
179
288
  private lastPowerJson = ''
180
289
  private readonly now: () => number
181
290
  /** The deployment's workspaces, consulted to resolve a card that pins none. */
@@ -193,13 +302,26 @@ export class TaskBoardHostService {
193
302
  now?: () => number
194
303
  commandDispatcher?: SessionCommandDispatcher
195
304
  workspaceRegistry?: TaskBoardWorkspaceRegistry
305
+ /**
306
+ * The owner peer every gateway request the runner makes speaks for.
307
+ * Production passes the peer bound to the plugin fiber (see
308
+ * {@link createOwnerPeer}); absent is fine for tests and bare mounts,
309
+ * where the runner binds one to a fresh root context.
310
+ */
311
+ ownerPeer?: GatewayPeer
196
312
  /**
197
313
  * Permission baseline of the confirmation gate: a fixed value, or a live
198
314
  * resolver the board re-reads so a Host Settings change needs no remount.
199
315
  */
200
316
  sessionDefaultPermission?: TaskPermission | (() => TaskPermission)
201
317
  maxSubtaskDepth?: number
202
- team?: TaskBoardTeamDispatcher
318
+ /**
319
+ * Live reader of the deployment's new-card defaults (volatile config reads).
320
+ * The board publishes them for the create dialog and re-reads them for every
321
+ * create that opts in, so a settings edit reaches the next created card
322
+ * without remounting the row. Absent means the deployment configures none.
323
+ */
324
+ cardDefaults?: () => CardDefaults
203
325
  timers?: HostTimerFace
204
326
  /**
205
327
  * Live GLOBAL native /goal switch (a volatile config read). Read ONCE per
@@ -217,19 +339,69 @@ export class TaskBoardHostService {
217
339
  verificationSettings?: () => VerificationSettings
218
340
  /** The host model catalog the acceptance contract resolves its route from. */
219
341
  verificationCatalog?: () => Promise<ModelCatalogView | undefined>
220
- operatorPeer?: () => PeerScope | undefined
342
+ /**
343
+ * Live admission width for run launches: the number of launches (one
344
+ * session creation and its prompt each) that may be in flight at once. Read
345
+ * per admission, so editing the setting bounds the next launch of a run that
346
+ * is still queueing. Absent means the default width.
347
+ */
348
+ runLaunchWidth?: () => number
349
+ /**
350
+ * Live daily token cap (a volatile config read). 0 — the default, and what
351
+ * every deployment that never configured one keeps — ends the gate before
352
+ * anything is measured. A positive cap refuses a run whose day already spent
353
+ * it, on both the action path and the cron path.
354
+ */
355
+ spendBudgetTokens?: () => number
356
+ /**
357
+ * Today's measured spend in tokens, or undefined when this deployment keeps
358
+ * no readable usage ledger. Defaults to the family usage ledger reader.
359
+ */
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
373
+ /**
374
+ * Whether this deployment runs the legacy Agent Teams runtime. Read at
375
+ * launch, only for a run the board is about to force under the dispatcher
376
+ * preset: such a deployment cannot orchestrate, so the run fails closed on
377
+ * the card instead of deadlocking in a session nobody answers (issue #2031).
378
+ * Absent means "not proven legacy", which keeps the force exactly as it is.
379
+ */
380
+ legacyAgentTeams?: () => boolean
221
381
  } = {}) {
222
382
  this.ledger = options.ledger ?? new HostTaskLedger(undefined, undefined, {
223
383
  sessionDefaultPermission: options.sessionDefaultPermission,
224
384
  maxSubtaskDepth: options.maxSubtaskDepth,
385
+ cardDefaults: options.cardDefaults,
386
+ spendBudgetTokens: options.spendBudgetTokens,
387
+ spendUsedToday: options.spendUsedToday,
388
+ })
389
+ this.attachmentStore = options.attachments ?? (() => undefined)
390
+ this.runner = new HostExecutionRunner(gateway, options.commandDispatcher, options.workspaceRegistry, undefined, options.ownerPeer, {
391
+ attachments: this.attachmentStore,
392
+ llm: options.modelInfo,
393
+ ...(options.legacyAgentTeams === undefined ? {} : { legacyAgentTeams: options.legacyAgentTeams }),
225
394
  })
226
- this.runner = new HostExecutionRunner(gateway, options.commandDispatcher, options.workspaceRegistry, undefined, options.operatorPeer)
227
395
  this.workspaceRegistry = options.workspaceRegistry
228
- this.team = options.team
229
396
  this.timers = options.timers ?? PROCESS_TIMERS
230
397
  this.power = options.power ?? new PowerInhibitor()
231
398
  this.now = options.now ?? Date.now
232
399
  this.goalRunEnabled = options.goalRunEnabled ?? (() => false)
400
+ this.cardDefaults = options.cardDefaults ?? (() => ({}))
401
+ this.runLaunchWidth = options.runLaunchWidth ?? (() => DEFAULT_RUN_LAUNCH_WIDTH)
402
+ this.spendBudgetTokens = options.spendBudgetTokens ?? (() => DEFAULT_SPEND_BUDGET_TOKENS)
403
+ this.spendUsedToday = options.spendUsedToday ?? (now => usedTokensToday(now))
404
+ this.launches = new LaunchAdmissionQueue(() => normalizeRunLaunchWidth(this.runLaunchWidth()))
233
405
  this.verificationSettings = options.verificationSettings ?? (() => ({ enabled: false, model: '', reasoningEffort: '' }))
234
406
  this.verificationCatalog = options.verificationCatalog ?? (async () => undefined)
235
407
  this.extensions = new TaskBoardExtensionRegistry({
@@ -237,6 +409,15 @@ export class TaskBoardHostService {
237
409
  // Capability writes go through the board's own action path, so every
238
410
  // board gate (content freeze, running lock, permission gate) still holds.
239
411
  apply: (action, initiator) => this.applyBoardAction(crypto.randomUUID(), action, initiator),
412
+ // Delivery into a run the board already owns is the runner's session wire
413
+ // call, never a second execution path.
414
+ followUp: (sessionId, text) => this.runner.followUp(sessionId, text),
415
+ // A rework is a run request like any other: it opens its execution through
416
+ // the same action path, so the running lock, the permission confirmation,
417
+ // the acceptance contract and the spend cap all apply to it.
418
+ rework: (taskId, instructions, initiator) => {
419
+ this.applyBoardAction(crypto.randomUUID(), { kind: 'rework', taskId, instructions }, initiator)
420
+ },
240
421
  now: this.now,
241
422
  })
242
423
  installStreamErrorGuards()
@@ -317,10 +498,20 @@ export class TaskBoardHostService {
317
498
  this.emit()
318
499
  }
319
500
 
501
+ /**
502
+ * The board's published snapshot.
503
+ *
504
+ * Every read path serializes this object — the HTTP `state` answer, the
505
+ * `action` answer through {@link apply}, and the remote bridge's
506
+ * `board.snapshot` — so a provider's integration credentials are stripped
507
+ * once, here, instead of at each exit. The ledger keeps them verbatim for the
508
+ * provider's own in-process read.
509
+ */
320
510
  snapshot(): TaskBoardSnapshot {
321
511
  const state = this.ledger.state()
322
512
  const published = this.extensions.published()
323
- return {
513
+ const cardDefaults = cardDefaultsOf(this.cardDefaults())
514
+ return projectSnapshotForWire({
324
515
  schemaVersion: TASK_BOARD_SCHEMA_VERSION,
325
516
  revision: state.revision,
326
517
  tasks: state.tasks,
@@ -328,13 +519,19 @@ export class TaskBoardHostService {
328
519
  power: this.power.snapshot(),
329
520
  sessionDefaultPermission: this.ledger.sessionDefaultPermission,
330
521
  maxSubtaskDepth: this.ledger.maxSubtaskDepth,
331
- teamRunAvailable: this.team !== undefined,
332
522
  // The GLOBAL native-/goal switch is published live for the UI, but the
333
523
  // service freezes its own read at launch: this mirror is for the FORM
334
524
  // (enable/disable + explanation), never for a run already in flight.
335
525
  goalRunEnabled: this.goalRunEnabled(),
526
+ // The new-card defaults are published live for the same reason the switch
527
+ // is: the create dialog prefills from them, and each creating session
528
+ // re-reads them for the create it submits.
529
+ ...(cardDefaults === undefined ? {} : { cardDefaults }),
530
+ // The attachment limits travel with the snapshot so the browser can
531
+ // refuse an oversized selection before it uploads anything.
532
+ ...(this.attachmentStore() === undefined ? {} : { attachmentLimits: publishedAttachmentLimits(this.attachmentStore()) }),
336
533
  ...(Object.keys(published).length === 0 ? {} : { extensions: published }),
337
- }
534
+ })
338
535
  }
339
536
 
340
537
  /**
@@ -407,18 +604,67 @@ export class TaskBoardHostService {
407
604
  return { ...action, input: { ...input, workspaceId } }
408
605
  }
409
606
 
607
+ /**
608
+ * Apply an action whose attachments the Host proved against the official
609
+ * storage first.
610
+ *
611
+ * This is the board's trust boundary for attachment metadata: the browser
612
+ * asserts the size, the type and the digest of every object it uploaded, and
613
+ * the Host reads the stored objects back (an image is compared, a file is
614
+ * streamed and its digest recomputed) before the ledger commits the claim.
615
+ * An attachment the storage cannot prove is refused, so a spoofed client
616
+ * claim never becomes a stored fact.
617
+ */
618
+ async applyVerified(requestId: string, action: TaskBoardAction, initiator?: string): Promise<TaskBoardSnapshot> {
619
+ if (!this.active) throw new Error('task board is disabled')
620
+ // A provider action never carries attachments: it is routed through the
621
+ // registry exactly like every other extension call.
622
+ if (action.kind === 'extension-action') return await this.apply(requestId, action, initiator)
623
+ await this.verifyActionAttachments(action)
624
+ return projectSnapshotForWire(this.applyBoardAction(requestId, action, initiator, true))
625
+ }
626
+
627
+ /**
628
+ * Prove every attachment of an action against the official storage.
629
+ *
630
+ * An action without attachments is untouched: the board keeps working in a
631
+ * deployment that serves no attachment storage at all.
632
+ */
633
+ private async verifyActionAttachments(action: Exclude<TaskBoardAction, { kind: 'extension-action' }>): Promise<void> {
634
+ const attachments = attachmentsOfAction(action)
635
+ if (attachments === undefined || attachments.length === 0) return
636
+ const store = this.attachmentStore()
637
+ if (store === undefined) throw new Error('this deployment serves no attachment storage')
638
+ // The failure keeps its CLASS: a storage that is unavailable must reach
639
+ // the caller as "the storage is unavailable" (503), not as a generic
640
+ // rejected action (400).
641
+ await verifyAttachments(store, attachments)
642
+ }
643
+
410
644
  apply(requestId: string, action: Extract<TaskBoardAction, { kind: 'extension-action' }>, initiator?: string): Promise<TaskBoardSnapshot>
411
645
  apply(requestId: string, action: Exclude<TaskBoardAction, { kind: 'extension-action' }>, initiator?: string): TaskBoardSnapshot
412
646
  apply(requestId: string, action: TaskBoardAction, initiator?: string): TaskBoardSnapshot | Promise<TaskBoardSnapshot>
413
647
  apply(requestId: string, action: TaskBoardAction, initiator?: string): TaskBoardSnapshot | Promise<TaskBoardSnapshot> {
414
648
  if (!this.active) throw new Error('task board is disabled')
649
+ // A caller that never met the HTTP envelope parser can name a kind this build
650
+ // does not implement. It is refused here, in the board's own vocabulary: the
651
+ // ledger has no case for it, and letting it through committed an unchanged
652
+ // document under a fresh revision — which every connected client then reloads
653
+ // a whole snapshot for.
654
+ const kind = (action as { kind?: unknown } | null | undefined)?.kind
655
+ if (typeof kind !== 'string' || !Object.hasOwn(ACTION_KINDS, kind)) {
656
+ throw new Error(`unknown task board action kind: ${String(kind)}`)
657
+ }
415
658
  // Provider actions never touch the ledger directly: the registry routes the
416
659
  // action to the owning extension, whose own capability calls come back
417
660
  // through applyBoardAction and every board gate below.
418
661
  if (action.kind === 'extension-action') {
419
662
  return this.handleExtensionAction(action)
420
663
  }
421
- return this.applyBoardAction(requestId, action, initiator)
664
+ // The answer to a write is a read like any other — it crosses the same wire
665
+ // (the HTTP action route and the remote bridge's board.apply) — so it leaves
666
+ // through the same projection as snapshot().
667
+ return projectSnapshotForWire(this.applyBoardAction(requestId, action, initiator))
422
668
  }
423
669
 
424
670
  /**
@@ -426,15 +672,16 @@ export class TaskBoardHostService {
426
672
  * calls and the same-origin wire both land here, so the two surfaces can
427
673
  * never disagree about a card.
428
674
  */
429
- private applyBoardAction(requestId: string, action: Exclude<TaskBoardAction, { kind: 'extension-action' }>, initiator?: string): TaskBoardSnapshot {
430
- const before = this.statusMap()
431
- // Fail closed before the ledger opens anything: a card opted into team
432
- // execution cannot run in a deployment that serves no Agent Teams service,
433
- // and silently degrading it to a plain cascade would misreport the work.
434
- if (this.team === undefined && (action.kind === 'run' || action.kind === 'rerun')) {
435
- const task = this.ledger.state().tasks.find(item => item.id === action.taskId)
436
- if (task?.teamRun === true) throw new Error('Agent Teams is unavailable in this deployment')
675
+ private applyBoardAction(requestId: string, action: Exclude<TaskBoardAction, { kind: 'extension-action' }>, initiator?: string, attachmentVerified = false): TaskBoardSnapshot {
676
+ // Attachments reach the ledger only through the VERIFIED action path: the
677
+ // in-process capability face, the agent tools and the legacy import never
678
+ // carry them, and an action that does is refused here rather than
679
+ // committed without the storage proof.
680
+ if (!attachmentVerified && attachmentsOfAction(action) !== undefined) {
681
+ throw new Error('attachments must be applied through the verified attachment action route')
437
682
  }
683
+ const before = this.statusMap()
684
+ if (action.kind === 'run' || action.kind === 'rerun' || action.kind === 'rework') this.assertSpendCap()
438
685
  const result = this.ledger.applyRequest(requestId, this.withInheritedWorkspace(action, initiator), initiator)
439
686
  if (result.runs !== undefined) this.dispatchRuns(result.runs)
440
687
  // A committed write that can move a rule moves the nearest trigger;
@@ -454,6 +701,25 @@ export class TaskBoardHostService {
454
701
  }
455
702
  }
456
703
 
704
+ /**
705
+ * Refuse a run whose day already spent the cap.
706
+ *
707
+ * A cap of 0 — the shipped default — answers before the measurement is read:
708
+ * no ledger file is opened and nothing is summed, which is what keeps a board
709
+ * that never configured a cap identical to the one before it existed.
710
+ *
711
+ * The refusal is a thrown message rather than a code: the wire hands its text
712
+ * to the caller as board-refused, exactly like every other refusal this board
713
+ * makes.
714
+ */
715
+ private assertSpendCap(): void {
716
+ const cap = this.spendBudgetTokens()
717
+ if (!(cap > 0)) return
718
+ const used = this.spendUsedToday(this.now())
719
+ if (used === undefined || !spendCapReached(used, cap)) return
720
+ throw new Error(spendCapMessage(used, cap))
721
+ }
722
+
457
723
  /** Route one provider action and answer the resulting board snapshot. */
458
724
  private async handleExtensionAction(action: Extract<TaskBoardAction, { kind: 'extension-action' }>): Promise<TaskBoardSnapshot> {
459
725
  await this.extensions.handleAction({
@@ -486,6 +752,14 @@ export class TaskBoardHostService {
486
752
 
487
753
  dispose(): void {
488
754
  this.disposed = true
755
+ // Launches still waiting for a slot can never start now: settle them so
756
+ // their cards leave the running column here, instead of waiting for the
757
+ // next Host start's interrupted-start recovery. Launches already in flight
758
+ // are left to finish — their session may already exist.
759
+ const abandoned = this.launches.drain()
760
+ if (abandoned.length > 0) {
761
+ safeConsoleError(`[dsh-task-board] ${abandoned.length} run member(s) were still waiting for a launch slot when the Host stopped; each is settled as cancelled`)
762
+ }
489
763
  this.extensions.dispose()
490
764
  this.clearScheduleTimer()
491
765
  this.clearPollBackoff()
@@ -496,39 +770,61 @@ export class TaskBoardHostService {
496
770
  this.listeners.clear()
497
771
  }
498
772
 
499
- private async launch(opened: OpenedRun, others: readonly OpenedRun[] = [], schedule?: ScheduledRunContext): Promise<void> {
773
+ private async launch(opened: OpenedRun, schedule?: ScheduledRunContext, freezeContract?: RunContractFreezer): Promise<void> {
500
774
  /** The session this launch attached to the execution, once it exists. */
501
775
  let attached: string | undefined
502
776
  try {
503
- // A team run always mints a fresh Lead session: teammates are immutable
504
- // children of that session, so reusing an older one would collide on
505
- // their names and orphan the previous team.
506
- const team = opened.task.teamRun === true
507
- const reuseSessionId = team ? undefined : await this.reuseSessionFor(opened.task)
508
- // Both modes tell the launched agent what else this run opens; only a team
509
- // run names teammates, because only then does this session own them.
510
- const peers = others.length === 0 ? undefined : others.map(other => ({
511
- id: other.task.id,
512
- title: other.task.title,
513
- ...(team ? { name: teammateName(other.task.title, other.execution.runGroupId ?? other.task.id, other.task.id) } : {}),
514
- }))
777
+ // One run opens ONE session: the card's own. Its unfinished subtasks are
778
+ // dispatched from inside that session, so a card that carries them is
779
+ // forced under the dispatcher preset and told which cards to pick up. The
780
+ // force is applied here, per execution; the card's stored `mode` is
781
+ // never rewritten by it.
782
+ const forcedPreset = this.ledger.hasOutstandingDescendants(opened.task.id) ? LIANGSHEN_PRESET_ID : undefined
783
+ const descendants = forcedPreset === undefined ? [] : this.ledger.outstandingDescendants(opened.task.id)
784
+ // The rework this execution carries, when it carries one: it decides both
785
+ // the session this run continues in and the section the prompt states.
786
+ const rework = opened.execution.rework
787
+ // A forced preset is not the card's own composition, so continuing a
788
+ // session composed from another preset would be refused anyway: mint a
789
+ // fresh one and run the tree the way this execution requires. A rework
790
+ // has no such freedom — its whole point is the conversation the reviewer
791
+ // read — so it fails instead of quietly opening a new one.
792
+ let reuseSessionId: string | undefined
793
+ if (rework === undefined) {
794
+ reuseSessionId = forcedPreset === undefined ? await this.reuseSessionFor(opened.task) : undefined
795
+ } else {
796
+ if (forcedPreset !== undefined) throw new Error(REWORK_SESSION_REASON)
797
+ reuseSessionId = await this.reworkSessionFor(opened.task)
798
+ }
515
799
  // A cron-triggered run additionally states its own firing instant and
516
800
  // rule zone, so a scheduled job can resolve "today" without guessing.
517
- const promptContext = peers === undefined && schedule === undefined ? undefined : {
518
- ...(peers === undefined ? {} : { peers }),
519
- ...(team ? { team: true } : {}),
801
+ const contextParts = {
802
+ ...(descendants.length === 0 ? {} : {
803
+ descendants: descendants.map(descendant => ({
804
+ id: descendant.id,
805
+ title: descendant.title,
806
+ status: descendant.status,
807
+ })),
808
+ }),
520
809
  ...(schedule === undefined ? {} : { schedule }),
810
+ ...(rework === undefined ? {} : { rework }),
521
811
  }
812
+ const promptContext = Object.keys(contextParts).length === 0 ? undefined : contextParts
522
813
  // Freeze this execution's acceptance contract BEFORE the session is
523
814
  // prompted: a settings change made while the run is in flight must not
524
815
  // retrofit the rule that will judge it. A card that opted out resolves the
525
816
  // same contract from an OFF switch: the board-wide switch decides the
526
817
  // default, the card decides this execution, and both are read here.
527
- const settings = this.verificationSettings()
528
- // The GLOBAL native-/goal switch is read ONCE here and carried by value
529
- // for the whole execution: a settings edit after this point can only
818
+ //
819
+ // The read is the run GROUP's when the queue handed one down: admission
820
+ // delays a member's launch, so a per-execution read would let a settings
821
+ // edit made while later members wait reach some members of one run and not
822
+ // others. One group, one contract — and still frozen before the group's
823
+ // first session is prompted.
824
+ const { settings, globalGoalEnabled, catalog } = await (freezeContract ?? (() => this.freezeRunContract()))()
825
+ // The GLOBAL native-/goal switch is read ONCE per run group and carried by
826
+ // value for the whole execution: a settings edit after this point can only
530
827
  // affect executions that start later.
531
- const globalGoalEnabled = this.goalRunEnabled() === true
532
828
  // The card must ASK for the goal run: the option is off by default, so an
533
829
  // absent value is a plain turn exactly like an explicit false.
534
830
  const goalEnabled = globalGoalEnabled && opened.task.goalRun === true
@@ -537,7 +833,7 @@ export class TaskBoardHostService {
537
833
  const skippedBy: ExecutionVerification['applicability'] = opened.task.skipVerification === true ? 'skipped' : 'disabled'
538
834
  const contract = resolveContract(
539
835
  { ...settings, enabled: settings.enabled && opened.task.skipVerification !== true },
540
- await this.verificationCatalog(),
836
+ catalog,
541
837
  )
542
838
  // An execution that will not become a goal run can never fire the
543
839
  // completion gate, so it is marked with the reason that actually applied:
@@ -552,15 +848,18 @@ export class TaskBoardHostService {
552
848
  const initial: ExecutionVerification = {
553
849
  contract,
554
850
  attempts: [],
555
- applicability: team ? 'team-member' : !contract.enabled ? skippedBy : notArmed,
851
+ applicability: !contract.enabled ? skippedBy : notArmed,
556
852
  }
557
853
  this.ledger.setVerification(opened.task.id, opened.execution.id, initial)
558
854
  const sessionId = await this.runner.launch(opened.task, {
559
855
  ...(reuseSessionId === undefined ? {} : { reuseSessionId }),
856
+ ...(forcedPreset === undefined ? {} : { agentPreset: forcedPreset }),
560
857
  ...(promptContext === undefined ? {} : { promptContext }),
561
858
  // The frozen global switch travels with the launch, so the runner's
562
859
  // arming decision is exactly the one made above.
563
860
  goalEnabled,
861
+ // The same catalog snapshot the acceptance contract was frozen from.
862
+ catalog,
564
863
  // Bind the session to the execution before the prompt is queued, so the
565
864
  // completion gate can never observe the agent without its binding.
566
865
  onSession: (id) => {
@@ -568,13 +867,10 @@ export class TaskBoardHostService {
568
867
  this.ledger.attachSession(opened.task.id, opened.execution.id, id)
569
868
  },
570
869
  onGoalArmed: (armed) => {
571
- this.setApplicability(opened.task.id, opened.execution.id, team
572
- ? 'team-member'
573
- : !contract.enabled ? skippedBy : armed ? 'enforced' : notArmed)
870
+ this.setApplicability(opened.task.id, opened.execution.id, !contract.enabled ? skippedBy : armed ? 'enforced' : notArmed)
574
871
  },
575
872
  })
576
873
  if (attached === undefined) this.ledger.attachSession(opened.task.id, opened.execution.id, sessionId)
577
- if (team) for (const teammate of others) this.scheduleTeammate(teammate, sessionId)
578
874
  } catch (error) {
579
875
  const launchedSession = error instanceof SessionLaunchError ? error.sessionId : undefined
580
876
  if (launchedSession !== undefined) {
@@ -585,53 +881,56 @@ export class TaskBoardHostService {
585
881
  // failed launch can never silently spend the user's run budget. A manual
586
882
  // run, and a launch that DID reach a session, are never refunded.
587
883
  if (schedule !== undefined && attached === undefined && launchedSession === undefined) {
588
- this.ledger.refundScheduledOccurrence(opened.task.id, this.now())
589
- // The refund runs after the fire already armed the next target, and a
590
- // refunded occurrence can restore one the fire had just cleared (a rule
591
- // that spent its last run). Re-arm so the restored occurrence is served
592
- // at its own instant rather than lost until some unrelated write.
593
- this.refreshSchedule()
884
+ this.refundUnstartedSchedule(opened.task.id)
594
885
  }
595
886
  this.settleAndNotify(opened.task.id, opened.execution.id, 'failed', error instanceof Error ? error.message : String(error))
596
887
  }
597
888
  }
598
889
 
599
- private scheduleTeammate(opened: OpenedRun, leadSessionId: string): void {
600
- void this.spawnTeammate(opened, leadSessionId).catch(error => {
601
- safeConsoleError('[dsh-task-board] teammate spawn settlement failed', error)
602
- })
890
+ /**
891
+ * Read the acceptance contract one run group freezes, in the order the board
892
+ * has always read it: the acceptance settings, then the global native-/goal
893
+ * switch, then the model catalog that both resolves the contract's route and
894
+ * decides the reasoning effort the session may be given.
895
+ */
896
+ private async freezeRunContract(): Promise<FrozenRunContract> {
897
+ const settings = this.verificationSettings()
898
+ const globalGoalEnabled = this.goalRunEnabled() === true
899
+ const catalog = await this.verificationCatalog()
900
+ return { settings, globalGoalEnabled, catalog }
603
901
  }
604
902
 
605
903
  /**
606
- * Spawn one teammate inside the Lead session and attach the teammate's
607
- * session to the subtask execution, so the existing session monitor settles
608
- * it from the teammate's own turn like any other execution. A spawn that
609
- * fails settles the subtask as failed immediately, which then folds into the
610
- * Lead's cascade verdict.
904
+ * A {@link RunContractFreezer} that reads once and hands the SAME value to
905
+ * every later caller of one run group. A read that fails is not cached: the
906
+ * next member reads again, exactly as a per-execution read would have.
611
907
  */
612
- private async spawnTeammate(opened: OpenedRun, leadSessionId: string): Promise<void> {
613
- const team = this.team
614
- if (team === undefined) {
615
- this.settleAndNotify(opened.task.id, opened.execution.id, 'failed', 'Agent Teams is unavailable in this deployment')
616
- return
617
- }
618
- try {
619
- const member = await team.spawn({
620
- leadSessionId,
621
- name: teammateName(opened.task.title, opened.execution.runGroupId ?? opened.task.id, opened.task.id),
622
- description: opened.task.title,
623
- prompt: promptText(opened.task),
908
+ private contractFreezerForRunGroup(): RunContractFreezer {
909
+ let pending: Promise<FrozenRunContract> | undefined
910
+ return () => {
911
+ pending ??= this.freezeRunContract().catch((error: unknown) => {
912
+ pending = undefined
913
+ throw error
624
914
  })
625
- if (member.sessionId === undefined || member.sessionId === '') {
626
- this.settleAndNotify(opened.task.id, opened.execution.id, 'failed', member.error ?? 'teammate provisioning failed')
627
- return
628
- }
629
- this.ledger.attachSession(opened.task.id, opened.execution.id, member.sessionId)
630
- } catch (error) {
631
- this.settleAndNotify(opened.task.id, opened.execution.id, 'failed', error instanceof Error ? error.message : String(error))
915
+ return pending
632
916
  }
633
917
  }
634
918
 
919
+ /**
920
+ * Give back the occurrence a launch consumed, for a launch that never reached
921
+ * a session: a failed launch, or one the Host abandoned while it was still
922
+ * waiting for an admission slot. A manual run, and a launch that DID reach a
923
+ * session, are never refunded.
924
+ */
925
+ private refundUnstartedSchedule(taskId: string): void {
926
+ this.ledger.refundScheduledOccurrence(taskId, this.now())
927
+ // The refund runs after the fire already armed the next target, and a
928
+ // refunded occurrence can restore one the fire had just cleared (a rule
929
+ // that spent its last run). Re-arm so the restored occurrence is served
930
+ // at its own instant rather than lost until some unrelated write.
931
+ this.refreshSchedule()
932
+ }
933
+
635
934
  /**
636
935
  * One roster pass, and whether it could read the session tree.
637
936
  *
@@ -698,10 +997,13 @@ export class TaskBoardHostService {
698
997
  * reads no roster at all, and a read that fails mints a fresh conversation
699
998
  * exactly as an unknown roster always did.
700
999
  * @param task - the task about to run.
1000
+ * @param force - continue the settled session regardless of the card's own
1001
+ * opt-in (a rework), which the reuse rule accepts without waiving any of its
1002
+ * evidence conditions.
701
1003
  * @returns the session id to continue in, or undefined for a fresh session.
702
1004
  */
703
- private async reuseSessionFor(task: TaskRecord): Promise<string | undefined> {
704
- if (task.reuseSession !== true) return undefined
1005
+ private async reuseSessionFor(task: TaskRecord, force?: boolean): Promise<string | undefined> {
1006
+ if (task.reuseSession !== true && force !== true) return undefined
705
1007
  let running: Awaited<ReturnType<HostExecutionRunner['listRunning']>>
706
1008
  try {
707
1009
  running = await this.runner.listRunning()
@@ -713,7 +1015,29 @@ export class TaskBoardHostService {
713
1015
  return undefined
714
1016
  }
715
1017
  if (!running.known) return undefined
716
- return reusableSessionId(task, new Set(running.items.filter(item => !item.running).map(item => item.sessionId)))
1018
+ return reusableSessionId(
1019
+ task,
1020
+ new Set(running.items.filter(item => !item.running).map(item => item.sessionId)),
1021
+ force === true ? { force: true } : {},
1022
+ )
1023
+ }
1024
+
1025
+ /**
1026
+ * The session a rework continues, or the refusal that says why it cannot.
1027
+ *
1028
+ * A rework exists for one conversation — the one the reviewer read before
1029
+ * sending the work back — so the evidence that this Host still reaches it is
1030
+ * required, exactly as it is for a card that opted into reuse. What a rework
1031
+ * does NOT get is the fresh-conversation fallback: launching there would hand
1032
+ * the reviewer's instructions to an agent that never saw the work, so the run
1033
+ * fails with a readable reason instead.
1034
+ * @param task - the card being reworked.
1035
+ * @returns the session id this rework continues in.
1036
+ */
1037
+ private async reworkSessionFor(task: TaskRecord): Promise<string> {
1038
+ const sessionId = await this.reuseSessionFor(task, true)
1039
+ if (sessionId === undefined) throw new Error(REWORK_SESSION_REASON)
1040
+ return sessionId
717
1041
  }
718
1042
 
719
1043
  /** Reuse the session list this poll already fetched: one list RPC per tick, not 1 + E. */
@@ -764,10 +1088,13 @@ export class TaskBoardHostService {
764
1088
  : verificationOnlyInvalid(verification)
765
1089
  ? INVALID_ONLY_VERIFICATION_REASON
766
1090
  : NO_MATCHING_PASS_VERIFICATION_REASON,
1091
+ result.summary,
767
1092
  )
768
1093
  continue
769
1094
  }
770
- this.settleAndNotify(execution.taskId, execution.executionId, result.outcome, 'error' in result ? result.error : undefined)
1095
+ // The run's closing text rides whichever verdict it earned: a failed
1096
+ // execution still leaves what it managed to say.
1097
+ this.settleAndNotify(execution.taskId, execution.executionId, result.outcome, 'error' in result ? result.error : undefined, result.summary)
771
1098
  } catch {
772
1099
  // A transient inspection failure never settles a running execution.
773
1100
  }
@@ -787,20 +1114,20 @@ export class TaskBoardHostService {
787
1114
  * ancestor of it — in the running column with no way out. The first poll of
788
1115
  * each streak is logged, so the Host log names the session.
789
1116
  */
790
- private settleAndNotify(taskId: string, executionId: string, outcome: ExecutionOutcome, error?: string): void {
1117
+ private settleAndNotify(taskId: string, executionId: string, outcome: ExecutionOutcome, error?: string, summary?: ExecutionSummary): void {
791
1118
  const before = this.ledger.getTask(taskId)
792
1119
  if (before?.executions.find(entry => entry.id === executionId)?.endedAt !== undefined) {
793
1120
  // Already settled: the ledger would no-op, and re-emitting would report
794
1121
  // the same settlement twice.
795
- this.ledger.settle(taskId, executionId, outcome, error)
1122
+ this.ledger.settle(taskId, executionId, outcome, error, summary)
796
1123
  return
797
1124
  }
798
- const previousStatus = before?.status
799
- this.ledger.settle(taskId, executionId, outcome, error)
800
- const task = this.ledger.getTask(taskId)
801
- if (task !== undefined && previousStatus !== undefined && previousStatus !== task.status) {
802
- this.extensions.emitStatusChanged({ taskId, status: task.status, previous: previousStatus })
803
- }
1125
+ // One settlement can move more than the settled card: a run whose own card
1126
+ // is terminal also writes the inherited verdict onto the subtasks it never
1127
+ // dispatched. Compare the whole board so the provider events cover those too.
1128
+ const statuses = this.statusMap()
1129
+ this.ledger.settle(taskId, executionId, outcome, error, summary)
1130
+ this.emitStatusChanges(statuses)
804
1131
  this.extensions.emitExecutionSettled({
805
1132
  taskId,
806
1133
  executionId,
@@ -978,20 +1305,18 @@ export class TaskBoardHostService {
978
1305
  }
979
1306
 
980
1307
  /**
981
- * Launch one run set. The root goes first and receives the run shape in its
982
- * prompt (which members this run opens, and how they run); every plain-cascade
983
- * member then launches on its own so one refused participant cannot hold the
984
- * others back. A team run's members are spawned inside the root's Lead
985
- * session instead, once that session exists.
1308
+ * Launch the one run a run request opened. A run request names one card and
1309
+ * opens one execution for it; the card's own session dispatches its subtasks
1310
+ * as subagents, so nothing else is enqueued here.
1311
+ *
1312
+ * The launch still goes through the admission queue, which admits at most
1313
+ * `runLaunchWidth` launches at a time — that bound now applies across
1314
+ * concurrent runs rather than across the members of one run.
986
1315
  */
987
1316
  private dispatchRuns(runs: readonly OpenedRun[], schedule?: ScheduledRunContext): void {
988
- if (runs.length === 0) return
989
- const root = runs.find(run => run.dispatch !== 'teammate') ?? runs[0]
990
- const others = runs.filter(run => run !== root)
991
- this.scheduleLaunch(root, others, schedule)
992
- for (const run of others) {
993
- if (run.dispatch !== 'teammate') this.scheduleLaunch(run, [], schedule)
994
- }
1317
+ const root = runs[0]
1318
+ if (root === undefined) return
1319
+ this.scheduleLaunch(root, schedule, this.contractFreezerForRunGroup())
995
1320
  }
996
1321
 
997
1322
  /**
@@ -1004,10 +1329,58 @@ export class TaskBoardHostService {
1004
1329
  this.ledger.setVerification(taskId, executionId, { ...verification, applicability })
1005
1330
  }
1006
1331
 
1007
- private scheduleLaunch(opened: OpenedRun, others: readonly OpenedRun[] = [], schedule?: ScheduledRunContext): void {
1008
- void this.launch(opened, others, schedule).catch(error => {
1332
+ private scheduleLaunch(opened: OpenedRun, schedule?: ScheduledRunContext, freezeContract?: RunContractFreezer): void {
1333
+ this.enqueueLaunch(opened, () => this.launch(opened, schedule, freezeContract).catch(error => {
1009
1334
  safeConsoleError('[dsh-task-board] execution launch settlement failed', error)
1010
- })
1335
+ }), schedule)
1336
+ }
1337
+
1338
+ /**
1339
+ * Hand one launch to the admission queue, or abandon it on the spot when the
1340
+ * Host is already stopping: a queue entry created after {@link dispose} would
1341
+ * otherwise never be drained, and its card would sit in the running column
1342
+ * until the next Host start recovered it.
1343
+ */
1344
+ private enqueueLaunch(opened: OpenedRun, start: () => Promise<void>, schedule?: ScheduledRunContext): void {
1345
+ const launch: QueuedLaunch = {
1346
+ groupId: opened.execution.runGroupId ?? opened.task.id,
1347
+ start: async () => {
1348
+ // Waiting for a slot is time the execution can be settled in: a manual
1349
+ // settle, or a team run folded onto its Lead's verdict, can close a
1350
+ // member's execution before it ever started. Starting it then would
1351
+ // create a session no execution is watching, so a launch whose
1352
+ // execution is already closed is dropped instead.
1353
+ if (!this.isExecutionOpen(opened)) return
1354
+ await start()
1355
+ },
1356
+ abandon: () => this.abandonQueuedRun(opened, schedule),
1357
+ }
1358
+ if (this.disposed) {
1359
+ launch.abandon()
1360
+ return
1361
+ }
1362
+ this.launches.enqueue(launch)
1363
+ }
1364
+
1365
+ /** Whether one opened execution is still open in the ledger. */
1366
+ private isExecutionOpen(opened: OpenedRun): boolean {
1367
+ const execution = this.ledger.getTask(opened.task.id)?.executions.find(entry => entry.id === opened.execution.id)
1368
+ return execution !== undefined && execution.endedAt === undefined
1369
+ }
1370
+
1371
+ /**
1372
+ * Take one launch that never started out of the running column.
1373
+ *
1374
+ * Settled as CANCELLED, not failed: nothing about the run's work went wrong —
1375
+ * the Host stopped before the launch got a slot, which is exactly what the
1376
+ * next start's interrupted-start recovery records for an execution that never
1377
+ * reached a session. A scheduled occurrence that never reached a session is
1378
+ * refunded on the same terms as any other pre-session failure, so a run the
1379
+ * Host never started cannot silently spend the user's run budget.
1380
+ */
1381
+ private abandonQueuedRun(opened: OpenedRun, schedule?: ScheduledRunContext): void {
1382
+ if (schedule !== undefined) this.refundUnstartedSchedule(opened.task.id)
1383
+ this.settleAndNotify(opened.task.id, opened.execution.id, 'cancelled', ABANDONED_LAUNCH_REASON)
1011
1384
  }
1012
1385
 
1013
1386
  private schedulePoll(): void {