@andorra-labs/code 0.1.13 → 0.1.15

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 (168) hide show
  1. package/dist/src/account-presentation.js +4 -1
  2. package/dist/src/acp-agent.d.ts +54 -0
  3. package/dist/src/acp-agent.js +991 -0
  4. package/dist/src/agent-execution.js +304 -140
  5. package/dist/src/agent-mcp-catalog.js +2 -0
  6. package/dist/src/agent-mcp.d.ts +2 -0
  7. package/dist/src/agent-mcp.js +86 -4
  8. package/dist/src/andorra/endpoint.d.ts +7 -0
  9. package/dist/src/andorra/endpoint.js +46 -0
  10. package/dist/src/andorra/entry.d.ts +21 -0
  11. package/dist/src/andorra/entry.js +118 -0
  12. package/dist/src/andorra/errors.d.ts +2 -0
  13. package/dist/src/andorra/errors.js +39 -0
  14. package/dist/src/andorra/hosted.d.ts +55 -0
  15. package/dist/src/andorra/hosted.js +130 -0
  16. package/dist/src/andorra/monitor.d.ts +151 -0
  17. package/dist/src/andorra/monitor.js +393 -0
  18. package/dist/src/andorra/notices.d.ts +16 -0
  19. package/dist/src/andorra/notices.js +38 -0
  20. package/dist/src/andorra/opt-in.d.ts +58 -0
  21. package/dist/src/andorra/opt-in.js +112 -0
  22. package/dist/src/andorra/request-watch.d.ts +6 -0
  23. package/dist/src/andorra/request-watch.js +10 -0
  24. package/dist/src/andorra/state.d.ts +86 -0
  25. package/dist/src/andorra/state.js +238 -0
  26. package/dist/src/andorra/terminal.d.ts +70 -0
  27. package/dist/src/andorra/terminal.js +125 -0
  28. package/dist/src/andorra/usage-format.d.ts +9 -0
  29. package/dist/src/andorra/usage-format.js +19 -0
  30. package/dist/src/anthropic-credentials.js +9 -1
  31. package/dist/src/app-server/protocol.d.ts +10 -2
  32. package/dist/src/app-server/protocol.js +1 -1
  33. package/dist/src/app-server/workspace.d.ts +1 -0
  34. package/dist/src/app-server/workspace.js +141 -10
  35. package/dist/src/app-server.d.ts +35 -0
  36. package/dist/src/app-server.js +377 -124
  37. package/dist/src/auth/AuthManager.d.ts +9 -0
  38. package/dist/src/auth/AuthManager.js +164 -24
  39. package/dist/src/auth/deployment.d.ts +1 -0
  40. package/dist/src/auth/deployment.js +1 -0
  41. package/dist/src/auth/index.d.ts +1 -1
  42. package/dist/src/auth/index.js +1 -1
  43. package/dist/src/auth/store.d.ts +26 -0
  44. package/dist/src/auth/store.js +34 -1
  45. package/dist/src/browser-bridge.d.ts +1 -0
  46. package/dist/src/browser-bridge.js +5 -2
  47. package/dist/src/browser-external-app.d.ts +27 -0
  48. package/dist/src/browser-external-app.js +60 -0
  49. package/dist/src/browser-panel-tool.d.ts +6 -0
  50. package/dist/src/browser-panel-tool.js +36 -0
  51. package/dist/src/browser-runner.js +1 -1
  52. package/dist/src/browser-server.d.ts +5 -0
  53. package/dist/src/browser-server.js +27 -3
  54. package/dist/src/browser-stealth.d.ts +19 -1
  55. package/dist/src/browser-stealth.js +23 -3
  56. package/dist/src/browser-ui/tokens.css +4 -4
  57. package/dist/src/browser-view.d.ts +81 -0
  58. package/dist/src/browser-view.js +289 -18
  59. package/dist/src/bug-report.d.ts +81 -0
  60. package/dist/src/bug-report.js +235 -0
  61. package/dist/src/claude-provider.d.ts +2 -1
  62. package/dist/src/claude-provider.js +10 -8
  63. package/dist/src/cli-sign-in.d.ts +3 -1
  64. package/dist/src/cli-sign-in.js +4 -1
  65. package/dist/src/cli.js +205 -58
  66. package/dist/src/coding-tools.js +7 -7
  67. package/dist/src/command-screens.d.ts +26 -3
  68. package/dist/src/command-screens.js +323 -85
  69. package/dist/src/commands.d.ts +7 -1
  70. package/dist/src/commands.js +79 -27
  71. package/dist/src/completion-gates.d.ts +22 -0
  72. package/dist/src/completion-gates.js +11 -0
  73. package/dist/src/config.d.ts +11 -1
  74. package/dist/src/config.js +134 -3
  75. package/dist/src/dashboard-view.d.ts +2 -0
  76. package/dist/src/dashboard-view.js +11 -2
  77. package/dist/src/decision/PreparedSteps.js +1 -1
  78. package/dist/src/decision/applyToolMenu.js +1 -1
  79. package/dist/src/decision/toolFamilies.js +1 -1
  80. package/dist/src/decision/types.d.ts +1 -0
  81. package/dist/src/google-provider.d.ts +31 -0
  82. package/dist/src/google-provider.js +153 -0
  83. package/dist/src/graph-health.d.ts +11 -0
  84. package/dist/src/graph-health.js +36 -4
  85. package/dist/src/graph-manager-chat.d.ts +33 -0
  86. package/dist/src/graph-manager-chat.js +165 -6
  87. package/dist/src/graph-runner.js +27 -0
  88. package/dist/src/graph-selection.js +2 -1
  89. package/dist/src/graph-sync.d.ts +1 -0
  90. package/dist/src/graph-sync.js +93 -34
  91. package/dist/src/graph-tool.d.ts +2 -0
  92. package/dist/src/graph-tool.js +2 -2
  93. package/dist/src/graph-ui/app.js +92 -10
  94. package/dist/src/graph-ui/edge-router.js +121 -53
  95. package/dist/src/graph-ui/manager.js +40 -5
  96. package/dist/src/graph-ui/style.css +5 -2
  97. package/dist/src/graph-ui/tokens.css +4 -4
  98. package/dist/src/graph-visibility.d.ts +31 -0
  99. package/dist/src/graph-visibility.js +102 -0
  100. package/dist/src/graphs.js +1 -3
  101. package/dist/src/hardened-runtime.js +1 -1
  102. package/dist/src/live-model.d.ts +24 -0
  103. package/dist/src/live-model.js +37 -0
  104. package/dist/src/managed-sign-in.d.ts +1 -0
  105. package/dist/src/managed-sign-in.js +13 -0
  106. package/dist/src/membership-errors.d.ts +2 -0
  107. package/dist/src/membership-errors.js +6 -2
  108. package/dist/src/membership.d.ts +13 -2
  109. package/dist/src/membership.js +39 -8
  110. package/dist/src/model-context-windows.d.ts +2 -0
  111. package/dist/src/model-context-windows.js +24 -0
  112. package/dist/src/model-health-cache.js +1 -1
  113. package/dist/src/model-metadata.d.ts +1 -0
  114. package/dist/src/model-metadata.js +47 -3
  115. package/dist/src/paged-transcript.d.ts +2 -0
  116. package/dist/src/paged-transcript.js +16 -0
  117. package/dist/src/palette.d.ts +1 -0
  118. package/dist/src/palette.js +1 -1
  119. package/dist/src/permissions.js +17 -4
  120. package/dist/src/provider-connection.js +32 -0
  121. package/dist/src/provider-engine.d.ts +5 -0
  122. package/dist/src/provider-engine.js +3 -3
  123. package/dist/src/provider-import.js +3 -1
  124. package/dist/src/provider-settings.d.ts +16 -1
  125. package/dist/src/provider-settings.js +50 -22
  126. package/dist/src/providers.d.ts +29 -3
  127. package/dist/src/providers.js +100 -18
  128. package/dist/src/react-runtime.js +33 -12
  129. package/dist/src/read-document-tool.d.ts +2 -0
  130. package/dist/src/read-document-tool.js +6 -6
  131. package/dist/src/remote/engine-pool.js +31 -6
  132. package/dist/src/run-control.d.ts +2 -2
  133. package/dist/src/run-control.js +9 -6
  134. package/dist/src/runtime-environment.d.ts +1 -0
  135. package/dist/src/runtime-environment.js +13 -0
  136. package/dist/src/runtime.d.ts +2 -0
  137. package/dist/src/runtime.js +2 -1
  138. package/dist/src/save-lock.js +14 -7
  139. package/dist/src/session-title.d.ts +3 -0
  140. package/dist/src/session-title.js +5 -2
  141. package/dist/src/sessions.d.ts +1 -0
  142. package/dist/src/sessions.js +4 -2
  143. package/dist/src/sign-in-detection.d.ts +1 -1
  144. package/dist/src/sign-in-detection.js +10 -3
  145. package/dist/src/sign-in-offer.js +1 -1
  146. package/dist/src/skill-commands.js +1 -1
  147. package/dist/src/skills/bundled/bug-report/SKILL.md +80 -0
  148. package/dist/src/skills/bundled/graph-manager/SKILL.md +9 -1
  149. package/dist/src/skills/bundled/graph-manager/errors.md +2 -1
  150. package/dist/src/skills/bundled/provenance.json +743 -738
  151. package/dist/src/skills/runtime-skills.js +1 -0
  152. package/dist/src/subagent-run.d.ts +2 -0
  153. package/dist/src/subagent-run.js +14 -3
  154. package/dist/src/telemetry/schema.d.ts +1 -1
  155. package/dist/src/telemetry/schema.js +2 -2
  156. package/dist/src/telemetry/uploader.d.ts +7 -1
  157. package/dist/src/telemetry/uploader.js +11 -2
  158. package/dist/src/terminal-links.d.ts +16 -0
  159. package/dist/src/terminal-links.js +113 -0
  160. package/dist/src/terminal-ui.d.ts +29 -1
  161. package/dist/src/terminal-ui.js +113 -24
  162. package/dist/src/tool-catalog.js +1 -1
  163. package/dist/src/trajectory.js +6 -1
  164. package/dist/src/transcript.d.ts +2 -0
  165. package/dist/src/transcript.js +5 -1
  166. package/dist/src/types.d.ts +5 -0
  167. package/dist/src/workspace-instructions.js +1 -1
  168. package/package.json +13 -1
@@ -11,6 +11,7 @@ import { structuredText } from './code-intelligence/CodeIntelligenceManager.js';
11
11
  import { buildMemoryBlock } from './memory/MemoryRetriever.js';
12
12
  import { discoverRuntimeSkills, matchRuntimeSkill, runtimeSkillTools } from './skills/runtime-skills.js';
13
13
  import { promptSkillReferences } from './skills/prompt-skills.js';
14
+ import { BUG_REPORT_SKILL, bugReportTool } from './bug-report.js';
14
15
  import { toolFamilies, routeToolFamilies, decisionExecutionGuidance } from './decision/toolFamilies.js';
15
16
  import { allowsGraphRouting, route as codeGraphRoute } from './code-intelligence/ContextRouter.js';
16
17
  import { randomUUID } from 'node:crypto';
@@ -59,6 +60,11 @@ Each writing spawn returns a change record: an id (use it exactly as returned),
59
60
  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
61
  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
62
  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".`;
63
+ // An Orchestrator that declares its own outcomes routes every completion through one of them, delivered or not.
64
+ const ROUTED_DELEGATION_INSTRUCTIONS = DELEGATION_INSTRUCTIONS
65
+ .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.')
66
+ .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.');
67
+ const ROUTED_RESUMED_DELEGATION_INSTRUCTIONS = RESUMED_DELEGATION_INSTRUCTIONS.replace(/ Completing as "delivered".*$/, '');
62
68
  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
69
  function mergeLimits(node, supplied = {}) {
64
70
  const limits = resolveLimits(supplied);
@@ -141,10 +147,13 @@ export async function executeAgentNode(node, options) {
141
147
  options = { ...options, runId: randomUUID() };
142
148
  const store = options.artifactStore ?? new ArtifactStore(options.runId ?? randomUUID());
143
149
  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)) {
150
+ // With declared outcomes the Orchestrator picks its route itself; with a single outcome, delegation needs a routed delivered port.
151
+ const routedDelegation = orchestrator && delegatesWriting(node) && node.completion?.mode === 'outcomes';
152
+ const delegationActive = routedDelegation || (orchestrator && delegatesWriting(node) && !!options.graph?.edges.some(edge => edge.source === node.id && edge.outcome === DELIVERED_OUTCOME));
153
+ const resumedDelegationInstructions = routedDelegation ? ROUTED_RESUMED_DELEGATION_INSTRUCTIONS : RESUMED_DELEGATION_INSTRUCTIONS;
154
+ if (delegationActive && options.resumeMessages?.[0]?.role === 'system' && !options.resumeMessages[0].content.includes(resumedDelegationInstructions)) {
146
155
  const [system, ...rest] = options.resumeMessages;
147
- options = { ...options, resumeMessages: [{ ...system, content: `${system.content}\n\n${RESUMED_DELEGATION_INSTRUCTIONS}` }, ...rest] };
156
+ options = { ...options, resumeMessages: [{ ...system, content: `${system.content}\n\n${resumedDelegationInstructions}` }, ...rest] };
148
157
  }
149
158
  const retainedIntake = orchestrator && options.resumeMessages && options.resumeState?.orchestratorIntake?.nodeId === node.id
150
159
  ? options.resumeState.orchestratorIntake : undefined;
@@ -156,6 +165,55 @@ export async function executeAgentNode(node, options) {
156
165
  const maxTotal = Math.min(policy.maxTotal ?? 8, node.maxSubagents ?? Infinity);
157
166
  const approve = serializeApprovals((name, args, approvalSignal) => bounded.approve(name, args, approvalSignal), () => permissionMode(bounded));
158
167
  let active = 0, total = 0;
168
+ // A subagent the parent stopped waiting on because the user sent the parent a message. It keeps
169
+ // working; the parent collects it with wait_subagent, writes to it with message_subagent, or stops it
170
+ // with cancel_subagent.
171
+ const background = new Map();
172
+ const subagentInboxes = new Map();
173
+ const backgroundNotices = [];
174
+ const backgroundGuard = () => background.size === 0 ? undefined
175
+ : `Subagent ${[...background.keys()].join(', ')} is still running in the background. Collect it with wait_subagent or stop it with cancel_subagent before finishing.`;
176
+ const holdSubagent = (id, role, work, cancel, inbox, steer) => {
177
+ if (!steer)
178
+ return work;
179
+ return new Promise((resolveCall, rejectCall) => {
180
+ let settled = false;
181
+ const handBack = () => {
182
+ if (settled)
183
+ return;
184
+ settled = true;
185
+ const entry = { role, work, cancel, inbox, done: false };
186
+ background.set(id, entry);
187
+ void work.catch(() => { }).finally(() => {
188
+ entry.done = true;
189
+ if (background.get(id) === entry)
190
+ 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.` });
191
+ });
192
+ resolveCall(JSON.stringify({ status: 'running', subagentId: id, role,
193
+ 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.' }));
194
+ };
195
+ work.then(value => { if (!settled) {
196
+ settled = true;
197
+ steer.removeEventListener('abort', handBack);
198
+ resolveCall(value);
199
+ } }, error => { if (!settled) {
200
+ settled = true;
201
+ steer.removeEventListener('abort', handBack);
202
+ rejectCall(error);
203
+ } });
204
+ if (steer.aborted)
205
+ handBack();
206
+ else
207
+ steer.addEventListener('abort', handBack, { once: true });
208
+ });
209
+ };
210
+ const reapBackground = async () => {
211
+ for (const [id, entry] of [...background]) {
212
+ background.delete(id);
213
+ entry.cancel.abort(new Error('The agent that started this subagent finished.'));
214
+ await entry.work.catch(() => { });
215
+ }
216
+ };
159
217
  const changes = new Map();
160
218
  const delegationRoots = [];
161
219
  const liveWorktrees = new Set();
@@ -471,7 +529,7 @@ export async function executeAgentNode(node, options) {
471
529
  if (policy.enabled && maxTotal > 0 && depth < (policy.maxDepth ?? 1) && !(delegationActive && depth > 0)) {
472
530
  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
531
  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) => {
532
+ execute: async (args, callContext) => {
475
533
  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
534
  throw new Error('Choose a configured role and provide a task of 1–16000 characters');
477
535
  const role = policy.roles?.find(item => item.id === args.role);
@@ -514,19 +572,30 @@ export async function executeAgentNode(node, options) {
514
572
  contextPolicy: { history: false, maxChars: Math.min(contextChars, 16000) } };
515
573
  if (depth > 0 && active >= (policy.maxConcurrent ?? 3))
516
574
  throw new Error('Nested spawn would exceed concurrent subagent limit; finish current work first');
575
+ // A message for the parent ends the wait for a free slot too: the subagents holding the slots keep
576
+ // running in the background, so a queued call would otherwise keep the parent from reading it.
577
+ const steer = depth === 0 ? callContext.steerSignal : undefined;
517
578
  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); };
579
+ const free = await new Promise((resolveWait, reject) => {
580
+ const cleanup = () => { callContext.signal.removeEventListener('abort', abort); steer?.removeEventListener('abort', steered); };
581
+ const ready = () => { cleanup(); resolveWait(true); };
582
+ const leave = () => { const i = waiters.indexOf(ready); if (i >= 0)
583
+ waiters.splice(i, 1); cleanup(); };
584
+ const abort = () => { leave(); reject(callContext.signal.reason); };
585
+ const steered = () => { leave(); resolveWait(false); };
523
586
  waiters.push(ready);
524
- parentContext.signal.addEventListener('abort', abort, { once: true });
525
- if (parentContext.signal.aborted)
587
+ callContext.signal.addEventListener('abort', abort, { once: true });
588
+ steer?.addEventListener('abort', steered, { once: true });
589
+ if (callContext.signal.aborted)
526
590
  abort();
591
+ else if (steer?.aborted)
592
+ steered();
527
593
  });
594
+ if (!free)
595
+ return JSON.stringify({ status: 'not_started', role: role.id,
596
+ 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
597
  }
529
- parentContext.signal.throwIfAborted();
598
+ callContext.signal.throwIfAborted();
530
599
  if (total >= maxTotal) {
531
600
  waiters.shift()?.();
532
601
  throw new Error('Maximum total subagents reached');
@@ -534,132 +603,206 @@ export async function executeAgentNode(node, options) {
534
603
  active++;
535
604
  total++;
536
605
  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.`;
606
+ const cancel = new AbortController();
607
+ const childSignal = AbortSignal.any([callContext.signal, cancel.signal]);
608
+ const inbox = [];
609
+ subagentInboxes.set(id, inbox);
610
+ // Everything the subagent's start waits on (Git, the worktree approval) ends when the subagent is
611
+ // cancelled, not only its model run.
612
+ const parentContext = { ...callContext, signal: childSignal, steerSignal: undefined,
613
+ ...(callContext.userSignal ? { userSignal: AbortSignal.any([callContext.userSignal, cancel.signal]) } : {}) };
614
+ const untilCancelled = (pending) => new Promise((resolvePending, rejectPending) => {
615
+ const abort = () => rejectPending(childSignal.reason);
616
+ if (childSignal.aborted) {
617
+ abort();
618
+ return;
561
619
  }
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;
620
+ childSignal.addEventListener('abort', abort, { once: true });
621
+ pending.then(value => { childSignal.removeEventListener('abort', abort); resolvePending(value); }, error => { childSignal.removeEventListener('abort', abort); rejectPending(error); });
622
+ });
623
+ const work = (async () => {
624
+ let workspaceArtifact;
625
+ let delegatedWorktree;
626
+ let keepWorktree = false;
627
+ try {
628
+ const parentWorkspace = parentContext.workspace;
629
+ let workspace = parentWorkspace;
630
+ let task = args.task;
631
+ if (delegated) {
632
+ if (parentCapabilities.git !== 'write')
633
+ throw new Error('Creating child worktrees requires parent Git write capability');
634
+ await assertDelegationGit(parentWorkspace, parentContext.signal);
635
+ const inside = relative(await repositoryRoot(parentWorkspace, parentContext.signal), await realpath(parentWorkspace));
636
+ const temporaryDirectoryPrefix = join(tmpdir(), 'andorra-subagent-');
637
+ const approvalArgs = { role: role.id, workspace: parentWorkspace, temporaryDirectoryPrefix,
638
+ 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>'],
639
+ 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.' };
640
+ await untilCancelled(authorizeDelegatedWorktree(callContext, approvalArgs));
641
+ const base = await snapshotWorkspace(parentWorkspace, parentContext.signal);
642
+ await untilCancelled(authorizeDelegatedWorktree(callContext, approvalArgs));
643
+ const worktree = await addChangeWorktree(parentWorkspace, base, parentContext.signal);
644
+ liveWorktrees.add(worktree);
645
+ delegatedWorktree = { worktree, base };
646
+ workspace = inside ? join(worktree, inside) : worktree;
647
+ 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.`;
648
+ }
649
+ else if (policy.workspace === 'worktree' && writingChild) {
650
+ if (parentCapabilities.git !== 'write')
651
+ throw new Error('Creating child worktrees requires parent Git write capability');
652
+ const temporaryDirectoryPrefix = join(tmpdir(), 'andorra-subagent-');
653
+ const approvalArgs = { role: role.id, workspace, temporaryDirectoryPrefix,
654
+ operations: ['git status --porcelain', 'create temporary directory', 'git worktree add --detach <temporary-directory>/worktree HEAD'],
655
+ 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.' };
656
+ let audited = false, explicitlyApproved = false;
657
+ const authorizeWorktree = async () => {
658
+ parentContext.signal.throwIfAborted();
582
659
  assertPlanMutationAllowed(parentContext);
583
- }
584
- assertPlanMutationAllowed(parentContext);
660
+ while (!audited || (!explicitlyApproved && permissionMode(parentContext) !== 'full-access')) {
661
+ await approveOperation({ ...parentContext, approve: async (...approval) => {
662
+ const allowed = await parentContext.approve(...approval);
663
+ assertPlanMutationAllowed(parentContext);
664
+ if (allowed === true)
665
+ explicitlyApproved = true;
666
+ return allowed;
667
+ } }, 'spawn_subagent.worktree', approvalArgs);
668
+ audited = true;
669
+ assertPlanMutationAllowed(parentContext);
670
+ }
671
+ assertPlanMutationAllowed(parentContext);
672
+ };
673
+ await authorizeWorktree();
674
+ const gitOptions = { cwd: workspace, signal: parentContext.signal, windowsHide: true, timeout: 15000, maxBuffer: 65536 };
675
+ const args = ['-c', 'core.hooksPath=', '-c', 'core.fsmonitor=false'];
676
+ const { stdout } = await exec('git', [...args, 'status', '--porcelain'], gitOptions);
677
+ if (stdout.trim())
678
+ throw new Error('Separate worktrees require a clean parent working tree. Commit or stash changes before delegation.');
679
+ await authorizeWorktree();
680
+ const directory = await mkdtemp(temporaryDirectoryPrefix);
681
+ workspace = join(directory, 'worktree');
682
+ await authorizeWorktree();
683
+ await exec('git', [...args, 'worktree', 'add', '--detach', workspace, 'HEAD'], gitOptions);
684
+ workspaceArtifact = await store.put('git-worktree', JSON.stringify({ workspace, role: role.id, note: 'Changes retained for explicit inspection and integration; not merged automatically.' }));
685
+ }
686
+ child.limits = {
687
+ ...(policy.maxWallTimeMs === undefined ? {} : { wallTimeMs: policy.maxWallTimeMs }),
688
+ ...(limits.maxIterations === undefined ? {} : { maxIterations: Math.min(limits.maxIterations, 40) }),
585
689
  };
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.' }));
690
+ await emit('subagent.started', { subagentId: id, role: role.id, depth: depth + 1,
691
+ ...(callContext.toolCallId ? { toolCallId: callContext.toolCallId } : {}),
692
+ ...(callContext.toolInvocationId ? { toolInvocationId: callContext.toolInvocationId } : {}),
693
+ ...(childProvider ? { provider: childProvider } : {}), ...(childModel ? { model: childModel } : {}),
694
+ task, ...(Object.keys(childInputs).length > 0 ? { input: childInputs } : {}) });
695
+ let result;
696
+ try {
697
+ result = await run(child, { ...parentContext, signal: childSignal, steerSignal: undefined, workspace, ...(parentContext.delegationRoots ? { delegationRoots: undefined } : {}) }, depth + 1, childInputs, task, id, fallbackAttempt, delegated ? 'delegated-worktree' : undefined);
698
+ }
699
+ catch (error) {
700
+ await emit('subagent.completed', { subagentId: id, role: role.id, status: childSignal.aborted ? 'cancelled' : 'failed' });
701
+ throw error;
702
+ }
703
+ finally {
704
+ if (delegatedWorktree)
705
+ await stopWorktreeJobs(delegatedWorktree.worktree);
706
+ }
707
+ if (result.telemetry)
708
+ mergeRunTelemetry(telemetry, result.telemetry);
709
+ if (result.status === 'succeeded' && researchResults.get(result))
710
+ observedResearch = true;
711
+ await emit('subagent.completed', { subagentId: id, role: role.id, status: result.status });
712
+ const returnedArtifacts = [...(result.completion?.artifacts ?? []), ...(workspaceArtifact ? [workspaceArtifact] : [])];
713
+ for (const artifact of returnedArtifacts)
714
+ scopedRefs.add(artifact.ref);
715
+ references(result.completion?.output, scopedRefs);
716
+ const observation = { status: result.status, reason: result.reason, outcome: result.completion?.outcome, output: result.completion?.output, artifacts: returnedArtifacts };
717
+ if (delegatedWorktree) {
718
+ observation.tests = result.completion?.tests ?? [];
719
+ const collected = result.status === 'succeeded' ? await collectChange(delegatedWorktree.worktree, delegatedWorktree.base, parentContext.signal) : undefined;
720
+ if (collected?.files.length) {
721
+ const { worktree, base } = delegatedWorktree;
722
+ let changeId = `change-${randomUUID().slice(0, 8)}`;
723
+ while (changes.has(changeId))
724
+ changeId = `change-${randomUUID().slice(0, 8)}`;
725
+ const truncated = collected.diff.length > DELEGATION_DIFF_LIMIT;
726
+ let diffArtifact, diffNote;
727
+ try {
728
+ diffArtifact = await store.put('delegation-diff', collected.diff);
729
+ scopedRefs.add(diffArtifact.ref);
730
+ }
731
+ catch (error) {
732
+ 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.`;
733
+ }
734
+ const root = await realpath(worktree);
735
+ changes.set(changeId, { id: changeId, subagentId: id, role: role.id, worktree, base, tree: collected.tree, files: collected.files, state: 'pending',
736
+ provider: result.provider ?? childProvider, model: result.model ?? childModel, conflicts: [], ...(diffArtifact ? { diffArtifact } : {}) });
737
+ delegationRoots.push(root);
738
+ keepWorktree = true;
739
+ await emit('subagent.change', { subagentId: id, changeId, state: 'pending', files: collected.files.map(file => file.path) });
740
+ observation.change = { id: changeId, worktree, files: collected.files, diff: truncated ? collected.diff.slice(0, DELEGATION_DIFF_LIMIT) : collected.diff, truncated,
741
+ ...(diffArtifact ? { diffArtifact } : {}), ...(diffNote ? { diffNote } : {}) };
742
+ }
743
+ }
744
+ return JSON.stringify(observation);
598
745
  }
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 } : {}) });
746
+ finally {
747
+ subagentInboxes.delete(id);
748
+ if (delegatedWorktree && !keepWorktree)
749
+ await dropWorktree(delegatedWorktree.worktree);
750
+ active--;
751
+ waiters.shift()?.();
752
+ }
753
+ })();
754
+ return holdSubagent(id, role.id, work, cancel, inbox, steer);
755
+ } });
756
+ if (depth === 0) {
757
+ const backgrounded = (args, name, extra = []) => {
758
+ if (Object.keys(args).some(key => key !== 'id' && !extra.includes(key)) || typeof args.id !== 'string')
759
+ throw new Error(`${name} takes the subagentId of a subagent that is running in the background`);
760
+ const entry = background.get(args.id);
761
+ if (!entry)
762
+ throw new Error('No subagent with that id is running in the background. A spawn_subagent call that returned a result has already finished.');
763
+ return { id: args.id, entry };
764
+ };
765
+ const idParameter = { type: 'string', minLength: 1, description: 'The subagentId from a spawn_subagent or wait_subagent result whose status is running.' };
766
+ 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.',
767
+ parameters: { type: 'object', properties: { id: idParameter }, required: ['id'], additionalProperties: false },
768
+ execute: async (args, ctx) => {
769
+ ctx.signal.throwIfAborted();
770
+ const { id, entry } = backgrounded(args, 'wait_subagent');
771
+ background.delete(id);
772
+ return holdSubagent(id, entry.role, entry.work, entry.cancel, entry.inbox, ctx.steerSignal);
773
+ } });
774
+ 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.',
775
+ parameters: { type: 'object', properties: { id: idParameter, message: { type: 'string', minLength: 1, maxLength: 16000 } }, required: ['id', 'message'], additionalProperties: false },
776
+ execute: async (args, ctx) => {
777
+ ctx.signal.throwIfAborted();
778
+ const { id, entry } = backgrounded(args, 'message_subagent', ['message']);
779
+ if (typeof args.message !== 'string' || !args.message.trim() || args.message.length > 16000)
780
+ throw new Error('Provide the message as a string of 1-16000 characters');
781
+ if (entry.done)
782
+ throw new Error('That subagent has already finished. Collect its result with wait_subagent.');
783
+ 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()}` });
784
+ ctx.runControl?.notifySteer(id);
785
+ await emit('subagent.messaged', { subagentId: id, role: entry.role, text: args.message.trim() });
786
+ 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.' });
787
+ } });
788
+ tools.push({ name: 'cancel_subagent', description: 'Stop a subagent that is running in the background. Work it has not reported is discarded.',
789
+ parameters: { type: 'object', properties: { id: idParameter }, required: ['id'], additionalProperties: false },
790
+ execute: async (args, ctx) => {
791
+ ctx.signal.throwIfAborted();
792
+ const { id, entry } = backgrounded(args, 'cancel_subagent');
793
+ background.delete(id);
794
+ entry.cancel.abort(new Error('Cancelled by the agent that started this subagent.'));
795
+ const output = await entry.work.catch(() => undefined);
605
796
  let result;
606
797
  try {
607
- result = await run(child, { ...parentContext, workspace, ...(parentContext.delegationRoots ? { delegationRoots: undefined } : {}) }, depth + 1, childInputs, task, id, fallbackAttempt, delegated ? 'delegated-worktree' : undefined);
798
+ result = output === undefined ? undefined : JSON.parse(output);
608
799
  }
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
- }
800
+ catch {
801
+ result = undefined;
653
802
  }
654
- return JSON.stringify(observation);
655
- }
656
- finally {
657
- if (delegatedWorktree && !keepWorktree)
658
- await dropWorktree(delegatedWorktree.worktree);
659
- active--;
660
- waiters.shift()?.();
661
- }
662
- } });
803
+ return JSON.stringify({ status: 'cancelled', subagentId: id, role: entry.role, ...(result === undefined ? {} : { result }) });
804
+ } });
805
+ }
663
806
  }
664
807
  if (delegationActive && depth === 0) {
665
808
  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 +935,7 @@ export async function executeAgentNode(node, options) {
792
935
  tools = tools.map(requirePublishedPlan);
793
936
  const decisionRoles = tools.some(tool => tool.name === 'spawn_subagent')
794
937
  ? (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');
938
+ 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
939
  const graphNodeId = options.nodeId ?? node.id;
797
940
  const laterNodes = options.graph ? laterAgentNodes(options.graph, graphNodeId) : [];
798
941
  const routeTester = options.graph ? testerOnEveryRoute(options.graph, graphNodeId) : undefined;
@@ -855,6 +998,9 @@ export async function executeAgentNode(node, options) {
855
998
  }).map(requirePublishedPlan) : [];
856
999
  if (skillTools.length)
857
1000
  tools = tools.filter(tool => tool.name !== 'read_skill_resource');
1001
+ // The report tool exists only in a run that carries the bug-report skill, so no other run pays for its schema.
1002
+ if (depth === 0 && [...inheritedSkills, ...promptSkills].includes(BUG_REPORT_SKILL))
1003
+ tools.push(bugReportTool({ emit }));
858
1004
  const effectiveTask = typeof inputs.taskInstruction === 'string' && inputs.taskInstruction.trim() ? inputs.taskInstruction.trim() : task;
859
1005
  const graphFirstSearch = depth === 0 && !!codeIntel?.active && codeGraphRoute(effectiveTask) === 'graph';
860
1006
  const decisionTask = depth > 0 ? task : options.decisionPreflight?.task ?? effectiveTask;
@@ -876,6 +1022,10 @@ export async function executeAgentNode(node, options) {
876
1022
  const discardedAtRetry = [];
877
1023
  for (let attempt = 1; attempt <= attempts; attempt++) {
878
1024
  context.signal.throwIfAborted();
1025
+ // A retry starts over: a subagent the last attempt left in the background is stopped first, before its
1026
+ // worktree is removed underneath it and before the new attempt could start it again.
1027
+ if (depth === 0 && attempt > 1)
1028
+ await reapBackground();
879
1029
  if (delegationActive && depth === 0 && attempt > 1)
880
1030
  for (const change of await releaseChanges())
881
1031
  discardedAtRetry.push(change.id);
@@ -991,7 +1141,7 @@ export async function executeAgentNode(node, options) {
991
1141
  && configured.provider === undefined && configured.model === undefined && !options.modelPinned && !liveSelected
992
1142
  && hasAdaptiveAlternative(efficiency.adaptiveRouting, nodeBaseline, options.configuredModels ?? []),
993
1143
  },
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 => {
1144
+ }, { 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
1145
  if (signal.aborted)
996
1146
  return;
997
1147
  return recordDecision(event);
@@ -1307,9 +1457,17 @@ export async function executeAgentNode(node, options) {
1307
1457
  attemptTools = applyToolProfile(attemptTools, options.toolProfile);
1308
1458
  const engineRecoverTools = applyToolProfile([...(recoverTools ?? []), ...compatibilityRecoverTools.filter(tool => !(recoverTools ?? []).some(current => current.name === tool.name))], options.toolProfile);
1309
1459
  let replaying = attempt > 1 && consumedSteers.length > 0;
1460
+ // A subagent reads only what is addressed to it: what its parent sent with message_subagent, and
1461
+ // what the user sent to it by name. Messages to the parent never reach it.
1462
+ const subagentSteering = (id) => {
1463
+ const inbox = subagentInboxes.get(id);
1464
+ if (inbox === undefined)
1465
+ return undefined;
1466
+ return async (signal) => [...inbox.splice(0), ...(await options.getSubagentSteeringMessages?.(id, signal) ?? [])];
1467
+ };
1310
1468
  const steeringSource = options.getSteeringMessages;
1311
1469
  const steeringForAttempt = steeringSource === undefined ? undefined : async (signal) => {
1312
- const fresh = await steeringSource(signal);
1470
+ const fresh = [...await steeringSource(signal), ...backgroundNotices.splice(0)];
1313
1471
  const replay = replaying ? [...consumedSteers] : [];
1314
1472
  replaying = false;
1315
1473
  for (const message of fresh)
@@ -1331,7 +1489,7 @@ export async function executeAgentNode(node, options) {
1331
1489
  } } : {}) }, conversation) : undefined,
1332
1490
  onTodosUpdated: orchestrator && depth === 0 ? () => { publishedPlan = true; options.onTodosUpdated?.(); } : options.onTodosUpdated,
1333
1491
  subagentId, limits: executionLimits, contextCharCeiling, systemPrompt: attemptPrompt, nodeInstruction: configured.instruction,
1334
- getSteeringMessages: subagentId ? undefined : steeringForAttempt,
1492
+ getSteeringMessages: subagentId ? subagentSteering(subagentId) : steeringForAttempt,
1335
1493
  attachments: subagentId ? undefined : options.attachments,
1336
1494
  canonicalTask: orchestrator && depth === 0 ? options.task : undefined,
1337
1495
  ...(finalAnswerOutcomes.length ? { finalAnswerOutcomes } : {}),
@@ -1341,6 +1499,9 @@ export async function executeAgentNode(node, options) {
1341
1499
  looping: options.modifierIteration !== undefined, copies: node.modifiers?.parallel?.mode === 'copies', ...(completionPolicy.mode === 'single' ? { defaultOutcome: completionPolicy.outcome } : {})
1342
1500
  }) } : {}),
1343
1501
  completionGuard: orchestrator && depth === 0 ? completion => {
1502
+ const waiting = backgroundGuard();
1503
+ if (waiting)
1504
+ return waiting;
1344
1505
  const missing = missingSkillError();
1345
1506
  if (missing)
1346
1507
  return missing;
@@ -1350,16 +1511,18 @@ export async function executeAgentNode(node, options) {
1350
1511
  const output = completion.output;
1351
1512
  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
1513
  return 'Return requirements, acceptanceCriteria, designConsiderations and codebaseFindings as string arrays and a nonempty taskInstruction in the structured handoff.';
1353
- if (completion.outcome === DELIVERED_OUTCOME) {
1514
+ if (routedDelegation || completion.outcome === DELIVERED_OUTCOME) {
1515
+ const finishing = routedDelegation ? 'completing' : 'completing as delivered';
1354
1516
  if (active > 0)
1355
- return 'Wait for every running subagent to finish before completing as delivered.';
1517
+ return `Wait for every running subagent to finish before ${finishing}.`;
1356
1518
  const records = [...changes.values()];
1357
1519
  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'))
1520
+ return `Accept or discard every change before ${finishing}.`;
1521
+ if (!routedDelegation && !records.some(change => change.state === 'landed'))
1360
1522
  return 'Land at least one accepted change before completing as delivered.';
1361
1523
  }
1362
- } : inheritedSkills.length || promptSkills.length ? () => missingSkillError() : undefined, completionPolicy, outputSchema: configured.outputSchema,
1524
+ } : depth === 0 && policy.enabled ? () => backgroundGuard() ?? (inheritedSkills.length || promptSkills.length ? missingSkillError() : undefined)
1525
+ : inheritedSkills.length || promptSkills.length ? () => missingSkillError() : undefined, completionPolicy, outputSchema: configured.outputSchema,
1363
1526
  history: configured.contextPolicy?.history ? options.history : [],
1364
1527
  task: attemptRepoBlock ? `${taskBase}\n\n${attemptRepoBlock}` : taskBase,
1365
1528
  onUsage: (usage, origin) => {
@@ -1406,7 +1569,7 @@ export async function executeAgentNode(node, options) {
1406
1569
  result.reason = 'Needs clarification: use ask_user to confirm the user design considerations before implementation.';
1407
1570
  delete result.completion;
1408
1571
  }
1409
- if (delegationActive && result.status === 'succeeded' && result.completion?.outcome === DELIVERED_OUTCOME) {
1572
+ if (delegationActive && result.status === 'succeeded' && result.completion && (routedDelegation ? [...changes.values()].some(change => change.state === 'landed') : result.completion.outcome === DELIVERED_OUTCOME)) {
1410
1573
  const content = JSON.stringify({ changes: [...changes.values()].map(change => ({
1411
1574
  id: change.id, subagentId: change.subagentId, role: change.role, provider: change.provider, model: change.model, state: change.state,
1412
1575
  files: change.files, conflicts: change.conflicts ?? [], ...(change.diffArtifact ? { diffArtifact: change.diffArtifact } : {}),
@@ -1438,6 +1601,7 @@ export async function executeAgentNode(node, options) {
1438
1601
  }
1439
1602
  finally {
1440
1603
  try {
1604
+ await reapBackground();
1441
1605
  if (delegationActive)
1442
1606
  await releaseChanges();
1443
1607
  }