@andorra-labs/code 0.1.13 → 0.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/dist/src/account-presentation.js +4 -1
  2. package/dist/src/agent-execution.js +300 -140
  3. package/dist/src/agent-mcp.js +2 -2
  4. package/dist/src/andorra/endpoint.d.ts +7 -0
  5. package/dist/src/andorra/endpoint.js +46 -0
  6. package/dist/src/andorra/entry.d.ts +21 -0
  7. package/dist/src/andorra/entry.js +100 -0
  8. package/dist/src/andorra/errors.d.ts +2 -0
  9. package/dist/src/andorra/errors.js +39 -0
  10. package/dist/src/andorra/hosted.d.ts +52 -0
  11. package/dist/src/andorra/hosted.js +126 -0
  12. package/dist/src/andorra/monitor.d.ts +151 -0
  13. package/dist/src/andorra/monitor.js +393 -0
  14. package/dist/src/andorra/notices.d.ts +7 -0
  15. package/dist/src/andorra/notices.js +15 -0
  16. package/dist/src/andorra/opt-in.d.ts +58 -0
  17. package/dist/src/andorra/opt-in.js +112 -0
  18. package/dist/src/andorra/request-watch.d.ts +6 -0
  19. package/dist/src/andorra/request-watch.js +10 -0
  20. package/dist/src/andorra/state.d.ts +86 -0
  21. package/dist/src/andorra/state.js +238 -0
  22. package/dist/src/andorra/terminal.d.ts +68 -0
  23. package/dist/src/andorra/terminal.js +125 -0
  24. package/dist/src/andorra/usage-format.d.ts +9 -0
  25. package/dist/src/andorra/usage-format.js +19 -0
  26. package/dist/src/anthropic-credentials.js +9 -1
  27. package/dist/src/app-server/protocol.d.ts +6 -2
  28. package/dist/src/app-server/protocol.js +1 -1
  29. package/dist/src/app-server.d.ts +27 -0
  30. package/dist/src/app-server.js +292 -85
  31. package/dist/src/auth/AuthManager.d.ts +9 -0
  32. package/dist/src/auth/AuthManager.js +161 -21
  33. package/dist/src/auth/deployment.d.ts +1 -0
  34. package/dist/src/auth/deployment.js +1 -0
  35. package/dist/src/auth/index.d.ts +1 -1
  36. package/dist/src/auth/index.js +1 -1
  37. package/dist/src/auth/store.d.ts +26 -0
  38. package/dist/src/auth/store.js +34 -1
  39. package/dist/src/browser-runner.js +1 -1
  40. package/dist/src/browser-stealth.d.ts +19 -1
  41. package/dist/src/browser-stealth.js +23 -3
  42. package/dist/src/browser-ui/tokens.css +4 -4
  43. package/dist/src/browser-view.d.ts +65 -0
  44. package/dist/src/browser-view.js +229 -16
  45. package/dist/src/cli.js +43 -26
  46. package/dist/src/command-screens.d.ts +17 -1
  47. package/dist/src/command-screens.js +192 -21
  48. package/dist/src/commands.d.ts +7 -1
  49. package/dist/src/commands.js +78 -27
  50. package/dist/src/config.d.ts +6 -1
  51. package/dist/src/config.js +86 -3
  52. package/dist/src/dashboard-view.d.ts +2 -0
  53. package/dist/src/dashboard-view.js +11 -2
  54. package/dist/src/decision/PreparedSteps.js +1 -1
  55. package/dist/src/decision/applyToolMenu.js +1 -1
  56. package/dist/src/decision/toolFamilies.js +1 -1
  57. package/dist/src/decision/types.d.ts +1 -0
  58. package/dist/src/graph-health.d.ts +11 -0
  59. package/dist/src/graph-health.js +36 -4
  60. package/dist/src/graph-manager-chat.d.ts +33 -0
  61. package/dist/src/graph-manager-chat.js +159 -5
  62. package/dist/src/graph-runner.js +27 -0
  63. package/dist/src/graph-selection.js +2 -1
  64. package/dist/src/graph-ui/app.js +25 -2
  65. package/dist/src/graph-ui/manager.js +40 -5
  66. package/dist/src/graph-ui/style.css +5 -2
  67. package/dist/src/graph-ui/tokens.css +4 -4
  68. package/dist/src/graphs.js +1 -3
  69. package/dist/src/hardened-runtime.js +1 -1
  70. package/dist/src/membership-errors.js +1 -1
  71. package/dist/src/membership.d.ts +10 -2
  72. package/dist/src/membership.js +20 -6
  73. package/dist/src/model-context-windows.d.ts +2 -0
  74. package/dist/src/model-context-windows.js +24 -0
  75. package/dist/src/model-health-cache.js +1 -1
  76. package/dist/src/model-metadata.d.ts +1 -0
  77. package/dist/src/model-metadata.js +40 -3
  78. package/dist/src/palette.d.ts +1 -0
  79. package/dist/src/palette.js +1 -1
  80. package/dist/src/permissions.js +17 -4
  81. package/dist/src/provider-connection.js +15 -0
  82. package/dist/src/provider-settings.d.ts +16 -1
  83. package/dist/src/provider-settings.js +36 -20
  84. package/dist/src/providers.d.ts +14 -2
  85. package/dist/src/providers.js +69 -11
  86. package/dist/src/react-runtime.js +12 -7
  87. package/dist/src/remote/engine-pool.js +5 -4
  88. package/dist/src/run-control.d.ts +2 -2
  89. package/dist/src/run-control.js +9 -6
  90. package/dist/src/runtime.d.ts +2 -0
  91. package/dist/src/runtime.js +2 -1
  92. package/dist/src/sessions.d.ts +1 -0
  93. package/dist/src/sessions.js +4 -2
  94. package/dist/src/skills/bundled/graph-manager/errors.md +1 -1
  95. package/dist/src/skills/bundled/provenance.json +738 -738
  96. package/dist/src/subagent-run.d.ts +2 -0
  97. package/dist/src/subagent-run.js +14 -3
  98. package/dist/src/telemetry/schema.d.ts +1 -1
  99. package/dist/src/telemetry/schema.js +2 -2
  100. package/dist/src/terminal-ui.d.ts +21 -0
  101. package/dist/src/terminal-ui.js +73 -10
  102. package/dist/src/transcript.js +3 -0
  103. package/dist/src/types.d.ts +3 -0
  104. package/dist/src/workspace-instructions.js +1 -1
  105. package/package.json +12 -1
@@ -26,6 +26,9 @@ export function publishableMembership(status, membership) {
26
26
  return membership;
27
27
  }
28
28
  export function jevAllowance(membership, today) {
29
+ if (membership.unlimited === true) {
30
+ return { quota: `Jev ${today} today`, notice: ' Unlimited Jev calls.' };
31
+ }
29
32
  const days = membership.windowDays ?? 30;
30
33
  const window = membership.windowDecisionLimit;
31
34
  if (window === undefined || membership.fairUse === undefined)
@@ -71,7 +74,7 @@ export function createAccountPresentationReader(deps) {
71
74
  return {
72
75
  label: `Signed in | ${plan}${email ? ` | ${email}` : ''}`,
73
76
  jevQuota: allowance?.quota ?? (quota ? `Jev ${usage}/${limit.toLocaleString('en-US')} UTC` : 'Jev quota unavailable'),
74
- notice: `Jev runs on Agent nodes that turn it on; use /jev to toggle.${allowance?.notice ?? quota} ${membership.paid ? 'Orchestrator, graph builder, and custom graphs are enabled.' : 'The free tier includes 1 custom graph of up to 3 nodes; paid membership unlocks the Orchestrator and more graphs.'}`,
77
+ notice: `Jev runs on Agent nodes that turn it on; use /jev to toggle it for a session.${allowance?.notice ?? quota} ${membership.paid ? 'Orchestrator, graph builder, and custom graphs are enabled.' : 'The free tier includes 1 custom graph of up to 3 nodes; paid membership unlocks the Orchestrator and more graphs.'}`,
75
78
  };
76
79
  }
77
80
  catch {
@@ -59,6 +59,11 @@ Each writing spawn returns a change record: an id (use it exactly as returned),
59
59
  Decide every change: accept_change with its id lands it in the working folder as uncommitted edits; discard_change drops it. A new subagent starts from the working folder, so it sees landed work only, never a change still waiting for your decision. To build on a change, accept it first and then spawn the follow-up. When work is wrong or incomplete, discard it and spawn a redo whose task carries your review findings, then review the redo. A conflict lands nothing and names the files: the change no longer fits the working folder and accepting it again conflicts again, so discard it, spawn a redo (it starts from the folder as it now stands) and accept the redo.
60
60
  Complete with "delivered" only when no subagent is still running, at least one change landed, and every change is accepted or discarded. Never write code or run commands yourself: you have no write or shell tools, and the change tools take only an id. The one exception is remove_untracked_file, for a stray untracked file left by mistake (such as one named nul or after a sentence); remove it yourself instead of asking the user to.`;
61
61
  const RESUMED_DELEGATION_INSTRUCTIONS = `This run was resumed. Changes from before the resume are no longer tracked: their ids are unknown to accept_change and discard_change, and their worktrees are gone. Work that was already landed stays in the working folder. Spawn again for anything that was still undecided. Completing as "delivered" needs at least one change accepted after the resume; otherwise complete as "completed".`;
62
+ // An Orchestrator that declares its own outcomes routes every completion through one of them, delivered or not.
63
+ const ROUTED_DELEGATION_INSTRUCTIONS = DELEGATION_INSTRUCTIONS
64
+ .replace(/^This Orchestrator can also deliver[^\n]*/, 'This Orchestrator can also implement the work through writing subagents before it completes. Whether or not subagents implemented anything, complete with exactly one of the declared outcomes, chosen from this node\'s prompt and the state of the work: for example a route that releases work your subagents delivered, or one that sends work on for testing or for the next node to implement. There is no separate delivered outcome.')
65
+ .replace('Complete with "delivered" only when no subagent is still running, at least one change landed, and every change is accepted or discarded.', 'Complete only when no subagent is still running and every change is accepted or discarded.');
66
+ const ROUTED_RESUMED_DELEGATION_INSTRUCTIONS = RESUMED_DELEGATION_INSTRUCTIONS.replace(/ Completing as "delivered".*$/, '');
62
67
  const RETAINED_CLARIFICATION_INSTRUCTION = 'This attempt retains a previous clarification: the user already answered this intake and their confirmed decisions are included in the task text. That answer satisfies the clarification requirement, so do not ask those questions again. Ask only if a genuinely new decision is required to hand off.';
63
68
  function mergeLimits(node, supplied = {}) {
64
69
  const limits = resolveLimits(supplied);
@@ -141,10 +146,13 @@ export async function executeAgentNode(node, options) {
141
146
  options = { ...options, runId: randomUUID() };
142
147
  const store = options.artifactStore ?? new ArtifactStore(options.runId ?? randomUUID());
143
148
  const orchestrator = node.agentRole === 'orchestrator';
144
- const delegationActive = orchestrator && delegatesWriting(node) && !!options.graph?.edges.some(edge => edge.source === node.id && edge.outcome === DELIVERED_OUTCOME);
145
- if (delegationActive && options.resumeMessages?.[0]?.role === 'system' && !options.resumeMessages[0].content.includes(RESUMED_DELEGATION_INSTRUCTIONS)) {
149
+ // With declared outcomes the Orchestrator picks its route itself; with a single outcome, delegation needs a routed delivered port.
150
+ const routedDelegation = orchestrator && delegatesWriting(node) && node.completion?.mode === 'outcomes';
151
+ const delegationActive = routedDelegation || (orchestrator && delegatesWriting(node) && !!options.graph?.edges.some(edge => edge.source === node.id && edge.outcome === DELIVERED_OUTCOME));
152
+ const resumedDelegationInstructions = routedDelegation ? ROUTED_RESUMED_DELEGATION_INSTRUCTIONS : RESUMED_DELEGATION_INSTRUCTIONS;
153
+ if (delegationActive && options.resumeMessages?.[0]?.role === 'system' && !options.resumeMessages[0].content.includes(resumedDelegationInstructions)) {
146
154
  const [system, ...rest] = options.resumeMessages;
147
- options = { ...options, resumeMessages: [{ ...system, content: `${system.content}\n\n${RESUMED_DELEGATION_INSTRUCTIONS}` }, ...rest] };
155
+ options = { ...options, resumeMessages: [{ ...system, content: `${system.content}\n\n${resumedDelegationInstructions}` }, ...rest] };
148
156
  }
149
157
  const retainedIntake = orchestrator && options.resumeMessages && options.resumeState?.orchestratorIntake?.nodeId === node.id
150
158
  ? options.resumeState.orchestratorIntake : undefined;
@@ -156,6 +164,55 @@ export async function executeAgentNode(node, options) {
156
164
  const maxTotal = Math.min(policy.maxTotal ?? 8, node.maxSubagents ?? Infinity);
157
165
  const approve = serializeApprovals((name, args, approvalSignal) => bounded.approve(name, args, approvalSignal), () => permissionMode(bounded));
158
166
  let active = 0, total = 0;
167
+ // A subagent the parent stopped waiting on because the user sent the parent a message. It keeps
168
+ // working; the parent collects it with wait_subagent, writes to it with message_subagent, or stops it
169
+ // with cancel_subagent.
170
+ const background = new Map();
171
+ const subagentInboxes = new Map();
172
+ const backgroundNotices = [];
173
+ const backgroundGuard = () => background.size === 0 ? undefined
174
+ : `Subagent ${[...background.keys()].join(', ')} is still running in the background. Collect it with wait_subagent or stop it with cancel_subagent before finishing.`;
175
+ const holdSubagent = (id, role, work, cancel, inbox, steer) => {
176
+ if (!steer)
177
+ return work;
178
+ return new Promise((resolveCall, rejectCall) => {
179
+ let settled = false;
180
+ const handBack = () => {
181
+ if (settled)
182
+ return;
183
+ settled = true;
184
+ const entry = { role, work, cancel, inbox, done: false };
185
+ background.set(id, entry);
186
+ void work.catch(() => { }).finally(() => {
187
+ entry.done = true;
188
+ if (background.get(id) === entry)
189
+ backgroundNotices.push({ role: 'user', content: `Engine notice, not written by the user: subagent ${role} (${id}) has finished in the background. Call wait_subagent with its id to collect its result.` });
190
+ });
191
+ resolveCall(JSON.stringify({ status: 'running', subagentId: id, role,
192
+ message: 'The user sent you a message, so this call returned early. The subagent is still working in the background and nothing it did is lost. Read the user\'s message first. Then pass an instruction on with message_subagent, stop the subagent with cancel_subagent, or collect its result with wait_subagent. You cannot finish while it is running.' }));
193
+ };
194
+ work.then(value => { if (!settled) {
195
+ settled = true;
196
+ steer.removeEventListener('abort', handBack);
197
+ resolveCall(value);
198
+ } }, error => { if (!settled) {
199
+ settled = true;
200
+ steer.removeEventListener('abort', handBack);
201
+ rejectCall(error);
202
+ } });
203
+ if (steer.aborted)
204
+ handBack();
205
+ else
206
+ steer.addEventListener('abort', handBack, { once: true });
207
+ });
208
+ };
209
+ const reapBackground = async () => {
210
+ for (const [id, entry] of [...background]) {
211
+ background.delete(id);
212
+ entry.cancel.abort(new Error('The agent that started this subagent finished.'));
213
+ await entry.work.catch(() => { });
214
+ }
215
+ };
159
216
  const changes = new Map();
160
217
  const delegationRoots = [];
161
218
  const liveWorktrees = new Set();
@@ -471,7 +528,7 @@ export async function executeAgentNode(node, options) {
471
528
  if (policy.enabled && maxTotal > 0 && depth < (policy.maxDepth ?? 1) && !(delegationActive && depth > 0)) {
472
529
  tools.push({ name: 'spawn_subagent', description: 'Run one configured role on a bounded task. Its typed result returns as an observation. Batch spawn calls can run concurrently within configured limits. Role contracts: ' + JSON.stringify((policy.roles ?? []).map(role => ({ id: role.id, name: role.name, instruction: role.instruction, inputSchema: role.inputSchema, outputSchema: role.outputSchema }))),
473
530
  parameters: { type: 'object', properties: { role: { type: 'string', enum: (policy.roles ?? []).map(role => role.id) }, task: { type: 'string' }, input: { type: 'object' } }, required: ['role', 'task'], additionalProperties: false },
474
- execute: async (args, parentContext) => {
531
+ execute: async (args, callContext) => {
475
532
  if (Object.keys(args).some(key => !['role', 'task', 'input'].includes(key)) || typeof args.role !== 'string' || typeof args.task !== 'string' || !args.task.trim() || args.task.length > 16000)
476
533
  throw new Error('Choose a configured role and provide a task of 1–16000 characters');
477
534
  const role = policy.roles?.find(item => item.id === args.role);
@@ -514,19 +571,30 @@ export async function executeAgentNode(node, options) {
514
571
  contextPolicy: { history: false, maxChars: Math.min(contextChars, 16000) } };
515
572
  if (depth > 0 && active >= (policy.maxConcurrent ?? 3))
516
573
  throw new Error('Nested spawn would exceed concurrent subagent limit; finish current work first');
574
+ // A message for the parent ends the wait for a free slot too: the subagents holding the slots keep
575
+ // running in the background, so a queued call would otherwise keep the parent from reading it.
576
+ const steer = depth === 0 ? callContext.steerSignal : undefined;
517
577
  while (active >= (policy.maxConcurrent ?? 3)) {
518
- await new Promise((resolveWait, reject) => {
519
- const cleanup = () => parentContext.signal.removeEventListener('abort', abort);
520
- const ready = () => { cleanup(); resolveWait(); };
521
- const abort = () => { const i = waiters.indexOf(ready); if (i >= 0)
522
- waiters.splice(i, 1); cleanup(); reject(parentContext.signal.reason); };
578
+ const free = await new Promise((resolveWait, reject) => {
579
+ const cleanup = () => { callContext.signal.removeEventListener('abort', abort); steer?.removeEventListener('abort', steered); };
580
+ const ready = () => { cleanup(); resolveWait(true); };
581
+ const leave = () => { const i = waiters.indexOf(ready); if (i >= 0)
582
+ waiters.splice(i, 1); cleanup(); };
583
+ const abort = () => { leave(); reject(callContext.signal.reason); };
584
+ const steered = () => { leave(); resolveWait(false); };
523
585
  waiters.push(ready);
524
- parentContext.signal.addEventListener('abort', abort, { once: true });
525
- if (parentContext.signal.aborted)
586
+ callContext.signal.addEventListener('abort', abort, { once: true });
587
+ steer?.addEventListener('abort', steered, { once: true });
588
+ if (callContext.signal.aborted)
526
589
  abort();
590
+ else if (steer?.aborted)
591
+ steered();
527
592
  });
593
+ if (!free)
594
+ return JSON.stringify({ status: 'not_started', role: role.id,
595
+ message: 'Not started: the user sent you a message while this subagent was waiting for a free slot. Read the message, then call spawn_subagent again if this task is still needed.' });
528
596
  }
529
- parentContext.signal.throwIfAborted();
597
+ callContext.signal.throwIfAborted();
530
598
  if (total >= maxTotal) {
531
599
  waiters.shift()?.();
532
600
  throw new Error('Maximum total subagents reached');
@@ -534,132 +602,206 @@ export async function executeAgentNode(node, options) {
534
602
  active++;
535
603
  total++;
536
604
  const id = randomUUID();
537
- let workspaceArtifact;
538
- let delegatedWorktree;
539
- let keepWorktree = false;
540
- try {
541
- const parentWorkspace = parentContext.workspace;
542
- let workspace = parentWorkspace;
543
- let task = args.task;
544
- if (delegated) {
545
- if (parentCapabilities.git !== 'write')
546
- throw new Error('Creating child worktrees requires parent Git write capability');
547
- await assertDelegationGit(parentWorkspace, parentContext.signal);
548
- const inside = relative(await repositoryRoot(parentWorkspace, parentContext.signal), await realpath(parentWorkspace));
549
- const temporaryDirectoryPrefix = join(tmpdir(), 'andorra-subagent-');
550
- const approvalArgs = { role: role.id, workspace: parentWorkspace, temporaryDirectoryPrefix,
551
- operations: ['git snapshot of the working folder through a temporary index (no ref, stash or index change)', 'create temporary directory', 'git worktree add --detach <temporary-directory>/worktree <snapshot>'],
552
- warning: 'UNSANDBOXED: Git and PATH executables can access the entire host filesystem and network. This operation creates a temporary worktree outside the workspace and writes protected Git metadata, including an external common Git directory. One grant covers every writing subagent of this Orchestrator visit; a change reaches the working folder only when the Orchestrator accepts it.' };
553
- await authorizeDelegatedWorktree(parentContext, approvalArgs);
554
- const base = await snapshotWorkspace(parentWorkspace, parentContext.signal);
555
- await authorizeDelegatedWorktree(parentContext, approvalArgs);
556
- const worktree = await addChangeWorktree(parentWorkspace, base, parentContext.signal);
557
- liveWorktrees.add(worktree);
558
- delegatedWorktree = { worktree, base };
559
- workspace = inside ? join(worktree, inside) : worktree;
560
- task += `\n\nThis task runs in a separate Git worktree started from the working folder as it stands: ${workspace}. Files ignored by Git (for example node_modules) are not in this worktree. Install what you need inside this worktree if a build or test requires it. Report the commands and tests you ran and their results in the tests list of your completion. This worktree shares the Git repository of the user's working folder: do not create or change stashes, branches, tags or Git configuration. Commit only if the task needs it; commits stay in this worktree, and your result is taken from the files as you leave them.`;
605
+ const cancel = new AbortController();
606
+ const childSignal = AbortSignal.any([callContext.signal, cancel.signal]);
607
+ const inbox = [];
608
+ subagentInboxes.set(id, inbox);
609
+ // Everything the subagent's start waits on (Git, the worktree approval) ends when the subagent is
610
+ // cancelled, not only its model run.
611
+ const parentContext = { ...callContext, signal: childSignal, steerSignal: undefined,
612
+ ...(callContext.userSignal ? { userSignal: AbortSignal.any([callContext.userSignal, cancel.signal]) } : {}) };
613
+ const untilCancelled = (pending) => new Promise((resolvePending, rejectPending) => {
614
+ const abort = () => rejectPending(childSignal.reason);
615
+ if (childSignal.aborted) {
616
+ abort();
617
+ return;
561
618
  }
562
- else if (policy.workspace === 'worktree' && writingChild) {
563
- if (parentCapabilities.git !== 'write')
564
- throw new Error('Creating child worktrees requires parent Git write capability');
565
- const temporaryDirectoryPrefix = join(tmpdir(), 'andorra-subagent-');
566
- const approvalArgs = { role: role.id, workspace, temporaryDirectoryPrefix,
567
- operations: ['git status --porcelain', 'create temporary directory', 'git worktree add --detach <temporary-directory>/worktree HEAD'],
568
- warning: 'UNSANDBOXED: Git and PATH executables can access the entire host filesystem and network. This operation creates a temporary worktree outside the workspace and writes protected Git metadata, including an external common Git directory. Changes are retained for inspection.' };
569
- let audited = false, explicitlyApproved = false;
570
- const authorizeWorktree = async () => {
571
- parentContext.signal.throwIfAborted();
572
- assertPlanMutationAllowed(parentContext);
573
- while (!audited || (!explicitlyApproved && permissionMode(parentContext) !== 'full-access')) {
574
- await approveOperation({ ...parentContext, approve: async (...approval) => {
575
- const allowed = await parentContext.approve(...approval);
576
- assertPlanMutationAllowed(parentContext);
577
- if (allowed === true)
578
- explicitlyApproved = true;
579
- return allowed;
580
- } }, 'spawn_subagent.worktree', approvalArgs);
581
- audited = true;
619
+ childSignal.addEventListener('abort', abort, { once: true });
620
+ pending.then(value => { childSignal.removeEventListener('abort', abort); resolvePending(value); }, error => { childSignal.removeEventListener('abort', abort); rejectPending(error); });
621
+ });
622
+ const work = (async () => {
623
+ let workspaceArtifact;
624
+ let delegatedWorktree;
625
+ let keepWorktree = false;
626
+ try {
627
+ const parentWorkspace = parentContext.workspace;
628
+ let workspace = parentWorkspace;
629
+ let task = args.task;
630
+ if (delegated) {
631
+ if (parentCapabilities.git !== 'write')
632
+ throw new Error('Creating child worktrees requires parent Git write capability');
633
+ await assertDelegationGit(parentWorkspace, parentContext.signal);
634
+ const inside = relative(await repositoryRoot(parentWorkspace, parentContext.signal), await realpath(parentWorkspace));
635
+ const temporaryDirectoryPrefix = join(tmpdir(), 'andorra-subagent-');
636
+ const approvalArgs = { role: role.id, workspace: parentWorkspace, temporaryDirectoryPrefix,
637
+ operations: ['git snapshot of the working folder through a temporary index (no ref, stash or index change)', 'create temporary directory', 'git worktree add --detach <temporary-directory>/worktree <snapshot>'],
638
+ warning: 'UNSANDBOXED: Git and PATH executables can access the entire host filesystem and network. This operation creates a temporary worktree outside the workspace and writes protected Git metadata, including an external common Git directory. One grant covers every writing subagent of this Orchestrator visit; a change reaches the working folder only when the Orchestrator accepts it.' };
639
+ await untilCancelled(authorizeDelegatedWorktree(callContext, approvalArgs));
640
+ const base = await snapshotWorkspace(parentWorkspace, parentContext.signal);
641
+ await untilCancelled(authorizeDelegatedWorktree(callContext, approvalArgs));
642
+ const worktree = await addChangeWorktree(parentWorkspace, base, parentContext.signal);
643
+ liveWorktrees.add(worktree);
644
+ delegatedWorktree = { worktree, base };
645
+ workspace = inside ? join(worktree, inside) : worktree;
646
+ task += `\n\nThis task runs in a separate Git worktree started from the working folder as it stands: ${workspace}. Files ignored by Git (for example node_modules) are not in this worktree. Install what you need inside this worktree if a build or test requires it. Report the commands and tests you ran and their results in the tests list of your completion. This worktree shares the Git repository of the user's working folder: do not create or change stashes, branches, tags or Git configuration. Commit only if the task needs it; commits stay in this worktree, and your result is taken from the files as you leave them.`;
647
+ }
648
+ else if (policy.workspace === 'worktree' && writingChild) {
649
+ if (parentCapabilities.git !== 'write')
650
+ throw new Error('Creating child worktrees requires parent Git write capability');
651
+ const temporaryDirectoryPrefix = join(tmpdir(), 'andorra-subagent-');
652
+ const approvalArgs = { role: role.id, workspace, temporaryDirectoryPrefix,
653
+ operations: ['git status --porcelain', 'create temporary directory', 'git worktree add --detach <temporary-directory>/worktree HEAD'],
654
+ warning: 'UNSANDBOXED: Git and PATH executables can access the entire host filesystem and network. This operation creates a temporary worktree outside the workspace and writes protected Git metadata, including an external common Git directory. Changes are retained for inspection.' };
655
+ let audited = false, explicitlyApproved = false;
656
+ const authorizeWorktree = async () => {
657
+ parentContext.signal.throwIfAborted();
582
658
  assertPlanMutationAllowed(parentContext);
583
- }
584
- assertPlanMutationAllowed(parentContext);
659
+ while (!audited || (!explicitlyApproved && permissionMode(parentContext) !== 'full-access')) {
660
+ await approveOperation({ ...parentContext, approve: async (...approval) => {
661
+ const allowed = await parentContext.approve(...approval);
662
+ assertPlanMutationAllowed(parentContext);
663
+ if (allowed === true)
664
+ explicitlyApproved = true;
665
+ return allowed;
666
+ } }, 'spawn_subagent.worktree', approvalArgs);
667
+ audited = true;
668
+ assertPlanMutationAllowed(parentContext);
669
+ }
670
+ assertPlanMutationAllowed(parentContext);
671
+ };
672
+ await authorizeWorktree();
673
+ const gitOptions = { cwd: workspace, signal: parentContext.signal, windowsHide: true, timeout: 15000, maxBuffer: 65536 };
674
+ const args = ['-c', 'core.hooksPath=', '-c', 'core.fsmonitor=false'];
675
+ const { stdout } = await exec('git', [...args, 'status', '--porcelain'], gitOptions);
676
+ if (stdout.trim())
677
+ throw new Error('Separate worktrees require a clean parent working tree. Commit or stash changes before delegation.');
678
+ await authorizeWorktree();
679
+ const directory = await mkdtemp(temporaryDirectoryPrefix);
680
+ workspace = join(directory, 'worktree');
681
+ await authorizeWorktree();
682
+ await exec('git', [...args, 'worktree', 'add', '--detach', workspace, 'HEAD'], gitOptions);
683
+ workspaceArtifact = await store.put('git-worktree', JSON.stringify({ workspace, role: role.id, note: 'Changes retained for explicit inspection and integration; not merged automatically.' }));
684
+ }
685
+ child.limits = {
686
+ ...(policy.maxWallTimeMs === undefined ? {} : { wallTimeMs: policy.maxWallTimeMs }),
687
+ ...(limits.maxIterations === undefined ? {} : { maxIterations: Math.min(limits.maxIterations, 40) }),
585
688
  };
586
- await authorizeWorktree();
587
- const gitOptions = { cwd: workspace, signal: parentContext.signal, windowsHide: true, timeout: 15000, maxBuffer: 65536 };
588
- const args = ['-c', 'core.hooksPath=', '-c', 'core.fsmonitor=false'];
589
- const { stdout } = await exec('git', [...args, 'status', '--porcelain'], gitOptions);
590
- if (stdout.trim())
591
- throw new Error('Separate worktrees require a clean parent working tree. Commit or stash changes before delegation.');
592
- await authorizeWorktree();
593
- const directory = await mkdtemp(temporaryDirectoryPrefix);
594
- workspace = join(directory, 'worktree');
595
- await authorizeWorktree();
596
- await exec('git', [...args, 'worktree', 'add', '--detach', workspace, 'HEAD'], gitOptions);
597
- workspaceArtifact = await store.put('git-worktree', JSON.stringify({ workspace, role: role.id, note: 'Changes retained for explicit inspection and integration; not merged automatically.' }));
689
+ await emit('subagent.started', { subagentId: id, role: role.id, depth: depth + 1,
690
+ ...(callContext.toolCallId ? { toolCallId: callContext.toolCallId } : {}),
691
+ ...(callContext.toolInvocationId ? { toolInvocationId: callContext.toolInvocationId } : {}),
692
+ ...(childProvider ? { provider: childProvider } : {}), ...(childModel ? { model: childModel } : {}),
693
+ task, ...(Object.keys(childInputs).length > 0 ? { input: childInputs } : {}) });
694
+ let result;
695
+ try {
696
+ result = await run(child, { ...parentContext, signal: childSignal, steerSignal: undefined, workspace, ...(parentContext.delegationRoots ? { delegationRoots: undefined } : {}) }, depth + 1, childInputs, task, id, fallbackAttempt, delegated ? 'delegated-worktree' : undefined);
697
+ }
698
+ catch (error) {
699
+ await emit('subagent.completed', { subagentId: id, role: role.id, status: childSignal.aborted ? 'cancelled' : 'failed' });
700
+ throw error;
701
+ }
702
+ finally {
703
+ if (delegatedWorktree)
704
+ await stopWorktreeJobs(delegatedWorktree.worktree);
705
+ }
706
+ if (result.telemetry)
707
+ mergeRunTelemetry(telemetry, result.telemetry);
708
+ if (result.status === 'succeeded' && researchResults.get(result))
709
+ observedResearch = true;
710
+ await emit('subagent.completed', { subagentId: id, role: role.id, status: result.status });
711
+ const returnedArtifacts = [...(result.completion?.artifacts ?? []), ...(workspaceArtifact ? [workspaceArtifact] : [])];
712
+ for (const artifact of returnedArtifacts)
713
+ scopedRefs.add(artifact.ref);
714
+ references(result.completion?.output, scopedRefs);
715
+ const observation = { status: result.status, reason: result.reason, outcome: result.completion?.outcome, output: result.completion?.output, artifacts: returnedArtifacts };
716
+ if (delegatedWorktree) {
717
+ observation.tests = result.completion?.tests ?? [];
718
+ const collected = result.status === 'succeeded' ? await collectChange(delegatedWorktree.worktree, delegatedWorktree.base, parentContext.signal) : undefined;
719
+ if (collected?.files.length) {
720
+ const { worktree, base } = delegatedWorktree;
721
+ let changeId = `change-${randomUUID().slice(0, 8)}`;
722
+ while (changes.has(changeId))
723
+ changeId = `change-${randomUUID().slice(0, 8)}`;
724
+ const truncated = collected.diff.length > DELEGATION_DIFF_LIMIT;
725
+ let diffArtifact, diffNote;
726
+ try {
727
+ diffArtifact = await store.put('delegation-diff', collected.diff);
728
+ scopedRefs.add(diffArtifact.ref);
729
+ }
730
+ catch (error) {
731
+ diffNote = `The full diff could not be stored as an artifact (${error instanceof Error ? error.message : String(error)}); read the changed files inside the worktree.`;
732
+ }
733
+ const root = await realpath(worktree);
734
+ changes.set(changeId, { id: changeId, subagentId: id, role: role.id, worktree, base, tree: collected.tree, files: collected.files, state: 'pending',
735
+ provider: result.provider ?? childProvider, model: result.model ?? childModel, conflicts: [], ...(diffArtifact ? { diffArtifact } : {}) });
736
+ delegationRoots.push(root);
737
+ keepWorktree = true;
738
+ await emit('subagent.change', { subagentId: id, changeId, state: 'pending', files: collected.files.map(file => file.path) });
739
+ observation.change = { id: changeId, worktree, files: collected.files, diff: truncated ? collected.diff.slice(0, DELEGATION_DIFF_LIMIT) : collected.diff, truncated,
740
+ ...(diffArtifact ? { diffArtifact } : {}), ...(diffNote ? { diffNote } : {}) };
741
+ }
742
+ }
743
+ return JSON.stringify(observation);
598
744
  }
599
- child.limits = {
600
- ...(policy.maxWallTimeMs === undefined ? {} : { wallTimeMs: policy.maxWallTimeMs }),
601
- ...(limits.maxIterations === undefined ? {} : { maxIterations: Math.min(limits.maxIterations, 40) }),
602
- };
603
- await emit('subagent.started', { subagentId: id, role: role.id, depth: depth + 1,
604
- ...(childProvider ? { provider: childProvider } : {}), ...(childModel ? { model: childModel } : {}) });
745
+ finally {
746
+ subagentInboxes.delete(id);
747
+ if (delegatedWorktree && !keepWorktree)
748
+ await dropWorktree(delegatedWorktree.worktree);
749
+ active--;
750
+ waiters.shift()?.();
751
+ }
752
+ })();
753
+ return holdSubagent(id, role.id, work, cancel, inbox, steer);
754
+ } });
755
+ if (depth === 0) {
756
+ const backgrounded = (args, name, extra = []) => {
757
+ if (Object.keys(args).some(key => key !== 'id' && !extra.includes(key)) || typeof args.id !== 'string')
758
+ throw new Error(`${name} takes the subagentId of a subagent that is running in the background`);
759
+ const entry = background.get(args.id);
760
+ if (!entry)
761
+ throw new Error('No subagent with that id is running in the background. A spawn_subagent call that returned a result has already finished.');
762
+ return { id: args.id, entry };
763
+ };
764
+ const idParameter = { type: 'string', minLength: 1, description: 'The subagentId from a spawn_subagent or wait_subagent result whose status is running.' };
765
+ tools.push({ name: 'wait_subagent', description: 'Wait for a subagent that is running in the background and return its result, exactly as spawn_subagent would have. If the user sends you another message while you wait, this returns early again with status running.',
766
+ parameters: { type: 'object', properties: { id: idParameter }, required: ['id'], additionalProperties: false },
767
+ execute: async (args, ctx) => {
768
+ ctx.signal.throwIfAborted();
769
+ const { id, entry } = backgrounded(args, 'wait_subagent');
770
+ background.delete(id);
771
+ return holdSubagent(id, entry.role, entry.work, entry.cancel, entry.inbox, ctx.steerSignal);
772
+ } });
773
+ tools.push({ name: 'message_subagent', description: 'Send an instruction to a subagent that is running in the background. It stops what it is doing to read it, then carries on. Use this to pass on what the user asked for; the subagent never sees the user\'s messages to you.',
774
+ parameters: { type: 'object', properties: { id: idParameter, message: { type: 'string', minLength: 1, maxLength: 16000 } }, required: ['id', 'message'], additionalProperties: false },
775
+ execute: async (args, ctx) => {
776
+ ctx.signal.throwIfAborted();
777
+ const { id, entry } = backgrounded(args, 'message_subagent', ['message']);
778
+ if (typeof args.message !== 'string' || !args.message.trim() || args.message.length > 16000)
779
+ throw new Error('Provide the message as a string of 1-16000 characters');
780
+ if (entry.done)
781
+ throw new Error('That subagent has already finished. Collect its result with wait_subagent.');
782
+ entry.inbox.push({ role: 'user', content: `Message from ${node.name ?? 'the agent that started you'}, sent while you work. Follow it:\n${args.message.trim()}` });
783
+ ctx.runControl?.notifySteer(id);
784
+ await emit('subagent.messaged', { subagentId: id, role: entry.role, text: args.message.trim() });
785
+ return JSON.stringify({ delivered: true, subagentId: id, message: 'The subagent reads this before its next step and keeps working. Collect its result with wait_subagent.' });
786
+ } });
787
+ tools.push({ name: 'cancel_subagent', description: 'Stop a subagent that is running in the background. Work it has not reported is discarded.',
788
+ parameters: { type: 'object', properties: { id: idParameter }, required: ['id'], additionalProperties: false },
789
+ execute: async (args, ctx) => {
790
+ ctx.signal.throwIfAborted();
791
+ const { id, entry } = backgrounded(args, 'cancel_subagent');
792
+ background.delete(id);
793
+ entry.cancel.abort(new Error('Cancelled by the agent that started this subagent.'));
794
+ const output = await entry.work.catch(() => undefined);
605
795
  let result;
606
796
  try {
607
- result = await run(child, { ...parentContext, workspace, ...(parentContext.delegationRoots ? { delegationRoots: undefined } : {}) }, depth + 1, childInputs, task, id, fallbackAttempt, delegated ? 'delegated-worktree' : undefined);
797
+ result = output === undefined ? undefined : JSON.parse(output);
608
798
  }
609
- catch (error) {
610
- await emit('subagent.completed', { subagentId: id, role: role.id, status: parentContext.signal.aborted ? 'cancelled' : 'failed' });
611
- throw error;
612
- }
613
- finally {
614
- if (delegatedWorktree)
615
- await stopWorktreeJobs(delegatedWorktree.worktree);
616
- }
617
- if (result.telemetry)
618
- mergeRunTelemetry(telemetry, result.telemetry);
619
- if (result.status === 'succeeded' && researchResults.get(result))
620
- observedResearch = true;
621
- await emit('subagent.completed', { subagentId: id, role: role.id, status: result.status });
622
- const returnedArtifacts = [...(result.completion?.artifacts ?? []), ...(workspaceArtifact ? [workspaceArtifact] : [])];
623
- for (const artifact of returnedArtifacts)
624
- scopedRefs.add(artifact.ref);
625
- references(result.completion?.output, scopedRefs);
626
- const observation = { status: result.status, reason: result.reason, outcome: result.completion?.outcome, output: result.completion?.output, artifacts: returnedArtifacts };
627
- if (delegatedWorktree) {
628
- observation.tests = result.completion?.tests ?? [];
629
- const collected = result.status === 'succeeded' ? await collectChange(delegatedWorktree.worktree, delegatedWorktree.base, parentContext.signal) : undefined;
630
- if (collected?.files.length) {
631
- const { worktree, base } = delegatedWorktree;
632
- let changeId = `change-${randomUUID().slice(0, 8)}`;
633
- while (changes.has(changeId))
634
- changeId = `change-${randomUUID().slice(0, 8)}`;
635
- const truncated = collected.diff.length > DELEGATION_DIFF_LIMIT;
636
- let diffArtifact, diffNote;
637
- try {
638
- diffArtifact = await store.put('delegation-diff', collected.diff);
639
- scopedRefs.add(diffArtifact.ref);
640
- }
641
- catch (error) {
642
- diffNote = `The full diff could not be stored as an artifact (${error instanceof Error ? error.message : String(error)}); read the changed files inside the worktree.`;
643
- }
644
- const root = await realpath(worktree);
645
- changes.set(changeId, { id: changeId, subagentId: id, role: role.id, worktree, base, tree: collected.tree, files: collected.files, state: 'pending',
646
- provider: result.provider ?? childProvider, model: result.model ?? childModel, conflicts: [], ...(diffArtifact ? { diffArtifact } : {}) });
647
- delegationRoots.push(root);
648
- keepWorktree = true;
649
- await emit('subagent.change', { subagentId: id, changeId, state: 'pending', files: collected.files.map(file => file.path) });
650
- observation.change = { id: changeId, worktree, files: collected.files, diff: truncated ? collected.diff.slice(0, DELEGATION_DIFF_LIMIT) : collected.diff, truncated,
651
- ...(diffArtifact ? { diffArtifact } : {}), ...(diffNote ? { diffNote } : {}) };
652
- }
799
+ catch {
800
+ result = undefined;
653
801
  }
654
- return JSON.stringify(observation);
655
- }
656
- finally {
657
- if (delegatedWorktree && !keepWorktree)
658
- await dropWorktree(delegatedWorktree.worktree);
659
- active--;
660
- waiters.shift()?.();
661
- }
662
- } });
802
+ return JSON.stringify({ status: 'cancelled', subagentId: id, role: entry.role, ...(result === undefined ? {} : { result }) });
803
+ } });
804
+ }
663
805
  }
664
806
  if (delegationActive && depth === 0) {
665
807
  const idOnly = () => ({ type: 'object', properties: { id: { type: 'string', minLength: 1, description: 'The change id from a spawn_subagent result.' } }, required: ['id'], additionalProperties: false });
@@ -792,7 +934,7 @@ export async function executeAgentNode(node, options) {
792
934
  tools = tools.map(requirePublishedPlan);
793
935
  const decisionRoles = tools.some(tool => tool.name === 'spawn_subagent')
794
936
  ? (policy.roles ?? []).map(role => role.id) : [];
795
- const systemPrompt = [orchestrator && depth === 0 ? ORCHESTRATOR_INSTRUCTIONS : '', orchestrator && depth === 0 && delegationActive ? DELEGATION_INSTRUCTIONS : '', configured.systemPrompt ?? configured.prompt ?? ''].filter(Boolean).join('\n\n');
937
+ const systemPrompt = [orchestrator && depth === 0 ? ORCHESTRATOR_INSTRUCTIONS : '', orchestrator && depth === 0 && delegationActive ? (routedDelegation ? ROUTED_DELEGATION_INSTRUCTIONS : DELEGATION_INSTRUCTIONS) : '', configured.systemPrompt ?? configured.prompt ?? ''].filter(Boolean).join('\n\n');
796
938
  const graphNodeId = options.nodeId ?? node.id;
797
939
  const laterNodes = options.graph ? laterAgentNodes(options.graph, graphNodeId) : [];
798
940
  const routeTester = options.graph ? testerOnEveryRoute(options.graph, graphNodeId) : undefined;
@@ -876,6 +1018,10 @@ export async function executeAgentNode(node, options) {
876
1018
  const discardedAtRetry = [];
877
1019
  for (let attempt = 1; attempt <= attempts; attempt++) {
878
1020
  context.signal.throwIfAborted();
1021
+ // A retry starts over: a subagent the last attempt left in the background is stopped first, before its
1022
+ // worktree is removed underneath it and before the new attempt could start it again.
1023
+ if (depth === 0 && attempt > 1)
1024
+ await reapBackground();
879
1025
  if (delegationActive && depth === 0 && attempt > 1)
880
1026
  for (const change of await releaseChanges())
881
1027
  discardedAtRetry.push(change.id);
@@ -991,7 +1137,7 @@ export async function executeAgentNode(node, options) {
991
1137
  && configured.provider === undefined && configured.model === undefined && !options.modelPinned && !liveSelected
992
1138
  && hasAdaptiveAlternative(efficiency.adaptiveRouting, nodeBaseline, options.configuredModels ?? []),
993
1139
  },
994
- }, { runId: options.runId, nodeId: configured.id, invocationId: randomUUID() }, { codeGraph: depth === 0 && !!codeIntel?.active && repoRoom() >= 512 && codeGraphRoute(effectiveTask) === 'graph', memory: depth === 0 && (options.decisionPreflight?.memory ?? (configured.agentRole !== 'orchestrator' && !!options.memory?.activeFor(options.runId) && options.memory.automaticRetrieval)) }, signal, event => {
1140
+ }, { runId: options.runId, nodeId: configured.id, invocationId: randomUUID(), ...(subagentId ? { subagentId } : {}) }, { codeGraph: depth === 0 && !!codeIntel?.active && repoRoom() >= 512 && codeGraphRoute(effectiveTask) === 'graph', memory: depth === 0 && (options.decisionPreflight?.memory ?? (configured.agentRole !== 'orchestrator' && !!options.memory?.activeFor(options.runId) && options.memory.automaticRetrieval)) }, signal, event => {
995
1141
  if (signal.aborted)
996
1142
  return;
997
1143
  return recordDecision(event);
@@ -1307,9 +1453,17 @@ export async function executeAgentNode(node, options) {
1307
1453
  attemptTools = applyToolProfile(attemptTools, options.toolProfile);
1308
1454
  const engineRecoverTools = applyToolProfile([...(recoverTools ?? []), ...compatibilityRecoverTools.filter(tool => !(recoverTools ?? []).some(current => current.name === tool.name))], options.toolProfile);
1309
1455
  let replaying = attempt > 1 && consumedSteers.length > 0;
1456
+ // A subagent reads only what is addressed to it: what its parent sent with message_subagent, and
1457
+ // what the user sent to it by name. Messages to the parent never reach it.
1458
+ const subagentSteering = (id) => {
1459
+ const inbox = subagentInboxes.get(id);
1460
+ if (inbox === undefined)
1461
+ return undefined;
1462
+ return async (signal) => [...inbox.splice(0), ...(await options.getSubagentSteeringMessages?.(id, signal) ?? [])];
1463
+ };
1310
1464
  const steeringSource = options.getSteeringMessages;
1311
1465
  const steeringForAttempt = steeringSource === undefined ? undefined : async (signal) => {
1312
- const fresh = await steeringSource(signal);
1466
+ const fresh = [...await steeringSource(signal), ...backgroundNotices.splice(0)];
1313
1467
  const replay = replaying ? [...consumedSteers] : [];
1314
1468
  replaying = false;
1315
1469
  for (const message of fresh)
@@ -1331,7 +1485,7 @@ export async function executeAgentNode(node, options) {
1331
1485
  } } : {}) }, conversation) : undefined,
1332
1486
  onTodosUpdated: orchestrator && depth === 0 ? () => { publishedPlan = true; options.onTodosUpdated?.(); } : options.onTodosUpdated,
1333
1487
  subagentId, limits: executionLimits, contextCharCeiling, systemPrompt: attemptPrompt, nodeInstruction: configured.instruction,
1334
- getSteeringMessages: subagentId ? undefined : steeringForAttempt,
1488
+ getSteeringMessages: subagentId ? subagentSteering(subagentId) : steeringForAttempt,
1335
1489
  attachments: subagentId ? undefined : options.attachments,
1336
1490
  canonicalTask: orchestrator && depth === 0 ? options.task : undefined,
1337
1491
  ...(finalAnswerOutcomes.length ? { finalAnswerOutcomes } : {}),
@@ -1341,6 +1495,9 @@ export async function executeAgentNode(node, options) {
1341
1495
  looping: options.modifierIteration !== undefined, copies: node.modifiers?.parallel?.mode === 'copies', ...(completionPolicy.mode === 'single' ? { defaultOutcome: completionPolicy.outcome } : {})
1342
1496
  }) } : {}),
1343
1497
  completionGuard: orchestrator && depth === 0 ? completion => {
1498
+ const waiting = backgroundGuard();
1499
+ if (waiting)
1500
+ return waiting;
1344
1501
  const missing = missingSkillError();
1345
1502
  if (missing)
1346
1503
  return missing;
@@ -1350,16 +1507,18 @@ export async function executeAgentNode(node, options) {
1350
1507
  const output = completion.output;
1351
1508
  if (!output || typeof output.taskInstruction !== 'string' || !output.taskInstruction.trim() || ['requirements', 'acceptanceCriteria', 'designConsiderations', 'codebaseFindings'].some(key => !Array.isArray(output[key]) || output[key].some(value => typeof value !== 'string')))
1352
1509
  return 'Return requirements, acceptanceCriteria, designConsiderations and codebaseFindings as string arrays and a nonempty taskInstruction in the structured handoff.';
1353
- if (completion.outcome === DELIVERED_OUTCOME) {
1510
+ if (routedDelegation || completion.outcome === DELIVERED_OUTCOME) {
1511
+ const finishing = routedDelegation ? 'completing' : 'completing as delivered';
1354
1512
  if (active > 0)
1355
- return 'Wait for every running subagent to finish before completing as delivered.';
1513
+ return `Wait for every running subagent to finish before ${finishing}.`;
1356
1514
  const records = [...changes.values()];
1357
1515
  if (records.some(change => change.state === 'pending' || change.state === 'conflict'))
1358
- return 'Accept or discard every change before completing as delivered.';
1359
- if (!records.some(change => change.state === 'landed'))
1516
+ return `Accept or discard every change before ${finishing}.`;
1517
+ if (!routedDelegation && !records.some(change => change.state === 'landed'))
1360
1518
  return 'Land at least one accepted change before completing as delivered.';
1361
1519
  }
1362
- } : inheritedSkills.length || promptSkills.length ? () => missingSkillError() : undefined, completionPolicy, outputSchema: configured.outputSchema,
1520
+ } : depth === 0 && policy.enabled ? () => backgroundGuard() ?? (inheritedSkills.length || promptSkills.length ? missingSkillError() : undefined)
1521
+ : inheritedSkills.length || promptSkills.length ? () => missingSkillError() : undefined, completionPolicy, outputSchema: configured.outputSchema,
1363
1522
  history: configured.contextPolicy?.history ? options.history : [],
1364
1523
  task: attemptRepoBlock ? `${taskBase}\n\n${attemptRepoBlock}` : taskBase,
1365
1524
  onUsage: (usage, origin) => {
@@ -1406,7 +1565,7 @@ export async function executeAgentNode(node, options) {
1406
1565
  result.reason = 'Needs clarification: use ask_user to confirm the user design considerations before implementation.';
1407
1566
  delete result.completion;
1408
1567
  }
1409
- if (delegationActive && result.status === 'succeeded' && result.completion?.outcome === DELIVERED_OUTCOME) {
1568
+ if (delegationActive && result.status === 'succeeded' && result.completion && (routedDelegation ? [...changes.values()].some(change => change.state === 'landed') : result.completion.outcome === DELIVERED_OUTCOME)) {
1410
1569
  const content = JSON.stringify({ changes: [...changes.values()].map(change => ({
1411
1570
  id: change.id, subagentId: change.subagentId, role: change.role, provider: change.provider, model: change.model, state: change.state,
1412
1571
  files: change.files, conflicts: change.conflicts ?? [], ...(change.diffArtifact ? { diffArtifact: change.diffArtifact } : {}),
@@ -1438,6 +1597,7 @@ export async function executeAgentNode(node, options) {
1438
1597
  }
1439
1598
  finally {
1440
1599
  try {
1600
+ await reapBackground();
1441
1601
  if (delegationActive)
1442
1602
  await releaseChanges();
1443
1603
  }