返回 CodeWhale
members.js
根目录 / crates / plugins / assets / agent-teams / lib / members.js
1 /**
2 * Member subagent lifecycle: spawn a continuable child per member, deliver
3 * task turns and step-boundary messages, and observe its activity.
4 *
5 * Members are durable continuable subagents of the captain, so a member keeps
6 * its conversation across turns and across harness restarts: the captain
7 * queues its next turn through {@link deliverToMember}, it works through its turn
8 * (updating team state through the `agent_teams_*` tools), and becomes idle
9 * again. Its final assistant message is not readable programmatically, so the
10 * member persists its report into the captain's mailbox and the task records,
11 * which the captain reads through `agent_teams_status`.
12 * @module dsh-agent-teams/members
13 */
14 import { installModelSelection } from '@deepseek-ai/dsh-agent';
15 // Declaration merge only: makes ctx.subagents visible.
16 import { foldSubagentDescriptor } from '@deepseek-ai/dsh-subagent';
17 import { createUserMessage, LlmError, ReasoningEffortId } from '@deepseek-ai/dsh-llm';
18 import { randomUUID } from 'node:crypto';
19 import { join } from 'node:path';
20 import { agentTeamsSource, observedSessionFormatVersion, outputLimitTurn, guardSubagentCreation, startMember, usesManagedActivations, guardSubagentDelivery, installContinuableMemberSetup, memberToolFilter, queueMemberPrompt, restrictableToolNames, startMemberWithLenientFilter, steerMemberPrompt, sessionOwnEvents } from "./harness-compat.js";
21 import { markMailboxDelivered, appendMailbox, CAPTAIN_KEY, createMessage, readRetiredMemberIds, readTeamSync, readTeam, releaseMailboxDelivery, withTeamLock, writeTeam } from "./state.js";
22 import { mailboxPrompt } from "./mailbox.js";
23 import { nearestLiveLead } from "./lineage.js";
24 import { appendTeamEvent, captainSessionOf } from "./events.js";
25 import { TERMINAL_TASK_STATUSES } from "./types.js";
26 /** Persona snapshot of a profile protocol; the full text lives on team.json. */
27 export const PERSONA_PROTOCOL_MAX_CHARS = 400;
28 /**
29 * Restore the SessionId brand on a value that round-tripped through the
30 * durable team file. The brand is erased by JSON serialization; the value
31 * originated from `startContinuable`/`agent.id`, so this cast is the boundary
32 * restoration, not a new assertion.
33 */
34 function brandedSessionId(value) {
35 return value;
36 }
37 /**
38 * Compose one member route from request, plugin configuration and the captain
39 * session, without performing any I/O. This is the single place where the
40 * precedence between the captain's route and a configured member default is
41 * decided, so a configured model can never be silently paired with whichever
42 * provider the captain happens to sit on (issue #189).
43 *
44 * Precedence: explicit request > plugin configuration > captain session. Model
45 * ids are used verbatim: a `/` inside a model id is part of that id and is
46 * never treated as a provider separator.
47 *
48 * `derivedProvider` is true only for a bare configured `memberModel` with no
49 * provider anywhere, which is the one shape whose owner must come from the
50 * provider catalogs.
51 * @param request - the captain-supplied and plugin-configured route halves.
52 * @param captain - the captain's current session route.
53 * @returns the composed route, or `undefined` when a half cannot be determined.
54 */
55 export function composeMemberRoute(request, captain) {
56 const explicitProvider = request.provider?.trim();
57 const explicitModel = request.model?.trim();
58 const configuredModel = request.defaultModel?.trim();
59 const configuredProvider = request.defaultProvider?.trim();
60 if (explicitProvider !== undefined && explicitModel === undefined)
61 return undefined;
62 if (explicitProvider === '' || explicitModel === '' || configuredModel === '' || configuredProvider === '')
63 return undefined;
64 const providerValue = explicitProvider ?? configuredProvider ?? captain.provider;
65 const providerSource = explicitProvider !== undefined ? 'request' : configuredProvider !== undefined ? 'config' : 'captain';
66 const modelValue = explicitModel ?? configuredModel ?? captain.model;
67 const modelSource = explicitModel !== undefined ? 'request' : configuredModel !== undefined ? 'config' : 'captain';
68 return {
69 provider: { value: providerValue, source: providerSource },
70 model: { value: modelValue, source: modelSource },
71 // A named provider is authoritative, and a named model keeps the route the
72 // caller asked for. Only a model-only plugin default is allowed to have its
73 // owner discovered from the catalogs.
74 derivedProvider: providerSource === 'captain' && modelSource === 'config',
75 };
76 }
77 /**
78 * Validate a resolved roster against every provider catalog before any child
79 * session is created. Catalogs are advisory when empty (some adapters accept
80 * dynamic model ids), but a non-empty catalog is authoritative enough to
81 * catch a typo that would otherwise boot a child and fail on its first turn.
82 */
83 export async function validateMemberLlmSelections(ctx, selections, signal) {
84 const catalogs = new Map();
85 for (const selection of selections) {
86 if (signal?.aborted === true)
87 throw signal.reason ?? new Error('member model validation was cancelled');
88 let catalog = catalogs.get(selection.provider);
89 if (catalog === undefined) {
90 catalog = await ctx.llm.listModels(selection.provider);
91 catalogs.set(selection.provider, catalog);
92 }
93 if (catalog.length === 0 || catalog.some((model) => model.id === selection.model))
94 continue;
95 const available = catalog.slice(0, 8).map((model) => model.id).join(', ');
96 throw new Error(`unknown member model "${selection.model}" for provider "${selection.provider}"`
97 + `${available === '' ? '' : ` (available: ${available}${catalog.length > 8 ? ', …' : ''})`}`);
98 }
99 }
100 const MEMBER_LABEL_PREFIX = 'agent-teams:';
101 const FALLBACK_FAILURE_CODES = new Set([
102 'QUOTA', 'RATE_LIMIT', 'AUTH', 'MISSING_CREDENTIAL', 'NO_ADAPTER',
103 // The account-backed DeepSeek adapter remaps equivalent provider failures.
104 'ACCOUNT_QUOTA', 'ACCOUNT_TOKEN_INVALID', 'ACCOUNT_SIGN_IN_REQUIRED',
105 ]);
106 export function isFallbackFailureCode(code) {
107 return FALLBACK_FAILURE_CODES.has(code);
108 }
109 /** Pure state transition used by the request-error handler and TDD tests. */
110 export function selectFallbackRoute(current, fallback, failureCode, alreadySwitched) {
111 if (alreadySwitched || fallback === undefined || !isFallbackFailureCode(failureCode)) {
112 return { retry: false, switched: alreadySwitched, selection: current };
113 }
114 return { retry: true, switched: true, selection: fallback };
115 }
116 /** Deliver a durable member report to the live captain at its next model step. */
117 export function steerCaptainReport(captain, from, content, receipt) {
118 try {
119 captain.steer(createUserMessage({
120 content: [{ type: 'text', text: receipt ?? `AgentTeams message from member ${from}:\n\n${content}` }],
121 source: agentTeamsSource({ kind: 'agent-teams' }, observedSessionFormatVersion(captain)),
122 }));
123 return true;
124 }
125 catch {
126 return false;
127 }
128 }
129 /**
130 * Classify a final member turn failure against the durable record. Pure, so the
131 * policy is testable without a lock or a Harness.
132 *
133 * A failure may only mutate the attempt the plugin actually observed. When that
134 * attempt is gone — the member moved on to newer work, the task was
135 * reassigned to a newer attempt, or the member generation was replaced — the
136 * late error carries no authority and stays silent. When the failure belongs to
137 * the current generation but its work already settled, the task and member are
138 * left exactly as they are and only a durable captain note is added: otherwise
139 * an operator cannot tell a clean run from one whose member's last turn died
140 * (429, auth failure, crash) after the delivery landed (issue #205).
141 * @param observed - the live member/task capability captured at the error event.
142 * @param current - the current durable member record and open task, if any.
143 * @returns the disposition for this failure.
144 */
145 export function classifyMemberFailure(observed, current) {
146 const member = current.member;
147 // Only the exact member generation observed at the error event may report it.
148 // A replaced generation (same name, new session id) or a member record that is
149 // gone cannot be failed by that child's late error.
150 if (member === undefined || member.id !== observed.memberId)
151 return 'ignored';
152 const task = current.task;
153 if (task === undefined) {
154 if (observed.openAttemptOnly === true)
155 return 'ignored';
156 // No open attempt is owned by this generation any more, so nothing here may
157 // be mutated — but the failure itself must still be recorded. `working` is
158 // NOT evidence of newer work: `syncMemberStatus` writes it as soon as the
159 // turn runs, while a task completed earlier in that same turn leaves no open
160 // attempt behind (the reporter's run A). Only a *concrete* superseded open
161 // attempt — the branch below — or a replaced generation may stay silent.
162 return 'noted_settled';
163 }
164 if (task.id !== observed.task?.id || task.attemptId !== observed.task?.attemptId
165 || task.attempt !== observed.task?.attempt)
166 return 'ignored';
167 return 'failed_attempt';
168 }
169 /**
170 * The surviving durable record of the capability observed at the error event,
171 * or `undefined` when there is nothing honest to say about it.
172 *
173 * A task is only described as *settled* when its durable status is terminal
174 * (`completed`/`failed`/`cancelled`). A non-terminal record — for example a task
175 * that was claimed and then unclaimed or reassigned while the error was queued —
176 * must fall back to the plain "no open attempt" wording instead of implying a
177 * delivery landed.
178 */
179 export function settledTaskRecord(observed, tasks) {
180 if (observed === undefined)
181 return undefined;
182 const record = tasks.find(candidate => candidate.id === observed.id);
183 if (record === undefined)
184 return undefined;
185 return TERMINAL_TASK_STATUSES.includes(record.status) ? record : undefined;
186 }
187 /**
188 * Build the durable captain note for one recorded failure. Pure, so the wording
189 * boundaries are testable without a lock or a Harness.
190 * @param memberName - the member that failed.
191 * @param summary - the failure message plus its code.
192 * @param disposition - what the failure was allowed to do.
193 * @param task - the open attempt that was failed, when there was one.
194 * @param settledRecord - the terminal record of the observed task, when it exists.
195 * @returns the exact message the captain will read.
196 */
197 export function memberFailureMessage(memberName, summary, disposition, task, settledRecord) {
198 const head = `Member "${memberName}" hit an unrecoverable turn failure: ${summary}.`;
199 if (disposition === 'failed_attempt' && task !== undefined) {
200 return `${head} Task ${task.id} ("${task.subject}") was marked failed; reassign it or retry when ready.`;
201 }
202 if (settledRecord === undefined) {
203 return disposition === 'noted_settled'
204 ? `${head} No open attempt was owned; no task state was changed.`
205 : `${head} No open attempt was owned.`;
206 }
207 // Only a completed record supports a claim about delivered work. A failed or
208 // cancelled record is described by its actual closed state.
209 return settledRecord.status === 'completed'
210 ? `${head} Task ${settledRecord.id} ("${settledRecord.subject}") had already completed; its state and output were left unchanged. This member's last turn died after its work landed.`
211 : `${head} Task ${settledRecord.id} ("${settledRecord.subject}") was already closed as ${settledRecord.status}; its record was left unchanged. This member's last turn died after that task had closed.`;
212 }
213 /** Record a final turn failure, never an intermediate request retry. */
214 export async function failMemberOpenAttempt(ctx, stateRoot, teamId, memberName, failure, fallbackSession, observed) {
215 const summary = `${failure.message} (code ${failure.code})`;
216 const lockKey = `team:${stateRoot}:${teamId}`;
217 const prepared = await withTeamLock(lockKey, async () => {
218 const team = await readTeam(stateRoot, teamId);
219 if (team === undefined || team.halted === true || team.captainSessionId !== observed.captainSessionId)
220 return;
221 const member = team.members.find(candidate => candidate.name === memberName && candidate.id === observed.memberId);
222 const task = team.tasks.find(candidate => candidate.assignee === memberName
223 && (candidate.status === 'claimed' || candidate.status === 'in_progress'));
224 // A reassign, completion, or recreated member may win the lock while the
225 // final error is queued. Only the capability observed at that event may fail.
226 const disposition = classifyMemberFailure(observed, {
227 member,
228 task,
229 observedRecord: observed.task === undefined
230 ? undefined
231 : team.tasks.find(candidate => candidate.id === observed.task.id),
232 });
233 if (disposition === 'ignored')
234 return;
235 if (disposition === 'failed_attempt' && task !== undefined) {
236 // Historical records may lack a capability id. Bind this failure report
237 // to the terminal attempt so a later retry invalidates unread mail.
238 if (observed.openAttemptOnly === true)
239 task.attemptId ??= randomUUID();
240 task.status = 'failed';
241 task.output = summary;
242 task.updatedAt = Date.now();
243 }
244 if (member !== undefined && ctx.agents.get(brandedSessionId(member.id))?.status !== 'running')
245 member.status = 'idle';
246 // Only a terminal record of the observed task may be described, and only a
247 // completed one supports a claim about delivered work. Anything else — a
248 // never-assigned member, or a record left pending/claimed while the error was
249 // queued — gets the plain "no open attempt" wording.
250 const settledRecord = disposition === 'noted_settled'
251 ? settledTaskRecord(observed.task, team.tasks)
252 : undefined;
253 const message = {
254 ...createMessage(memberName, CAPTAIN_KEY, memberFailureMessage(memberName, summary, disposition, task, settledRecord)),
255 ...observed.openAttemptOnly === true && task?.attemptId !== undefined
256 ? { sourceTaskId: task.id, sourceAttemptId: task.attemptId, sourceTaskStatus: 'failed' }
257 : {},
258 deliveryClaimedAt: Date.now(),
259 };
260 if (disposition === 'failed_attempt')
261 await writeTeam(stateRoot, team);
262 await appendMailbox(stateRoot, team.id, CAPTAIN_KEY, message);
263 if (disposition === 'failed_attempt' && task !== undefined) {
264 appendTeamEvent(ctx, captainSessionOf(ctx, team.captainSessionId, fallbackSession), 'agent-teams/task-updated', {
265 teamId, taskId: task.id, status: task.status, assignee: memberName, output: task.output,
266 });
267 }
268 appendTeamEvent(ctx, captainSessionOf(ctx, team.captainSessionId, fallbackSession), 'agent-teams/message-sent', {
269 teamId: team.id,
270 messageId: message.id,
271 from: memberName,
272 to: CAPTAIN_KEY,
273 content: message.content,
274 ts: message.ts,
275 });
276 return { captainSessionId: team.captainSessionId, message };
277 });
278 if (prepared === undefined)
279 return false;
280 // Use the same lease/acknowledgment contract as send_message, outside the
281 // team lock: steering can synchronously start another agent turn.
282 const captain = nearestLiveLead(ctx, { captainSessionId: prepared.captainSessionId });
283 const delivered = captain !== undefined && steerCaptainReport(captain, memberName, prepared.message.content, mailboxPrompt(teamId, CAPTAIN_KEY, [prepared.message]));
284 await withTeamLock(lockKey, () => delivered
285 ? markMailboxDelivered(stateRoot, teamId, CAPTAIN_KEY, [prepared.message.id])
286 : releaseMailboxDelivery(stateRoot, teamId, CAPTAIN_KEY, [prepared.message.id]));
287 return true;
288 }
289 async function commitFallbackRoute(stateRoot, teamId, memberName, child, fallback, signal, ctx, activate) {
290 return withTeamLock(`team:${stateRoot}:${teamId}`, async () => {
291 const team = await readTeam(stateRoot, teamId);
292 if (signal.aborted || team === undefined || team.captainSessionId !== child.session.header.parentSession || team.halted === true)
293 return false;
294 const member = team.members.find(candidate => candidate.name === memberName && candidate.id === child.id);
295 if (member === undefined || member.status === 'removed' || member.stopping === true)
296 return false;
297 member.activeProvider = fallback.provider;
298 member.activeModel = fallback.model;
299 member.fallbackActive = true;
300 let committed = false;
301 const onCommit = () => {
302 committed = true;
303 activate();
304 };
305 try {
306 await writeTeam(stateRoot, team, { signal, onCommit });
307 }
308 catch (error) {
309 if (committed)
310 throw error;
311 ctx.logger.warn(`agent-teams: failed to persist fallback route: ${String(error)}`);
312 if (!signal.aborted)
313 onCommit();
314 }
315 return committed;
316 });
317 }
318 function pendingSelectionKey(parentSessionId, label) {
319 return `${parentSessionId}\u0000${label}`;
320 }
321 function selectionFromMember(member) {
322 if (member?.provider === undefined || member.model === undefined)
323 return undefined;
324 const provider = (member.activeProvider ?? member.provider).trim();
325 const model = (member.activeModel ?? member.model).trim();
326 if (provider === '' || model === '')
327 return undefined;
328 // Effort ids belong to the original model. After a fallback, its own
329 // provider default remains authoritative, including after cold recovery.
330 const reasoningEffort = member.fallbackActive === true ? undefined : member.reasoningEffort?.trim();
331 return {
332 provider,
333 model,
334 ...reasoningEffort === undefined || reasoningEffort === '' ? {} : { reasoningEffort },
335 ...member.fallback === undefined || member.fallbackActive === true ? {} : { fallback: member.fallback },
336 };
337 }
338 function modelSelection(selection) {
339 return {
340 provider: selection.provider,
341 model: selection.model,
342 ...selection.reasoningEffort === undefined
343 ? {}
344 : { reasoningEffort: ReasoningEffortId(selection.reasoningEffort) },
345 };
346 }
347 /**
348 * Resolve one member's complete model selection. Ordinary members snapshot the
349 * captain's current request route and reasoning effort. When provider or model
350 * changes, effort is intentionally omitted so the target model materializes
351 * its own default instead of receiving an adapter-owned id from another route.
352 * An explicit effort overrides either policy; the sentinel "default" also
353 * selects the target model's default. The final effort is validated against
354 * the target model before a child is created.
355 *
356 * A configured `memberModel` is a route preference, not a blind model-id
357 * override: it is paired with `memberLlmProvider` (or its own `provider/model`
358 * form) when configured, and when only a bare model id is configured it is
359 * adopted by the captain's provider only if that provider actually advertises
360 * it. Otherwise the catalog decides: exactly one advertising provider wins,
361 * none or several produce an actionable error listing them (issue #189). A
362 * provider the caller *named* — explicitly or via configuration — is never
363 * silently switched away from.
364 */
365 export async function resolveMemberLlmSelection(ctx, captain, request, signal) {
366 const explicitProvider = request.provider?.trim();
367 const explicitModel = request.model?.trim();
368 const defaultModel = request.defaultModel?.trim();
369 const defaultProvider = request.defaultProvider?.trim();
370 const explicitEffort = request.reasoningEffort?.trim();
371 const fallback = request.fallback;
372 if (request.provider !== undefined && explicitProvider === '') {
373 throw new Error('member LLM provider must not be empty');
374 }
375 if (request.model !== undefined && explicitModel === '') {
376 throw new Error('member model must not be empty');
377 }
378 if (request.defaultModel !== undefined && defaultModel === '') {
379 throw new Error('configured memberModel must not be empty');
380 }
381 if (request.defaultProvider !== undefined && defaultProvider === '') {
382 throw new Error('configured memberLlmProvider must not be empty');
383 }
384 if (request.reasoningEffort !== undefined && explicitEffort === '') {
385 throw new Error('member reasoning effort must not be empty');
386 }
387 // An explicit provider needs an explicit model; `memberModel` is used
388 // verbatim, so a `/` inside a model id is never a provider separator.
389 if (explicitProvider !== undefined && explicitModel === undefined) {
390 throw new Error('an explicit member LLM provider requires an explicit member model');
391 }
392 const current = captain.session.requestHeader()?.config;
393 const currentProvider = current?.provider ?? captain.options.provider;
394 const currentModel = current?.model ?? captain.options.model;
395 if (currentProvider === undefined || currentModel === undefined) {
396 throw new Error('cannot resolve the member LLM route from the current captain session');
397 }
398 // The plugin-wide default only applies where the caller did not choose a
399 // model. `request.defaultModel` belongs to the plugin configuration; a
400 // request-level `model` is a user choice and is never re-routed.
401 const composed = composeMemberRoute({
402 provider: request.provider,
403 model: request.model,
404 defaultModel: defaultModel,
405 defaultProvider: defaultProvider,
406 }, { provider: currentProvider, model: currentModel });
407 if (composed === undefined) {
408 throw new Error('cannot resolve the member LLM route from the current captain session');
409 }
410 // Only a bare configured `memberModel` may have its owner resolved from the
411 // catalogs. A named provider (explicit or configured) is authoritative — a
412 // model it does not advertise is a hard error, never a silent switch — and a
413 // model the caller named keeps that caller's route.
414 const provider = composed.derivedProvider
415 ? await resolveMemberModelOwner(ctx, currentProvider, composed.model.value, signal)
416 : composed.provider.value;
417 // Effort ids belong to one exact provider/model capability. Preserve the
418 // captain's effort only on the same route; a changed route must resolve its
419 // own default. Explicit effort still wins, while "default" forces that
420 // target-default behavior even when the route did not change.
421 const model = composed.model.value;
422 const sameRoute = provider === currentProvider && model === currentModel;
423 const reasoningEffort = explicitEffort === undefined
424 ? sameRoute
425 ? current?.reasoningEffort
426 : undefined
427 : explicitEffort === 'default'
428 ? undefined
429 : ReasoningEffortId(explicitEffort);
430 let resolved;
431 try {
432 resolved = await ctx.llm.resolveCallConfig({
433 provider,
434 model,
435 ...reasoningEffort === undefined
436 ? {}
437 : { reasoningEffort },
438 }, signal);
439 }
440 catch (error) {
441 throw new Error(describeMemberRouteFailure(provider, model, error), { cause: error });
442 }
443 return {
444 provider: resolved.provider,
445 model: resolved.model,
446 ...resolved.reasoningEffort === undefined
447 ? {}
448 : { reasoningEffort: String(resolved.reasoningEffort) },
449 ...fallback === undefined ? {} : { fallback },
450 };
451 }
452 /**
453 * Pick the provider that owns a configured bare model id when the captain's
454 * provider does not advertise it. Only an unambiguous owner is accepted: zero
455 * advertising providers and several advertising providers both fail with the
456 * catalog, because guessing between real providers changes which account and
457 * quota the user's members run on (issue #189).
458 * @returns the resolved provider id.
459 */
460 async function resolveMemberModelOwner(ctx, captainProvider, model, signal) {
461 // Enumeration is optional: an adapter that cannot list its providers must not
462 // turn a resolvable route into a crash. Such a route keeps the captain's
463 // provider and lets the durable adapter report the real failure.
464 const listProviders = ctx.llm.listProviders;
465 if (typeof listProviders !== 'function')
466 return captainProvider;
467 const owners = [];
468 for (const provider of listProviders.call(ctx.llm)) {
469 if (signal?.aborted === true)
470 throw signal.reason ?? new Error('member model resolution was cancelled');
471 const catalog = await ctx.llm.listModels(provider.id);
472 if (catalog.length === 0)
473 continue;
474 if (catalog.some((candidate) => candidate.id === model))
475 owners.push(provider.id);
476 }
477 if (owners.includes(captainProvider))
478 return captainProvider;
479 if (owners.length === 1)
480 return owners[0];
481 if (owners.length === 0) {
482 throw new Error(`no configured provider advertises the member model "${model}".`
483 + ` The captain's provider "${captainProvider}" does not serve it either.`
484 + ' Name the owner explicitly with memberLlmProvider, or pass provider + model to agent_teams_add_member.');
485 }
486 throw new Error(`the member model "${model}" is advertised by ${owners.length} providers (${owners.join(', ')}),`
487 + ' so its owner is ambiguous. Name it explicitly with memberLlmProvider, or pass provider + model to agent_teams_add_member.');
488 }
489 /** Turn a raw adapter failure into an actionable, route-naming error. */
490 function describeMemberRouteFailure(provider, model, error) {
491 const message = error instanceof Error ? error.message : String(error);
492 const code = typeof error === 'object' && error !== null && 'code' in error ? String(error.code) : '';
493 const hint = code === 'UNKNOWN_MODEL' || code === 'NO_ADAPTER' || code === 'INVALID_CONFIG'
494 ? ` The member route was composed from the captain's session and the plugin configuration;`
495 + ' set memberLlmProvider when the configured member model belongs to a'
496 + " different provider than the captain's session."
497 : '';
498 return `cannot use the member LLM route "${provider}/${model}": ${message}${code === '' ? '' : ` (code ${code})`}.${hint}`;
499 }
500 /**
501 * Install the member selection bridge for every fresh or cold-resumed
502 * continuable child. Fresh creation reads the pending in-memory selection;
503 * cold resume restores the same selection from the owning team's durable
504 * record. Legacy members without a complete saved route retain Harness's
505 * descriptor provider/model behavior.
506 */
507 export function installMemberSelectionRuntime(ctx, stateDir, onFailureSettled) {
508 const pending = new Map();
509 const pendingSetup = new Map();
510 installContinuableMemberSetup(ctx, (childCtx, child) => {
511 const descriptor = foldSubagentDescriptor(sessionOwnEvents(child.session));
512 if (descriptor?.mode !== 'continuable' || !descriptor.label.startsWith(MEMBER_LABEL_PREFIX)) {
513 return () => undefined;
514 }
515 const parentSessionId = child.session.header.parentSession;
516 if (parentSessionId === undefined)
517 return () => undefined;
518 const identity = descriptor.label.slice(MEMBER_LABEL_PREFIX.length);
519 const separator = identity.indexOf(':');
520 if (separator < 1 || separator === identity.length - 1)
521 return () => undefined;
522 const teamId = identity.slice(0, separator);
523 const memberName = identity.slice(separator + 1);
524 const workspace = child.session.header.cwd ?? process.cwd();
525 const stateRoot = join(workspace, stateDir);
526 const key = pendingSelectionKey(parentSessionId, descriptor.label);
527 // Internal settlement wakeups bypass the public delivery guard. Recheck
528 // exact durable membership on every proposed step, including cold resume.
529 const disposeAdmission = childCtx.on('agent/pre-step', async (payload, next) => {
530 if (payload.agent.id !== child.id)
531 return next();
532 const admitted = await withTeamLock(`team:${stateRoot}:${teamId}`, async () => {
533 const team = await readTeam(stateRoot, teamId);
534 return team?.captainSessionId === parentSessionId && team.phase !== 'staged' && team.halted !== true
535 && team.members.some(member => member.id === child.id && member.name === memberName && member.status !== 'removed' && member.stopping !== true)
536 && !team.tasks.some(task => task.reassigning === true && task.assignee === memberName);
537 });
538 if (!admitted)
539 return { kind: 'reject' };
540 return next();
541 });
542 // New activations no longer persist persona/toolFilter in host descriptors.
543 // Install them before the first request, and restore the exact saved values
544 // after a cold resume. Historical descriptors remain owned by Harness.
545 const savedTeam = pending.has(key) ? undefined : readTeamSync(stateRoot, teamId);
546 const savedMember = savedTeam?.captainSessionId === parentSessionId
547 ? savedTeam.members.find(member => member.id === child.id && member.name === memberName)
548 : undefined;
549 const setup = pendingSetup.get(key) ?? savedMember?.runtimeSetup;
550 if (usesManagedActivations(ctx.subagents) && savedMember !== undefined
551 && setup === undefined && descriptor.toolFilter === undefined) {
552 disposeAdmission();
553 throw new Error('agent-teams: saved member runtime setup is missing; refusing an unrestricted resume');
554 }
555 let disposeSetup = () => undefined;
556 if (usesManagedActivations(ctx.subagents) && setup !== undefined) {
557 try {
558 const stopFilter = childCtx.tools.restrict(setup.toolFilter);
559 try {
560 const stopPersona = childCtx.systemPrompt.section({
561 name: 'deployment:persona-prefix',
562 order: childCtx.systemPrompt.getSectionOrder('DEPLOYMENT_PERSONA_PREFIX'),
563 text: setup.persona,
564 });
565 disposeSetup = () => { stopPersona(); stopFilter(); };
566 }
567 catch (error) {
568 stopFilter();
569 throw error;
570 }
571 }
572 catch (error) {
573 disposeAdmission();
574 throw error;
575 }
576 }
577 const cleanupAdmission = () => { disposeSetup(); disposeAdmission(); };
578 let selection = pending.get(key);
579 if (selection === undefined) {
580 const team = readTeamSync(stateRoot, teamId);
581 if (team?.captainSessionId !== parentSessionId)
582 return cleanupAdmission;
583 const durableMember = team.members.find(member => member.name === memberName);
584 selection = selectionFromMember(durableMember);
585 if (selection !== undefined && (descriptor.agentProvider !== durableMember?.provider || descriptor.agentModel !== durableMember?.model)) {
586 throw new Error(`agent-teams: saved model route for member "${memberName}" does not match its subagent descriptor`);
587 }
588 }
589 const observeFailedAttempt = () => {
590 try {
591 // Capture the capability synchronously, before a handoff or lock wait
592 // can move the member to another task attempt.
593 const snapshot = readTeamSync(stateRoot, teamId);
594 if (snapshot?.captainSessionId !== parentSessionId)
595 return;
596 const member = snapshot.members.find(item => item.id === child.id && item.name === memberName && item.status !== 'removed');
597 if (member === undefined)
598 return;
599 const task = snapshot.tasks.find(item => item.assignee === memberName
600 && (item.status === 'claimed' || item.status === 'in_progress'));
601 return { captainSessionId: parentSessionId, memberId: child.id, task };
602 }
603 catch (error) {
604 ctx.logger.warn(`agent-teams: failed to observe member turn failure: ${String(error)}`);
605 }
606 };
607 let lastFailedTurn;
608 const recordFailure = async (turn, failure, observed) => {
609 if (turn === lastFailedTurn)
610 return;
611 lastFailedTurn = turn;
612 try {
613 const recorded = await failMemberOpenAttempt(ctx, stateRoot, teamId, memberName, failure, child.session, observed);
614 if (!recorded)
615 return;
616 // The failure event precedes driver quiescence. Observe the real
617 // lifecycle and kick explicitly even if its idle event was missed.
618 // Never force an active Agent's status to idle or retry the failed task.
619 await child.whenIdle();
620 await withTeamLock(`team:${stateRoot}:${teamId}`, async () => {
621 const team = await readTeam(stateRoot, teamId);
622 const current = team?.members.find(item => item.id === child.id && item.name === memberName && item.status !== 'removed');
623 if (team?.captainSessionId !== parentSessionId || current === undefined || child.status !== 'idle')
624 return;
625 if (current.status !== 'idle') {
626 current.status = 'idle';
627 await writeTeam(stateRoot, team);
628 }
629 });
630 await onFailureSettled?.(workspace, teamId, memberName);
631 }
632 catch (error) {
633 ctx.logger.warn(`agent-teams: failed to record member turn failure: ${String(error)}`);
634 }
635 };
636 // Harness emits agent/error only after request recovery is exhausted. In
637 // particular, llm-retry's "always" policy calls downstream request-error
638 // listeners before it retries; that waterfall cannot declare a turn dead.
639 const disposeFailure = childCtx.on('agent/error', (payload) => {
640 if (payload.agent.id !== child.id || payload.turn === lastFailedTurn)
641 return;
642 const observed = observeFailedAttempt();
643 if (observed === undefined)
644 return;
645 const failure = payload.error instanceof LlmError ? payload.error.failure : {
646 code: 'UNKNOWN',
647 message: payload.error instanceof Error ? payload.error.message : String(payload.error),
648 };
649 return recordFailure(payload.turn, failure, observed);
650 });
651 let cappedAttempt;
652 const disposeOutputLimit = childCtx.on('session/event', (session, event) => {
653 if (session !== child.session)
654 return;
655 // The host's turn reason stays max-tokens even if fresh steering runs
656 // another step. Only the last executed step can leave an attempt stuck.
657 if (event.type === 'step/start')
658 cappedAttempt = undefined;
659 const turn = outputLimitTurn(event);
660 if (turn !== undefined) {
661 const observed = observeFailedAttempt();
662 if (observed?.task !== undefined)
663 cappedAttempt = { turn, observed };
664 }
665 if (event.type !== 'turn/end')
666 return;
667 const capped = cappedAttempt;
668 cappedAttempt = undefined;
669 if (capped?.turn !== event.data.turn || event.data.reason?.kind !== 'max-tokens')
670 return;
671 return recordFailure(capped.turn, {
672 code: 'MAX_TOKENS',
673 message: 'Model output-token limit reached before the member closed this task',
674 }, { ...capped.observed, openAttemptOnly: true });
675 });
676 const cleanupFailure = () => { disposeOutputLimit(); disposeFailure(); cleanupAdmission(); };
677 // Legacy teams still need failure reporting even without a saved route.
678 if (selection === undefined)
679 return cleanupFailure;
680 const selectionRef = { current: modelSelection(selection), assembled: undefined };
681 // Newer Harness owns the next-step selection in the Agent's durable model
682 // API. Its installModelSelection hook now only contributes switch notices.
683 const model = child.model;
684 const nativeModel = typeof model?.select === 'function' ? model : undefined;
685 nativeModel?.select(selectionRef.current);
686 const disposeSelection = installModelSelection(childCtx, selectionRef);
687 const fallback = selection.fallback;
688 let switched = false;
689 const recoveryLifetime = new AbortController();
690 const disposeFallback = childCtx.on('agent/request-error', async (payload, next) => {
691 if (payload.agent.id !== child.id)
692 return next();
693 const transition = selectFallbackRoute(selectionRef.current, fallback, payload.failure.code, switched);
694 if (fallback === undefined || !transition.retry)
695 return next();
696 // The turn can survive plugin unload. Stop any queued recovery when
697 // this child setup is disposed while waiting for the team lock.
698 const signal = AbortSignal.any([payload.signal, recoveryLifetime.signal]);
699 if (signal.aborted)
700 return next();
701 const committed = await commitFallbackRoute(stateRoot, teamId, memberName, child, fallback, signal, ctx, () => {
702 switched = transition.switched;
703 selectionRef.current = transition.selection;
704 ctx.logger.warn(`agent-teams: member ${child.id} switching to fallback ${fallback.provider}/${fallback.model} after ${payload.failure.code}`);
705 if (nativeModel === undefined) {
706 // Legacy recovery rebuilds the request without rerunning assembly.
707 selectionRef.assembled = transition.selection;
708 return;
709 }
710 // Modern recovery fixes the route for all retries of a prepared step.
711 // Close that step without failing its task, then wake the same member in
712 // a new turn. The assignment and any completed calls are already in its
713 // session history, so there is no task retry or replay of input.
714 nativeModel.select(transition.selection);
715 const continuation = createUserMessage({
716 content: [{ type: 'text', text: 'AgentTeams switched to the configured fallback model. Continue the current work from the conversation history and recorded task state.' }],
717 source: agentTeamsSource({ kind: 'agent-teams' }, observedSessionFormatVersion(child)),
718 });
719 if (signal.aborted)
720 return;
721 child.cancel({ kind: 'hook', reason: 'agent-teams/model-fallback' }, { keepInbox: true });
722 try {
723 child.followup(continuation);
724 }
725 catch (error) {
726 // Cancellation suppresses the host's agent/error event, so a rejected
727 // continuation still needs to settle the observed attempt.
728 const observed = observeFailedAttempt();
729 if (observed !== undefined)
730 void recordFailure(payload.turn, payload.failure, observed);
731 throw error;
732 }
733 });
734 if (!committed)
735 return next();
736 return nativeModel === undefined ? { kind: 'retry' } : undefined;
737 });
738 return () => {
739 recoveryLifetime.abort();
740 disposeFallback();
741 disposeSelection();
742 cleanupFailure();
743 };
744 });
745 return {
746 isPendingMember(agent) {
747 const parent = agent.session.header.parentSession;
748 const descriptor = foldSubagentDescriptor(sessionOwnEvents(agent.session));
749 return parent !== undefined && descriptor?.mode === 'continuable'
750 && pending.has(pendingSelectionKey(parent, descriptor.label));
751 },
752 async withPending(parentSessionId, label, selection, operation, setup) {
753 const key = pendingSelectionKey(parentSessionId, label);
754 if (pending.has(key)) {
755 throw new Error(`member model selection is already pending for "${label}"`);
756 }
757 pending.set(key, selection);
758 if (setup !== undefined)
759 pendingSetup.set(key, setup);
760 try {
761 return await operation();
762 }
763 finally {
764 pending.delete(key);
765 pendingSetup.delete(key);
766 }
767 },
768 };
769 }
770 function configuredExecutionPrompt(member, config) {
771 const prompt = member.executionPrompt?.trim() || config.executionPrompt?.trim();
772 return prompt === undefined || prompt === '' ? undefined : prompt;
773 }
774 function truncatedPersonaProtocol(protocol) {
775 if (protocol === undefined || protocol.trim() === '')
776 return '(none)';
777 if (protocol.length <= PERSONA_PROTOCOL_MAX_CHARS)
778 return protocol;
779 return `${protocol.slice(0, PERSONA_PROTOCOL_MAX_CHARS)}… [truncated]`;
780 }
781 function assignedNonTerminalCount(team, memberName) {
782 return team.tasks.filter(task => (task.assignee === memberName && !TERMINAL_TASK_STATUSES.includes(task.status))).length;
783 }
784 /**
785 * The member's system prompt (persona), shadowing the deployment persona for
786 * that child. Self-contained: it replaces the whole persona section.
787 * Frozen at spawn: draft must already carry the Team goal and profile protocol.
788 * @param team - the team the member joined.
789 * @param member - the member record (name/role are read before spawning).
790 * @param stateDir - configured state directory, so the member can locate the
791 * team files with its own file tools.
792 */
793 export function memberPersona(team, member, stateDir, executionPrompt) {
794 const goal = team.description?.trim() || '(not provided)';
795 const injectedPrompt = member.executionPrompt?.trim() || executionPrompt?.trim();
796 const protocol = truncatedPersonaProtocol(team.profile?.protocol);
797 return `You are ${member.name}, a member of the multi-agent team "${team.name}" running inside DeepSeek Harness AgentTeams. The captain leads the team; you are a worker member${member.role ? ` with the role: ${member.role}` : ''}.
798
799 Team context:
800 - Team id: ${team.id}
801 - Your name inside the team (use it as \`from\`/identity): ${member.name}
802 - Team goal: ${goal}
803 - Profile protocol: ${protocol}
804 ${injectedPrompt === undefined || injectedPrompt === '' ? '' : `- Execution guidance:
805 ${injectedPrompt}
806 `}- The team state lives under ${stateDir}/${team.id}/ (team.json and inbox/*.jsonl). You may inspect these files read-only for diagnostics, but never edit them directly; use the agent_teams_* tools so JSON escaping and concurrent updates stay safe.
807 - The captain and your teammates reach you through messages. Coordination arrives at your nearest model step. Apply it to your current attempt; a task assignment starts a separate turn.
808 When you receive a task, treat the assignment prompt's dependency results as source material. Do not ignore them.
809
810 Working rules:
811 1. When you receive a task assignment, call agent_teams_claim_task with the task id. Keep the returned attempt_id: include it in every agent_teams_update_task call for that execution attempt. Then mark the task in_progress.
812 2. Work thoroughly with your available tools; do not cut corners.
813 3. When finishing a task:
814 - use status=completed only when the task's success criteria are satisfied;
815 - use status=failed when blocking findings or validation failures mean downstream work must not proceed;
816 - include a concise output in either case;
817 - a stale-attempt rejection means the captain reassigned or took over the task; stop touching that task and wait for new work.
818 claimed cannot jump to completed. Mark in_progress first, then completed or failed.
819 Include attempt_id on every update. Then report once as described below and become idle.
820 4. Send one short report with agent_teams_send_message (to=captain) when you complete a task or hit a blocker. Include source_task_id and source_attempt_id in task reports; a stale source rejection means stop, never relabel an old result with a new attempt. The captain is also your parent: this single message satisfies both reporting duties. Do not repeat it through the native send_message tool or send acknowledgments that add no new information.
821 5. To ask a teammate something, use agent_teams_send_message with to=<teammate name>; the message lands in their mailbox and wakes them directly — teammates talk to each other without the captain in the loop. The same applies to the captain (to=captain).
822 6. After your turn becomes idle, the shared task scheduler may assign your next ready task automatically. Never claim a second task while you still own unfinished work.
823 7. If you already own an open attempt (claimed or in_progress) and receive mail, treat it as guidance for that same attempt_id unless the mail explicitly tells you to stop or fail. Do not claim a new task in that turn.
824 8. Do not start a teammate's assigned task. Do not privately tell the next-stage member to start; the scheduler assigns unlocked work after you become idle.
825 9. You are a worker: do not create or delete teams, reassign tasks, or add/remove members — that is the captain's job.
826 10. Quality-gate kinds carry a contract (kind, objective, inScope, acceptance, verify). Stay inside inScope. Do not mark your own implementation as review pass. Review/requirements complete only with verdict=pass; needs_revision/reject must fail with findings. Mail is not a formal next review. Completed work must not be repeated to attach late evidence: call update_task on the original task with its attempt_id and acceptanceResults/commandsRun/evidence_note; supplements are append-only and cannot change its verdict.`;
827 }
828 /**
829 * The initial user message delivered when the member is created.
830 * Counts non-terminal tasks already assigned to this member on the in-memory draft.
831 * @param team - the team the member joined.
832 * @param memberName - canonical member name used to count assigned pending work.
833 */
834 export function memberWelcome(team, memberName) {
835 const assigned = assignedNonTerminalCount(team, memberName);
836 return `You have joined the team "${team.name}" as a member. Wait for an automatic assignment or a captain message.
837 Current team status: ${team.tasks.length} task(s), ${assigned} pending task(s) assigned to you.
838 Do not start work until the scheduler or captain assigns a task in this turn.`;
839 }
840 /**
841 * Spawn one member as a durable continuable subagent of the captain and fill
842 * `member.id` with its child session id. On failure nothing is persisted.
843 * @param ctx - the plugin context (injects `subagents`).
844 * @param config - member runtime knobs.
845 * @param selections - fresh/cold child model-selection bridge.
846 * @param llmSelection - resolved provider/model/reasoning snapshot.
847 * @param captain - the exact live captain agent (the calling agent).
848 * @param team - the team record (read-only here).
849 * @param member - the member draft whose `id` is filled on success.
850 * @param stateDir - configured state directory (for the persona).
851 * @param signal - caller cancellation, forwarded to the start.
852 * @param initialPrompt - first turn text; the welcome message when omitted.
853 * @param resolvedFilter - the member's effective tool filter (a selected
854 * policy, or the legacy captain-only filter when the member has none). The
855 * caller resolves it so `spawnMember` forwards exactly one immutable filter
856 * to `startContinuable`.
857 * @param relaxableDeny - deny names the lenient retry may drop for this
858 * member; the caller narrows it for a policy member so a name the owner
859 * declared is never silently removed.
860 */
861 export async function spawnMember(ctx, config, selections, llmSelection, captain, team, member, stateDir, signal, initialPrompt, resolvedFilter, relaxableDeny) {
862 // Fail loud at the first use: provider registration is a sibling plugin's
863 // effect and may settle after this plugin mounts. Capability checks here
864 // mirror what startContinuable would reject, with an actionable error.
865 const provider = ctx.subagents.getProvider(config.provider);
866 if (provider === undefined) {
867 throw new Error(`agent-teams: no subagent provider "${config.provider}" is registered (available: ${ctx.subagents.list().join(', ') || 'none'}) — `
868 + 'check that the subagent provider row (e.g. subagent-spawn) is mounted in the composition');
869 }
870 if (provider.prepareContinuable === undefined) {
871 throw new Error(`agent-teams: provider "${config.provider}" does not support continuable members`);
872 }
873 const legacyCapabilities = provider.capabilities;
874 if (!usesManagedActivations(ctx.subagents) && !legacyCapabilities.persona) {
875 throw new Error(`agent-teams: provider "${config.provider}" cannot apply a member persona`);
876 }
877 if (!usesManagedActivations(ctx.subagents) && !legacyCapabilities.toolFilter) {
878 throw new Error(`agent-teams: provider "${config.provider}" cannot restrict captain-only tools for members`);
879 }
880 const label = `${MEMBER_LABEL_PREFIX}${team.id}:${member.name}`;
881 // The legacy filter of a member without a configured tool policy: the
882 // captain-only deny list plus the depth entries this host registers.
883 const requestedFilter = resolvedFilter ?? memberToolFilter(config.maxDepth, restrictableToolNames(captain));
884 // The lenient retry may drop names this host reports unknown; keep the exact
885 // filter the host accepted for the durable member setup.
886 let acceptedFilter = requestedFilter;
887 const start = await startMemberWithLenientFilter(toolFilter => {
888 acceptedFilter = toolFilter;
889 const setup = { persona: memberPersona(team, member, stateDir, config.executionPrompt), toolFilter };
890 return selections.withPending(captain.id, label, llmSelection, () => startMember(ctx.subagents, {
891 provider: config.provider,
892 label,
893 request: {
894 prompt: [{ type: 'text', text: initialPrompt ?? memberWelcome(team, member.name) }],
895 parent: captain,
896 persona: memberPersona(team, member, stateDir, config.executionPrompt),
897 // Depth deny entries name host tools; resolve them against the
898 // running host's registry so a renamed delegation tool cannot abort
899 // the spawn (see memberToolFilter). Depth is still enforced by the
900 // parent-chain guard installed at plugin mount. A filter the host
901 // still rejects is retried without the names it reported.
902 toolFilter,
903 agentOptions: {
904 provider: llmSelection.provider,
905 model: llmSelection.model,
906 ...llmSelection.reasoningEffort === undefined
907 ? {}
908 : { reasoningEffort: ReasoningEffortId(llmSelection.reasoningEffort) },
909 },
910 // Harness request.maxDepth caps the absolute depth of THIS creation;
911 // it is not inherited by later delegations. The guard below enforces
912 // the configured member-relative descendant budget instead.
913 },
914 signal,
915 }), setup);
916 }, requestedFilter, relaxableDeny);
917 member.id = start.childId;
918 if (usesManagedActivations(ctx.subagents)) {
919 member.runtimeSetup = { persona: memberPersona(team, member, stateDir, config.executionPrompt), toolFilter: acceptedFilter };
920 }
921 // Only a policy member carries a persisted filter snapshot; a member without
922 // a policy keeps its public record shape. Legacy descriptors or runtimeSetup
923 // restore the filter on cold resume, depending on the host generation.
924 if (member.toolFilter !== undefined)
925 member.toolFilter = { ...acceptedFilter };
926 }
927 /**
928 * Deliver one message to a member as its next FIFO turn. Best effort: a
929 * failure (member gone or not continuable) is logged and reported as `false`
930 * so the caller can decide (mailbox delivery still happened).
931 *
932 * Any team sender can route through this helper: the captain is the direct
933 * parent of every member, and the caller passes the captain's live Agent
934 * (its own when the captain calls, the registry-resolved one when a member
935 * sends) — mirroring the Claude Code mailbox model where the writer writes
936 * the target's inbox and the target picks it up on its own.
937 * @param ctx - the plugin context (injects `subagents`).
938 * @param captain - the exact live captain agent (the member's direct parent).
939 * @param childId - the member's durable child session id.
940 * @param text - the message content.
941 * @param signal - caller cancellation, forwarded to the delivery.
942 * @returns whether the member inbox accepted the message.
943 */
944 export async function deliverToMember(ctx, captain, childId, text, signal, mode = 'queue') {
945 try {
946 const content = [{ type: 'text', text }];
947 if (mode === 'steer')
948 await steerMemberPrompt(ctx.subagents, captain, brandedSessionId(childId), content, signal, ctx.agents.get(brandedSessionId(childId)));
949 else
950 await queueMemberPrompt(ctx.subagents, captain, brandedSessionId(childId), content, signal);
951 return true;
952 }
953 catch (error) {
954 ctx.logger.warn(`agent-teams: prompt delivery to member ${childId} failed: ${String(error)}`);
955 return false;
956 }
957 }
958 /**
959 * Request cancellation of one live member's current turn. Best effort, fire
960 * and return; the target may keep running until it observes the signal.
961 * @param ctx - the plugin context (injects `subagents`).
962 * @param captain - the exact live captain agent (the member's parent).
963 * @param childId - the member's durable child session id.
964 */
965 export function interruptMember(ctx, captain, childId) {
966 try {
967 ctx.subagents.interrupt(brandedSessionId(childId), { kind: 'ancestor', agent: captain });
968 }
969 catch (error) {
970 ctx.logger.warn(`agent-teams: interrupt of member ${childId} failed: ${String(error)}`);
971 }
972 }
973 /**
974 * Install the missing per-child retirement boundary above Harness rc.6.
975 *
976 * Upstream `interrupt()` deliberately preserves continuable sessions and the
977 * upstream seam exposes no targeted forget/retire method. The durable
978 * AgentTeams index therefore rejects every inbox delivery before it can cold-resume a
979 * retired member. Catalog rows deliberately remain discoverable: Harness rc.8
980 * uses the direct-child catalog to authorize historical transcript reads and
981 * `openSubagent()`, so filtering those rows would make an archived member's
982 * persisted conversation inaccessible. Exact ids keep unrelated subagents
983 * untouched while the delivery boundary still prevents further model turns.
984 */
985 export function installRetiredMemberGuard(ctx, stateDir) {
986 guardSubagentDelivery(ctx, async (parent, childId) => {
987 const retired = await readRetiredMemberIds(join(parent.session.header.cwd ?? process.cwd(), stateDir));
988 return retired.has(childId);
989 });
990 }
991 /** Bound all descendant creation, including renamed tools and code-runtime calls. */
992 export function installMemberDelegationGuard(ctx, stateDir, maxDepth) {
993 let active = true;
994 const check = (parent) => {
995 if (!active)
996 return;
997 let ancestor = parent;
998 let depth = 1;
999 while (ancestor !== undefined) {
1000 const descriptor = foldSubagentDescriptor(sessionOwnEvents(ancestor.session));
1001 if (descriptor?.label?.startsWith(MEMBER_LABEL_PREFIX)) {
1002 const identity = descriptor.label.slice(MEMBER_LABEL_PREFIX.length);
1003 const separator = identity.indexOf(':');
1004 let team;
1005 try {
1006 team = readTeamSync(join(ancestor.session.header.cwd ?? process.cwd(), stateDir), identity.slice(0, separator));
1007 }
1008 catch (error) {
1009 // Distinguish "team state unreadable" (e.g. a corrupt team.json) from
1010 // the guarded rejections below: reject with an actionable message
1011 // instead of leaking the raw parse error through subagents.start.
1012 throw new Error(`AgentTeams delegation guard could not read the team state of "${identity.slice(0, separator)}" (its team.json may be corrupt or unreadable): ${String(error)}`);
1013 }
1014 const member = team?.members.find(item => item.id === ancestor.id && item.name === identity.slice(separator + 1));
1015 if (member === undefined || member.status === 'removed' || member.stopping === true || team?.halted === true)
1016 throw new Error('AgentTeams member is no longer admitting delegated work');
1017 if (depth > maxDepth)
1018 throw new Error(`AgentTeams member delegation limit (${maxDepth}) reached; report to the captain instead of spawning another agent`);
1019 return;
1020 }
1021 const parentId = ancestor.session.header.parentSession;
1022 ancestor = parentId === undefined ? undefined : ctx.agents.get(parentId);
1023 depth++;
1024 }
1025 };
1026 guardSubagentCreation(ctx, check);
1027 ctx.effect(() => () => { active = false; }, 'agent-teams: delegation guard lifetime');
1028 }
1029 /**
1030 * Snapshot the real driver activity for durable member ids.
1031 *
1032 * The team record is the membership authority, so this path intentionally no
1033 * longer depends on `listChildren()`'s versioned projection shape. Harness
1034 * rc.8 changed those rows to branded `SessionId` values plus residency-only
1035 * `activity`; neither is needed to answer whether the live Agent driver is
1036 * running, idle, or absent/ready.
1037 * @param ctx - the plugin context (injects `agents`).
1038 * @param memberIds - child ids restored from the durable team record.
1039 * @returns child id → live activity.
1040 */
1041 export function memberActivity(ctx, memberIds) {
1042 const activity = new Map();
1043 for (const id of memberIds) {
1044 if (id === '')
1045 continue;
1046 const live = ctx.agents.get(brandedSessionId(id));
1047 activity.set(id, live === undefined ? 'ready' : live.status);
1048 }
1049 return activity;
1050 }
1051
1051 lines JAVASCRIPT