@fish-under-sea/dsh-agent-teams-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 (179) hide show
  1. package/NOTICE.md +13 -7
  2. package/README.en.md +20 -12
  3. package/README.md +20 -12
  4. package/compatibility.json +82 -46
  5. package/icon.png +0 -0
  6. package/lib/artifacts.js +148 -25
  7. package/lib/client/ActivityPanel.js +26 -5
  8. package/lib/client/WorkspaceActivity.js +6 -4
  9. package/lib/client/activity-monitor.js +113 -41
  10. package/lib/client/locales.js +14 -0
  11. package/lib/client.js +433 -199
  12. package/lib/client.js.map +1 -1
  13. package/lib/command.js +7 -4
  14. package/lib/git-artifact-stamp.json +2 -2
  15. package/lib/harness-compat.js +120 -62
  16. package/lib/index.js +7 -10
  17. package/lib/mailbox.js +15 -5
  18. package/lib/members.js +221 -154
  19. package/lib/snapshot.js +15 -10
  20. package/lib/state.js +41 -8
  21. package/lib/tools.js +123 -64
  22. package/lib/types/artifacts.d.ts +6 -3
  23. package/lib/types/client/activity-monitor.d.ts +13 -4
  24. package/lib/types/client/locales.d.ts +14 -0
  25. package/lib/types/harness-compat.d.ts +63 -16
  26. package/lib/types/mailbox.d.ts +2 -0
  27. package/lib/types/members.d.ts +5 -17
  28. package/lib/types/snapshot.d.ts +12 -7
  29. package/lib/types/state.d.ts +10 -3
  30. package/lib/types/types.d.ts +5 -0
  31. package/lib/types/web-routes.d.ts +2 -0
  32. package/lib/types/workspace-audit-service.d.ts +35 -0
  33. package/lib/types/workspace-audit-worker.d.ts +1 -0
  34. package/lib/web-routes.js +31 -0
  35. package/lib/workspace-audit-service.js +165 -0
  36. package/lib/workspace-audit-worker.js +11 -0
  37. package/lib/workspace-audit.js +6 -5
  38. package/locale/en.json +6 -0
  39. package/locale/zh.json +6 -0
  40. package/package.json +69 -64
  41. package/pnpm-workspace.yaml +306 -273
  42. package/release-notes/v0.1.25.md +16 -0
  43. package/release-notes/v0.1.26.md +19 -0
  44. package/release-notes/v0.1.27.md +42 -0
  45. package/release-notes/v0.1.28.md +45 -0
  46. package/release-notes/v0.1.29.md +23 -0
  47. package/release-notes/v1.1.0.md +42 -0
  48. package/release-notes/v2.0.0.md +17 -0
  49. package/scripts/artwork-role-match.test.mjs +517 -0
  50. package/scripts/capabilities.test.mjs +301 -0
  51. package/scripts/check-install-channel.mjs +55 -0
  52. package/scripts/check-install-channel.test.mjs +39 -0
  53. package/scripts/clean-build.mjs +14 -0
  54. package/scripts/client-harness-migration.test.mjs +46 -0
  55. package/scripts/compatibility.mjs +20 -0
  56. package/scripts/compatibility.test.mjs +187 -0
  57. package/scripts/corrupt-teamjson.test.mjs +180 -0
  58. package/scripts/custom-artwork.test.mjs +273 -0
  59. package/scripts/fallback-tdd.mjs +61 -0
  60. package/scripts/fixtures/harness-benchmark-scope.mjs +16 -0
  61. package/scripts/fixtures/harness-benchmark-scope.test.mjs +18 -0
  62. package/scripts/fixtures/harness-complex-case.mjs +201 -0
  63. package/scripts/fixtures/harness-complex-case.test.mjs +21 -0
  64. package/scripts/fixtures/harness-complex-oracle.mjs +63 -0
  65. package/scripts/fixtures/harness-issue-case.mjs +51 -0
  66. package/scripts/fixtures/harness-issue159-case.mjs +28 -0
  67. package/scripts/fixtures/harness-model-case.mjs +127 -0
  68. package/scripts/fixtures/harness-model-case.test.mjs +37 -0
  69. package/scripts/fixtures/harness-model-driver.mjs +100 -0
  70. package/scripts/fixtures/harness-runtime-credentials.mjs +23 -0
  71. package/scripts/fixtures/harness-runtime-entry.mjs +171 -0
  72. package/scripts/fixtures/harness-runtime-idle.mjs +42 -0
  73. package/scripts/fixtures/harness-runtime-llm.mjs +193 -0
  74. package/scripts/fixtures/harness-runtime-protocol.mjs +187 -0
  75. package/scripts/fixtures/harness-runtime-resume.mjs +24 -0
  76. package/scripts/fixtures/harness-runtime-stability.mjs +282 -0
  77. package/scripts/fixtures/harness-runtime-tools.mjs +13 -0
  78. package/scripts/fixtures/harness-runtime-web-approval.mjs +341 -0
  79. package/scripts/fixtures/issue-336-audit-worker.mjs +18 -0
  80. package/scripts/git-artifacts.mjs +64 -0
  81. package/scripts/git-artifacts.test.mjs +32 -0
  82. package/scripts/harness-compat-tdd.mjs +492 -0
  83. package/scripts/harness-issue-verify.mjs +26 -0
  84. package/scripts/harness-model-benchmark.mjs +163 -0
  85. package/scripts/harness-runtime-platform.test.mjs +31 -0
  86. package/scripts/harness-runtime-scenarios.mjs +297 -0
  87. package/scripts/harness-runtime-verify.mjs +169 -0
  88. package/scripts/harness-source-verify.mjs +211 -0
  89. package/scripts/harness-source-verify.test.mjs +97 -0
  90. package/scripts/harness-validation.mjs +68 -0
  91. package/scripts/harness-validation.test.mjs +95 -0
  92. package/scripts/http-body.test.mjs +72 -0
  93. package/scripts/import-vendor-artwork.mjs +78 -0
  94. package/scripts/inline-plan-blank-optional-tdd.mjs +121 -0
  95. package/scripts/issue-159.test.mjs +78 -0
  96. package/scripts/issue-188.test.mjs +148 -0
  97. package/scripts/issue-189.test.mjs +100 -0
  98. package/scripts/issue-203-card.test.mjs +181 -0
  99. package/scripts/issue-205.test.mjs +163 -0
  100. package/scripts/issue-234.test.mjs +424 -0
  101. package/scripts/issue-236-stale-module.test.mjs +63 -0
  102. package/scripts/issue-236.test.mjs +59 -0
  103. package/scripts/issue-262.test.mjs +98 -0
  104. package/scripts/issue-336.test.mjs +404 -0
  105. package/scripts/legacy-session-source-repair.test.mjs +201 -0
  106. package/scripts/lifecycle-verify.mjs +1573 -0
  107. package/scripts/lineage-identity.test.mjs +77 -0
  108. package/scripts/member-failure-tdd.mjs +451 -0
  109. package/scripts/member-spawn-recovery.test.mjs +92 -0
  110. package/scripts/quality-gates-amend.test.mjs +161 -0
  111. package/scripts/quality-gates-content-bound.test.mjs +572 -0
  112. package/scripts/quality-gates-cross-binding.test.mjs +184 -0
  113. package/scripts/quality-gates-excluded-scope.test.mjs +163 -0
  114. package/scripts/quality-gates-repair-scope.test.mjs +143 -0
  115. package/scripts/quality-gates-repair-wiring.test.mjs +189 -0
  116. package/scripts/quality-gates-tdd.mjs +1238 -0
  117. package/scripts/quality-gates-work-order.test.mjs +494 -0
  118. package/scripts/readme-version.mjs +89 -0
  119. package/scripts/readme-version.test.mjs +77 -0
  120. package/scripts/release-metadata.mjs +45 -0
  121. package/scripts/release-metadata.test.mjs +66 -0
  122. package/scripts/scoped-release.test.mjs +52 -0
  123. package/scripts/stability-tdd.mjs +144 -0
  124. package/scripts/stress-verify.mjs +548 -0
  125. package/scripts/symlink-support.mjs +46 -0
  126. package/scripts/sync-skill.mjs +103 -0
  127. package/scripts/tool-policies.test.mjs +280 -0
  128. package/scripts/update-skills.mjs +105 -0
  129. package/scripts/update-skills.test.mjs +79 -0
  130. package/scripts/upgrade-status.mjs +66 -0
  131. package/scripts/upgrade-status.test.mjs +83 -0
  132. package/scripts/verify-package.mjs +73 -0
  133. package/scripts/verify.mjs +2199 -0
  134. package/scripts/web-routes-verify.mjs +142 -0
  135. package/scripts/workspace-activity.test.mjs +346 -0
  136. package/scripts/workspace-summary.test.mjs +49 -0
  137. package/src/artifacts.ts +487 -0
  138. package/src/artwork-source.ts +262 -0
  139. package/src/capabilities.ts +113 -0
  140. package/src/client/ActivityPanel.module.css +2390 -0
  141. package/src/client/ActivityPanel.tsx +1507 -0
  142. package/src/client/AgentTeamsCard.module.css +148 -0
  143. package/src/client/AgentTeamsCard.tsx +155 -0
  144. package/src/client/StagingPlanEditor.tsx +829 -0
  145. package/src/client/TeamChatEntry.tsx +27 -0
  146. package/src/client/WorkspaceActivity.module.css +41 -0
  147. package/src/client/WorkspaceActivity.tsx +137 -0
  148. package/src/client/activity-model.ts +372 -0
  149. package/src/client/activity-monitor.ts +440 -0
  150. package/src/client/agent-teams-card-definition.ts +250 -0
  151. package/src/client/artwork.ts +374 -0
  152. package/src/client/icons.tsx +17 -0
  153. package/src/client/index.tsx +140 -0
  154. package/src/client/locales.ts +481 -0
  155. package/src/client/panel-geometry.ts +194 -0
  156. package/src/client/session-navigation.ts +73 -0
  157. package/src/client/workspace-state.ts +52 -0
  158. package/src/command.ts +145 -0
  159. package/src/css-modules.d.ts +4 -0
  160. package/src/event-types.ts +177 -0
  161. package/src/events.ts +78 -0
  162. package/src/harness-compat.ts +570 -0
  163. package/src/index.ts +599 -0
  164. package/src/lineage.ts +248 -0
  165. package/src/mailbox.ts +185 -0
  166. package/src/members.ts +1230 -0
  167. package/src/profiles.ts +765 -0
  168. package/src/quality-gates.ts +2124 -0
  169. package/src/scheduler.ts +554 -0
  170. package/src/snapshot.ts +333 -0
  171. package/src/state.ts +1317 -0
  172. package/src/tool-names.ts +14 -0
  173. package/src/tool-policies.ts +219 -0
  174. package/src/tools.ts +2939 -0
  175. package/src/types.ts +414 -0
  176. package/src/web-routes.ts +128 -0
  177. package/src/workspace-audit-service.ts +182 -0
  178. package/src/workspace-audit-worker.ts +12 -0
  179. package/src/workspace-audit.ts +57 -0
package/src/tools.ts ADDED
@@ -0,0 +1,2939 @@
1
+ import { drainMemberChildren } from './harness-compat.ts'
2
+ /**
3
+ * The `agent_teams_*` model-facing tools.
4
+ *
5
+ * The captain (the agent that created the team) orchestrates: members are
6
+ * continuable subagents it spawns and wakes. Members share the same tools and
7
+ * drive their own task state, mirroring the Claude Code AgentTeams flow:
8
+ * create team → add members → create tasks with dependencies → claim/assign →
9
+ * work → report → status → delete.
10
+ * @module dsh-agent-teams/tools
11
+ */
12
+
13
+ import type { Context } from '@deepseek-ai/cordis'
14
+ import type { Agent } from '@deepseek-ai/dsh-agent'
15
+ import { createUserMessage } from '@deepseek-ai/dsh-llm'
16
+ import type { SessionId } from '@deepseek-ai/dsh-session'
17
+ import type { JsonValue } from '@deepseek-ai/dsh-util-values'
18
+ import { defineTool } from '@deepseek-ai/dsh-tools'
19
+ import type { ToolRunContext } from '@deepseek-ai/dsh-tools'
20
+ import { join } from 'node:path'
21
+ import { appendTeamEvent, captainSessionOf } from './events.ts'
22
+ import {
23
+ amendTaskContract,
24
+ acknowledgeMailbox,
25
+ markMailboxDelivered,
26
+ discardMailboxMessages,
27
+ appendMailbox,
28
+ archiveTeamDir,
29
+ beginTaskAttempt,
30
+ CAPTAIN_KEY,
31
+ createMessage,
32
+ createTeamDir,
33
+ findTeamByCaptain,
34
+ findTeamByParticipant,
35
+ cancelUnfinishedTask,
36
+ invalidateTaskAttempt,
37
+ readUnreadMailbox,
38
+ readMailbox,
39
+ recordRetiredMemberIds,
40
+ releaseMailboxDelivery,
41
+ readTeam,
42
+ sanitizeKey,
43
+ transitionError,
44
+ unsatisfiedDependencies,
45
+ withTeamLock,
46
+ writeTeam,
47
+ validateCreateTask,
48
+ evaluateQualityCompletion,
49
+ planQualityFollowUp,
50
+ resumeTeamState,
51
+ buildCoverageMatrix,
52
+ canDeclareDelivery,
53
+ describeQualityLoop,
54
+ sanitizeReviewAcceptance,
55
+ sanitizeReviewObjective,
56
+ isValidFindingLine,
57
+ normalizeBlankOptionalTaskFields,
58
+ taskKindOf,
59
+ } from './state.ts'
60
+ import { appendTaskEvidence } from './quality-gates.ts'
61
+ import {
62
+ artifactDrift,
63
+ bindReviewToRevision,
64
+ deliveryArtifactPaths,
65
+ deliveryScopePatterns,
66
+ isQualityKind,
67
+ verdictScopePatterns,
68
+ } from './quality-gates.ts'
69
+ import type { DeliveryAudit } from './quality-gates.ts'
70
+ import { workspaceAuditor } from './workspace-audit-service.ts'
71
+ import { readArtifactScope, snapshotWorkspacePaths, workspacePathExists } from './artifacts.ts'
72
+ import { agentTeamsSource, observedSessionFormatVersion, restrictableToolNames } from './harness-compat.ts'
73
+ import { memberSpawnRelaxableDeny, optionalToolPolicy, requireToolPolicy, resolveMemberToolFilter, type MemberToolFilter, type MemberToolPolicy } from './tool-policies.ts'
74
+ import type { ContractAmendmentInput } from './state.ts'
75
+ import type { AcceptanceResult, ArtifactDigest, ArtifactSnapshot, CommandResult, ReviewFinding, ReviewVerdict, TaskKind } from './types.ts'
76
+ import {
77
+ captainRouteOf,
78
+ deliverToMember,
79
+ installRetiredMemberGuard,
80
+ installMemberSelectionRuntime,
81
+ installMemberDelegationGuard,
82
+ memberActivity,
83
+ resolveMemberLlmSelection,
84
+ spawnMember,
85
+ steerCaptainReport,
86
+ validateMemberLlmSelections,
87
+ type MemberRuntimeConfig,
88
+ } from './members.ts'
89
+ import { TERMINAL_TASK_STATUSES, type TeamMember, type TeamMessage, type TeamState, type TeamTask } from './types.ts'
90
+ import { collectCompletedDependencyOutputs, formatDependencyOutputs, installTeamScheduler } from './scheduler.ts'
91
+ import { installMailboxAdmission, isCurrentMail, mailboxContent, mailboxPrompt, readCurrentMailboxLocked } from './mailbox.ts'
92
+ import { resolveTeamProfile } from './profiles.ts'
93
+ import { forkLineageNote, leadIdentityOf, leadIdentityOfAsync, nearestLiveLead, sessionLeadsTeam, sessionLeadsTeamAsync } from './lineage.ts'
94
+
95
+ export { steerCaptainReport } from './members.ts'
96
+
97
+ /** Resolved plugin config consumed by the tools. */
98
+ export interface ToolsConfig {
99
+ /** State directory name under the captain's workspace. */
100
+ stateDir: string
101
+ /** Member subagent provider name. */
102
+ memberProvider: string
103
+ /** Optional member model override. */
104
+ memberModel?: string
105
+ /** Optional member LLM provider, paired with `memberModel` (issue #189). */
106
+ memberLlmProvider?: string
107
+ /** Prompt injected into member personas and assignments. */
108
+ executionPrompt?: string
109
+ /** Plugin fallback route. */
110
+ fallback?: import('./profiles.ts').TeamModelFallbackConfig
111
+ /** Member delegation depth cap. */
112
+ memberMaxDepth?: number
113
+ /** Team size cap (members). */
114
+ maxMembers: number
115
+ /** Named team profiles from the active DSH profile. */
116
+ profiles: Record<string, import('./profiles.ts').TeamProfileConfig>
117
+ /** Owner-declared reusable member tool policies, keyed by policy id (#59). */
118
+ toolPolicies: Record<string, MemberToolPolicy>
119
+ }
120
+
121
+ /** Browser/UI mutations allowed while a plan is waiting for approval. */
122
+ export type StagedPlanMutation =
123
+ | {
124
+ action: 'update_member'
125
+ memberName: string
126
+ role?: string | null
127
+ provider: string
128
+ model: string
129
+ reasoningEffort?: string | null
130
+ executionPrompt?: string | null
131
+ /** Selected tool-policy id; an empty string clears it back to no policy. */
132
+ toolPolicy?: string
133
+ }
134
+ | {
135
+ action: 'update_task'
136
+ taskId: string
137
+ subject: string
138
+ description?: string | null
139
+ assignee?: string | null
140
+ dependencies: string[]
141
+ }
142
+ | {
143
+ action: 'add_task'
144
+ subject: string
145
+ description?: string | null
146
+ assignee?: string | null
147
+ dependencies: string[]
148
+ }
149
+ | { action: 'remove_task'; taskId: string }
150
+ | { action: 'remove_member'; memberName: string }
151
+
152
+ /** Runtime bridge shared by model-facing tools and the Web staging surface. */
153
+ export interface AgentTeamsRuntime {
154
+ isPendingMember(agent: Agent): boolean
155
+ updateStagedPlan(captain: Agent, teamId: string, mutation: StagedPlanMutation, signal?: AbortSignal): Promise<TeamState>
156
+ updateStagedPlanBatch(captain: Agent, teamId: string, mutations: readonly StagedPlanMutation[], signal?: AbortSignal): Promise<TeamState>
157
+ approveStagedTeam(captain: Agent, teamId: string, signal?: AbortSignal): Promise<{ teamId: string; members: number; tasks: number }>
158
+ continueStagedPlanning(captain: Agent, teamId: string): Promise<{ teamId: string; alreadyWaiting: boolean }>
159
+ discardStagedTeam(captain: Agent, teamId: string): Promise<{ teamId: string }>
160
+ }
161
+
162
+ /** The caller agent, or a loud failure for non-agent callers. */
163
+ function requireCaptain(exec: ToolRunContext): Agent {
164
+ if (!exec.agent) {
165
+ throw new Error('agent_teams tools require a calling agent (exec.agent was undefined)')
166
+ }
167
+ return exec.agent
168
+ }
169
+
170
+ /** The captain's workspace directory (team state root parent). */
171
+ function workspaceOf(agent: Agent): string {
172
+ return agent.session.header.cwd ?? process.cwd()
173
+ }
174
+
175
+ /** Resolved absolute state root. */
176
+ function stateRootOf(workspace: string, config: ToolsConfig): string {
177
+ return join(workspace, config.stateDir)
178
+ }
179
+
180
+ /** Process-local lock key scoped by workspace state root and team id. */
181
+ function teamLockKey(stateRoot: string, teamId: string): string {
182
+ return `team:${stateRoot}:${teamId}`
183
+ }
184
+
185
+ /**
186
+ * Bind a closing verdict to the revision it judged, using the snapshot taken
187
+ * when its attempt started (if any) to notice that the workspace changed while
188
+ * the gate was being formed. A verdict that ran over a moving workspace binds
189
+ * the drift explicitly instead of claiming the current bytes.
190
+ */
191
+ function bindClosingVerdict(workspace: string, team: TeamState, task: TeamTask): void {
192
+ if (task.status !== 'completed') return
193
+ const kind = taskKindOf(task)
194
+ if (kind !== 'review' && kind !== 'requirements' && kind !== 'verification') return
195
+ if ((kind === 'review' || kind === 'requirements') && task.verdict !== 'pass') return
196
+ const scope = verdictScopePatterns(team, task)
197
+ if (scope.length === 0) return
198
+ const read = readArtifactScope(workspace, scope)
199
+ const duringDrift = task.verdictStartSnapshot === undefined
200
+ ? []
201
+ : artifactDrift(task.verdictStartSnapshot.artifacts, read.artifacts)
202
+ const bound = bindReviewToRevision(team, task, {
203
+ artifacts: read.artifacts,
204
+ gaps: read.gaps,
205
+ scope,
206
+ duringDrift,
207
+ })
208
+ task.reviewedTaskId = bound.reviewedTaskId
209
+ task.reviewedAttempt = bound.reviewedAttempt
210
+ task.reviewedArtifacts = bound.reviewedArtifacts
211
+ task.reviewedGaps = bound.reviewedGaps
212
+ task.reviewedScope = bound.reviewedScope
213
+ task.reviewedDuringDrift = bound.reviewedDuringDrift
214
+ task.verdictStartSnapshot = undefined
215
+ }
216
+
217
+ /** Process-local lock key enforcing one active team per captain session. */
218
+ function captainLockKey(stateRoot: string, captainId: string): string {
219
+ return `captain:${stateRoot}:${captainId}`
220
+ }
221
+
222
+ /** The team this captain currently leads, or a loud failure. */
223
+ async function requireCaptainTeam(ctx: Context, workspace: string, config: ToolsConfig, captain: Agent): Promise<TeamState> {
224
+ const team = await findTeamByCaptain(stateRootOf(workspace, config), captain.id, await leadIdentityOfAsync(ctx, captain.session))
225
+ if (team === undefined) {
226
+ throw new Error(`you are not leading any team yet — call agent_teams_create first${forkLineageNote(captain.session)}`)
227
+ }
228
+ return team
229
+ }
230
+
231
+ /** The team this captain or active member currently participates in. */
232
+ async function requireParticipantTeam(ctx: Context, workspace: string, config: ToolsConfig, caller: Agent): Promise<TeamState> {
233
+ const team = await findTeamByParticipant(stateRootOf(workspace, config), caller.id, await leadIdentityOfAsync(ctx, caller.session))
234
+ if (team === undefined) {
235
+ throw new Error(`you do not lead or belong to any active team yet${forkLineageNote(caller.session)}`)
236
+ }
237
+ return team
238
+ }
239
+
240
+ type ParticipantIdentity =
241
+ | { kind: 'captain'; name: typeof CAPTAIN_KEY }
242
+ | { kind: 'member'; name: string }
243
+
244
+ /** Re-derive a caller's role from fresh state while holding the team lock. */
245
+ async function participantIdentityOf(ctx: Context, team: TeamState, agentId: string): Promise<ParticipantIdentity | undefined> {
246
+ if (await sessionLeadsTeamAsync(ctx, team, agentId)) return { kind: 'captain', name: CAPTAIN_KEY }
247
+ const member = team.members.find((candidate) => candidate.id === agentId && candidate.status !== 'removed')
248
+ return member === undefined ? undefined : { kind: 'member', name: member.name }
249
+ }
250
+
251
+ /** Fresh state for a team that still exists; never falls back to stale lookup data. */
252
+ async function requireFreshTeam(stateRoot: string, teamId: string): Promise<TeamState> {
253
+ const fresh = await readTeam(stateRoot, teamId)
254
+ if (fresh === undefined) throw new Error(`team "${teamId}" is no longer active`)
255
+ return fresh
256
+ }
257
+
258
+ /** Fresh state with captain authorization rechecked inside the lock. */
259
+ async function requireFreshCaptainTeam(
260
+ ctx: Context,
261
+ stateRoot: string,
262
+ teamId: string,
263
+ captainId: string,
264
+ ): Promise<TeamState> {
265
+ const fresh = await requireFreshTeam(stateRoot, teamId)
266
+ if (!(await sessionLeadsTeamAsync(ctx, fresh, captainId))) {
267
+ throw new Error(`only the captain of team "${fresh.name}" (session ${fresh.captainSessionId}) or one of its fork descendants may perform this operation`)
268
+ }
269
+ return fresh
270
+ }
271
+
272
+ /** Fresh state and caller identity rechecked inside the lock. */
273
+ async function requireFreshParticipant(
274
+ ctx: Context,
275
+ stateRoot: string,
276
+ teamId: string,
277
+ callerId: string,
278
+ ): Promise<{ team: TeamState; identity: ParticipantIdentity }> {
279
+ const fresh = await requireFreshTeam(stateRoot, teamId)
280
+ const identity = await participantIdentityOf(ctx, fresh, callerId)
281
+ if (identity === undefined) throw new Error(`you are no longer an active participant in team "${fresh.name}"`)
282
+ return { team: fresh, identity }
283
+ }
284
+
285
+ /** Look up one live (non-removed) member by display name. */
286
+ function requireMember(team: TeamState, name: string): TeamMember {
287
+ const member = team.members.find((candidate) => candidate.name === name && candidate.status !== 'removed')
288
+ if (member === undefined) {
289
+ throw new Error(`no active member named "${name}" in team "${team.name}"`)
290
+ }
291
+ return member
292
+ }
293
+
294
+ /** Look up one task by id. */
295
+ function requireTask(team: TeamState, taskId: string): TeamTask {
296
+ const task = team.tasks.find((candidate) => candidate.id === taskId)
297
+ if (task === undefined) {
298
+ throw new Error(`no task "${taskId}" in team "${team.name}" — use agent_teams_status to list tasks`)
299
+ }
300
+ return task
301
+ }
302
+
303
+ function requireStagedTeam(team: TeamState): void {
304
+ if (team.phase !== 'staged') {
305
+ throw new Error(`team "${team.name}" is already running; its plan can no longer be edited`)
306
+ }
307
+ if (team.halted === true) throw new Error(`team "${team.name}" is halted, not awaiting plan approval`)
308
+ }
309
+
310
+ function trimmedOptional(value: string | null | undefined): string | undefined {
311
+ const trimmed = value?.trim()
312
+ return trimmed === undefined || trimmed === '' ? undefined : trimmed
313
+ }
314
+
315
+ /** Whether one materialized plan member carries no roster content at all. */
316
+ function isEmptyPlanMember(member: unknown): boolean {
317
+ if (member === undefined || member === null) return true
318
+ if (typeof member !== 'object') return typeof member === 'string' && member.trim() === ''
319
+ return Object.values(member as Record<string, unknown>).every(value =>
320
+ value === undefined || value === null || (typeof value === 'string' && value.trim() === ''))
321
+ }
322
+
323
+ /**
324
+ * Some model gateways materialize optional object parameters instead of
325
+ * omitting them: a call that only passed `profile` arrives carrying
326
+ * `plan: { members: [], tasks: [] }`, or one placeholder member whose every
327
+ * field is blank (issue #234). Such a plan carries no roster, so it must count
328
+ * as an omitted plan — the same invariant issue #99 established for a blank
329
+ * `profile` string (a materialized blank equals "not provided").
330
+ * @param plan - the materialized inline plan argument.
331
+ * @returns whether the plan carries no member content and no task at all.
332
+ */
333
+ function isEmptyInlinePlan(plan: { readonly members?: unknown, readonly tasks?: unknown }): boolean {
334
+ const members = plan.members
335
+ const tasks = plan.tasks
336
+ const emptyMembers = !Array.isArray(members) || members.length === 0 || members.every(member => isEmptyPlanMember(member))
337
+ const emptyTasks = !Array.isArray(tasks) || tasks.length === 0
338
+ return emptyMembers && emptyTasks
339
+ }
340
+
341
+ /**
342
+ * Resolve one member's selected tool policy into the persisted policy id and
343
+ * the immutable effective filter (#59).
344
+ *
345
+ * An unknown id fails here — before the member is written and before any child
346
+ * is created — so a typo can never persist a half-configured member or leave a
347
+ * resumable orphan behind. A member without a policy resolves to `{}`: the
348
+ * previous behavior and record shape stay untouched.
349
+ * @param config - resolved plugin config (declared policies + depth cap).
350
+ * @param captain - the live captain, whose registry view names the host tools.
351
+ * @param policyId - the selected policy id, or undefined for no policy.
352
+ * @returns the member fields to persist (`toolPolicy` + `toolFilter`), or `{}`.
353
+ */
354
+ function memberToolSelection(
355
+ config: ToolsConfig,
356
+ captain: Agent,
357
+ policyId: string | undefined,
358
+ ): Pick<TeamMember, 'toolPolicy' | 'toolFilter'> {
359
+ if (policyId === undefined) return {}
360
+ const policy = requireToolPolicy(config.toolPolicies, policyId)
361
+ return {
362
+ toolPolicy: policyId,
363
+ toolFilter: resolveMemberToolFilter(policy, {
364
+ maxDepth: config.memberMaxDepth,
365
+ knownTools: restrictableToolNames(captain),
366
+ }),
367
+ }
368
+ }
369
+
370
+ /**
371
+ * Deny names the lenient spawn retry may drop for one member.
372
+ *
373
+ * A member without a policy keeps the built-in #163/#164 recovery path. A
374
+ * policy member may only relax built-in entries the owner did not declare
375
+ * itself (`memberSpawnRelaxableDeny`), and a selected policy id this
376
+ * deployment no longer declares relaxes nothing: the member then fails loud
377
+ * instead of spawning under a different filter.
378
+ * @param config - resolved plugin config.
379
+ * @param member - the member being spawned.
380
+ * @returns the relaxable deny names, or undefined for the legacy default.
381
+ */
382
+ function memberRelaxableDeny(config: ToolsConfig, member: TeamMember): readonly string[] | undefined {
383
+ if (member.toolPolicy === undefined) return undefined
384
+ return memberSpawnRelaxableDeny(optionalToolPolicy(config.toolPolicies, member.toolPolicy), true)
385
+ }
386
+
387
+ /** Validate references and cycles before a staged graph can be saved or run. */
388
+ function validateStagedGraph(team: TeamState, requireRunnable: boolean): void {
389
+ const members = team.members.filter((member) => member.status !== 'removed')
390
+ if (requireRunnable && members.length === 0) throw new Error('add at least one member before approving the plan')
391
+ if (requireRunnable && team.tasks.length === 0) throw new Error('add at least one task before approving the plan')
392
+ const memberNames = new Set(members.map((member) => member.name))
393
+ const taskIds = new Set(team.tasks.map((task) => task.id))
394
+ for (const task of team.tasks) {
395
+ if (task.subject.trim() === '') throw new Error(`task "${task.id}" must have a subject`)
396
+ if (task.assignee !== undefined && task.assignee !== CAPTAIN_KEY && !memberNames.has(task.assignee)) {
397
+ throw new Error(`task "${task.id}" assignee "${task.assignee}" is not an active member`)
398
+ }
399
+ for (const dependency of task.dependencies) {
400
+ if (dependency === task.id) throw new Error(`task "${task.id}" cannot depend on itself`)
401
+ if (!taskIds.has(dependency)) throw new Error(`task "${task.id}" depends on unknown task "${dependency}"`)
402
+ }
403
+ }
404
+ const visiting = new Set<string>()
405
+ const visited = new Set<string>()
406
+ const byId = new Map(team.tasks.map((task) => [task.id, task]))
407
+ const visit = (taskId: string): void => {
408
+ if (visiting.has(taskId)) throw new Error(`task dependency graph contains a cycle at "${taskId}"`)
409
+ if (visited.has(taskId)) return
410
+ visiting.add(taskId)
411
+ for (const dependency of byId.get(taskId)?.dependencies ?? []) visit(dependency)
412
+ visiting.delete(taskId)
413
+ visited.add(taskId)
414
+ }
415
+ for (const task of team.tasks) visit(task.id)
416
+ }
417
+
418
+ function memberOpenTask(team: TeamState, memberName: string, exceptTaskId?: string): TeamTask | undefined {
419
+ return team.tasks.find(task => task.id !== exceptTaskId
420
+ && task.assignee === memberName
421
+ && (task.status === 'claimed' || task.status === 'in_progress'))
422
+ }
423
+
424
+ function taskDetails(team: TeamState, task: TeamTask): string {
425
+ return [task.subject, task.description ?? '',
426
+ `Kind: ${task.kind ?? 'work'}`,
427
+ `Objective: ${task.objective ?? ''}`,
428
+ `In scope: ${(task.inScope ?? []).join(', ')}; Out of scope: ${(task.outOfScope ?? []).join(', ')}`,
429
+ `Acceptance: ${(task.acceptance ?? []).join('; ')}`,
430
+ `Verify: ${(task.verify ?? []).join('; ')}`,
431
+ `Dependency results:\n${formatDependencyOutputs(collectCompletedDependencyOutputs(team.tasks, task.id))}`,
432
+ ].join('\n')
433
+ }
434
+
435
+ /** Captain work is immediate, not a durable scheduler lane: allow one unfinished takeover at a time. */
436
+ function captainOpenTask(team: TeamState, exceptTaskId?: string): TeamTask | undefined {
437
+ return team.tasks.find(task => task.id !== exceptTaskId
438
+ && task.assignee === CAPTAIN_KEY
439
+ && !TERMINAL_TASK_STATUSES.includes(task.status))
440
+ }
441
+
442
+ /** Stop every currently-resident member activation for one halted team.
443
+ *
444
+ * Interrupt requests only cancel the member's current model turn and retain its
445
+ * activation. Draining the selected direct children is the stronger lifecycle
446
+ * boundary: it waits for the activation handles to release, so a child cannot
447
+ * keep executing after the captain-chat Stop control has reported success.
448
+ */
449
+ /**
450
+ * The live Agent the host admits member operations from.
451
+ *
452
+ * Harness continuable delivery is authorized against the member's durable
453
+ * direct parent (`subagents.authorizeLineage`), which is the session that
454
+ * spawned it — the team's recorded captain. A captain acting from its own fork
455
+ * therefore commands members *through* that session:
456
+ *
457
+ * - while the recorded captain is resident, its Agent is used directly;
458
+ * - while it is cold, this resolves it through the public session controller
459
+ * (`workspaceRegistry.create` + `sessionController.create` with the existing
460
+ * session id — attach/resume only: no prompt, no model request, and the
461
+ * durable `captainSessionId` is never rewritten);
462
+ * - when the composition exposes neither service, or the resume fails, the
463
+ * operation fails with an explicit bounded error instead of migrating team
464
+ * ownership to a session the host would reject at delivery time.
465
+ *
466
+ * @param ctx - the plugin context (injects `agents`).
467
+ * @param team - current team state.
468
+ * @param caller - the captain-side session performing the operation.
469
+ * @returns the caller itself, or the live recorded captain session.
470
+ */
471
+ async function memberOperationParent(ctx: Context, team: TeamState, caller: Agent): Promise<Agent> {
472
+ if (caller.id === team.captainSessionId) return caller
473
+ const resident = ctx.agents.get(team.captainSessionId as SessionId)
474
+ if (resident !== undefined) return resident
475
+ const resumed = await resumeLeadAnchor(ctx, team, caller)
476
+ if (resumed !== undefined) return resumed
477
+ throw new Error(`member operations require the live captain session ${team.captainSessionId} that owns team "${team.name}"; this session is its fork and ${resumeUnavailableReason(ctx, team)}`)
478
+ }
479
+
480
+ /**
481
+ * Best-effort live anchor for scheduler calls: the recorded captain when
482
+ * resident, the resumed one when this composition can attach it, and
483
+ * `undefined` otherwise (the scheduler then keeps its existing
484
+ * registry-only behavior). Never throws, so mutating tools stay usable on
485
+ * compositions without a session controller.
486
+ * @param ctx - the plugin context (injects `agents`).
487
+ * @param team - the team whose recorded captain is the delivery parent.
488
+ * @param caller - the captain-side session performing the operation.
489
+ * @returns the anchor agent when one is live, else undefined.
490
+ */
491
+ async function liveLeadAnchorAgent(ctx: Context, team: Pick<TeamState, 'captainSessionId' | 'name'>, caller: Agent): Promise<Agent | undefined> {
492
+ if (caller.id === team.captainSessionId) return caller
493
+ const resident = ctx.agents.get(team.captainSessionId as SessionId)
494
+ if (resident !== undefined) return resident
495
+ return resumeLeadAnchor(ctx, team as TeamState, caller)
496
+ }
497
+
498
+ /** Why the recorded captain could not be resumed, for one bounded error message. */
499
+ function resumeUnavailableReason(ctx: Context, team: TeamState): string {
500
+ const services = optionalTeamServices(ctx)
501
+ if (services.controller === undefined || services.registry === undefined) {
502
+ return 'this composition exposes no session controller to resume it, so add_member, member delivery and member drain are unavailable from the fork'
503
+ }
504
+ return `resuming it through the session controller failed (its workspace is "${team.name}"'s workspace)`
505
+ }
506
+
507
+ /** Public optional services used only to attach the recorded captain session. */
508
+ function optionalTeamServices(ctx: Context): {
509
+ controller?: { create?: (request: { sessionId: string; workspaceId: string; agentPreset?: string }) => Promise<unknown> }
510
+ registry?: { create?: (path: string, title?: string) => Promise<{ id: string }> }
511
+ } {
512
+ const get = (ctx as unknown as { get?: (name: string) => unknown }).get
513
+ if (typeof get !== 'function') return {}
514
+ const read = (name: string): unknown => {
515
+ try { return get.call(ctx, name) } catch { return undefined }
516
+ }
517
+ return {
518
+ controller: read('sessionController') as { create?: (request: { sessionId: string; workspaceId: string; agentPreset?: string }) => Promise<unknown> } | undefined,
519
+ registry: read('workspaceRegistry') as { create?: (path: string, title?: string) => Promise<{ id: string }> } | undefined,
520
+ }
521
+ }
522
+
523
+ /**
524
+ * Attach the team's recorded captain session in this process without sending a
525
+ * prompt: the Harness controller's create-with-existing-id path resumes the
526
+ * session and leaves every durable field (including `captainSessionId`)
527
+ * untouched.
528
+ * @returns the resumed Agent, or undefined when this composition cannot resume it.
529
+ */
530
+ async function resumeLeadAnchor(ctx: Context, team: TeamState, caller: Agent): Promise<Agent | undefined> {
531
+ const { controller, registry } = optionalTeamServices(ctx)
532
+ if (controller?.create === undefined || registry?.create === undefined) return undefined
533
+ const cwd = caller.session.header.cwd ?? process.cwd()
534
+ try {
535
+ const workspace = await registry.create(cwd, cwd)
536
+ await controller.create({ sessionId: team.captainSessionId, workspaceId: workspace.id, agentPreset: 'standard' })
537
+ return ctx.agents.get(team.captainSessionId as SessionId)
538
+ } catch (error: unknown) {
539
+ ctx.logger.warn(`agent-teams: could not resume the recorded captain session ${team.captainSessionId}: ${String(error)}`)
540
+ return undefined
541
+ }
542
+ }
543
+
544
+ async function stopTeamMemberActivations(
545
+ ctx: Context,
546
+ captain: Agent,
547
+ members: readonly TeamMember[],
548
+ signal?: AbortSignal,
549
+ ): Promise<void> {
550
+ const memberIds = members.filter(member => member.id !== '').map(member => member.id as SessionId)
551
+ if (memberIds.length === 0) return
552
+ // Every supported exact host has targeted recursive drain. Unlike interrupt,
553
+ // it closes admission and clears queued work before awaiting descendants.
554
+ signal?.throwIfAborted()
555
+ await drainMemberChildren(ctx.subagents, captain, memberIds)
556
+ }
557
+
558
+ export async function haltTeamWork(input: {
559
+ ctx: Context
560
+ stateRoot: string
561
+ teamId: string
562
+ captain: Agent
563
+ signal?: AbortSignal
564
+ }): Promise<{ teamName: string; captainSessionId: string; cancelledTasks: number; alreadyHalted: boolean }> {
565
+ const halted = await withTeamLock(teamLockKey(input.stateRoot, input.teamId), async () => {
566
+ const fresh = await requireFreshCaptainTeam(input.ctx, input.stateRoot, input.teamId, input.captain.id)
567
+ if (fresh.halted === true) {
568
+ return {
569
+ teamName: fresh.name,
570
+ captainSessionId: fresh.captainSessionId,
571
+ cancelledTasks: fresh.tasks.filter((task) => task.status === 'cancelled').length,
572
+ alreadyHalted: true,
573
+ members: fresh.members.filter((member) => member.id !== '' && member.status !== 'removed').map((member) => ({ ...member })),
574
+ }
575
+ }
576
+ const now = Date.now()
577
+ let cancelledTasks = 0
578
+ for (const task of fresh.tasks) {
579
+ if (TERMINAL_TASK_STATUSES.includes(task.status)) continue
580
+ cancelUnfinishedTask(task, 'Stopped from the captain chat.')
581
+ cancelledTasks += 1
582
+ }
583
+ for (const member of fresh.members) {
584
+ if (member.status === 'removed') continue
585
+ member.status = 'idle'
586
+ }
587
+ fresh.halted = true
588
+ fresh.haltedAt = now
589
+ await writeTeam(input.stateRoot, fresh)
590
+ appendTeamEvent(input.ctx, captainSessionOf(input.ctx, fresh.captainSessionId, input.captain.session), 'agent-teams/team-halted', {
591
+ teamId: fresh.id,
592
+ cancelledTasks,
593
+ })
594
+ return {
595
+ teamName: fresh.name,
596
+ captainSessionId: fresh.captainSessionId,
597
+ cancelledTasks,
598
+ alreadyHalted: false,
599
+ members: fresh.members.filter((member) => member.id !== '' && member.status !== 'removed').map((member) => ({ ...member })),
600
+ }
601
+ })
602
+ // Persist the stop boundary first, then abort the Captain before draining
603
+ // children. Otherwise its current model turn can observe `halted`, call
604
+ // resume, and race the still-running HTTP stop request.
605
+ input.captain.cancel({ kind: 'user' }, { keepInbox: true })
606
+ // Members are children of the recorded captain session, so the parent-bound
607
+ // drain must run as that session when a fork requested the stop.
608
+ const haltAnchor = input.captain.id === halted.captainSessionId
609
+ ? input.captain
610
+ : input.ctx.agents.get(halted.captainSessionId as SessionId)
611
+ if (haltAnchor === undefined) {
612
+ input.ctx.logger.warn(`agent-teams: captain session ${halted.captainSessionId} is not live; member activations of "${halted.teamName}" were not drained from this session`)
613
+ } else {
614
+ await stopTeamMemberActivations(input.ctx, haltAnchor, halted.members, input.signal)
615
+ }
616
+ // Interrupting a child emits a trailing subagent-settled notification. That
617
+ // notification can start a fresh Captain turn after the first cancellation,
618
+ // so close the stop boundary again once every child activation has drained.
619
+ // Queued user input is preserved both times; only runtime-generated work is
620
+ // prevented from silently resuming the halted team.
621
+ input.captain.cancel({ kind: 'user' }, { keepInbox: true })
622
+ return {
623
+ teamName: halted.teamName,
624
+ captainSessionId: halted.captainSessionId,
625
+ cancelledTasks: halted.cancelledTasks,
626
+ alreadyHalted: halted.alreadyHalted,
627
+ }
628
+ }
629
+
630
+ /** Web approval has no tool result in the captain's conversation. */
631
+ export function stagedPlanApprovedContext(teamName: string): string {
632
+ return [
633
+ `The user approved the staged AgentTeams plan "${teamName}" from the pre-run review UI.`,
634
+ 'Approval has committed; the scheduler owns dispatch of the approved team. Do not approve again, recreate the roster, or send messages merely to start assigned tasks.',
635
+ 'Acknowledge the approval and handle any reports or user work already pending. Yield only when waiting for members is the remaining action. Their reports will wake you automatically; do not busy-poll status or keep a turn running just to wait.',
636
+ 'On a report, inspect the result and coordinate the next necessary action. If work has since been halted, respect that state and resume only on an explicit user request.',
637
+ ].join('\n')
638
+ }
639
+
640
+ /** Context queued after the human rejects a staged plan. */
641
+ export function stagedPlanDiscardContext(teamName: string): string {
642
+ return [
643
+ `The user discarded the staged AgentTeams plan "${teamName}" from the pre-run review UI.`,
644
+ 'That decision is final for this draft: it has been archived, no members were created, and no tasks may run.',
645
+ 'Do not call agent_teams_create, agent_teams_approve, or recreate a replacement team merely because the old team is no longer active.',
646
+ 'Wait for a later explicit user request. If the next user message is unrelated to AgentTeams, answer it normally and do not start a team.',
647
+ ].join('\n')
648
+ }
649
+
650
+ /** Model-facing continuation that turns the review UI back into a conversation. */
651
+ export function stagedPlanFeedbackContext(teamName: string): string {
652
+ return [
653
+ `The user selected "Return to chat and revise" for the staged AgentTeams plan "${teamName}".`,
654
+ 'The existing staged plan is still the only draft. Do not create a replacement team, approve it, spawn members, edit the plan, or start work in this turn.',
655
+ 'Ask the user one concise, concrete question about what they want changed, then stop and wait for their answer.',
656
+ 'After the user answers, revise this same staged roster and DAG with one atomic agent_teams_edit_plan call, summarize the changes, and ask the user to review the updated plan again.',
657
+ ].join('\n')
658
+ }
659
+
660
+ /**
661
+ * Register every `agent_teams_*` tool into the shared tools registry.
662
+ * @param ctx - the plugin context (injects `tools`).
663
+ * @param config - resolved tool config.
664
+ */
665
+ export function registerAgentTeamsTools(ctx: Context, config: ToolsConfig): AgentTeamsRuntime {
666
+ // Own the lazy worker before any asynchronous tool/route callback can race
667
+ // with unload. Late callbacks retain a closed service and fail safely.
668
+ const auditor = workspaceAuditor(ctx)
669
+ installRetiredMemberGuard(ctx, config.stateDir)
670
+ installMemberDelegationGuard(ctx, config.stateDir, config.memberMaxDepth ?? 0)
671
+ installMailboxAdmission(ctx, config.stateDir)
672
+ const scheduler = installTeamScheduler(ctx, { stateDir: config.stateDir, executionPrompt: config.executionPrompt, dispatch: dispatchMember })
673
+
674
+ async function dispatchMember(captain: Agent, teamId: string, memberName: string, text: string, signal: AbortSignal, mode: 'queue' | 'steer', attemptId?: string): Promise<boolean> {
675
+ const root = stateRootOf(workspaceOf(captain), config)
676
+ // Record why a member never started. The scheduler treats a failed dispatch as
677
+ // "not now" and retries, so without this the captain only ever sees an
678
+ // unexplained `unspawned` member and no diagnostic reaches any surface.
679
+ const recordSpawnError = async (reason: string): Promise<void> => {
680
+ try {
681
+ await withTeamLock(teamLockKey(root, teamId), async () => {
682
+ const fresh = await requireFreshCaptainTeam(ctx, root, teamId, captain.id)
683
+ const failed = fresh.members.find(item => item.name === memberName && item.status !== 'removed')
684
+ if (failed === undefined || failed.id !== '') return
685
+ failed.spawnError = reason
686
+ await writeTeam(root, fresh)
687
+ })
688
+ } catch (error: unknown) {
689
+ ctx.logger.warn(`agent-teams: could not record the member start failure for ${memberName}: ${String(error)}`)
690
+ }
691
+ }
692
+ let orphan: TeamMember | undefined
693
+ try {
694
+ return await withTeamLock(teamLockKey(root, teamId), async () => {
695
+ const team = await readTeam(root, teamId)
696
+ if (team === undefined || !(await sessionLeadsTeamAsync(ctx, team, captain.id)) || team.halted === true || team.phase === 'staged') return false
697
+ const member = team.members.find(item => item.name === memberName && item.status !== 'removed')
698
+ if (member === undefined || member.stopping === true || team.tasks.some(task => task.reassigning === true && task.assignee === memberName)) return false
699
+ if (attemptId !== undefined && !team.tasks.some(task => task.attemptId === attemptId && task.assignee === memberName && (task.status === 'claimed' || task.status === 'in_progress'))) return false
700
+ if (member.id !== '') return deliverToMember(ctx, captain, member.id, text, signal, mode)
701
+ const selection = await resolveMemberLlmSelection(ctx, captain, {
702
+ provider: member.provider, model: member.model, reasoningEffort: member.reasoningEffort, fallback: member.fallback,
703
+ }, signal)
704
+ await spawnMember(ctx, memberRuntime(config), memberSelections, selection, captain, team, member, config.stateDir, signal, text, member.toolFilter, memberRelaxableDeny(config, member))
705
+ orphan = { ...member }
706
+ delete member.spawnError
707
+ await writeTeam(root, team)
708
+ orphan = undefined
709
+ return true
710
+ })
711
+ } catch (error: unknown) {
712
+ if (orphan !== undefined) {
713
+ await recordRetiredMemberIds(root, [orphan.id])
714
+ await stopTeamMemberActivations(ctx, captain, [orphan])
715
+ }
716
+ // The stack carries the failing frame; the message alone rarely does.
717
+ let reason = String(error)
718
+ if (error instanceof Error && typeof error.stack === 'string' && error.stack !== '') reason = error.stack
719
+ ctx.logger.warn(`agent-teams: member dispatch failed for ${memberName}: ${String(error)}`)
720
+ await recordSpawnError(reason)
721
+ return false
722
+ }
723
+ }
724
+
725
+ const updatePlanBatch = async (captain: Agent, teamId: string, mutations: readonly StagedPlanMutation[], signal?: AbortSignal, allowPendingEdits = false): Promise<TeamState> => {
726
+ if (mutations.length === 0) throw new Error('at least one staged plan operation is required')
727
+ const workspace = workspaceOf(captain)
728
+ const stateRoot = stateRootOf(workspace, config)
729
+ return withTeamLock(teamLockKey(stateRoot, teamId), async () => {
730
+ const fresh = await requireFreshCaptainTeam(ctx, stateRoot, teamId, captain.id)
731
+ const staged = fresh.phase === 'staged'
732
+ if (!staged && !allowPendingEdits) requireStagedTeam(fresh)
733
+ if (fresh.halted === true) throw new Error('team is halted; resume before editing tasks')
734
+ if (!staged && mutations.some(mutation => mutation.action !== 'update_task')) {
735
+ throw new Error('a running team only permits update_task edits to pending, never-started tasks; roster and removal edits require a staged plan')
736
+ }
737
+ for (const mutation of mutations) {
738
+ if (mutation.action === 'update_member') {
739
+ const member = requireMember(fresh, mutation.memberName)
740
+ if (member.id !== '') throw new Error(`staged member "${member.name}" was already spawned`)
741
+ const selection = await resolveMemberLlmSelection(ctx, captain, {
742
+ provider: mutation.provider,
743
+ model: mutation.model,
744
+ reasoningEffort: trimmedOptional(mutation.reasoningEffort),
745
+ fallback: member.fallback,
746
+ }, signal)
747
+ member.role = trimmedOptional(mutation.role)
748
+ member.provider = selection.provider
749
+ member.model = selection.model
750
+ member.reasoningEffort = selection.reasoningEffort
751
+ member.executionPrompt = trimmedOptional(mutation.executionPrompt)
752
+ // The roster editor replaces route/prompt fields; the tool policy is
753
+ // only touched when the mutation names one, so a plan revision cannot
754
+ // silently widen a member's tool set.
755
+ if (mutation.toolPolicy !== undefined) {
756
+ const selected = memberToolSelection(config, captain, trimmedOptional(mutation.toolPolicy))
757
+ member.toolPolicy = selected.toolPolicy
758
+ member.toolFilter = selected.toolFilter
759
+ }
760
+ } else if (mutation.action === 'update_task') {
761
+ const task = requireTask(fresh, mutation.taskId)
762
+ if (task.status !== 'pending' || (task.attempt ?? 0) !== 0 || task.reassigning === true) {
763
+ throw new Error(`task "${task.id}" has already started and cannot be edited`)
764
+ }
765
+ if (!staged && mutation.assignee === CAPTAIN_KEY) throw new Error('use reassign_task for captain takeover')
766
+ const subject = mutation.subject.trim()
767
+ if (subject === '') throw new Error('task subject must not be empty')
768
+ task.subject = subject
769
+ task.description = trimmedOptional(mutation.description)
770
+ task.assignee = trimmedOptional(mutation.assignee)
771
+ task.dependencies = [...new Set(mutation.dependencies.map((item) => item.trim()).filter(Boolean))]
772
+ task.updatedAt = Date.now()
773
+ } else if (mutation.action === 'add_task') {
774
+ const subject = mutation.subject.trim()
775
+ if (subject === '') throw new Error('task subject must not be empty')
776
+ fresh.taskSeq += 1
777
+ const now = Date.now()
778
+ fresh.tasks.push({
779
+ id: `t${fresh.taskSeq}`,
780
+ subject,
781
+ description: trimmedOptional(mutation.description),
782
+ status: 'pending',
783
+ assignee: trimmedOptional(mutation.assignee),
784
+ dependencies: [...new Set(mutation.dependencies.map((item) => item.trim()).filter(Boolean))],
785
+ attempt: 0,
786
+ kind: 'work',
787
+ createdAt: now,
788
+ updatedAt: now,
789
+ })
790
+ } else if (mutation.action === 'remove_task') {
791
+ const task = requireTask(fresh, mutation.taskId)
792
+ const dependent = fresh.tasks.find((candidate) => candidate.dependencies.includes(task.id))
793
+ if (dependent !== undefined) {
794
+ throw new Error(`task "${task.id}" is still required by "${dependent.id}"; update that dependency before removing the task`)
795
+ }
796
+ fresh.tasks = fresh.tasks.filter((candidate) => candidate.id !== task.id)
797
+ } else {
798
+ const member = requireMember(fresh, mutation.memberName)
799
+ if (member.id !== '') throw new Error(`staged member "${member.name}" was already spawned`)
800
+ const owned = fresh.tasks.filter((task) => task.assignee === member.name)
801
+ if (owned.length > 0) {
802
+ throw new Error(`member "${member.name}" still owns planned tasks: ${owned.map((task) => task.id).join(', ')}; update or remove those tasks first`)
803
+ }
804
+ fresh.members = fresh.members.filter((candidate) => candidate !== member)
805
+ }
806
+ }
807
+ validateStagedGraph(fresh, false)
808
+ if (!staged) {
809
+ for (const mutation of mutations) {
810
+ if (mutation.action !== 'update_task') continue
811
+ const task = requireTask(fresh, mutation.taskId)
812
+ const validation = validateCreateTask({ ...fresh, tasks: fresh.tasks.filter(item => item.id !== task.id) }, task)
813
+ if (!validation.ok) throw new Error(validation.error ?? 'edited task violates the quality contract')
814
+ }
815
+ } else fresh.planReviewState = 'awaiting_review'
816
+ signal?.throwIfAborted()
817
+ await writeTeam(stateRoot, fresh)
818
+ return fresh
819
+ })
820
+ }
821
+
822
+ // Browser review controls retain their staged-only contract.
823
+ const updateStagedPlanBatch: AgentTeamsRuntime['updateStagedPlanBatch'] = (captain, teamId, mutations, signal) => (
824
+ updatePlanBatch(captain, teamId, mutations, signal)
825
+ )
826
+
827
+ const updateStagedPlan: AgentTeamsRuntime['updateStagedPlan'] = async (captain, teamId, mutation, signal) => (
828
+ updateStagedPlanBatch(captain, teamId, [mutation], signal)
829
+ )
830
+
831
+ const approveStagedTeam: AgentTeamsRuntime['approveStagedTeam'] = async (captain, teamId, signal) => {
832
+ const workspace = workspaceOf(captain)
833
+ const stateRoot = stateRootOf(workspace, config)
834
+ const runSignal = signal ?? new AbortController().signal
835
+ const approved = await withTeamLock(teamLockKey(stateRoot, teamId), async () => {
836
+ const fresh = await requireFreshCaptainTeam(ctx, stateRoot, teamId, captain.id)
837
+ requireStagedTeam(fresh)
838
+ // A staged removal has no child session to retain in history. Drop those
839
+ // placeholders before transitioning to the stricter running shape.
840
+ fresh.members = fresh.members.filter((member) => member.status !== 'removed')
841
+ validateStagedGraph(fresh, true)
842
+ const selections = []
843
+ for (const member of fresh.members) {
844
+ const selection = await resolveMemberLlmSelection(ctx, captain, {
845
+ provider: member.provider, model: member.model, reasoningEffort: member.reasoningEffort, fallback: member.fallback,
846
+ }, runSignal)
847
+ selections.push(selection)
848
+ member.provider = selection.provider
849
+ member.model = selection.model
850
+ member.reasoningEffort = selection.reasoningEffort
851
+ }
852
+ await validateMemberLlmSelections(ctx, selections, runSignal)
853
+ fresh.phase = 'running'
854
+ delete fresh.planReviewState
855
+ fresh.approvedAt = Date.now()
856
+ await writeTeam(stateRoot, fresh)
857
+ return { teamId: fresh.id, members: fresh.members.length, tasks: fresh.tasks.length }
858
+ })
859
+ try {
860
+ await scheduler.kickTeam(workspace, teamId, await liveLeadAnchorAgent(ctx, { captainSessionId: captain.id, name: teamId }, captain))
861
+ } catch (error: unknown) {
862
+ // Approval is already durably committed. A transient wake-up failure is
863
+ // recoverable by the next status/member lifecycle kick and must not make
864
+ // the UI report that an already-running team failed to approve.
865
+ ctx.logger.warn(`agent-teams: post-approval kick failed for "${teamId}": ${String(error)}`)
866
+ }
867
+ return approved
868
+ }
869
+
870
+ const continueStagedPlanning: AgentTeamsRuntime['continueStagedPlanning'] = async (captain, teamId) => {
871
+ const workspace = workspaceOf(captain)
872
+ const stateRoot = stateRootOf(workspace, config)
873
+ const prepared = await withTeamLock(teamLockKey(stateRoot, teamId), async () => {
874
+ const fresh = await requireFreshCaptainTeam(ctx, stateRoot, teamId, captain.id)
875
+ requireStagedTeam(fresh)
876
+ if (fresh.planReviewState === 'awaiting_feedback') {
877
+ return { teamName: fresh.name, alreadyWaiting: true }
878
+ }
879
+ fresh.planReviewState = 'awaiting_feedback'
880
+ await writeTeam(stateRoot, fresh)
881
+ return { teamName: fresh.name, alreadyWaiting: false }
882
+ })
883
+ if (prepared.alreadyWaiting) return { teamId, alreadyWaiting: true }
884
+
885
+ // End any planning turn that is still producing tool calls. A plugin
886
+ // follow-up submitted after cancellation is queued as the next turn by the
887
+ // Harness Agent contract, so it cannot race ahead and recreate the team.
888
+ captain.cancel({ kind: 'user' }, { keepInbox: true })
889
+ try {
890
+ captain.followup(createUserMessage({
891
+ content: [{ type: 'text', text: stagedPlanFeedbackContext(prepared.teamName) }],
892
+ source: agentTeamsSource({ kind: 'agent-teams' }, observedSessionFormatVersion(captain)),
893
+ }))
894
+ } catch (error: unknown) {
895
+ // Do not leave the durable UI in a false waiting state when the live
896
+ // Captain disappeared between lookup and delivery.
897
+ await withTeamLock(teamLockKey(stateRoot, teamId), async () => {
898
+ const fresh = await requireFreshCaptainTeam(ctx, stateRoot, teamId, captain.id)
899
+ requireStagedTeam(fresh)
900
+ if (fresh.planReviewState === 'awaiting_feedback') {
901
+ fresh.planReviewState = 'awaiting_review'
902
+ await writeTeam(stateRoot, fresh)
903
+ }
904
+ })
905
+ throw error
906
+ }
907
+ return { teamId, alreadyWaiting: false }
908
+ }
909
+
910
+ const discardStagedTeam: AgentTeamsRuntime['discardStagedTeam'] = async (captain, teamId) => {
911
+ const workspace = workspaceOf(captain)
912
+ const stateRoot = stateRootOf(workspace, config)
913
+ const discarded = await withTeamLock(teamLockKey(stateRoot, teamId), async () => {
914
+ const fresh = await requireFreshCaptainTeam(ctx, stateRoot, teamId, captain.id)
915
+ requireStagedTeam(fresh)
916
+ appendTeamEvent(ctx, captainSessionOf(ctx, fresh.captainSessionId, captain.session), 'agent-teams/plan-discarded', {
917
+ teamId: fresh.id,
918
+ })
919
+ // A staged plan owns no child sessions. Archiving releases the captain
920
+ // immediately while retaining the rejected graph for later inspection.
921
+ await archiveTeamDir(stateRoot, fresh.id)
922
+ return { teamId: fresh.id, teamName: fresh.name }
923
+ })
924
+ // Preserve this control fact for the next genuine user turn, then abort the
925
+ // still-running Captain turn. Without both operations a late model step can
926
+ // observe the missing active team and incorrectly create it again.
927
+ try {
928
+ captain.inject(createUserMessage({
929
+ content: [{ type: 'text', text: stagedPlanDiscardContext(discarded.teamName) }],
930
+ source: agentTeamsSource({ kind: 'agent-teams' }, observedSessionFormatVersion(captain)),
931
+ }))
932
+ } catch (error: unknown) {
933
+ // The archive is already authoritative. Cancellation still prevents a
934
+ // late step from recreating work; failure to park extra context is only a
935
+ // live-delivery warning and must not turn a successful discard into 409.
936
+ ctx.logger.warn(`agent-teams: failed to inject discard context for "${discarded.teamId}": ${String(error)}`)
937
+ }
938
+ captain.cancel({ kind: 'user' }, { keepInbox: true })
939
+ return { teamId: discarded.teamId }
940
+ }
941
+
942
+
943
+
944
+ ctx.tools.register(defineTool({
945
+ name: 'agent_teams_create',
946
+ description: 'Create a team. Use approval=required for a two-phase plan: members and tasks remain unspawned/unclaimed until the user reviews the Web plan and explicitly approves it. Optional profiles expand their configured roster; seed profiles also expand template tasks, while captain profiles leave the graph for the Captain to design. approval=automatic preserves the legacy immediate-execution path.',
947
+ parameters: {
948
+ name: { type: 'string', required: true, description: 'Name for the new team (used as its stable id).' },
949
+ description: { type: 'string', description: 'Team purpose / the goal the team will work on.' },
950
+ profile: { type: 'string', description: 'Optional configured profile name.' },
951
+ plan: {
952
+ type: 'object', additionalProperties: false,
953
+ description: 'Optional complete ordinary-work roster and DAG in one atomic call, instead of separate add_member/create_task rounds. Mutually exclusive with profile. For quality gates use create_task with the explicit quality contract.',
954
+ properties: {
955
+ members: { type: 'array', required: true, items: { type: 'object', additionalProperties: false, properties: {
956
+ name: { type: 'string', required: true }, role: { type: 'string', description: 'Member role token. Use one of: engineer、qa、security、researcher、designer、docs、data、operator、audio、video. Pick the closest bucket instead of inventing a new role name — an unknown role loses its role artwork and falls back to the vendor image. Chinese role words are accepted, but the token list is preferred.' },
957
+ provider: { type: 'string' }, model: { type: 'string' }, reasoning_effort: { type: 'string' },
958
+ tool_policy: { type: 'string', description: 'Optional owner-declared tool-policy id for this member.' },
959
+ } } },
960
+ tasks: { type: 'array', required: true, items: { type: 'object', additionalProperties: false, properties: {
961
+ id: { type: 'string', required: true, description: 'Local reference used by dependencies in this plan; the result maps it to a durable task id.' },
962
+ subject: { type: 'string', required: true }, description: { type: 'string' }, assignee: { type: 'string' },
963
+ dependencies: { type: 'array', items: { type: 'string' } },
964
+ } } },
965
+ },
966
+ },
967
+ approval: {
968
+ type: 'string',
969
+ enum: ['required', 'automatic'],
970
+ description: 'required stages the plan for explicit user review; automatic starts immediately. Defaults to automatic for API compatibility.',
971
+ },
972
+ },
973
+ output: {
974
+ schema: {
975
+ type: 'object',
976
+ additionalProperties: false,
977
+ properties: {
978
+ team_id: { type: 'string', required: true },
979
+ team_name: { type: 'string', required: true },
980
+ captain_session_id: { type: 'string', required: true },
981
+ state_dir: { type: 'string', required: true },
982
+ phase: { type: 'string', required: true },
983
+ profile: { type: 'string' },
984
+ task_planning: { type: 'string' },
985
+ members: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { member_name: { type: 'string', required: true }, member_id: { type: 'string', required: true }, member_role: { type: 'string' }, provider: { type: 'string', required: true }, model: { type: 'string', required: true }, reasoning_effort: { type: 'string' }, tool_policy: { type: 'string' }, status: { type: 'string', required: true } } } },
986
+ tasks: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { task_id: { type: 'string', required: true }, seed_id: { type: 'string', required: true }, subject: { type: 'string', required: true }, status: { type: 'string', required: true }, kind: { type: 'string' }, assignee: { type: 'string' }, dependencies: { type: 'array', items: { type: 'string' }, required: true } } } },
987
+ },
988
+ },
989
+ render: (args, value) => [{
990
+ type: 'text',
991
+ text: (value.phase === 'staged'
992
+ ? `Team "${value.team_name}" plan created under ${value.state_dir}. It is staged: finish the roster and DAG, then wait for the user to edit and approve it. Do not start or approve it yourself.`
993
+ : `Team "${value.team_name}" created (id ${value.team_id}) under ${value.state_dir}. You are the captain.`)
994
+ + (value.tasks === undefined ? '' : '\n' + value.tasks.map(task => `${task.task_id} [${task.seed_id}]: ${task.subject}; assignee=${task.assignee ?? 'unassigned'}; dependencies=${task.dependencies.join(',')}`).join('\n')),
995
+ }],
996
+ // The conversation card folds this durable result, and the card cannot
997
+ // reproduce the host's key cleaning for every name (issue #203). Publish
998
+ // the canonical identity instead of letting a client re-derive it.
999
+ presentationMeta: (_args, value) => ({
1000
+ team_id: value.team_id,
1001
+ team_name: value.team_name,
1002
+ captain_session_id: value.captain_session_id,
1003
+ phase: value.phase,
1004
+ ...value.members === undefined ? {} : {
1005
+ members: value.members.map(member => ({
1006
+ id: member.member_id,
1007
+ name: member.member_name,
1008
+ role: member.member_role ?? '',
1009
+ status: member.status,
1010
+ })),
1011
+ },
1012
+ }),
1013
+ },
1014
+ async execute(args, exec) {
1015
+ const captain = requireCaptain(exec)
1016
+ const workspace = workspaceOf(captain)
1017
+ const stateRoot = stateRootOf(workspace, config)
1018
+ const teamName = args.name.trim()
1019
+ if (teamName === '') throw new Error('team name must not be empty')
1020
+ const teamId = sanitizeKey(teamName)
1021
+ const staged = args.approval === 'required'
1022
+ // Some models materialize optional parameters as "" instead of omitting
1023
+ // them (issue #99). The profile is optional, so treat a blank value
1024
+ // exactly like an omitted one instead of failing every create call.
1025
+ const profileName = args.profile !== undefined && args.profile.trim() !== ''
1026
+ ? args.profile.trim()
1027
+ : undefined
1028
+ // Gateways materialize the optional `plan` object the same way (issue
1029
+ // #234): an empty shell carries no roster, so it is an omitted plan and
1030
+ // the profile / inline-plan exclusion below stays untouched.
1031
+ const inlinePlan = args.plan !== undefined && !isEmptyInlinePlan(args.plan) ? args.plan : undefined
1032
+ if (profileName !== undefined && inlinePlan !== undefined) throw new Error('choose either a configured profile or an inline plan')
1033
+ const created = await withTeamLock(captainLockKey(stateRoot, captain.id), async () => {
1034
+ const current = await findTeamByParticipant(stateRoot, captain.id, await leadIdentityOfAsync(ctx, captain.session))
1035
+ if (current !== undefined) {
1036
+ const leads = await sessionLeadsTeamAsync(ctx, current, captain.id)
1037
+ const relationship = leads ? 'lead' : 'belong to'
1038
+ const guidance = leads
1039
+ ? 'Use agent_teams_status and continue the existing team. Do not delete and recreate it merely to continue work. End it only when the user explicitly wants a separate new team.'
1040
+ : 'Continue your assigned member work and report to your captain; do not create a separate team.'
1041
+ throw new Error(`you already ${relationship} team "${current.name}" (id ${current.id}). ${guidance}`)
1042
+ }
1043
+ return withTeamLock(teamLockKey(stateRoot, teamId), async () => {
1044
+ const existing = await readTeam(stateRoot, teamId)
1045
+ if (existing !== undefined) {
1046
+ throw new Error(`team id "${teamId}" is taken by another captain — pick a different team name`)
1047
+ }
1048
+ if (profileName === undefined && inlinePlan === undefined) {
1049
+ const state: TeamState = {
1050
+ name: teamName,
1051
+ id: teamId,
1052
+ description: args.description,
1053
+ captainSessionId: captain.id,
1054
+ createdAt: Date.now(),
1055
+ members: [],
1056
+ tasks: [],
1057
+ taskSeq: 0,
1058
+ ...staged ? { phase: 'staged' as const, planReviewState: 'awaiting_review' as const } : {},
1059
+ }
1060
+ await createTeamDir(stateRoot, state)
1061
+ return { committed: true as const, state }
1062
+ }
1063
+ return initializeProfileTeam({
1064
+ ctx,
1065
+ config,
1066
+ memberSelections,
1067
+ captain,
1068
+ exec,
1069
+ stateRoot,
1070
+ teamName,
1071
+ teamId,
1072
+ profileName: profileName ?? 'inline-plan',
1073
+ inlinePlan,
1074
+ description: args.description,
1075
+ staged,
1076
+ })
1077
+ })
1078
+ })
1079
+ if (created.committed) {
1080
+ try {
1081
+ await scheduler.kickTeam(workspace, created.state.id, await liveLeadAnchorAgent(ctx, created.state, captain))
1082
+ } catch (error: unknown) {
1083
+ ctx.logger.warn(`agent-teams: post-create kick failed for "${created.state.id}": ${String(error)}`)
1084
+ }
1085
+ try {
1086
+ appendTeamEvent(ctx, captain.session, 'agent-teams/team-created', {
1087
+ teamId: created.state.id,
1088
+ captainSessionId: captain.id,
1089
+ name: created.state.name,
1090
+ ...created.state.description !== undefined ? { description: created.state.description } : {},
1091
+ ...created.state.profile?.name === undefined ? {} : { profile: created.state.profile.name },
1092
+ })
1093
+ for (const member of created.state.members) {
1094
+ appendTeamEvent(ctx, captain.session, 'agent-teams/member-added', {
1095
+ teamId: created.state.id,
1096
+ memberId: member.id,
1097
+ name: member.name,
1098
+ ...member.role === undefined ? {} : { role: member.role },
1099
+ })
1100
+ }
1101
+ for (const task of created.state.tasks) {
1102
+ appendTeamEvent(ctx, captain.session, 'agent-teams/task-created', {
1103
+ teamId: created.state.id,
1104
+ taskId: task.id,
1105
+ subject: task.subject,
1106
+ dependencies: task.dependencies,
1107
+ ...task.assignee === undefined ? {} : { assignee: task.assignee },
1108
+ })
1109
+ }
1110
+ } catch (error: unknown) {
1111
+ ctx.logger.warn(`agent-teams: post-create events failed for "${created.state.id}": ${String(error)}`)
1112
+ }
1113
+ }
1114
+ const persisted = await readTeam(stateRoot, created.state.id).catch(() => undefined)
1115
+ const snapshot = persisted ?? created.state
1116
+ if (snapshot.profile === undefined && inlinePlan === undefined) {
1117
+ return {
1118
+ team_id: snapshot.id,
1119
+ team_name: snapshot.name,
1120
+ captain_session_id: snapshot.captainSessionId,
1121
+ state_dir: join(stateRoot, snapshot.id),
1122
+ phase: snapshot.phase ?? 'running',
1123
+ }
1124
+ }
1125
+ return {
1126
+ team_id: snapshot.id,
1127
+ team_name: snapshot.name,
1128
+ captain_session_id: snapshot.captainSessionId,
1129
+ state_dir: join(stateRoot, snapshot.id),
1130
+ phase: snapshot.phase ?? 'running',
1131
+ ...snapshot.profile === undefined ? {} : { profile: snapshot.profile.name },
1132
+ task_planning: snapshot.profile?.taskPlanning ?? 'seed',
1133
+ members: snapshot.members.map((member) => ({
1134
+ member_name: member.name,
1135
+ member_id: member.id,
1136
+ ...member.role === undefined ? {} : { member_role: member.role },
1137
+ provider: member.provider ?? '',
1138
+ model: member.model ?? '',
1139
+ ...member.reasoningEffort === undefined ? {} : { reasoning_effort: member.reasoningEffort },
1140
+ ...member.toolPolicy === undefined ? {} : { tool_policy: member.toolPolicy },
1141
+ status: member.status,
1142
+ })),
1143
+ tasks: snapshot.tasks.map((task) => ({
1144
+ task_id: task.id,
1145
+ seed_id: task.profileSeedId ?? '',
1146
+ subject: task.subject,
1147
+ status: task.status,
1148
+ ...task.kind === undefined ? {} : { kind: task.kind },
1149
+ ...task.assignee === undefined ? {} : { assignee: task.assignee },
1150
+ dependencies: task.dependencies,
1151
+ })),
1152
+ }
1153
+ },
1154
+ }))
1155
+
1156
+ ctx.tools.register(defineTool({
1157
+ name: 'agent_teams_edit_plan',
1158
+ description: 'Atomically revise an AgentTeams plan. While staged, edit tasks and roster without starting work. While running, only update_task is allowed, and only for pending tasks with no prior attempt: correct dependencies, assignees or descriptions before they start; newly ready work is scheduled after commit. Never edit active/finished attempts. Submit dependent edits in order. Never modify .agent-teams files directly.',
1159
+ parameters: {
1160
+ operations: {
1161
+ type: 'array',
1162
+ required: true,
1163
+ description: 'One atomic, ordered batch. Running teams allow only update_task for never-started pending tasks. If any operation is invalid, none of the edits are saved.',
1164
+ items: {
1165
+ type: 'object',
1166
+ additionalProperties: false,
1167
+ properties: {
1168
+ action: {
1169
+ type: 'string',
1170
+ required: true,
1171
+ enum: ['update_member', 'update_task', 'add_task', 'remove_task', 'remove_member'],
1172
+ },
1173
+ member_name: { type: 'string', description: 'Member name for update_member or remove_member.' },
1174
+ task_id: { type: 'string', description: 'Task id for update_task or remove_task.' },
1175
+ subject: { type: 'string', description: 'Required for add_task; optional replacement for update_task.' },
1176
+ description: { type: 'string', description: 'Optional task description.' },
1177
+ assignee: { type: 'string', description: 'Optional task assignee; an empty string moves it to the shared pool.' },
1178
+ dependencies: { type: 'array', items: { type: 'string' }, description: 'Complete replacement dependency list for a task.' },
1179
+ role: { type: 'string', description: 'Optional member role token; use one of: engineer、qa、security、researcher、designer、docs、data、operator、audio、video.' },
1180
+ provider: { type: 'string', description: 'Optional member provider; defaults to the current staged route.' },
1181
+ model: { type: 'string', description: 'Optional member model; defaults to the current staged route.' },
1182
+ reasoning_effort: { type: 'string', description: 'Optional member reasoning effort.' },
1183
+ execution_prompt: { type: 'string', description: 'Optional member-specific execution prompt.' },
1184
+ tool_policy: { type: 'string', description: 'Optional owner-declared tool-policy id for this member; an empty string clears it back to the unchanged default tool set.' },
1185
+ },
1186
+ },
1187
+ },
1188
+ },
1189
+ output: {
1190
+ schema: {
1191
+ type: 'object',
1192
+ additionalProperties: false,
1193
+ properties: {
1194
+ status: { type: 'string', required: true },
1195
+ team_id: { type: 'string', required: true },
1196
+ members: { type: 'number', required: true },
1197
+ tasks: { type: 'number', required: true },
1198
+ dependencies: { type: 'number', required: true },
1199
+ roster: { type: 'array', items: { type: 'string' }, required: true },
1200
+ graph: { type: 'array', items: { type: 'string' }, required: true },
1201
+ },
1202
+ },
1203
+ render: (_args, value) => [{
1204
+ type: 'text',
1205
+ text: `${value.status === 'staged' ? 'Staged plan' : 'Pending task graph'} updated atomically (${value.members} members, ${value.tasks} tasks, ${value.dependencies} dependencies). ${value.status === 'staged' ? 'No members were spawned and no tasks were scheduled.' : 'The scheduler will dispatch any newly ready work.'}\n${value.graph.join('\n')}`,
1206
+ }],
1207
+ },
1208
+ async execute(args, exec) {
1209
+ const captain = requireCaptain(exec)
1210
+ const workspace = workspaceOf(captain)
1211
+ const team = await requireCaptainTeam(ctx, workspace, config, captain)
1212
+ if (args.operations.length === 0) throw new Error('at least one staged plan operation is required')
1213
+
1214
+ const mutations: StagedPlanMutation[] = args.operations.map((operation, index) => {
1215
+ const label = `operation ${index + 1} (${operation.action})`
1216
+ if (operation.action === 'update_member') {
1217
+ const memberName = operation.member_name?.trim() ?? ''
1218
+ if (memberName === '') throw new Error(`${label} requires member_name`)
1219
+ const member = requireMember(team, memberName)
1220
+ return {
1221
+ action: 'update_member',
1222
+ memberName,
1223
+ role: operation.role ?? member.role,
1224
+ provider: operation.provider?.trim() || member.provider || '',
1225
+ model: operation.model?.trim() || member.model || '',
1226
+ reasoningEffort: operation.reasoning_effort ?? member.reasoningEffort,
1227
+ executionPrompt: operation.execution_prompt ?? member.executionPrompt,
1228
+ // Omitted means "keep the current policy": a route/prompt revision
1229
+ // must not silently change what the member may do.
1230
+ ...operation.tool_policy === undefined ? {} : { toolPolicy: operation.tool_policy },
1231
+ }
1232
+ }
1233
+ if (operation.action === 'update_task') {
1234
+ const taskId = operation.task_id?.trim() ?? ''
1235
+ if (taskId === '') throw new Error(`${label} requires task_id`)
1236
+ const task = requireTask(team, taskId)
1237
+ return {
1238
+ action: 'update_task',
1239
+ taskId,
1240
+ subject: operation.subject ?? task.subject,
1241
+ description: operation.description ?? task.description,
1242
+ assignee: operation.assignee ?? task.assignee,
1243
+ dependencies: operation.dependencies ?? task.dependencies,
1244
+ }
1245
+ }
1246
+ if (operation.action === 'add_task') {
1247
+ const subject = operation.subject?.trim() ?? ''
1248
+ if (subject === '') throw new Error(`${label} requires a non-empty subject`)
1249
+ return {
1250
+ action: 'add_task',
1251
+ subject,
1252
+ description: operation.description,
1253
+ assignee: operation.assignee,
1254
+ dependencies: operation.dependencies ?? [],
1255
+ }
1256
+ }
1257
+ if (operation.action === 'remove_task') {
1258
+ const taskId = operation.task_id?.trim() ?? ''
1259
+ if (taskId === '') throw new Error(`${label} requires task_id`)
1260
+ return { action: 'remove_task', taskId }
1261
+ }
1262
+ const memberName = operation.member_name?.trim() ?? ''
1263
+ if (memberName === '') throw new Error(`${label} requires member_name`)
1264
+ return { action: 'remove_member', memberName }
1265
+ })
1266
+ const updated = await updatePlanBatch(captain, team.id, mutations, exec.signal, true)
1267
+ if (updated.phase !== 'staged') await scheduler.kickTeam(workspace, team.id, await liveLeadAnchorAgent(ctx, team, captain))
1268
+ return {
1269
+ status: updated.phase ?? 'running',
1270
+ team_id: updated.id,
1271
+ members: updated.members.length,
1272
+ tasks: updated.tasks.length,
1273
+ dependencies: updated.tasks.reduce((sum, task) => sum + task.dependencies.length, 0),
1274
+ roster: updated.members.map((member) => `${member.name} (${member.role || 'member'}; ${member.provider ?? ''}/${member.model ?? ''})`),
1275
+ graph: updated.tasks.map((task) => `${task.id}: ${task.subject} -> ${task.assignee || 'shared'}${task.dependencies.length === 0 ? '' : `; depends on ${task.dependencies.join(', ')}`}`),
1276
+ }
1277
+ },
1278
+ }))
1279
+
1280
+ ctx.tools.register(defineTool({
1281
+ name: 'agent_teams_approve',
1282
+ description: 'Approve and start a staged team plan. Call this only in response to an explicit user approval in a new user turn; never call it during the turn that created or edited the plan. The Web Approve & Run button uses the same runtime directly.',
1283
+ parameters: {
1284
+ confirmation: { type: 'string', required: true, description: 'The user\'s explicit approval statement.' },
1285
+ },
1286
+ output: {
1287
+ schema: {
1288
+ type: 'object',
1289
+ additionalProperties: false,
1290
+ properties: {
1291
+ status: { type: 'string', required: true },
1292
+ team_id: { type: 'string', required: true },
1293
+ members: { type: 'number', required: true },
1294
+ tasks: { type: 'number', required: true },
1295
+ },
1296
+ },
1297
+ render: (_args, value) => [{
1298
+ type: 'text',
1299
+ text: `Team ${value.team_id} approved and running (${value.members} members, ${value.tasks} tasks).`,
1300
+ }],
1301
+ },
1302
+ async execute(args, exec) {
1303
+ if (args.confirmation.trim() === '') throw new Error('explicit user approval text is required')
1304
+ const captain = requireCaptain(exec)
1305
+ const workspace = workspaceOf(captain)
1306
+ const team = await requireCaptainTeam(ctx, workspace, config, captain)
1307
+ const approved = await approveStagedTeam(captain, team.id, exec.signal)
1308
+ return { status: 'running', team_id: approved.teamId, members: approved.members, tasks: approved.tasks }
1309
+ },
1310
+ }))
1311
+
1312
+ ctx.tools.register(defineTool({
1313
+ name: 'agent_teams_add_member',
1314
+ description: 'Add a member to the team roster. Planning and idle roster rows do not call a model. After approval, the member session starts with its first ready task or explicit message and remains durable for later work.',
1315
+ parameters: {
1316
+ name: { type: 'string', required: true, description: 'Unique member name inside the team.' },
1317
+ role: { type: 'string', description: 'Member role token — one of: engineer、qa、security、researcher、designer、docs、data、operator、audio、video. Do not invent a new role name: an unknown role misses its role artwork and shows the vendor fallback image.' },
1318
+ provider: { type: 'string', description: 'Optional LLM provider route. Use only when the user explicitly requests a different provider; requires model.' },
1319
+ model: { type: 'string', description: 'Optional model override. Omit for the captain\'s current model (or the configured memberModel default).' },
1320
+ reasoning_effort: { type: 'string', description: 'Optional reasoning effort override: one of the target model\'s supported effort ids, or "default" to force its default. When omitted, the captain\'s effort is inherited only for the same provider/model; a changed route uses the target default.' },
1321
+ executionPrompt: { type: 'string', description: 'Optional member-specific execution prompt. It remains editable while staged.' },
1322
+ tool_policy: { type: 'string', description: 'Optional id of a tool policy declared by the deployment owner (config toolPolicies). It restricts which global tools this member sees and may invoke: a policy allow-list also keeps the four coordination tools, and captain-only tools can never be reopened. Omit for the unchanged default tool set.' },
1323
+ },
1324
+ output: {
1325
+ schema: {
1326
+ type: 'object',
1327
+ additionalProperties: false,
1328
+ properties: {
1329
+ member_name: { type: 'string', required: true },
1330
+ member_id: { type: 'string', required: true },
1331
+ provider: { type: 'string', required: true },
1332
+ model: { type: 'string', required: true },
1333
+ reasoning_effort: { type: 'string' },
1334
+ tool_policy: { type: 'string' },
1335
+ status: { type: 'string', required: true },
1336
+ phase: { type: 'string', required: true },
1337
+ },
1338
+ },
1339
+ render: (args, value) => [{
1340
+ type: 'text',
1341
+ text: (value.phase === 'staged'
1342
+ ? `Member "${value.member_name}" added to the staged roster (${value.provider}/${value.model}); no child was spawned.`
1343
+ : `Member "${value.member_name}" added (session ${value.member_id || 'starts with first ready task'}, ${value.provider}/${value.model}${value.reasoning_effort === undefined ? '' : `, reasoning ${value.reasoning_effort}`}, status ${value.status}).`)
1344
+ + (value.tool_policy === undefined ? '' : ` Tool policy "${value.tool_policy}" applies to this member.`),
1345
+ }],
1346
+ },
1347
+ async execute(args, exec) {
1348
+ const captain = requireCaptain(exec)
1349
+ const workspace = workspaceOf(captain)
1350
+ const stateRoot = stateRootOf(workspace, config)
1351
+ const team = await requireCaptainTeam(ctx, workspace, config, captain)
1352
+ const created = await withTeamLock(teamLockKey(stateRoot, team.id), async () => {
1353
+ const fresh = await requireFreshCaptainTeam(ctx, stateRoot, team.id, captain.id)
1354
+ const memberName = args.name.trim()
1355
+ if (memberName === '') throw new Error('member name must not be empty')
1356
+ const memberKey = sanitizeKey(memberName)
1357
+ if (memberKey === CAPTAIN_KEY) {
1358
+ throw new Error(`member name "${args.name}" is reserved for the captain`)
1359
+ }
1360
+ if (fresh.members.some((candidate) => sanitizeKey(candidate.name) === memberKey)) {
1361
+ throw new Error(`member name "${args.name}" has already been used in team "${fresh.name}"`)
1362
+ }
1363
+ if (fresh.members.filter((candidate) => candidate.status !== 'removed').length >= config.maxMembers) {
1364
+ throw new Error(`team "${fresh.name}" is at its member cap (${config.maxMembers})`)
1365
+ }
1366
+ const selection = await resolveMemberLlmSelection(ctx, captain, {
1367
+ provider: trimmedOptional(args.provider),
1368
+ model: trimmedOptional(args.model),
1369
+ defaultModel: config.memberModel,
1370
+ defaultProvider: config.memberLlmProvider,
1371
+ reasoningEffort: trimmedOptional(args.reasoning_effort),
1372
+ fallback: config.fallback,
1373
+ }, exec.signal)
1374
+ const toolSelection = memberToolSelection(config, captain, trimmedOptional(args.tool_policy))
1375
+ const member: TeamMember = {
1376
+ id: '',
1377
+ name: memberName,
1378
+ role: args.role,
1379
+ provider: selection.provider,
1380
+ model: selection.model,
1381
+ reasoningEffort: selection.reasoningEffort,
1382
+ ...selection.fallback === undefined ? {} : { fallback: selection.fallback },
1383
+ executionPrompt: trimmedOptional(args.executionPrompt),
1384
+ ...toolSelection,
1385
+ joinedAt: Date.now(),
1386
+ status: 'idle',
1387
+ }
1388
+ await validateMemberLlmSelections(ctx, [selection], exec.signal)
1389
+ fresh.members.push(member)
1390
+ await writeTeam(stateRoot, fresh)
1391
+ appendTeamEvent(ctx, captainSessionOf(ctx, fresh.captainSessionId, captain.session), 'agent-teams/member-added', {
1392
+ teamId: fresh.id,
1393
+ memberId: member.id,
1394
+ name: member.name,
1395
+ ...member.role !== undefined ? { role: member.role } : {},
1396
+ })
1397
+ return {
1398
+ member_name: member.name,
1399
+ member_id: member.id,
1400
+ provider: selection.provider,
1401
+ model: selection.model,
1402
+ ...selection.reasoningEffort === undefined
1403
+ ? {}
1404
+ : { reasoning_effort: selection.reasoningEffort },
1405
+ ...member.toolPolicy === undefined ? {} : { tool_policy: member.toolPolicy },
1406
+ status: member.status,
1407
+ phase: fresh.phase ?? 'running',
1408
+ }
1409
+ })
1410
+ await scheduler.kickMember(workspace, team.id, created.member_name, await liveLeadAnchorAgent(ctx, team, captain))
1411
+ const latest = (await readTeam(stateRoot, team.id))?.members.find(member => member.name === created.member_name)
1412
+ return latest === undefined ? created : { ...created, member_id: latest.id, status: latest.status }
1413
+ },
1414
+ }))
1415
+
1416
+ ctx.tools.register(defineTool({
1417
+ name: 'agent_teams_remove_member',
1418
+ description: 'Remove a member safely: revoke its current attempts, return all unfinished owned tasks to the shared pending pool, interrupt its live turn, and mark it removed.',
1419
+ parameters: {
1420
+ name: { type: 'string', required: true, description: 'Name of the member to remove.' },
1421
+ },
1422
+ output: {
1423
+ schema: {
1424
+ type: 'object',
1425
+ additionalProperties: false,
1426
+ properties: {
1427
+ member_name: { type: 'string', required: true },
1428
+ status: { type: 'string', required: true },
1429
+ requeued_tasks: { type: 'array', items: { type: 'string' }, required: true },
1430
+ },
1431
+ },
1432
+ render: (args, value) => [{
1433
+ type: 'text',
1434
+ text: `Member "${value.member_name}" removed (status ${value.status}); requeued tasks: ${value.requeued_tasks.join(', ') || 'none'}.`,
1435
+ }],
1436
+ },
1437
+ async execute(args, exec) {
1438
+ const captain = requireCaptain(exec)
1439
+ const workspace = workspaceOf(captain)
1440
+ const stateRoot = stateRootOf(workspace, config)
1441
+ const team = await requireCaptainTeam(ctx, workspace, config, captain)
1442
+ const revoked = await withTeamLock(teamLockKey(stateRoot, team.id), async () => {
1443
+ const fresh = await requireFreshCaptainTeam(ctx, stateRoot, team.id, captain.id)
1444
+ const member = fresh.members.find(item => item.name === args.name)
1445
+ if (member === undefined) throw new Error(`no member \"${args.name}\" in team \"${fresh.name}\"`)
1446
+ const requeued: string[] = []
1447
+ for (const task of fresh.tasks) {
1448
+ if (task.assignee !== member.name || task.status === 'completed') continue
1449
+ invalidateTaskAttempt(task)
1450
+ task.reassigning = false
1451
+ requeued.push(task.id)
1452
+ }
1453
+ member.status = 'removed'
1454
+ await discardMailboxMessages(stateRoot, fresh.id, member.name, (await readUnreadMailbox(stateRoot, fresh.id, member.name)).map(message => message.id))
1455
+ await writeTeam(stateRoot, fresh)
1456
+ appendTeamEvent(ctx, captainSessionOf(ctx, fresh.captainSessionId, captain.session), 'agent-teams/member-removed', {
1457
+ teamId: fresh.id,
1458
+ memberId: member.id,
1459
+ })
1460
+ return { member: { ...member }, requeued }
1461
+ })
1462
+ if (revoked.member.id !== '') {
1463
+ await recordRetiredMemberIds(stateRoot, [revoked.member.id])
1464
+ await stopTeamMemberActivations(ctx, await memberOperationParent(ctx, team, captain), [revoked.member], exec.signal)
1465
+ }
1466
+ await scheduler.kickTeam(workspace, team.id, await liveLeadAnchorAgent(ctx, team, captain))
1467
+ return {
1468
+ member_name: revoked.member.name,
1469
+ status: revoked.member.status,
1470
+ requeued_tasks: revoked.requeued,
1471
+ }
1472
+ },
1473
+ }))
1474
+
1475
+ ctx.tools.register(defineTool({
1476
+ name: 'agent_teams_create_task',
1477
+ description: 'Create a task in your team\'s task list. Use kind=work (default) for research, repository audits and general tasks. kind=review is only a quality gate for an existing implementation/repair task via reviewedTaskId. Every call must include a non-empty subject, including verification and review tasks. Tasks can depend on other tasks (dependencies): a task is only claimable once every dependency is completed. Optionally assign it to a member, who still claims it before working.',
1478
+ parameters: {
1479
+ subject: { type: 'string', required: true, description: 'Required non-empty title for this task. Never omit it, including for verification or review tasks.' },
1480
+ description: { type: 'string', description: 'What needs to be done, in detail.' },
1481
+ dependencies: {
1482
+ type: 'array',
1483
+ items: { type: 'string' },
1484
+ description: 'Task ids this task depends on (must be completed before this task can be claimed).',
1485
+ },
1486
+ assignee: { type: 'string', description: 'Member name when an owner is specified. Omission puts this task in the shared pool; roles, subjects and descriptions do not assign an owner.' },
1487
+ kind: {
1488
+ type: 'string',
1489
+ enum: ['work', 'requirements', 'implementation', 'verification', 'review', 'repair', 'integration'],
1490
+ description: 'Explicit task kind. Omission means work with no quality gates, even if the subject says implementation/review. Quality kinds require a contract. An implementation may be planned before requirements passes when its dependency chain includes that requirements task.',
1491
+ },
1492
+ round: { type: 'number', description: '1-based review / requirements / repair round.' },
1493
+ objective: { type: 'string', description: 'Required non-empty objective for quality kinds.' },
1494
+ inScope: { type: 'array', items: { type: 'string' }, description: 'Workspace-relative POSIX paths this task may change.' },
1495
+ outOfScope: { type: 'array', items: { type: 'string' }, description: 'Workspace-relative POSIX paths this task must not change.' },
1496
+ acceptance: { type: 'array', items: { type: 'string' }, description: 'Acceptance criteria. Required for quality kinds.' },
1497
+ verify: { type: 'array', items: { type: 'string' }, description: 'Verification commands. Required for implementation/repair.' },
1498
+ deliverables: { type: 'array', items: { type: 'string' }, description: 'Expected deliverable paths or names.' },
1499
+ nonGoals: { type: 'array', items: { type: 'string' }, description: 'Explicit non-goals.' },
1500
+ reviewedTaskId: { type: 'string', description: 'Existing AgentTeams implementation/repair task id. Required for kind=review; an external repository audit is kind=work.' },
1501
+ sourceTaskId: { type: 'string', description: 'Source implementation/artifact. Required for kind=repair.' },
1502
+ sourceFindingIds: { type: 'array', items: { type: 'string' }, description: 'Finding ids this repair must close.' },
1503
+ coverageOf: { type: 'array', items: { type: 'string' }, description: 'User-constraint / goal items this task covers.' },
1504
+ resume: { type: 'boolean', description: 'If true, clear halted in the same lock before creating the task.' },
1505
+ resumeReason: { type: 'string', description: 'Required non-empty reason when resume=true.' },
1506
+ },
1507
+ output: {
1508
+ schema: {
1509
+ type: 'object',
1510
+ additionalProperties: false,
1511
+ properties: {
1512
+ task_id: { type: 'string', required: true },
1513
+ subject: { type: 'string', required: true },
1514
+ status: { type: 'string', required: true },
1515
+ kind: { type: 'string', required: true },
1516
+ assignee: { type: 'string' },
1517
+ },
1518
+ },
1519
+ render: (args, value) => [{
1520
+ type: 'text',
1521
+ text: `Task "${value.subject}" created as ${value.task_id} (status ${value.status}, kind ${value.kind}, ${value.assignee ? `assigned to ${value.assignee}` : 'unassigned shared pool'}).`,
1522
+ }],
1523
+ },
1524
+ async execute(args, exec) {
1525
+ const captain = requireCaptain(exec)
1526
+ const workspace = workspaceOf(captain)
1527
+ const stateRoot = stateRootOf(workspace, config)
1528
+ const team = await requireCaptainTeam(ctx, workspace, config, captain)
1529
+ // Some models materialize optional parameters as "" instead of omitting
1530
+ // them (issue #105). Normalize blank optional fields to omitted before
1531
+ // validation so a blank value can neither be rejected spuriously nor be
1532
+ // persisted into team.json, where it would brick the team on reload.
1533
+ const input = normalizeBlankOptionalTaskFields(args)
1534
+ const created = await withTeamLock(teamLockKey(stateRoot, team.id), async () => {
1535
+ const fresh = await requireFreshCaptainTeam(ctx, stateRoot, team.id, captain.id)
1536
+ const gate = validateCreateTask(fresh, {
1537
+ subject: input.subject,
1538
+ description: input.description,
1539
+ dependencies: input.dependencies,
1540
+ assignee: input.assignee,
1541
+ kind: input.kind as TaskKind | undefined,
1542
+ round: input.round,
1543
+ objective: input.objective,
1544
+ inScope: input.inScope,
1545
+ outOfScope: input.outOfScope,
1546
+ acceptance: input.acceptance,
1547
+ verify: input.verify,
1548
+ deliverables: input.deliverables,
1549
+ nonGoals: input.nonGoals,
1550
+ reviewedTaskId: input.reviewedTaskId,
1551
+ sourceTaskId: input.sourceTaskId,
1552
+ sourceFindingIds: input.sourceFindingIds,
1553
+ coverageOf: input.coverageOf,
1554
+ resume: input.resume,
1555
+ resumeReason: input.resumeReason,
1556
+ })
1557
+ if (!gate.ok) throw new Error(gate.error ?? 'create_task rejected by quality gates')
1558
+ if (fresh.halted === true) {
1559
+ const resumed = resumeTeamState(fresh, args.resumeReason ?? '')
1560
+ if (resumed.status !== 'resumed' || resumed.team === undefined) {
1561
+ throw new Error(resumed.error ?? 'team is halted; call agent_teams_resume or pass resume=true with resumeReason')
1562
+ }
1563
+ fresh.halted = false
1564
+ fresh.haltedAt = undefined
1565
+ appendTeamEvent(ctx, captainSessionOf(ctx, fresh.captainSessionId, captain.session), 'agent-teams/team-resumed', {
1566
+ teamId: fresh.id,
1567
+ reason: args.resumeReason ?? '',
1568
+ })
1569
+ }
1570
+ const dependencies = args.dependencies ?? []
1571
+ for (const dependency of dependencies) {
1572
+ if (!fresh.tasks.some((task) => task.id === dependency)) {
1573
+ throw new Error(`dependency "${dependency}" does not exist in team "${fresh.name}"`)
1574
+ }
1575
+ }
1576
+ if (args.assignee !== undefined) requireMember(fresh, args.assignee)
1577
+ const kind = gate.kind ?? 'work'
1578
+ const objective = kind === 'review' || kind === 'requirements'
1579
+ ? sanitizeReviewObjective(input.objective)
1580
+ : input.objective
1581
+ const acceptance = kind === 'review' || kind === 'requirements'
1582
+ ? sanitizeReviewAcceptance(input.acceptance)
1583
+ : input.acceptance
1584
+ const task: TeamTask = {
1585
+ id: `t${fresh.taskSeq + 1}`,
1586
+ subject: args.subject,
1587
+ description: args.description,
1588
+ status: 'pending',
1589
+ assignee: args.assignee,
1590
+ dependencies,
1591
+ attempt: 0,
1592
+ createdAt: Date.now(),
1593
+ updatedAt: Date.now(),
1594
+ kind,
1595
+ ...args.round === undefined ? {} : { round: args.round },
1596
+ ...objective === undefined ? {} : { objective },
1597
+ ...input.inScope === undefined ? {} : { inScope: input.inScope },
1598
+ ...input.outOfScope === undefined ? {} : { outOfScope: input.outOfScope },
1599
+ ...acceptance === undefined ? {} : { acceptance },
1600
+ ...input.verify === undefined ? {} : { verify: input.verify },
1601
+ ...input.deliverables === undefined ? {} : { deliverables: input.deliverables },
1602
+ ...input.nonGoals === undefined ? {} : { nonGoals: input.nonGoals },
1603
+ ...input.reviewedTaskId === undefined ? {} : { reviewedTaskId: input.reviewedTaskId },
1604
+ ...input.sourceTaskId === undefined ? {} : { sourceTaskId: input.sourceTaskId },
1605
+ ...input.sourceFindingIds === undefined ? {} : { sourceFindingIds: input.sourceFindingIds },
1606
+ ...input.coverageOf === undefined ? {} : { coverageOf: input.coverageOf },
1607
+ }
1608
+ fresh.taskSeq += 1
1609
+ fresh.tasks.push(task)
1610
+ await writeTeam(stateRoot, fresh)
1611
+ appendTeamEvent(ctx, captainSessionOf(ctx, fresh.captainSessionId, captain.session), 'agent-teams/task-created', {
1612
+ teamId: fresh.id,
1613
+ taskId: task.id,
1614
+ subject: task.subject,
1615
+ dependencies: task.dependencies,
1616
+ ...task.assignee !== undefined ? { assignee: task.assignee } : {},
1617
+ ...task.kind === undefined ? {} : { kind: task.kind },
1618
+ ...task.round === undefined ? {} : { round: task.round },
1619
+ })
1620
+ return {
1621
+ task_id: task.id,
1622
+ subject: task.subject,
1623
+ status: task.status,
1624
+ kind: taskKindOf(task),
1625
+ ...task.assignee !== undefined ? { assignee: task.assignee } : {},
1626
+ }
1627
+ })
1628
+ await scheduler.kickTeam(workspace, team.id, await liveLeadAnchorAgent(ctx, team, captain))
1629
+ return created
1630
+ },
1631
+ }))
1632
+
1633
+ ctx.tools.register(defineTool({
1634
+ name: 'agent_teams_reassign_task',
1635
+ description: 'Atomically retry, reassign, or let the captain take over one ready unfinished/failed task. The old attempt is revoked before its member is interrupted, so late updates cannot overwrite the new owner. Use assignee="captain" only when you will finish that task in this turn; a captain can own only one unfinished takeover at a time, and an unfinished takeover returns to the member pool when the captain becomes idle.',
1636
+ parameters: {
1637
+ task_id: { type: 'string', required: true, description: 'Task to retry/reassign.' },
1638
+ assignee: { type: 'string', required: true, description: 'Active member name, or "captain" for captain takeover.' },
1639
+ reason: { type: 'string', description: 'Why the task is being retried or reassigned.' },
1640
+ },
1641
+ output: {
1642
+ schema: {
1643
+ type: 'object',
1644
+ additionalProperties: false,
1645
+ properties: {
1646
+ task_id: { type: 'string', required: true },
1647
+ previous_assignee: { type: 'string', required: true },
1648
+ assignee: { type: 'string', required: true },
1649
+ status: { type: 'string', required: true },
1650
+ attempt: { type: 'number', required: true },
1651
+ attempt_id: { type: 'string' },
1652
+ },
1653
+ },
1654
+ render: (_args, value) => [{
1655
+ type: 'text',
1656
+ text: `Task ${value.task_id} reassigned ${value.previous_assignee || 'unassigned'} → ${value.assignee} (attempt ${value.attempt}, status ${value.status}${value.attempt_id ? `, attempt_id ${value.attempt_id}` : ''}).`,
1657
+ }],
1658
+ },
1659
+ async execute(args, exec) {
1660
+ const captain = requireCaptain(exec)
1661
+ const workspace = workspaceOf(captain)
1662
+ const stateRoot = stateRootOf(workspace, config)
1663
+ const team = await requireCaptainTeam(ctx, workspace, config, captain)
1664
+ const target = args.assignee.trim()
1665
+ if (target === '') throw new Error('reassignment assignee must not be empty')
1666
+
1667
+ const revoked = await withTeamLock(teamLockKey(stateRoot, team.id), async () => {
1668
+ const fresh = await requireFreshCaptainTeam(ctx, stateRoot, team.id, captain.id)
1669
+ const task = requireTask(fresh, args.task_id)
1670
+ if (task.status === 'completed') throw new Error(`completed task ${task.id} is immutable and cannot be reassigned`)
1671
+ if (task.reassigning === true) {
1672
+ const previousMember = fresh.members.find(member => member.id === task.handoffFromMemberId && member.stopping === true)
1673
+ if (task.assignee !== target || previousMember === undefined) throw new Error(`task ${task.id} is already being reassigned`)
1674
+ return { previousAssignee: previousMember.name, previousMember: { ...previousMember }, handoffId: task.handoffId }
1675
+ }
1676
+ const targetMember = target === CAPTAIN_KEY ? undefined : requireMember(fresh, target)
1677
+ if (target === CAPTAIN_KEY) {
1678
+ const busy = captainOpenTask(fresh, task.id)
1679
+ if (busy !== undefined) {
1680
+ throw new Error(`captain is busy with ${busy.id}; complete or reassign it before taking over ${task.id}`)
1681
+ }
1682
+ const pending = unsatisfiedDependencies(fresh.tasks, task.dependencies)
1683
+ if (pending.length > 0) {
1684
+ throw new Error(`task ${task.id} is blocked by unfinished dependencies: ${pending.join(', ')} — complete them before captain takeover`)
1685
+ }
1686
+ } else if (targetMember !== undefined) {
1687
+ const busy = memberOpenTask(fresh, targetMember.name, task.id)
1688
+ if (busy !== undefined) {
1689
+ throw new Error(`member "${targetMember.name}" is busy with ${busy.id}; finish or reassign it first`)
1690
+ }
1691
+ }
1692
+ const previousAssignee = task.assignee ?? ''
1693
+ const previousMember = (task.status !== 'claimed' && task.status !== 'in_progress')
1694
+ || task.assignee === undefined || task.assignee === CAPTAIN_KEY
1695
+ ? undefined
1696
+ : fresh.members.find(member => member.name === task.assignee && member.status !== 'removed')
1697
+ invalidateTaskAttempt(task, target, true)
1698
+ if (previousMember !== undefined) {
1699
+ previousMember.stopping = true
1700
+ task.handoffFromMemberId = previousMember.id
1701
+ await discardMailboxMessages(stateRoot, fresh.id, previousMember.name, (await readUnreadMailbox(stateRoot, fresh.id, previousMember.name)).map(message => message.id))
1702
+ }
1703
+ await writeTeam(stateRoot, fresh)
1704
+ return {
1705
+ previousAssignee,
1706
+ previousMember: previousMember === undefined ? undefined : { ...previousMember },
1707
+ handoffId: task.handoffId,
1708
+ }
1709
+ })
1710
+
1711
+ let quiescenceError: unknown
1712
+ if (revoked.previousMember !== undefined) {
1713
+ try {
1714
+ await stopTeamMemberActivations(ctx, await memberOperationParent(ctx, team, captain), [revoked.previousMember], exec.signal)
1715
+ } catch (error: unknown) {
1716
+ quiescenceError = error
1717
+ }
1718
+ }
1719
+
1720
+ await withTeamLock(teamLockKey(stateRoot, team.id), async () => {
1721
+ const fresh = await requireFreshCaptainTeam(ctx, stateRoot, team.id, captain.id)
1722
+ const task = requireTask(fresh, args.task_id)
1723
+ if (task.handoffId !== revoked.handoffId || task.assignee !== target || task.reassigning !== true) {
1724
+ throw new Error(`task ${task.id} changed during reassignment; refusing to overwrite the newer state`)
1725
+ }
1726
+ task.reassigning = quiescenceError !== undefined
1727
+ if (quiescenceError === undefined) {
1728
+ const previous = fresh.members.find(member => member.id === revoked.previousMember?.id)
1729
+ if (previous !== undefined) delete previous.stopping
1730
+ delete task.handoffFromMemberId
1731
+ }
1732
+ if (quiescenceError === undefined && target === CAPTAIN_KEY) {
1733
+ beginTaskAttempt(task, CAPTAIN_KEY)
1734
+ // The captain is already in the turn that requested takeover; there
1735
+ // is no later member claim handshake to move claimed -> in_progress.
1736
+ task.status = 'in_progress'
1737
+ task.updatedAt = Date.now()
1738
+ }
1739
+ await writeTeam(stateRoot, fresh)
1740
+ appendTeamEvent(ctx, captain.session, 'agent-teams/task-updated', {
1741
+ teamId: fresh.id,
1742
+ taskId: task.id,
1743
+ status: task.status,
1744
+ assignee: task.assignee,
1745
+ ...args.reason === undefined ? {} : { output: `Reassigned: ${args.reason}` },
1746
+ })
1747
+ })
1748
+ if (quiescenceError !== undefined) throw quiescenceError
1749
+ if (target !== CAPTAIN_KEY) await scheduler.kickMember(workspace, team.id, target, await liveLeadAnchorAgent(ctx, team, captain))
1750
+ const current = await readTeam(stateRoot, team.id)
1751
+ const task = current === undefined ? undefined : requireTask(current, args.task_id)
1752
+ if (task === undefined) throw new Error(`team "${team.name}" ended during reassignment`)
1753
+ return {
1754
+ task_id: task.id,
1755
+ previous_assignee: revoked.previousAssignee,
1756
+ assignee: task.assignee ?? '',
1757
+ status: task.status,
1758
+ attempt: task.attempt ?? 0,
1759
+ ...task.attemptId === undefined ? {} : { attempt_id: task.attemptId },
1760
+ }
1761
+ },
1762
+ }))
1763
+
1764
+ ctx.tools.register(defineTool({
1765
+ name: 'agent_teams_claim_task',
1766
+ description: 'Members claim their own ready task or read their existing attempt_id. Captains must use reassign_task to assign and wake a member; claim_task does not dispatch work. A member cannot own a second unfinished task. The returned attempt_id is required for updates and becomes stale after retry/reassignment.',
1767
+ parameters: {
1768
+ task_id: { type: 'string', required: true, description: 'The task id to claim.' },
1769
+ assignee: { type: 'string', description: 'Deprecated: claim_task only supports a member claiming its own task. Captains must use reassign_task.' },
1770
+ },
1771
+ output: {
1772
+ schema: {
1773
+ type: 'object',
1774
+ additionalProperties: false,
1775
+ properties: {
1776
+ task_id: { type: 'string', required: true },
1777
+ status: { type: 'string', required: true },
1778
+ assignee: { type: 'string', required: true },
1779
+ attempt: { type: 'number', required: true },
1780
+ attempt_id: { type: 'string' },
1781
+ task_details: { type: 'string', required: true },
1782
+ },
1783
+ },
1784
+ render: (args, value) => [{
1785
+ type: 'text',
1786
+ text: `Task ${value.task_id} claimed by ${value.assignee} (attempt ${value.attempt}${value.attempt_id ? `, attempt_id ${value.attempt_id}` : ''}, status ${value.status}).\n${value.task_details}`,
1787
+ }],
1788
+ },
1789
+ async execute(args, exec) {
1790
+ const caller = requireCaptain(exec)
1791
+ const workspace = workspaceOf(caller)
1792
+ const stateRoot = stateRootOf(workspace, config)
1793
+ const team = await requireParticipantTeam(ctx, workspace, config, caller)
1794
+ return withTeamLock(teamLockKey(stateRoot, team.id), async () => {
1795
+ const { team: fresh, identity } = await requireFreshParticipant(ctx, stateRoot, team.id, caller.id)
1796
+ const task = requireTask(fresh, args.task_id)
1797
+ if (task.reassigning === true) {
1798
+ throw new Error(`task ${task.id} is being reassigned; wait for the handoff to finish`)
1799
+ }
1800
+ // Gateways materialize this deprecated optional argument, and a model may
1801
+ // also restate its own member name. A blank or self-valued assignee is
1802
+ // harmless: it asks for exactly what a claim does anyway.
1803
+ const requestedAssignee = typeof args.assignee === 'string' && args.assignee.trim() !== ''
1804
+ ? args.assignee.trim()
1805
+ : undefined
1806
+ let assignee = task.assignee
1807
+ if (identity.kind === 'captain') {
1808
+ // A captain may read the capability of its already-started takeover,
1809
+ // but must never create a member claim without dispatching it (#125).
1810
+ if (requestedAssignee !== undefined || task.assignee !== CAPTAIN_KEY
1811
+ || (task.status !== 'claimed' && task.status !== 'in_progress')) {
1812
+ throw new Error('claim_task is for members claiming their own task; captains must use agent_teams_reassign_task to assign and wake a member')
1813
+ }
1814
+ } else {
1815
+ if (requestedAssignee !== undefined && requestedAssignee !== identity.name) {
1816
+ throw new Error('members cannot set assignee when claiming a task')
1817
+ }
1818
+ if (assignee !== undefined && assignee !== identity.name) {
1819
+ throw new Error(`task ${task.id} is assigned to "${assignee}", not you`)
1820
+ }
1821
+ assignee = identity.name
1822
+ }
1823
+ // Authorization must happen before the idempotent return: another
1824
+ // member must not receive a false success for somebody else's task.
1825
+ if (task.status === 'claimed' || task.status === 'in_progress') {
1826
+ if (assignee === undefined || task.assignee !== assignee) {
1827
+ throw new Error(`task ${task.id} is already claimed by "${task.assignee ?? 'nobody'}"`)
1828
+ }
1829
+ return {
1830
+ task_details: taskDetails(fresh, task),
1831
+ task_id: task.id,
1832
+ status: task.status,
1833
+ assignee,
1834
+ attempt: task.attempt ?? 0,
1835
+ ...task.attemptId === undefined ? {} : { attempt_id: task.attemptId },
1836
+ }
1837
+ }
1838
+ const pending = unsatisfiedDependencies(fresh.tasks, task.dependencies)
1839
+ if (pending.length > 0) {
1840
+ throw new Error(`task ${task.id} is blocked by unfinished dependencies: ${pending.join(', ')} — complete them first`)
1841
+ }
1842
+ const transition = transitionError(task.status, 'claimed')
1843
+ if (transition !== undefined) throw new Error(transition)
1844
+ if (assignee === undefined) {
1845
+ throw new Error('claiming an unassigned task needs an assignee (claim on behalf of a member)')
1846
+ }
1847
+ const busy = memberOpenTask(fresh, assignee, task.id)
1848
+ if (busy !== undefined) {
1849
+ throw new Error(`member "${assignee}" is busy with ${busy.id}; finish or reassign it first`)
1850
+ }
1851
+ const attemptId = beginTaskAttempt(task, assignee)
1852
+ await writeTeam(stateRoot, fresh)
1853
+ appendTeamEvent(ctx, captainSessionOf(ctx, fresh.captainSessionId, caller.session), 'agent-teams/task-updated', {
1854
+ teamId: fresh.id,
1855
+ taskId: task.id,
1856
+ status: task.status,
1857
+ assignee: task.assignee,
1858
+ })
1859
+ return {
1860
+ task_details: taskDetails(fresh, task),
1861
+ task_id: task.id,
1862
+ status: task.status,
1863
+ assignee: task.assignee ?? '',
1864
+ attempt: task.attempt ?? 0,
1865
+ attempt_id: attemptId,
1866
+ }
1867
+ })
1868
+ },
1869
+ }))
1870
+
1871
+ ctx.tools.register(defineTool({
1872
+ name: 'agent_teams_update_task',
1873
+ description: 'Update a task status/output. Members must supply the current attempt_id returned by claim_task; stale attempts are rejected after takeover/reassignment. Terminal results are immutable, but owners and the captain can append acceptanceResults/commandsRun/evidence_note as attributed supplemental evidence, without reclaiming or changing the verdict. A captain must use reassign_task(assignee="captain") before updating active member-owned work.',
1874
+ parameters: {
1875
+ task_id: { type: 'string', required: true, description: 'The task id to update.' },
1876
+ attempt_id: { type: 'string', description: 'Members must explicitly include the current attempt_id from their assignment/claim in EVERY update, including failed reviews with findings. If omitted, retry with the same current id; omission does not revoke the attempt.' },
1877
+ status: {
1878
+ type: 'string',
1879
+ enum: ['in_progress', 'completed', 'failed', 'cancelled'],
1880
+ description: 'New status (in_progress, completed, failed, cancelled).',
1881
+ },
1882
+ output: { type: 'string', description: 'Original result summary; immutable after completion/failure.' },
1883
+ evidence_note: { type: 'string', description: 'Append-only supplementary observation on a terminal task. Does not reopen work or change the original result.' },
1884
+ verdict: {
1885
+ type: 'string',
1886
+ enum: ['pass', 'needs_revision', 'reject'],
1887
+ description: 'Required for completing requirements/review. needs_revision and reject must fail the task.',
1888
+ },
1889
+ findings: {
1890
+ type: 'array',
1891
+ items: {
1892
+ type: 'object',
1893
+ additionalProperties: false,
1894
+ properties: {
1895
+ id: { type: 'string', required: true },
1896
+ severity: { type: 'string', enum: ['low', 'medium', 'high', 'blocker'], required: true },
1897
+ problem: { type: 'string', required: true },
1898
+ requiredFix: { type: 'string', required: true },
1899
+ file: { type: 'string' },
1900
+ line: { type: 'number' },
1901
+ resolved: { type: 'boolean' },
1902
+ },
1903
+ },
1904
+ description: 'Structured review findings. Required when verdict is needs_revision or reject; each item needs id, severity, problem, and requiredFix.',
1905
+ },
1906
+ changedPaths: {
1907
+ type: 'array',
1908
+ items: { type: 'string' },
1909
+ description: 'Workspace-relative POSIX paths changed by this implementation/repair.',
1910
+ },
1911
+ acceptanceResults: {
1912
+ type: 'array',
1913
+ items: {
1914
+ type: 'object',
1915
+ additionalProperties: false,
1916
+ properties: {
1917
+ criterion: { type: 'string', required: true },
1918
+ status: { type: 'string', enum: ['passed', 'failed'], required: true },
1919
+ evidence: { type: 'string' },
1920
+ },
1921
+ },
1922
+ description: 'Acceptance evidence in contract order: {criterion, status:"passed"|"failed", evidence?}. Supply one item per acceptance criterion.',
1923
+ },
1924
+ commandsRun: {
1925
+ type: 'array',
1926
+ items: {
1927
+ type: 'object',
1928
+ additionalProperties: false,
1929
+ properties: {
1930
+ command: { type: 'string', required: true },
1931
+ status: { type: 'string', enum: ['passed', 'failed'], required: true },
1932
+ exitCode: { type: 'number' },
1933
+ evidence: { type: 'string' },
1934
+ },
1935
+ },
1936
+ description: 'Verification evidence in contract order: {command, status:"passed"|"failed", exitCode?, evidence?}. Supply one item per verify command.',
1937
+ },
1938
+ },
1939
+ output: {
1940
+ schema: {
1941
+ type: 'object',
1942
+ additionalProperties: false,
1943
+ properties: {
1944
+ task_id: { type: 'string', required: true },
1945
+ status: { type: 'string', required: true },
1946
+ output: { type: 'string' },
1947
+ attempt: { type: 'number', required: true },
1948
+ attempt_id: { type: 'string' },
1949
+ evidence_count: { type: 'number' },
1950
+ follow_up: { type: 'string' },
1951
+ },
1952
+ },
1953
+ render: (args, value) => [{
1954
+ type: 'text',
1955
+ text: `Task ${value.task_id} attempt ${value.attempt} → ${value.status}${value.output !== undefined ? `\nOutput: ${value.output}` : ''}${value.evidence_count === undefined ? '' : `\nSupplemental evidence records: ${value.evidence_count}. Original result unchanged.`}${value.follow_up ? `\n${value.follow_up}` : ''}`,
1956
+ }],
1957
+ },
1958
+ async execute(args, exec) {
1959
+ const caller = requireCaptain(exec)
1960
+ const workspace = workspaceOf(caller)
1961
+ const stateRoot = stateRootOf(workspace, config)
1962
+ const team = await requireParticipantTeam(ctx, workspace, config, caller)
1963
+ let followUpMessage: import('./types.ts').TeamMessage | undefined
1964
+ const updated = await withTeamLock(teamLockKey(stateRoot, team.id), async () => {
1965
+ const { team: fresh, identity } = await requireFreshParticipant(ctx, stateRoot, team.id, caller.id)
1966
+ const task = requireTask(fresh, args.task_id)
1967
+ if (identity.kind === 'captain'
1968
+ && task.assignee !== undefined
1969
+ && task.assignee !== CAPTAIN_KEY
1970
+ && !TERMINAL_TASK_STATUSES.includes(task.status)
1971
+ && !(args.status === 'cancelled' && task.status === 'pending' && (task.attempt ?? 0) === 0 && task.reassigning !== true)) {
1972
+ throw new Error(`task ${task.id} is owned by member "${task.assignee}"; call agent_teams_reassign_task with assignee="captain" before takeover`)
1973
+ }
1974
+ if (identity.kind === 'member') {
1975
+ if (task.assignee !== identity.name) {
1976
+ throw new Error(`task ${task.id} is assigned to "${task.assignee ?? 'nobody'}", not you`)
1977
+ }
1978
+ if (task.attemptId !== undefined && (args.attempt_id === undefined || args.attempt_id.trim() === '')) {
1979
+ throw new Error(`missing attempt_id for task ${task.id}. Retry this update with attempt_id="${task.attemptId}" from your current assignment. This is a missing parameter, not a revoked attempt; do not restart the work or request reassignment.`)
1980
+ }
1981
+ if (task.attemptId !== undefined && args.attempt_id !== task.attemptId) {
1982
+ throw new Error(`stale attempt for task ${task.id}: expected the current attempt_id; stop work and request fresh assignment`)
1983
+ }
1984
+ }
1985
+ if (TERMINAL_TASK_STATUSES.includes(task.status)) {
1986
+ const appended = appendTaskEvidence(task, {
1987
+ ...args, findings: parseFindings(args.findings), changedPaths: normalizeBlankOptionalTaskFields(args).changedPaths,
1988
+ acceptanceResults: parseAcceptanceResults(args.acceptanceResults), commandsRun: parseCommandResults(args.commandsRun),
1989
+ }, identity.name)
1990
+ if (appended) await writeTeam(stateRoot, fresh)
1991
+ return {
1992
+ evidence_count: task.supplementalEvidence?.length ?? 0,
1993
+ task_id: task.id,
1994
+ status: task.status,
1995
+ attempt: task.attempt ?? 0,
1996
+ ...task.attemptId === undefined ? {} : { attempt_id: task.attemptId },
1997
+ ...task.output !== undefined ? { output: task.output } : {},
1998
+ }
1999
+ }
2000
+ if (args.evidence_note?.trim()) throw new Error('evidence_note is for terminal tasks; record active work with output and structured evidence')
2001
+ // Blank optional list entries (e.g. changedPaths:[""]) must not be
2002
+ // persisted: hasValidQualityTaskFields rejects them on reload and
2003
+ // would brick the whole team state (issue #105 class).
2004
+ const input = normalizeBlankOptionalTaskFields(args)
2005
+ const findings = parseFindings(args.findings)
2006
+ const acceptanceResults = parseAcceptanceResults(args.acceptanceResults)
2007
+ const commandsRun = parseCommandResults(args.commandsRun)
2008
+ const gate = evaluateQualityCompletion(task, {
2009
+ status: args.status,
2010
+ output: args.output,
2011
+ verdict: args.verdict as ReviewVerdict | undefined,
2012
+ findings,
2013
+ changedPaths: input.changedPaths,
2014
+ acceptanceResults,
2015
+ commandsRun,
2016
+ })
2017
+ if (!gate.ok) throw new Error(gate.error ?? 'update_task rejected by quality gates')
2018
+ if (args.status !== undefined) {
2019
+ const transition = transitionError(task.status, args.status)
2020
+ if (transition !== undefined) throw new Error(transition)
2021
+ task.status = args.status
2022
+ }
2023
+ if (args.output !== undefined) task.output = args.output
2024
+ if (args.verdict !== undefined) task.verdict = args.verdict as ReviewVerdict
2025
+ if (findings !== undefined) task.findings = findings
2026
+ if (input.changedPaths !== undefined) task.changedPaths = input.changedPaths
2027
+ if (acceptanceResults !== undefined) task.acceptanceResults = acceptanceResults
2028
+ if (commandsRun !== undefined) task.commandsRun = commandsRun
2029
+ // A passing gate is evidence about a revision: record which one, so a
2030
+ // later edit cannot leave the team advertising an unreviewed revision.
2031
+ bindClosingVerdict(workspace, fresh, task)
2032
+ task.updatedAt = Date.now()
2033
+ const priorDependencies = new Map(fresh.tasks.map(item => [item.id, [...item.dependencies]]))
2034
+ const followUp = (task.status === 'failed' && isQualityKind(taskKindOf(task)))
2035
+ ? applyQualityFollowUp(
2036
+ fresh,
2037
+ task,
2038
+ (paths) => snapshotWorkspacePaths(workspace, paths),
2039
+ (path) => workspacePathExists(workspace, path),
2040
+ )
2041
+ : undefined
2042
+ let followUpSummary: string | undefined
2043
+ if ((followUp?.created.length ?? 0) > 0) {
2044
+ const rewired = fresh.tasks.filter(item => priorDependencies.has(item.id) && JSON.stringify(priorDependencies.get(item.id)) !== JSON.stringify(item.dependencies))
2045
+ followUpSummary = `Automatic quality follow-up for ${task.id}: ${followUp!.created.map(item => `${item.id} (${item.kind}, owner=${item.assignee ?? 'unassigned'}, deps=${item.dependencies.join(',') || 'none'})`).join('; ')}.${rewired.length ? ` Updated dependencies: ${rewired.map(item => `${item.id} -> ${item.dependencies.join(',')}`).join('; ')}.` : ''} Use these tasks; do not create duplicate repair/review work.${followUp!.excludedFindings === undefined ? '' : ` Findings on default-excluded paths were not turned into a contract and stay with the user: ${followUp!.excludedFindings.join(', ')}.`}`
2046
+ followUpMessage = createMessage(CAPTAIN_KEY, CAPTAIN_KEY, followUpSummary)
2047
+ }
2048
+ if (followUp?.escalated === true) {
2049
+ await appendMailbox(stateRoot, fresh.id, CAPTAIN_KEY, createMessage(
2050
+ CAPTAIN_KEY,
2051
+ CAPTAIN_KEY,
2052
+ `Quality-gate loop escalated after ${task.id} (${task.kind ?? 'review'} verdict=${task.verdict}). Automatic repair/review stopped.${followUp.reason === undefined ? '' : ` Reason: ${followUp.reason}.`}${followUp.excludedFindings === undefined ? '' : ` Findings left for the user (default-excluded paths, not a member's to edit): ${followUp.excludedFindings.join(', ')}.`}`,
2053
+ ))
2054
+ }
2055
+ await writeTeam(stateRoot, fresh)
2056
+ if (followUpMessage !== undefined) await appendMailbox(stateRoot, fresh.id, CAPTAIN_KEY, followUpMessage)
2057
+ appendTeamEvent(ctx, captainSessionOf(ctx, fresh.captainSessionId, caller.session), 'agent-teams/task-updated', {
2058
+ teamId: fresh.id,
2059
+ taskId: task.id,
2060
+ status: task.status,
2061
+ ...task.assignee !== undefined ? { assignee: task.assignee } : {},
2062
+ ...task.output !== undefined ? { output: task.output } : {},
2063
+ ...task.verdict === undefined ? {} : { verdict: task.verdict },
2064
+ ...task.round === undefined ? {} : { round: task.round },
2065
+ })
2066
+ for (const created of followUp?.created ?? []) {
2067
+ appendTeamEvent(ctx, captainSessionOf(ctx, fresh.captainSessionId, caller.session), 'agent-teams/task-created', {
2068
+ teamId: fresh.id,
2069
+ taskId: created.id,
2070
+ subject: created.subject,
2071
+ dependencies: created.dependencies,
2072
+ ...created.assignee === undefined ? {} : { assignee: created.assignee },
2073
+ ...created.kind === undefined ? {} : { kind: created.kind },
2074
+ ...created.round === undefined ? {} : { round: created.round },
2075
+ })
2076
+ }
2077
+ return {
2078
+ ...followUpSummary === undefined ? {} : { follow_up: followUpSummary },
2079
+ task_id: task.id,
2080
+ status: task.status,
2081
+ attempt: task.attempt ?? 0,
2082
+ ...task.attemptId === undefined ? {} : { attempt_id: task.attemptId },
2083
+ ...task.output !== undefined ? { output: task.output } : {},
2084
+ }
2085
+ })
2086
+ if (followUpMessage !== undefined) {
2087
+ const captain = nearestLiveLead(ctx, team)
2088
+ if (captain !== undefined && steerCaptainReport(captain, CAPTAIN_KEY, followUpMessage.content, mailboxPrompt(team.id, CAPTAIN_KEY, [followUpMessage]))) {
2089
+ await withTeamLock(teamLockKey(stateRoot, team.id), () => markMailboxDelivered(stateRoot, team.id, CAPTAIN_KEY, [followUpMessage!.id]))
2090
+ }
2091
+ }
2092
+ await scheduler.kickTeam(workspace, team.id, await liveLeadAnchorAgent(ctx, team, caller))
2093
+ return updated
2094
+ },
2095
+ }))
2096
+
2097
+ ctx.tools.register(defineTool({
2098
+ name: 'agent_teams_amend_task',
2099
+ description: 'Captain-only controlled contract amendment for one non-terminal quality task: replace a wrong objective/acceptance/verify/inScope/outOfScope when the original contract makes honest completion impossible (for example a verify command that cannot pass, or an inScope that forbids the file the objective names). The amendment is appended to the task\'s revisions ledger with previous values and the reason, and is rejected once a review/requirements task has passed judgment on this task. Members cannot amend contracts; the implementer re-reads the amended contract before its next quality gate. Lists are full replacements, not deltas.',
2100
+ parameters: {
2101
+ task_id: { type: 'string', required: true, description: 'Task whose contract is being amended.' },
2102
+ reason: { type: 'string', required: true, description: 'Why the current contract is wrong; recorded in the revisions ledger.' },
2103
+ objective: { type: 'string', description: 'Replacement objective.' },
2104
+ acceptance: { type: 'array', items: { type: 'string' }, description: 'Replacement acceptance criteria (full list, not a delta).' },
2105
+ verify: { type: 'array', items: { type: 'string' }, description: 'Replacement verification commands (full list, not a delta).' },
2106
+ inScope: { type: 'array', items: { type: 'string' }, description: 'Replacement workspace-relative inScope paths (full list).' },
2107
+ outOfScope: { type: 'array', items: { type: 'string' }, description: 'Replacement workspace-relative outOfScope paths (full list).' },
2108
+ },
2109
+ output: {
2110
+ schema: {
2111
+ type: 'object',
2112
+ additionalProperties: false,
2113
+ properties: {
2114
+ task_id: { type: 'string', required: true },
2115
+ status: { type: 'string', required: true },
2116
+ revised_fields: { type: 'string', required: true },
2117
+ revision_count: { type: 'number', required: true },
2118
+ contract: { type: 'string', required: true },
2119
+ },
2120
+ },
2121
+ render: (_args, value) => [{
2122
+ type: 'text',
2123
+ text: `Task ${value.task_id} contract amended (${value.revised_fields}); ${value.revision_count} revision(s) on record, status ${value.status}. New contract: ${value.contract}`,
2124
+ }],
2125
+ },
2126
+ async execute(args, exec) {
2127
+ const captain = requireCaptain(exec)
2128
+ const workspace = workspaceOf(captain)
2129
+ const stateRoot = stateRootOf(workspace, config)
2130
+ const team = await requireCaptainTeam(ctx, workspace, config, captain)
2131
+ const amended = await withTeamLock(teamLockKey(stateRoot, team.id), async () => {
2132
+ const fresh = await requireFreshCaptainTeam(ctx, stateRoot, team.id, captain.id)
2133
+ const task = requireTask(fresh, args.task_id)
2134
+ const input: ContractAmendmentInput = {
2135
+ ...args.objective === undefined ? {} : { objective: args.objective },
2136
+ ...args.acceptance === undefined ? {} : { acceptance: args.acceptance },
2137
+ ...args.verify === undefined ? {} : { verify: args.verify },
2138
+ ...args.inScope === undefined ? {} : { inScope: args.inScope },
2139
+ ...args.outOfScope === undefined ? {} : { outOfScope: args.outOfScope },
2140
+ }
2141
+ const result = amendTaskContract(fresh, task, normalizeBlankOptionalTaskFields(input), CAPTAIN_KEY, args.reason)
2142
+ if (!result.ok || result.task === undefined) {
2143
+ throw new Error(result.error ?? 'amend_task rejected by quality gates')
2144
+ }
2145
+ Object.assign(task, result.task)
2146
+ task.updatedAt = Date.now()
2147
+ await writeTeam(stateRoot, fresh)
2148
+ return {
2149
+ taskId: task.id,
2150
+ status: task.status,
2151
+ fields: result.revision?.fields ?? [],
2152
+ revisionCount: task.revisions?.length ?? 0,
2153
+ contract: {
2154
+ ...task.objective === undefined ? {} : { objective: task.objective },
2155
+ ...task.acceptance === undefined ? {} : { acceptance: task.acceptance },
2156
+ ...task.verify === undefined ? {} : { verify: task.verify },
2157
+ ...task.inScope === undefined ? {} : { inScope: task.inScope },
2158
+ ...task.outOfScope === undefined ? {} : { outOfScope: task.outOfScope },
2159
+ },
2160
+ }
2161
+ })
2162
+ appendTeamEvent(ctx, captainSessionOf(ctx, team.captainSessionId, captain.session), 'agent-teams/task-amended', {
2163
+ teamId: team.id,
2164
+ taskId: amended.taskId,
2165
+ fields: amended.fields,
2166
+ reason: args.reason,
2167
+ })
2168
+ return {
2169
+ task_id: amended.taskId,
2170
+ status: amended.status,
2171
+ revised_fields: amended.fields.join(', '),
2172
+ revision_count: amended.revisionCount,
2173
+ contract: JSON.stringify(amended.contract),
2174
+ }
2175
+ },
2176
+ }))
2177
+
2178
+ ctx.tools.register(defineTool({
2179
+ name: 'agent_teams_send_message',
2180
+ description: 'Send coordination or current-task guidance directly to the captain or a teammate. A running recipient receives it at the next model step; an idle recipient wakes. Messages are durably retained until read. Use task creation/reassignment for a new unit of work, not repeated status nudges.',
2181
+ parameters: {
2182
+ source_task_id: { type: 'string', description: 'Sender task, NOT the recipient task. Members include it with source_attempt_id. Captains sending guidance normally omit both source fields.' },
2183
+ source_attempt_id: { type: 'string', description: 'Sender execution capability paired with source_task_id. Stale reports are rejected. Omit for ordinary captain guidance.' },
2184
+ to: { type: 'string', required: true, description: 'Recipient: "captain" or a member name.' },
2185
+ content: { type: 'string', required: true, description: 'The message text.' },
2186
+ from: { type: 'string', description: 'Sender (defaults to the caller: the captain, or the calling member).' },
2187
+ },
2188
+ output: {
2189
+ schema: {
2190
+ type: 'object',
2191
+ additionalProperties: false,
2192
+ properties: {
2193
+ message_id: { type: 'string', required: true },
2194
+ from: { type: 'string', required: true },
2195
+ to: { type: 'string', required: true },
2196
+ delivered: { type: 'string', required: true, description: 'live (accepted by the live captain), wake (member recipient woken), mailbox (durable inbox only), or duplicate (same message already retained).' },
2197
+ },
2198
+ },
2199
+ render: (args, value) => [{
2200
+ type: 'text',
2201
+ text: `Message ${value.message_id} ${value.from} → ${value.to} delivered via ${value.delivered}.`,
2202
+ }],
2203
+ },
2204
+ async execute(args, exec) {
2205
+ const caller = requireCaptain(exec)
2206
+ const workspace = workspaceOf(caller)
2207
+ const stateRoot = stateRootOf(workspace, config)
2208
+ const team = await requireParticipantTeam(ctx, workspace, config, caller)
2209
+ const to = args.to.trim()
2210
+ const prepared = await withTeamLock(teamLockKey(stateRoot, team.id), async () => {
2211
+ const { team: fresh, identity } = await requireFreshParticipant(ctx, stateRoot, team.id, caller.id)
2212
+ const from = identity.name
2213
+ // `from` may only be the caller's own identity: impersonating another
2214
+ // member (or the captain) would poison the mailbox and event records.
2215
+ if (args.from !== undefined && args.from !== from) {
2216
+ throw new Error(`agent_teams_send_message: "from" must be your own identity ("${from}"), not "${args.from}"`)
2217
+ }
2218
+ const sourceTaskId = args.source_task_id?.trim() || undefined
2219
+ const sourceAttemptId = args.source_attempt_id?.trim() || undefined
2220
+ if ((sourceTaskId === undefined) !== (sourceAttemptId === undefined)) throw new Error('send_message requires source_task_id and source_attempt_id together')
2221
+ const source = sourceTaskId === undefined
2222
+ ? identity.kind === 'member' ? memberOpenTask(fresh, identity.name) ?? fresh.tasks.filter(item => item.assignee === identity.name && item.attemptId !== undefined).sort((a, b) => b.updatedAt - a.updatedAt)[0] : undefined
2223
+ : requireTask(fresh, sourceTaskId)
2224
+ if (sourceTaskId !== undefined && (source?.assignee !== identity.name || source.attemptId !== sourceAttemptId)) {
2225
+ throw new Error('stale or foreign source attempt; stop sending results from the revoked task')
2226
+ }
2227
+ const sourceFields = source?.attemptId === undefined ? {} : { sourceTaskId: source.id, sourceAttemptId: source.attemptId, sourceTaskStatus: source.status }
2228
+ const owned = to === CAPTAIN_KEY ? undefined : memberOpenTask(fresh, requireMember(fresh, to).name)
2229
+ const duplicate = (await readMailbox(stateRoot, fresh.id, to)).find(message => message.from === from
2230
+ && message.content === args.content && message.taskId === owned?.id && message.attemptId === owned?.attemptId
2231
+ && message.sourceTaskId === sourceFields.sourceTaskId && message.sourceAttemptId === sourceFields.sourceAttemptId && message.sourceTaskStatus === sourceFields.sourceTaskStatus
2232
+ && isCurrentMail(fresh, message) && (message.attemptId !== undefined || message.sourceAttemptId !== undefined || message.readAt === undefined))
2233
+ if (duplicate !== undefined) return { kind: 'duplicate' as const, message: duplicate, from }
2234
+ if (to === CAPTAIN_KEY) {
2235
+ const message = { ...createMessage(from, CAPTAIN_KEY, args.content), ...sourceFields, deliveryClaimedAt: Date.now() }
2236
+ await appendMailbox(stateRoot, fresh.id, CAPTAIN_KEY, message)
2237
+ appendTeamEvent(ctx, captainSessionOf(ctx, fresh.captainSessionId, caller.session), 'agent-teams/message-sent', {
2238
+ teamId: fresh.id,
2239
+ messageId: message.id,
2240
+ from,
2241
+ to: CAPTAIN_KEY,
2242
+ content: args.content,
2243
+ ts: message.ts,
2244
+ })
2245
+ return { kind: 'captain' as const, fresh, identity, message, from }
2246
+ }
2247
+ if (fresh.halted === true) {
2248
+ throw new Error(`team "${fresh.name}" is halted; call agent_teams_resume before waking a member`)
2249
+ }
2250
+ const recipient = requireMember(fresh, to)
2251
+ const message = { ...createMessage(from, recipient.name, args.content), ...sourceFields, deliveryClaimedAt: Date.now(),
2252
+ ...owned?.attemptId === undefined ? {} : { taskId: owned.id, attemptId: owned.attemptId },
2253
+ }
2254
+ await appendMailbox(stateRoot, fresh.id, recipient.name, message)
2255
+ appendTeamEvent(ctx, captainSessionOf(ctx, fresh.captainSessionId, caller.session), 'agent-teams/message-sent', {
2256
+ teamId: fresh.id,
2257
+ messageId: message.id,
2258
+ from,
2259
+ to: recipient.name,
2260
+ content: args.content,
2261
+ ts: message.ts,
2262
+ })
2263
+ return { kind: 'member' as const, fresh, identity, message, from, recipient }
2264
+ })
2265
+
2266
+ if (prepared.kind === 'duplicate') return { message_id: prepared.message.id, from: prepared.from, to: prepared.message.to, delivered: 'duplicate' }
2267
+ // Resolve a live lead only after releasing the state lock: the recorded
2268
+ // captain while resident, otherwise the nearest live fork descendant, so
2269
+ // a human working in a fork still receives member reports. The plugin
2270
+ // mailbox is already durable if no lead session is live.
2271
+ const captain = nearestLiveLead(ctx, prepared.fresh)
2272
+ if (prepared.kind === 'captain') {
2273
+ let delivered: 'live' | 'mailbox' = 'mailbox'
2274
+ if (captain !== undefined && prepared.identity.kind === 'member') {
2275
+ delivered = steerCaptainReport(captain, prepared.from, args.content, mailboxPrompt(prepared.fresh.id, CAPTAIN_KEY, [prepared.message])) ? 'live' : 'mailbox'
2276
+ }
2277
+ if (delivered === 'live') {
2278
+ await withTeamLock(teamLockKey(stateRoot, prepared.fresh.id), () => (
2279
+ markMailboxDelivered(stateRoot, prepared.fresh.id, CAPTAIN_KEY, [prepared.message.id])
2280
+ ))
2281
+ } else {
2282
+ await withTeamLock(teamLockKey(stateRoot, prepared.fresh.id), () => (
2283
+ releaseMailboxDelivery(stateRoot, prepared.fresh.id, CAPTAIN_KEY, [prepared.message.id])
2284
+ ))
2285
+ }
2286
+ return { message_id: prepared.message.id, from: prepared.from, to: CAPTAIN_KEY, delivered }
2287
+ }
2288
+ let delivered: 'wake' | 'mailbox' = 'mailbox'
2289
+ if (captain !== undefined) {
2290
+ const text = mailboxPrompt(prepared.fresh.id, prepared.recipient.name, [prepared.message])
2291
+ const accepted = await dispatchMember(captain, prepared.fresh.id, prepared.recipient.name, text, exec.signal, 'steer', prepared.message.attemptId)
2292
+ delivered = accepted ? 'wake' : 'mailbox'
2293
+ if (accepted) {
2294
+ await withTeamLock(teamLockKey(stateRoot, prepared.fresh.id), () => (
2295
+ markMailboxDelivered(stateRoot, prepared.fresh.id, prepared.recipient.name, [prepared.message.id])
2296
+ ))
2297
+ }
2298
+ }
2299
+ if (delivered === 'mailbox') {
2300
+ await withTeamLock(teamLockKey(stateRoot, prepared.fresh.id), () => (
2301
+ releaseMailboxDelivery(stateRoot, prepared.fresh.id, prepared.recipient.name, [prepared.message.id])
2302
+ ))
2303
+ }
2304
+ return {
2305
+ message_id: prepared.message.id,
2306
+ from: prepared.from,
2307
+ to: prepared.recipient.name,
2308
+ delivered,
2309
+ }
2310
+ },
2311
+ }))
2312
+
2313
+ ctx.tools.register(defineTool({
2314
+ name: 'agent_teams_status',
2315
+ description: 'Team snapshot: members with live activity and tasks with status/assignee/dependencies/output. Captains also see every team mailbox; members see only their own inbox. Use after mailbox progress deliveries or for an explicit status request. After dispatch, end your turn while members work; do not repeatedly poll.',
2316
+ parameters: {},
2317
+ output: {
2318
+ schema: { type: 'object', additionalProperties: true, properties: {} },
2319
+ render: (_args, value) => [{ type: 'text', text: renderStatus(value) }],
2320
+ },
2321
+ async execute(_args, exec) {
2322
+ const caller = requireCaptain(exec)
2323
+ const workspace = workspaceOf(caller)
2324
+ const stateRoot = stateRootOf(workspace, config)
2325
+ const located = await requireParticipantTeam(ctx, workspace, config, caller)
2326
+ if (await sessionLeadsTeamAsync(ctx, located, caller.id)) {
2327
+ await scheduler.kickTeam(workspace, located.id, await memberOperationParent(ctx, located, caller))
2328
+ }
2329
+ const {
2330
+ team, identity, captainInbox, ownInbox, memberInboxes, mailboxWarnings, mailboxWarningCount,
2331
+ } = await withTeamLock(teamLockKey(stateRoot, located.id), async () => {
2332
+ // Authorize and read mail under the same lock. A team name can be
2333
+ // reused while the worker audits the previously captured state.
2334
+ const { team, identity } = await requireFreshParticipant(ctx, stateRoot, located.id, caller.id)
2335
+ const mailboxWarnings: string[] = []
2336
+ let mailboxWarningCount = 0
2337
+ const reportMalformed = (agentKey: string) => (lineNumber: number): void => {
2338
+ mailboxWarningCount += 1
2339
+ if (mailboxWarnings.length < 10) mailboxWarnings.push(`${agentKey} mailbox line ${lineNumber}`)
2340
+ }
2341
+ const captainInbox = identity.kind === 'captain'
2342
+ ? (await readCurrentMailboxLocked(stateRoot, team, CAPTAIN_KEY, reportMalformed(CAPTAIN_KEY))).slice(0, 10)
2343
+ : []
2344
+ let ownInbox: TeamMessage[] = []
2345
+ const memberInboxes: Record<string, { count: number; latest: string }> = {}
2346
+ for (const member of team.members) {
2347
+ if (member.status === 'removed' || (identity.kind === 'member' && member.name !== identity.name)) continue
2348
+ const messages = await readCurrentMailboxLocked(stateRoot, team, member.name, reportMalformed(member.name))
2349
+ if (identity.kind === 'member') ownInbox = messages.slice(0, 10)
2350
+ if (messages.length > 0) {
2351
+ memberInboxes[member.name] = {
2352
+ count: messages.length,
2353
+ latest: messages[messages.length - 1]?.content.slice(0, 200) ?? '',
2354
+ }
2355
+ }
2356
+ }
2357
+ return { team, identity, captainInbox, ownInbox, memberInboxes, mailboxWarnings, mailboxWarningCount }
2358
+ })
2359
+ const activity = memberActivity(ctx, team.members.map((member) => member.id))
2360
+ const audit = await auditor.audit(workspace, team, stateRoot)
2361
+ const members = team.members
2362
+ .filter((member) => member.status !== 'removed')
2363
+ .map((member) => ({
2364
+ name: member.name,
2365
+ role: member.role ?? '',
2366
+ provider: member.provider ?? '',
2367
+ model: member.model ?? '',
2368
+ reasoning_effort: member.reasoningEffort ?? '',
2369
+ tool_policy: member.toolPolicy ?? '',
2370
+ status: member.status,
2371
+ activity: member.id !== '' ? (activity.get(member.id) ?? 'unknown') : 'unspawned',
2372
+ ...member.spawnError === undefined ? {} : { spawn_error: member.spawnError },
2373
+ }))
2374
+ const tasks = team.tasks.map((task) => ({
2375
+ id: task.id,
2376
+ subject: task.subject,
2377
+ status: task.status,
2378
+ assignee: task.assignee ?? '',
2379
+ dependencies: task.dependencies,
2380
+ attempt: task.attempt ?? 0,
2381
+ attempt_id: task.attemptId ?? '',
2382
+ reassigning: task.reassigning === true,
2383
+ kind: taskKindOf(task),
2384
+ ...task.round === undefined ? {} : { round: task.round },
2385
+ ...task.verdict === undefined ? {} : { verdict: task.verdict },
2386
+ ...task.supplementalEvidence === undefined ? {} : { supplemental_evidence: JSON.stringify(task.supplementalEvidence) },
2387
+ ...task.findingSourceTaskIds === undefined ? {} : { fixes: task.findingSourceTaskIds.join(',') },
2388
+ findings_open: (task.findings ?? []).filter((finding) => finding.resolved !== true).length,
2389
+ ...task.profileSeedId === undefined ? {} : { seed_id: task.profileSeedId },
2390
+ ...task.output !== undefined ? { output: task.output } : {},
2391
+ }))
2392
+ const coverage = buildCoverageMatrix(
2393
+ [...new Set(team.tasks.flatMap((item) => item.coverageOf ?? []))],
2394
+ team.tasks,
2395
+ ).map((row) => ({
2396
+ goal_item: row.goal_item,
2397
+ task_ids: [...row.task_ids],
2398
+ status: row.status,
2399
+ ...row.evidence === undefined ? {} : { evidence: row.evidence },
2400
+ }))
2401
+ const deliveryCheck = canDeclareDelivery(team, audit)
2402
+ const delivery = {
2403
+ ok: deliveryCheck.ok,
2404
+ blockers: [...deliveryCheck.blockers],
2405
+ warnings: [...deliveryCheck.warnings],
2406
+ }
2407
+ const loop = describeQualityLoop(team, audit)
2408
+ const result = {
2409
+ team_id: team.id,
2410
+ team_name: team.name,
2411
+ description: team.description ?? '',
2412
+ phase: team.phase ?? 'running',
2413
+ halted: loop.halted,
2414
+ escalated: loop.escalated,
2415
+ loop_state: loop.state,
2416
+ loop_summary: loop.summary,
2417
+ deliverable: loop.deliverable,
2418
+ coverage,
2419
+ delivery,
2420
+ ...team.profile === undefined ? {} : {
2421
+ profile: {
2422
+ name: team.profile.name,
2423
+ ...team.profile.protocol === undefined
2424
+ ? {}
2425
+ : { protocol: team.profile.protocol.slice(0, 240) },
2426
+ ...team.profile.taskPlanning === undefined ? {} : { task_planning: team.profile.taskPlanning },
2427
+ },
2428
+ },
2429
+ viewer: identity.name,
2430
+ members,
2431
+ tasks,
2432
+ captain_inbox: captainInbox.map((message) => ({
2433
+ from: message.from,
2434
+ content: mailboxContent(message),
2435
+ ts: message.ts,
2436
+ })),
2437
+ member_inbox: ownInbox.map(message => ({ from: message.from, content: mailboxContent(message), ts: message.ts })),
2438
+ member_inboxes: memberInboxes,
2439
+ mailbox_warnings: mailboxWarnings,
2440
+ mailbox_warning_count: mailboxWarningCount,
2441
+ }
2442
+ const acknowledged = identity.kind === 'captain'
2443
+ ? captainInbox.map(message => message.id)
2444
+ : ownInbox.map(message => message.id)
2445
+ if (acknowledged.length > 0) {
2446
+ await withTeamLock(teamLockKey(stateRoot, team.id), async () => {
2447
+ // Keep acknowledgement after the audit, and never write through
2448
+ // the captured identity if the live team or recipient changed.
2449
+ const current = await readTeam(stateRoot, team.id).catch(() => undefined)
2450
+ if (current === undefined || current.captainSessionId !== team.captainSessionId || current.createdAt !== team.createdAt) return
2451
+ const recipient = await participantIdentityOf(ctx, current, caller.id)
2452
+ if (recipient?.kind !== identity.kind || recipient.name !== identity.name) return
2453
+ await acknowledgeMailbox(stateRoot, team.id, recipient.name, acknowledged)
2454
+ })
2455
+ }
2456
+ return result
2457
+ },
2458
+ }))
2459
+
2460
+ ctx.tools.register(defineTool({
2461
+ name: 'agent_teams_resume',
2462
+ description: 'Explicitly resume a halted team. Requires a non-empty reason. Does not recreate cancelled tasks; only still-pending work is scheduled.',
2463
+ parameters: {
2464
+ reason: { type: 'string', required: true, description: 'Why the team is being resumed.' },
2465
+ },
2466
+ output: {
2467
+ schema: {
2468
+ type: 'object',
2469
+ additionalProperties: false,
2470
+ properties: {
2471
+ status: { type: 'string', required: true },
2472
+ team_id: { type: 'string', required: true },
2473
+ reason: { type: 'string', required: true },
2474
+ },
2475
+ },
2476
+ render: (_args, value) => [{
2477
+ type: 'text',
2478
+ text: value.status === 'already_running'
2479
+ ? `Team ${value.team_id} is already running.`
2480
+ : `Team ${value.team_id} resumed (${value.reason}).`,
2481
+ }],
2482
+ },
2483
+ async execute(args, exec) {
2484
+ const captain = requireCaptain(exec)
2485
+ const workspace = workspaceOf(captain)
2486
+ const stateRoot = stateRootOf(workspace, config)
2487
+ const team = await requireCaptainTeam(ctx, workspace, config, captain)
2488
+ const result = await withTeamLock(teamLockKey(stateRoot, team.id), async () => {
2489
+ const fresh = await requireFreshCaptainTeam(ctx, stateRoot, team.id, captain.id)
2490
+ const resumed = resumeTeamState(fresh, args.reason)
2491
+ if (resumed.status === 'rejected') throw new Error(resumed.error ?? 'resume rejected')
2492
+ if (resumed.status === 'resumed') {
2493
+ fresh.halted = false
2494
+ fresh.haltedAt = undefined
2495
+ await writeTeam(stateRoot, fresh)
2496
+ appendTeamEvent(ctx, captainSessionOf(ctx, fresh.captainSessionId, captain.session), 'agent-teams/team-resumed', {
2497
+ teamId: fresh.id,
2498
+ reason: args.reason,
2499
+ })
2500
+ }
2501
+ return {
2502
+ status: resumed.status,
2503
+ team_id: fresh.id,
2504
+ reason: args.reason,
2505
+ }
2506
+ })
2507
+ if (result.status === 'resumed') await scheduler.kickTeam(workspace, team.id, await liveLeadAnchorAgent(ctx, team, captain))
2508
+ return result
2509
+ },
2510
+ }))
2511
+
2512
+ ctx.tools.register(defineTool({
2513
+ name: 'agent_teams_delete',
2514
+ description: 'End and archive your team: interrupts members and moves the current tasks and mailboxes out of active state for later inspection. Use when the work is done or explicitly abandoned. A same-name archive replaces its previous generation.',
2515
+ parameters: {},
2516
+ output: {
2517
+ schema: {
2518
+ type: 'object',
2519
+ additionalProperties: false,
2520
+ properties: {
2521
+ deleted: { type: 'boolean', required: true },
2522
+ team_name: { type: 'string', required: true },
2523
+ },
2524
+ },
2525
+ render: (args, value) => [{
2526
+ type: 'text',
2527
+ text: `Team "${value.team_name}" ended and archived.`,
2528
+ }],
2529
+ },
2530
+ async execute(_args, exec) {
2531
+ const captain = requireCaptain(exec)
2532
+ const workspace = workspaceOf(captain)
2533
+ const stateRoot = stateRootOf(workspace, config)
2534
+ const team = await requireCaptainTeam(ctx, workspace, config, captain)
2535
+ const members = await withTeamLock(teamLockKey(stateRoot, team.id), async () => {
2536
+ const fresh = await requireFreshCaptainTeam(ctx, stateRoot, team.id, captain.id)
2537
+ // Include previously removed members so deleting a pre-fix team also
2538
+ // retires durable catalog entries left behind by remove_member.
2539
+ const roster = fresh.members.map(member => ({ ...member }))
2540
+ for (const member of fresh.members) {
2541
+ await discardMailboxMessages(stateRoot, fresh.id, member.name, (await readUnreadMailbox(stateRoot, fresh.id, member.name)).map(message => message.id))
2542
+ if (member.status === 'removed') continue
2543
+ member.status = 'removed'
2544
+ for (const task of fresh.tasks) {
2545
+ if (task.assignee === member.name && !TERMINAL_TASK_STATUSES.includes(task.status)) invalidateTaskAttempt(task)
2546
+ }
2547
+ }
2548
+ await writeTeam(stateRoot, fresh)
2549
+ return roster
2550
+ })
2551
+ await recordRetiredMemberIds(stateRoot, members.map(member => member.id))
2552
+ await stopTeamMemberActivations(ctx, await memberOperationParent(ctx, team, captain), members, exec.signal)
2553
+ await withTeamLock(teamLockKey(stateRoot, team.id), async () => {
2554
+ const fresh = await requireFreshCaptainTeam(ctx, stateRoot, team.id, captain.id)
2555
+ appendTeamEvent(ctx, captainSessionOf(ctx, fresh.captainSessionId, captain.session), 'agent-teams/team-deleted', {
2556
+ teamId: fresh.id,
2557
+ })
2558
+ // Archive, not delete: tasks (with their dependency graph) and the
2559
+ // mailboxes stay on disk for later review and dependency rebuilds.
2560
+ await archiveTeamDir(stateRoot, fresh.id)
2561
+ })
2562
+ return { deleted: true, team_name: team.name }
2563
+ },
2564
+ }))
2565
+ // Live-member hydration validates saved filters against registered tools.
2566
+ const memberSelections = installMemberSelectionRuntime(ctx, config.stateDir, (workspace, teamId, memberName) => (
2567
+ scheduler.kickMember(workspace, teamId, memberName)
2568
+ ))
2569
+
2570
+ const runtime: AgentTeamsRuntime = {
2571
+ isPendingMember: memberSelections.isPendingMember,
2572
+ updateStagedPlan,
2573
+ updateStagedPlanBatch,
2574
+ approveStagedTeam,
2575
+ continueStagedPlanning,
2576
+ discardStagedTeam,
2577
+ }
2578
+
2579
+ return runtime
2580
+ }
2581
+
2582
+ async function initializeProfileTeam(input: {
2583
+ ctx: Context
2584
+ config: ToolsConfig
2585
+ memberSelections: ReturnType<typeof installMemberSelectionRuntime>
2586
+ captain: Agent
2587
+ exec: ToolRunContext
2588
+ stateRoot: string
2589
+ teamName: string
2590
+ teamId: string
2591
+ profileName: string
2592
+ inlinePlan?: import('./profiles.ts').TeamProfileConfig
2593
+ description?: string
2594
+ staged: boolean
2595
+ }): Promise<{ committed: true; state: TeamState }> {
2596
+ // Tool gateways can materialize omitted optional strings as blanks (#234).
2597
+ // Normalize only the tool-supplied roster; owner profile validation remains
2598
+ // strict, and required fields, unknown policies and route pairing still fail.
2599
+ const inlinePlan = input.inlinePlan === undefined ? undefined : {
2600
+ ...input.inlinePlan,
2601
+ members: input.inlinePlan.members.map(member => ({
2602
+ ...member,
2603
+ role: trimmedOptional(member.role),
2604
+ provider: trimmedOptional(member.provider),
2605
+ model: trimmedOptional(member.model),
2606
+ reasoning_effort: trimmedOptional(member.reasoning_effort),
2607
+ tool_policy: trimmedOptional(member.tool_policy),
2608
+ })),
2609
+ }
2610
+ const profile = resolveTeamProfile(inlinePlan === undefined ? input.config.profiles : { [input.profileName]: inlinePlan }, input.profileName, input.config.maxMembers)
2611
+ const selections: Awaited<ReturnType<typeof resolveMemberLlmSelection>>[] = []
2612
+ for (const template of profile.members) {
2613
+ selections.push(await resolveMemberLlmSelection(input.ctx, input.captain, {
2614
+ provider: template.provider,
2615
+ model: template.model,
2616
+ defaultModel: input.config.memberModel,
2617
+ defaultProvider: input.config.memberLlmProvider,
2618
+ reasoningEffort: template.reasoningEffort,
2619
+ fallback: template.fallback ?? profile.fallback ?? input.config.fallback,
2620
+ }, input.exec.signal))
2621
+ }
2622
+ await validateMemberLlmSelections(input.ctx, selections, input.exec.signal)
2623
+ const now = Date.now()
2624
+ const seedToActual = new Map(profile.tasks.map((template, index) => [template.id, `t${index + 1}`] as const))
2625
+ const draft: TeamState = {
2626
+ name: input.teamName,
2627
+ id: input.teamId,
2628
+ description: input.description,
2629
+ profile: {
2630
+ name: profile.name,
2631
+ ...profile.description === undefined ? {} : { description: profile.description },
2632
+ ...profile.protocol === undefined ? {} : { protocol: profile.protocol },
2633
+ ...profile.executionPrompt === undefined ? {} : { executionPrompt: profile.executionPrompt },
2634
+ ...profile.fallback === undefined ? {} : { fallback: profile.fallback },
2635
+ taskPlanning: profile.taskPlanning,
2636
+ ...profile.reviewPolicy === undefined ? {} : { reviewPolicy: profile.reviewPolicy },
2637
+ },
2638
+ ...profile.reviewPolicy === undefined ? {} : { reviewPolicy: profile.reviewPolicy },
2639
+ captainSessionId: input.captain.id,
2640
+ ...captainRouteOf(input.captain),
2641
+ createdAt: now,
2642
+ ...input.staged ? { phase: 'staged' as const, planReviewState: 'awaiting_review' as const } : {},
2643
+ members: profile.members.map((template, index) => {
2644
+ const selection = selections[index]!
2645
+ // A profile member selects a policy by id; an unknown id fails here,
2646
+ // before the team directory and any child session exist (#59).
2647
+ const toolSelection = memberToolSelection(input.config, input.captain, template.toolPolicy)
2648
+ return {
2649
+ id: '',
2650
+ name: template.name,
2651
+ role: template.role,
2652
+ provider: selection.provider,
2653
+ model: selection.model,
2654
+ reasoningEffort: selection.reasoningEffort,
2655
+ executionPrompt: template.executionPrompt ?? profile.executionPrompt ?? input.config.executionPrompt,
2656
+ ...selection.fallback === undefined ? {} : { fallback: selection.fallback },
2657
+ ...toolSelection,
2658
+ joinedAt: now,
2659
+ status: 'idle' as const,
2660
+ }
2661
+ }),
2662
+ tasks: profile.tasks.map((template, index) => ({
2663
+ id: `t${index + 1}`,
2664
+ profileSeedId: template.id,
2665
+ subject: template.subject,
2666
+ description: template.description,
2667
+ status: 'pending' as const,
2668
+ assignee: template.assignee,
2669
+ dependencies: template.dependencies.map((dependency) => seedToActual.get(dependency) ?? dependency),
2670
+ attempt: 0,
2671
+ createdAt: now,
2672
+ updatedAt: now,
2673
+ })),
2674
+ taskSeq: profile.tasks.length,
2675
+ }
2676
+ // Roster creation is durable planning only. The scheduler starts each
2677
+ // member with its first actual task once its dependencies are satisfied.
2678
+ if (input.inlinePlan !== undefined) delete draft.profile
2679
+ await createTeamDir(input.stateRoot, draft)
2680
+ return { committed: true, state: draft }
2681
+ }
2682
+
2683
+ function parseFindings(value: unknown): ReviewFinding[] | undefined {
2684
+ if (value === undefined) return undefined
2685
+ if (!Array.isArray(value)) throw new Error('findings must be an array')
2686
+ return value.map((item, index) => {
2687
+ if (typeof item !== 'object' || item === null || Array.isArray(item)) {
2688
+ throw new Error(`findings[${index}] must be an object`)
2689
+ }
2690
+ const raw = item as Record<string, unknown>
2691
+ if (typeof raw['id'] !== 'string' || raw['id'].trim() === '') throw new Error(`findings[${index}].id is required`)
2692
+ if (raw['severity'] !== 'low' && raw['severity'] !== 'medium' && raw['severity'] !== 'high' && raw['severity'] !== 'blocker') {
2693
+ throw new Error(`findings[${index}].severity is invalid`)
2694
+ }
2695
+ if (typeof raw['problem'] !== 'string' || raw['problem'].trim() === '') throw new Error(`findings[${index}].problem is required`)
2696
+ if (typeof raw['requiredFix'] !== 'string' || raw['requiredFix'].trim() === '') throw new Error(`findings[${index}].requiredFix is required`)
2697
+ return {
2698
+ id: raw['id'].trim(),
2699
+ severity: raw['severity'],
2700
+ problem: raw['problem'],
2701
+ requiredFix: raw['requiredFix'],
2702
+ // A blank optional file must be omitted, not persisted: durable-state
2703
+ // validation requires non-empty optional strings (issue #105 class).
2704
+ ...typeof raw['file'] === 'string' && raw['file'].trim() !== '' ? { file: raw['file'] } : {},
2705
+ // Only a contract-valid line is persisted. A model that materializes
2706
+ // "no line number" as -1 (or sends a non-integer) must not write a record
2707
+ // the durable validator rejects on the next read, which used to brick the
2708
+ // entire team (issue #188). The predicate is shared with
2709
+ // `isReviewFinding`, so the two sides cannot drift apart again.
2710
+ ...isValidFindingLine(raw['line']) ? { line: raw['line'] } : {},
2711
+ ...typeof raw['resolved'] === 'boolean' ? { resolved: raw['resolved'] } : {},
2712
+ }
2713
+ })
2714
+ }
2715
+
2716
+ function parseAcceptanceResults(value: unknown): AcceptanceResult[] | undefined {
2717
+ if (value === undefined) return undefined
2718
+ if (!Array.isArray(value)) throw new Error('acceptanceResults must be an array')
2719
+ return value.map((item, index) => {
2720
+ if (typeof item !== 'object' || item === null || Array.isArray(item)) {
2721
+ throw new Error(`acceptanceResults[${index}] must be an object`)
2722
+ }
2723
+ const raw = item as Record<string, unknown>
2724
+ if (typeof raw['criterion'] !== 'string' || raw['criterion'].trim() === '') {
2725
+ throw new Error(`acceptanceResults[${index}].criterion is required`)
2726
+ }
2727
+ if (raw['status'] !== 'passed' && raw['status'] !== 'failed') {
2728
+ throw new Error(`acceptanceResults[${index}].status must be passed or failed`)
2729
+ }
2730
+ return {
2731
+ criterion: raw['criterion'],
2732
+ status: raw['status'],
2733
+ ...typeof raw['evidence'] === 'string' ? { evidence: raw['evidence'] } : {},
2734
+ }
2735
+ })
2736
+ }
2737
+
2738
+ function parseCommandResults(value: unknown): CommandResult[] | undefined {
2739
+ if (value === undefined) return undefined
2740
+ if (!Array.isArray(value)) throw new Error('commandsRun must be an array')
2741
+ return value.map((item, index) => {
2742
+ if (typeof item !== 'object' || item === null || Array.isArray(item)) {
2743
+ throw new Error(`commandsRun[${index}] must be an object`)
2744
+ }
2745
+ const raw = item as Record<string, unknown>
2746
+ if (typeof raw['command'] !== 'string' || raw['command'].trim() === '') {
2747
+ throw new Error(`commandsRun[${index}].command is required`)
2748
+ }
2749
+ if (raw['status'] !== 'passed' && raw['status'] !== 'failed') {
2750
+ throw new Error(`commandsRun[${index}].status must be passed or failed`)
2751
+ }
2752
+ return {
2753
+ command: raw['command'],
2754
+ status: raw['status'],
2755
+ ...typeof raw['exitCode'] === 'number' ? { exitCode: raw['exitCode'] } : {},
2756
+ ...typeof raw['evidence'] === 'string' ? { evidence: raw['evidence'] } : {},
2757
+ }
2758
+ })
2759
+ }
2760
+
2761
+ export function applyQualityFollowUp(
2762
+ team: TeamState,
2763
+ closed: TeamTask,
2764
+ snapshotPaths?: (paths: readonly string[]) => ArtifactSnapshot,
2765
+ pathExists?: (path: string) => boolean,
2766
+ ): { created: TeamTask[]; escalated: boolean; reason?: string; excludedFindings?: string[] } {
2767
+ const planned = planQualityFollowUp(team, closed, pathExists === undefined ? {} : { pathExists })
2768
+ if (planned.escalated === true) team.escalated = true
2769
+ const created: TeamTask[] = []
2770
+ const existing = [...team.tasks]
2771
+ const now = Date.now()
2772
+ const idBySubject = new Map<string, string>()
2773
+ for (const draft of planned.created) {
2774
+ team.taskSeq += 1
2775
+ const id = `t${team.taskSeq}`
2776
+ if (draft.id !== undefined) idBySubject.set(draft.id, id)
2777
+ if (draft.subject !== undefined) idBySubject.set(draft.subject, id)
2778
+ const dependencies = (draft.dependencies ?? []).map((dependency) => {
2779
+ if (team.tasks.some((item) => item.id === dependency)) return dependency
2780
+ return idBySubject.get(dependency) ?? dependency
2781
+ })
2782
+ // Record the workspace the generated work order was derived from, so a
2783
+ // later round that changes a cited file can mark it stale instead of
2784
+ // letting a member read a frozen snapshot as authoritative (issue #174).
2785
+ const contractSnapshot = draft.contractPaths === undefined || draft.contractPaths.length === 0 || snapshotPaths === undefined
2786
+ ? undefined
2787
+ : snapshotPaths(draft.contractPaths)
2788
+ const next: TeamTask = {
2789
+ id,
2790
+ subject: draft.subject ?? `${draft.kind}-round-${draft.round ?? 1}`,
2791
+ status: 'pending',
2792
+ assignee: draft.assignee,
2793
+ dependencies,
2794
+ attempt: 0,
2795
+ createdAt: now,
2796
+ updatedAt: now,
2797
+ kind: draft.kind,
2798
+ ...draft.description === undefined ? {} : { description: draft.description },
2799
+ ...draft.round === undefined ? {} : { round: draft.round },
2800
+ ...draft.objective === undefined ? {} : { objective: draft.objective },
2801
+ ...draft.inScope === undefined ? {} : { inScope: draft.inScope },
2802
+ ...draft.outOfScope === undefined ? {} : { outOfScope: draft.outOfScope },
2803
+ ...draft.acceptance === undefined ? {} : { acceptance: draft.acceptance },
2804
+ ...draft.verify === undefined ? {} : { verify: draft.verify },
2805
+ ...draft.sourceTaskId === undefined ? {} : { sourceTaskId: draft.sourceTaskId },
2806
+ ...draft.sourceFindingIds === undefined ? {} : { sourceFindingIds: draft.sourceFindingIds },
2807
+ ...draft.findingSourceTaskIds === undefined ? {} : { findingSourceTaskIds: draft.findingSourceTaskIds },
2808
+ ...draft.reviewedTaskId === undefined ? {} : { reviewedTaskId: idBySubject.get(draft.reviewedTaskId) ?? draft.reviewedTaskId },
2809
+ ...contractSnapshot === undefined ? {} : { contractSnapshot },
2810
+ }
2811
+ team.tasks.push(next)
2812
+ created.push(next)
2813
+ }
2814
+ // A staged full delivery plan may already contain downstream integration
2815
+ // work that points at the first requirements/review gate. When that gate
2816
+ // opens an automatic revision loop, move only still-pending downstream
2817
+ // edges to the new terminal gate so the approved plan can continue after
2818
+ // the repair instead of waiting forever on an intentionally failed task.
2819
+ const replacement = created.at(-1)
2820
+ if (replacement !== undefined) {
2821
+ for (const task of existing) {
2822
+ if (task.status !== 'pending' || !task.dependencies.includes(closed.id)) continue
2823
+ task.dependencies = task.dependencies.map((dependency) => (
2824
+ dependency === closed.id ? replacement.id : dependency
2825
+ ))
2826
+ task.updatedAt = now
2827
+ }
2828
+ }
2829
+ return {
2830
+ created,
2831
+ escalated: planned.escalated === true,
2832
+ ...planned.reason === undefined ? {} : { reason: planned.reason },
2833
+ ...planned.excludedFindings === undefined ? {} : { excludedFindings: planned.excludedFindings },
2834
+ }
2835
+ }
2836
+
2837
+ /** Build the `memberRuntime` config handed to member helpers. */
2838
+ function memberRuntime(config: ToolsConfig): MemberRuntimeConfig {
2839
+ return {
2840
+ provider: config.memberProvider,
2841
+ maxDepth: config.memberMaxDepth,
2842
+ executionPrompt: config.executionPrompt,
2843
+ fallback: config.fallback,
2844
+ }
2845
+ }
2846
+
2847
+ /** Render the status snapshot as compact text for the model. */
2848
+ function renderStatus(value: JsonValue): string {
2849
+ const team = value as {
2850
+ team_name: string
2851
+ description?: string
2852
+ profile?: { name: string; protocol?: string; task_planning?: string }
2853
+ viewer: string
2854
+ members: {
2855
+ name: string
2856
+ role: string
2857
+ provider: string
2858
+ model: string
2859
+ reasoning_effort: string
2860
+ tool_policy: string
2861
+ status: string
2862
+ activity: string
2863
+ spawn_error?: string
2864
+ }[]
2865
+ tasks: { id: string; subject: string; status: string; assignee: string; dependencies: string[]; attempt: number; attempt_id: string; reassigning: boolean; seed_id?: string; output?: string; kind?: string; round?: number; verdict?: string; findings_open?: number; supplemental_evidence?: string; fixes?: string }[]
2866
+ captain_inbox: { from: string; content: string }[]
2867
+ member_inbox?: { from: string; content: string }[]
2868
+ member_inboxes: Record<string, { count: number; latest: string }>
2869
+ mailbox_warnings: string[]
2870
+ mailbox_warning_count: number
2871
+ halted?: boolean
2872
+ escalated?: boolean
2873
+ loop_state?: string
2874
+ loop_summary?: string
2875
+ deliverable?: boolean
2876
+ coverage?: { goal_item: string; status: string; task_ids: string[] }[]
2877
+ delivery?: { ok: boolean; blockers: string[]; warnings?: string[] }
2878
+ warnings?: string[]
2879
+ }
2880
+ const flags = [
2881
+ team.halted ? 'halted' : undefined,
2882
+ team.escalated ? 'escalated' : undefined,
2883
+ team.deliverable ? 'deliverable' : undefined,
2884
+ team.loop_state && team.loop_state !== 'running' && team.loop_state !== 'halted' && team.loop_state !== 'escalated'
2885
+ ? team.loop_state
2886
+ : undefined,
2887
+ ].filter((item): item is string => item !== undefined)
2888
+ const lines: string[] = [
2889
+ `Team "${team.team_name}"${team.description ? ` — ${team.description}` : ''}${flags.length > 0 ? ` [${flags.join(', ')}]` : ''}`,
2890
+ ...team.profile === undefined ? [] : [`Profile: ${team.profile.name}${team.profile.task_planning ? ` [${team.profile.task_planning}]` : ''}${team.profile.protocol ? ` — ${team.profile.protocol}` : ''}`],
2891
+ ...team.loop_summary ? [`Loop: ${team.loop_state ?? ''} — ${team.loop_summary}`.replace(/^Loop: — /u, 'Loop: ')] : [],
2892
+ `Viewing as: ${team.viewer}`,
2893
+ `Members (${team.members.length}):`,
2894
+ ...team.members.map((member) => {
2895
+ const route = member.provider && member.model ? ` · ${member.provider}/${member.model}` : ''
2896
+ const effort = member.reasoning_effort ? ` · reasoning ${member.reasoning_effort}` : ''
2897
+ const failure = member.spawn_error === undefined ? '' : `\n start failed: ${member.spawn_error.slice(0, 400)}`
2898
+ const policy = member.tool_policy ? ` · policy ${member.tool_policy}` : ''
2899
+ return ` - ${member.name} [${member.role}] ${member.status}/${member.activity}${route}${effort}${policy}${failure}`
2900
+ }),
2901
+ `Tasks (${team.tasks.length}):`,
2902
+ ...team.tasks.map((task) => {
2903
+ const deps = task.dependencies.length > 0 ? ` (deps: ${task.dependencies.join(',')})` : ''
2904
+ const output = task.output !== undefined ? `\n output: ${task.output.slice(0, 300)}` : ''
2905
+ const evidence = task.supplemental_evidence ? `\n Supplemental observations (original verdict unchanged): ${task.supplemental_evidence}` : ''
2906
+ const handoff = task.reassigning ? ' (reassigning)' : ''
2907
+ const seed = task.seed_id === undefined || task.seed_id === '' ? '' : ` seed ${task.seed_id}`
2908
+ const kind = task.kind ? ` ${task.kind}` : ''
2909
+ const round = task.round === undefined ? '' : ` r${task.round}`
2910
+ const verdict = task.verdict === undefined ? '' : ` verdict ${task.verdict}`
2911
+ const fixes = task.fixes === undefined ? '' : ` fixes ${task.fixes}`
2912
+ return ` - ${task.id} [${task.status}]${kind}${round}${verdict}${fixes} attempt ${task.attempt}${handoff}${seed} ${task.subject} → ${task.assignee || 'unassigned'}${deps}${output}${evidence}`
2913
+ }),
2914
+ ...team.coverage === undefined || team.coverage.length === 0 ? [] : [
2915
+ 'Coverage:',
2916
+ ...team.coverage.map((row) => ` - ${row.goal_item}: ${row.status} (${row.task_ids.join(',') || 'none'})`),
2917
+ ],
2918
+ ...team.delivery === undefined ? [] : [
2919
+ `Delivery: ${team.delivery.ok ? 'ok' : `blocked (${team.delivery.blockers.join('; ')})`}`,
2920
+ ],
2921
+ ...(team.delivery?.warnings ?? []).length === 0 ? [] : [
2922
+ 'Gate warnings (delivery is not blocked, but these recorded verdicts or generated work orders no longer describe the current bytes):',
2923
+ ...(team.delivery?.warnings ?? []).map((warning) => ` - ${warning}`),
2924
+ ],
2925
+ `Captain inbox (${team.captain_inbox.length}):`,
2926
+ ...team.captain_inbox.map((message) => ` - [${message.from}] ${message.content}`),
2927
+ ...(team.member_inbox ?? []).map(message => ` - [${message.from}] ${message.content}`),
2928
+ ]
2929
+ for (const [name, inbox] of Object.entries(team.member_inboxes)) {
2930
+ lines.push(`Member inbox ${name} (${inbox.count}): latest — ${inbox.latest.slice(0, 120)}`)
2931
+ }
2932
+ if (team.mailbox_warning_count > 0) {
2933
+ lines.push(
2934
+ `Mailbox warnings (${team.mailbox_warning_count}; malformed lines were skipped; showing up to 10):`,
2935
+ ...team.mailbox_warnings.map((warning) => ` - ${warning}`),
2936
+ )
2937
+ }
2938
+ return lines.join('\n')
2939
+ }