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