@xzzpig/pi-subagents 0.16.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/CHANGELOG.md +164 -1
  2. package/README.md +5 -3
  3. package/agents/claude-code-writer.md +1 -0
  4. package/agents/codex-exec-writer.md +1 -0
  5. package/agents/cursor-agent-writer.md +1 -0
  6. package/agents/reviewer.md +3 -2
  7. package/agents/worker.md +3 -2
  8. package/docs/agents.md +17 -10
  9. package/docs/configuration.md +21 -3
  10. package/docs/extension-api.md +70 -4
  11. package/docs/models.md +5 -3
  12. package/docs/observability.md +23 -13
  13. package/docs/standalone-background.md +4 -4
  14. package/docs/tool-reference.md +40 -19
  15. package/docs/watchdog.md +2 -0
  16. package/docs/workflows.md +57 -3
  17. package/inspector-runner.mjs +1 -1
  18. package/package.json +14 -8
  19. package/prompts/council.md +6 -3
  20. package/runner-peer-loader.mjs +4 -7
  21. package/runner-peer-preload.mjs +5 -7
  22. package/skills/pi-subagents/SKILL.md +1 -0
  23. package/skills/pi-subagents/references/constraints-and-recipes.md +5 -2
  24. package/skills/pi-subagents/references/execution-controls.md +6 -4
  25. package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
  26. package/skills/pi-subagents/references/multi-lane-orchestration.md +8 -0
  27. package/skills/pi-subagents/references/prompting-and-roles.md +16 -15
  28. package/src/agents/agent-eject.ts +3 -3
  29. package/src/agents/agent-management.ts +61 -52
  30. package/src/agents/agent-memory.ts +90 -3
  31. package/src/agents/agent-serializer.ts +4 -4
  32. package/src/agents/agents.ts +125 -51
  33. package/src/agents/global-npm-root.ts +58 -0
  34. package/src/agents/proactive-skills.ts +4 -1
  35. package/src/agents/runtime-agent-registry.ts +14 -11
  36. package/src/agents/skills.ts +42 -9
  37. package/src/api/delegation.ts +15 -0
  38. package/src/api/inspectors.ts +27 -0
  39. package/src/api/preflight.ts +60 -60
  40. package/src/extension/doctor.ts +9 -4
  41. package/src/extension/fanout-child.ts +8 -0
  42. package/src/extension/index.ts +101 -48
  43. package/src/extension/rpc.ts +10 -1
  44. package/src/extension/schemas.ts +12 -6
  45. package/src/extension/subagent-guide.ts +12 -4
  46. package/src/extension/tool-activation.ts +197 -0
  47. package/src/extension/tool-description.ts +1 -1
  48. package/src/inspectors/ghostty/plugin.ts +13 -1
  49. package/src/inspectors/plugins.ts +70 -3
  50. package/src/intercom/intercom-bridge.ts +2 -0
  51. package/src/intercom/native-supervisor-channel.ts +22 -15
  52. package/src/intercom/result-intercom.ts +4 -0
  53. package/src/runs/background/active-async-capacity.ts +3 -25
  54. package/src/runs/background/async-execution.ts +100 -140
  55. package/src/runs/background/async-job-tracker.ts +28 -34
  56. package/src/runs/background/async-resume.ts +16 -8
  57. package/src/runs/background/async-status.ts +2 -0
  58. package/src/runs/background/binary-bootstrap.ts +34 -6
  59. package/src/runs/background/fleet-view.ts +51 -7
  60. package/src/runs/background/notify.ts +93 -7
  61. package/src/runs/background/pid-namespace.ts +18 -0
  62. package/src/runs/background/process-terminal-candidate.ts +98 -0
  63. package/src/runs/background/process-terminal.ts +17 -96
  64. package/src/runs/background/result-watcher.ts +1 -1
  65. package/src/runs/background/retained-children.ts +3 -2
  66. package/src/runs/background/run-child-session.ts +16 -5
  67. package/src/runs/background/run-id-resolver.ts +10 -5
  68. package/src/runs/background/run-status.ts +10 -4
  69. package/src/runs/background/runner-aliases.ts +25 -15
  70. package/src/runs/background/runner-child-launch.ts +1 -2
  71. package/src/runs/background/runner-startup-failure.ts +56 -0
  72. package/src/runs/background/stale-run-reconciler.ts +19 -3
  73. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  74. package/src/runs/background/subagent-runner.ts +96 -287
  75. package/src/runs/background/wait-tool.ts +2 -0
  76. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  77. package/src/runs/foreground/execution.ts +217 -250
  78. package/src/runs/foreground/prompt-audit.ts +3 -9
  79. package/src/runs/foreground/subagent-executor.ts +377 -119
  80. package/src/runs/shared/acceptance.ts +167 -68
  81. package/src/runs/shared/capability-ceiling.ts +4 -1
  82. package/src/runs/shared/child-hooks.ts +1 -16
  83. package/src/runs/shared/child-launch.ts +22 -14
  84. package/src/runs/shared/child-runtime-config.ts +3 -0
  85. package/src/runs/shared/child-session.ts +52 -2
  86. package/src/runs/shared/child-tool-plan.ts +23 -113
  87. package/src/runs/shared/dynamic-fanout.ts +1 -1
  88. package/src/runs/shared/external-cli-runner.ts +3 -1
  89. package/src/runs/shared/external-job-bridge.ts +54 -0
  90. package/src/runs/shared/git-environment.ts +29 -0
  91. package/src/runs/shared/mcp-config-sources.ts +3 -0
  92. package/src/runs/shared/mcp-direct-tool-allowlist.ts +1 -1
  93. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  94. package/src/runs/shared/model-resolution.ts +6 -1
  95. package/src/runs/shared/nested-events.ts +67 -55
  96. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  97. package/src/runs/shared/parallel-utils.ts +2 -1
  98. package/src/runs/shared/pi-spawn.ts +92 -6
  99. package/src/runs/shared/single-output.ts +11 -2
  100. package/src/runs/shared/structured-output.ts +227 -7
  101. package/src/runs/shared/subagent-control.ts +2 -16
  102. package/src/runs/shared/subagent-prompt-runtime.ts +27 -5
  103. package/src/runs/shared/tool-availability.ts +2 -2
  104. package/src/runs/shared/tool-budget.ts +21 -0
  105. package/src/runs/shared/usage-reconciliation.ts +73 -0
  106. package/src/runs/shared/worktree.ts +35 -8
  107. package/src/shared/child-session-name.ts +4 -2
  108. package/src/shared/fork-context.ts +11 -4
  109. package/src/shared/launch-contract.ts +1 -1
  110. package/src/shared/pruned-fork.ts +69 -56
  111. package/src/shared/types.ts +52 -16
  112. package/src/slash/delegation-adapters.ts +25 -1
  113. package/src/slash/prompt-template-bridge.ts +16 -1
  114. package/src/slash/prompt-workflows.ts +12 -1
  115. package/src/slash/slash-commands.ts +7 -241
  116. package/src/slash/subagent-cost.ts +313 -0
  117. package/src/slash/subagents-admin.ts +28 -29
  118. package/src/tui/fleet-status.ts +24 -2
  119. package/src/tui/fleet.ts +7 -4
  120. package/src/tui/render.ts +53 -19
  121. package/src/watchdog/diff-tool.ts +24 -3
  122. package/src/watchdog/permission-arbiter.ts +13 -15
  123. package/src/watchdog/register-child.ts +10 -2
  124. package/src/watchdog/review.ts +14 -14
  125. package/src/watchdog/runtime.ts +2 -1
  126. package/src/watchdog/turn-delta.ts +11 -5
  127. package/src/workflows/scripted-workflow.ts +109 -23
  128. package/src/workflows/workflow-child-summary.ts +4 -2
  129. package/src/workflows/workflow-settlement.ts +4 -1
  130. package/src/runs/shared/completion-evidence.ts +0 -89
  131. package/src/runs/shared/completion-guard.ts +0 -255
  132. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  133. package/src/runs/shared/task-intent.ts +0 -244
@@ -3,7 +3,7 @@ import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
5
5
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
6
- import { discoverAgents, findBlockingAgentDiagnostic, formatUnknownAgentError, resolveAgentName, unknownAgentDiagnosticContext, type AgentConfig, type AgentDiscoveryDiagnostic, type AgentScope, type UnknownAgentDiagnosticContext } from "../../agents/agents.ts";
6
+ import { discoverAgents, discoverAgentsAll, findBlockingAgentDiagnostic, formatUnknownAgentError, resolveAgentName, unknownAgentDiagnosticContext, type AgentConfig, type AgentDiscoveryDiagnostic, type AgentScope, type UnknownAgentDiagnosticContext } from "../../agents/agents.ts";
7
7
  import { getArtifactsDir, getProjectArtifactPackagingWarning, getProjectSubagentsDir } from "../../shared/artifacts.ts";
8
8
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
9
9
  import { createCapacityResilientJsonWriter } from "../../shared/capacity-resilient-json.ts";
@@ -56,11 +56,12 @@ import { isScheduledRunAction } from "../background/scheduled-runs.ts";
56
56
  import { encodeIndexSegment } from "../background/index-segment.ts";
57
57
  import { enqueueChainAppendRequest, readPendingChainAppendRequests, runnerStepOutputNames } from "../background/chain-append.ts";
58
58
  import { ChainOutputValidationError, validateChainOutputBindingsWithContext } from "../shared/chain-outputs.ts";
59
- import { normalizeGateAcceptance, resolveAcceptanceReportMode, validateAcceptanceInput, validateExecutionAcceptance, validateExecutionAcceptancePolicy } from "../shared/acceptance.ts";
59
+ import { acceptanceHasTypedVerify, normalizeGateAcceptance, resolveAcceptanceReportMode, TYPED_VERIFY_OUTPUT_SCHEMA_CONFLICT, validateAcceptanceInput, validateExecutionAcceptance, validateExecutionAcceptancePolicy } from "../shared/acceptance.ts";
60
60
  import { canPreferFork, createForkContextResolver, resolveSubagentLaunchContext } from "../../shared/fork-context.ts";
61
61
  import { createPrunedForkSessionWriter } from "../../shared/pruned-fork.ts";
62
62
  import { resolveCurrentSessionId } from "../../shared/session-identity.ts";
63
63
  import { currentCompletionOwnerId } from "../../shared/completion-owner.ts";
64
+ import { SUBAGENT_ASYNC_COMPLETE_EVENT } from "../../shared/types.ts";
64
65
  import { applyIntercomBridgeToAgent, INTERCOM_BRIDGE_MARKER, resolveIntercomBridge, resolveIntercomSessionTarget, resolveSubagentIntercomTarget, type IntercomBridgeState } from "../../intercom/intercom-bridge.ts";
65
66
  import { formatControlIntercomMessage, formatControlNoticeMessage, resolveControlConfig, shouldNotifyControlEvent } from "../shared/subagent-control.ts";
66
67
  import { formatSpawnBudget, getSpawnBudgetSnapshot, grantSpawnBudget, preflightSpawnBudget, preflightSpawnBudgetGrant, reserveSpawnBudget } from "../shared/spawn-budget.ts";
@@ -68,14 +69,13 @@ import { claimRunFanoutBatch, claimRunFanoutBatchWithCommit, createRunFanoutBudg
68
69
  import { retainLiveForegroundNestedRoute } from "../../integrations/pi-web-session-liveness.ts";
69
70
  import { validateToolBudgetConfig } from "../shared/tool-budget.ts";
70
71
  import { usageBudgetExceededMessage, usageBudgetState, validateUsageBudgetConfig } from "../shared/usage-budget.ts";
71
- import { intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
72
+ import { assertAgentAllowedByCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
72
73
  import { isAgentContract } from "../shared/agent-contract.ts";
73
74
  import { normalizeExtensionBindings, type ExtensionBindings } from "../shared/extension-bindings.ts";
74
75
  import { resolveRequiredChildExtensions } from "../../shared/required-child-extensions.ts";
75
76
  import { finalizeSingleOutput, injectSingleOutputInstruction, normalizeSingleOutputOverride, outputPathMappingFromTask, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
76
77
  import { assertJsonSchemaObject, cleanupStructuredOutputRuntime, createStructuredOutputRuntime } from "../shared/structured-output.ts";
77
- import { compactForegroundDetails, getSingleResultOutput, readStatus, resolveChildCwd, sumResultsCost, sumResultsUsage, toAgentToolUsage } from "../../shared/utils.ts";
78
- import { createTaskMutationArbiter } from "../shared/llm-intent-arbiter.ts";
78
+ import { compactForegroundDetails, getSingleResultOutput, PROMPT_REDACTED, readStatus, resolveChildCwd, sumResultsCost, sumResultsUsage, toAgentToolUsage } from "../../shared/utils.ts";
79
79
  import { discardPreservedWorktrees, formatParallelHandoffError, formatParallelHandoffReference, formatStoredParallelHandoffCleanup, parallelHandoffPath, readParallelHandoffManifest, recordParallelHandoffMerge, recordParallelHandoffSupersession, writeParallelHandoffGroup, writeWorktreeSetupHandoff } from "../shared/parallel-handoff.ts";
80
80
  import { summarizeContextModes, type ContextMode, type ContextSummary } from "../shared/context-mode.ts";
81
81
  import {
@@ -101,7 +101,7 @@ import { promotePausedWorkflowIfSettled, reconcileDetachedWorkflowChildCompletio
101
101
  import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
102
102
  import { resolveAsyncRootResultPath, waitForImportedAsyncRoot } from "../background/chain-root-attachment.ts";
103
103
  import { fallbackResultPayloadPathForSessionRun, removeResultIndex, resultFilePath, writeAsyncResultFile } from "../background/result-files.ts";
104
- import { attachRootChildrenToSteps, createNestedRoute, findNestedControlResult, inheritedNestedParentAddressOf, inheritedNestedRouteOf, resolveNestedAsyncDir, snapshotNestedEventFiles, updateForegroundNestedProjection, writeNestedControlRequest, writeNestedEvent, type NestedParentAddress, type NestedRoute, type NestedRunResolutionScope } from "../shared/nested-events.ts";
104
+ import { attachRootChildrenToSteps, createNestedRoute, findNestedControlResult, inheritedNestedParentAddressOf, inheritedNestedRouteOf, nestedRunScope, resolveNestedAsyncDir, retainNestedLookupRoute, snapshotNestedEventFiles, updateForegroundNestedProjection, writeNestedControlRequest, writeNestedEvent, type NestedParentAddress, type NestedRoute, type NestedRunResolutionScope } from "../shared/nested-events.ts";
105
105
  import type { ChildRuntimeConfig } from "../shared/child-runtime-config.ts";
106
106
  import { resolveSubagentRunId, type ResolvedSubagentRunId } from "../background/run-id-resolver.ts";
107
107
  import { formatNestedRunStatusLines } from "../shared/nested-render.ts";
@@ -119,7 +119,7 @@ import type { MissionWorkflowChildUpdate } from "../../missions/types.ts";
119
119
  import { createMissionWorkflowState } from "../../missions/workflow-state.ts";
120
120
  import { resolveAuthorityDecision } from "../../policy/authority.ts";
121
121
  import { handleInspectorAction, INSPECTOR_ACTIONS } from "../../inspectors/actions.ts";
122
- import { createBuiltinInspectorPlugins } from "../../inspectors/plugins.ts";
122
+ import { getInspectorPlugins } from "../../inspectors/plugins.ts";
123
123
  import { handleHerdrProjectPaneAction, HERDR_PROJECT_PANE_ACTIONS } from "../../inspectors/herdr/project-panes.ts";
124
124
  import { previewSimpleWorkflowRun, runWorkflowScript, validateWorkflowScript, WorkflowScriptError, type WorkflowChildSettledNotification, type WorkflowLanePlan, type WorkflowReceiptResumeReference, type WorkflowScriptChildResult, type WorkflowScriptTraceEntry, type WorkflowSteerOptions, type WorkflowSteerResult } from "../../workflows/scripted-workflow.ts";
125
125
  import { formatIncrementalChildCompletion, incrementalChildCompletionTriggersTurn } from "../background/notify.ts";
@@ -198,9 +198,12 @@ import {
198
198
  DEFAULT_ARTIFACT_CONFIG,
199
199
  DEFAULT_FORK_PREAMBLE,
200
200
  SUBAGENT_ACTIONS,
201
+ SUBAGENT_ASYNC_STARTED_EVENT,
202
+ SUBAGENT_CHILD_STATUS_EVENT,
201
203
  SUBAGENT_CONTROL_EVENT,
202
204
  SUBAGENT_CONTROL_INTERCOM_EVENT,
203
205
  SUBAGENT_FOREGROUND_COMPLETE_EVENT,
206
+ SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
204
207
  checkSubagentDepth,
205
208
  resolveChildMaxSubagentDepth,
206
209
  resolveCurrentMaxSubagentDepth,
@@ -458,6 +461,7 @@ interface ExecutorDeps {
458
461
  getSubagentSessionRoot: (parentSessionFile: string | null) => string;
459
462
  expandTilde: (p: string) => string;
460
463
  discoverAgents: (cwd: string, scope: AgentScope, preferredModelProvider?: string) => { agents: AgentConfig[]; agentDiagnostics?: AgentDiscoveryDiagnostic[]; modelScope?: ModelScopeConfig; maxThinking?: AgentConfig["maxThinking"]; cwd?: string; scope?: AgentScope; directories?: UnknownAgentDiagnosticContext["directories"] };
464
+ discoverAgentsAll?: typeof discoverAgentsAll;
461
465
  onAgentsChanged?: () => void;
462
466
  allowMutatingManagementActions?: boolean;
463
467
  activateSupervisorTransport?: () => void;
@@ -555,35 +559,35 @@ function loadWorkflowScriptPath(params: SubagentParamsLike, runtimeCwd: string):
555
559
  }
556
560
 
557
561
  function currentProjectTrusted(ctx: Pick<ExtensionContext, "isProjectTrusted">): boolean {
558
- return ctx.isProjectTrusted?.() === true;
562
+ return ctx.isProjectTrusted?.() === true;
559
563
  }
560
564
 
561
565
  function trustedProjectCwd(ctx: ExtensionContext): string | undefined {
562
- return currentProjectTrusted(ctx) ? path.resolve(ctx.cwd) : undefined;
566
+ return currentProjectTrusted(ctx) ? path.resolve(ctx.cwd) : undefined;
563
567
  }
564
568
 
565
569
  function sandboxProfileTrustError(agent: AgentConfig, ctx: ExtensionContext, childCwd: string): string | undefined {
566
- return projectScopedProfileTrustError({
567
- kind: "sandbox",
568
- agentName: agent.name,
569
- profileName: agent.sandbox ?? "",
570
- projectScoped: Boolean(agent.sandbox) && (agent.source === "project" || agent.override?.scope === "project"),
571
- trustedCwd: trustedProjectCwd(ctx),
572
- effectiveCwd: path.resolve(childCwd),
573
- messageStyle: "executor",
574
- });
570
+ return projectScopedProfileTrustError({
571
+ kind: "sandbox",
572
+ agentName: agent.name,
573
+ profileName: agent.sandbox ?? "",
574
+ projectScoped: Boolean(agent.sandbox) && (agent.source === "project" || agent.override?.scope === "project"),
575
+ trustedCwd: trustedProjectCwd(ctx),
576
+ effectiveCwd: path.resolve(childCwd),
577
+ messageStyle: "executor",
578
+ });
575
579
  }
576
580
 
577
581
  function permissionProfileTrustError(agent: AgentConfig, ctx: ExtensionContext, childCwd: string): string | undefined {
578
- return projectScopedProfileTrustError({
579
- kind: "permission",
580
- agentName: agent.name,
581
- profileName: agent.permissionProfile ?? "",
582
- projectScoped: Boolean(agent.permissionProfile) && (agent.source === "project" || agent.override?.scope === "project"),
583
- trustedCwd: trustedProjectCwd(ctx),
584
- effectiveCwd: path.resolve(childCwd),
585
- messageStyle: "executor",
586
- });
582
+ return projectScopedProfileTrustError({
583
+ kind: "permission",
584
+ agentName: agent.name,
585
+ profileName: agent.permissionProfile ?? "",
586
+ projectScoped: Boolean(agent.permissionProfile) && (agent.source === "project" || agent.override?.scope === "project"),
587
+ trustedCwd: trustedProjectCwd(ctx),
588
+ effectiveCwd: path.resolve(childCwd),
589
+ messageStyle: "executor",
590
+ });
587
591
  }
588
592
 
589
593
  export function removeForegroundControlIfIdle(state: SubagentState, runId: string, trackRetainedNestedRoute?: (rootRunId: string) => void): boolean {
@@ -596,6 +600,7 @@ export function removeForegroundControlIfIdle(state: SubagentState, runId: strin
596
600
  console.error(`Failed to retain live nested descendants for foreground run '${runId}':`, error);
597
601
  }
598
602
  }
603
+ retainNestedLookupRoute(state, control?.nestedRoute, control?.sessionId);
599
604
  state.foregroundControls.delete(runId);
600
605
  if (state.lastForegroundControlId === runId) state.lastForegroundControlId = null;
601
606
  return true;
@@ -841,8 +846,8 @@ function rememberForegroundRun(state: SubagentState, input: { modelResponseAlias
841
846
  ...(result.detachedReason ? { detachedReason: result.detachedReason } : {}),
842
847
  ...(result.acceptance ? { acceptance: result.acceptance } : {}),
843
848
  ...(Object.keys(resumeContract).length ? { resumeContract } : {}),
844
- ...(result.sandbox ? { sandbox: result.sandbox } : {}),
845
- ...(result.permissionProfile ? { permissionProfile: result.permissionProfile } : {}),
849
+ ...(result.sandbox ? { sandbox: result.sandbox } : {}),
850
+ ...(result.permissionProfile ? { permissionProfile: result.permissionProfile } : {}),
846
851
  ...(result.launchContractDigest ? { launchContractDigest: result.launchContractDigest } : {}),
847
852
  ...(input.extensionBindings ? { extensionBindings: input.extensionBindings } : {}),
848
853
  ...(input.requiredExtensions?.length ? { requiredExtensions: input.requiredExtensions } : {}),
@@ -925,8 +930,8 @@ function updateRememberedForegroundChild(state: SubagentState, input: { runId: s
925
930
  ...(input.result.transcriptError ? { transcriptError: input.result.transcriptError } : {}),
926
931
  ...(input.result.detachedReason ? { detachedReason: input.result.detachedReason } : {}),
927
932
  ...(input.result.acceptance ? { acceptance: input.result.acceptance } : {}),
928
- ...(input.result.sandbox ? { sandbox: input.result.sandbox } : {}),
929
- ...(input.result.permissionProfile ? { permissionProfile: input.result.permissionProfile } : {}),
933
+ ...(input.result.sandbox ? { sandbox: input.result.sandbox } : {}),
934
+ ...(input.result.permissionProfile ? { permissionProfile: input.result.permissionProfile } : {}),
930
935
  ...(input.result.launchContractDigest ? { launchContractDigest: input.result.launchContractDigest } : {}),
931
936
  ...(input.result.launchResolvedExtensions ? { launchResolvedExtensions: input.result.launchResolvedExtensions } : {}),
932
937
  ...(input.result.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: input.result.runtimeAcknowledgedExtensions } : {}),
@@ -996,8 +1001,8 @@ function resolveForegroundResumeTarget(params: SubagentParamsLike, state: Subage
996
1001
  sessionFile,
997
1002
  ...(child.model ? { model: child.model } : {}),
998
1003
  ...(child.thinking ? { thinking: child.thinking } : {}),
999
- ...(child.sandbox ? { sandbox: child.sandbox } : {}),
1000
- ...(child.permissionProfile ? { permissionProfile: child.permissionProfile } : {}),
1004
+ ...(child.sandbox ? { sandbox: child.sandbox } : {}),
1005
+ ...(child.permissionProfile ? { permissionProfile: child.permissionProfile } : {}),
1001
1006
  ...(child.launchContractDigest ? { launchContractDigest: child.launchContractDigest } : {}),
1002
1007
  ...(child.resumeContract ? { resumeContract: child.resumeContract } : {}),
1003
1008
  ...(child.extensionBindings ? { extensionBindings: normalizeExtensionBindings(child.extensionBindings)!.value } : {}),
@@ -1019,8 +1024,8 @@ type NestedResumeSourceTarget = {
1019
1024
  sessionFile: string;
1020
1025
  model?: string;
1021
1026
  thinking?: AgentConfig["thinking"];
1022
- sandbox?: string;
1023
- permissionProfile?: string;
1027
+ sandbox?: string;
1028
+ permissionProfile?: string;
1024
1029
  launchContractDigest?: string;
1025
1030
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
1026
1031
  recoveryDescriptor?: SteeringRecoveryDescriptor;
@@ -1403,8 +1408,8 @@ function appendStepToAsyncChain(input: {
1403
1408
  currentModelProvider: parentModel?.provider,
1404
1409
  currentModel: parentModel,
1405
1410
  modelScope: discoveredForAppend.modelScope,
1406
- projectTrusted: currentProjectTrusted(input.ctx),
1407
- ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
1411
+ projectTrusted: currentProjectTrusted(input.ctx),
1412
+ ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
1408
1413
  modelResponseAliases: input.deps.config.modelResponseAliases,
1409
1414
  interactive: input.ctx.hasUI,
1410
1415
  permissions: input.deps.config.permissions,
@@ -1556,12 +1561,57 @@ function resolveNestedResumeTarget(match: ResolvedSubagentRunId & { kind: "neste
1556
1561
  index: 0,
1557
1562
  cwd: asyncDir ? path.dirname(asyncDir) : undefined,
1558
1563
  sessionFile: validateNestedSessionFile(run, trustedSessionRoots),
1559
- ...(recoveryDescriptor?.sandbox ?? run.sandbox ? { sandbox: recoveryDescriptor?.sandbox ?? run.sandbox } : {}),
1564
+ ...(recoveryDescriptor?.sandbox ?? run.sandbox ? { sandbox: recoveryDescriptor?.sandbox ?? run.sandbox } : {}),
1560
1565
  ...(run.capabilityCeiling ? { capabilityCeiling: run.capabilityCeiling } : {}),
1561
1566
  ...(recoveryDescriptor ? { recoveryDescriptor } : {}),
1562
1567
  });
1563
1568
  }
1564
1569
 
1570
+ function resolveNestedExternalJobResumeTarget(match: ResolvedSubagentRunId & { kind: "nested" }, params: SubagentParamsLike, deps: ExecutorDeps): AsyncResumeSourceTarget | undefined {
1571
+ const run = match.match.run;
1572
+ if (run.state === "stopped") return undefined;
1573
+ const asyncDir = resolveNestedAsyncDir(match.match.rootRunId, run);
1574
+ if (!asyncDir) return undefined;
1575
+ const status = readNestedRunStatus(asyncDir, run);
1576
+ const steps = status?.steps ?? [];
1577
+ const step = steps[params.index ?? 0];
1578
+ if (!step) {
1579
+ // An index outside an external-job run gets the async resolver's index error instead of a Pi revive.
1580
+ if (params.index === undefined || !steps.some((candidate) => candidate.runner?.type === "external-job")) return undefined;
1581
+ } else if (!step.runner) {
1582
+ // Pi steps record no runner, and neither does a launch status before the runner starts.
1583
+ // A session file means a Pi run; otherwise the agent definition says what the step runs.
1584
+ if (nestedRunSessionFile(run)) return undefined;
1585
+ const agent = deps.discoverAgents(status?.cwd ?? deps.state.baseCwd, resolveExecutionAgentScope(params.agentScope)).agents.find((candidate) => candidate.name === step.agent);
1586
+ if (agent?.runner?.type === "external-job") throw new Error(externalJobWithoutMetadataMessage(run.id));
1587
+ return undefined;
1588
+ } else if (step.runner.type !== "external-job") {
1589
+ return undefined;
1590
+ }
1591
+ // External-job runs have no Pi session, so resume them as a provider follow-up from their own run directory.
1592
+ const target = resolveAsyncResumeTarget(compactOptional<Parameters<typeof resolveAsyncResumeTarget>[0]>({ dir: asyncDir, index: params.index }), nestedRunScope(match.match.rootRunId), { requireSessionFile: false });
1593
+ if (target.kind === "live") throw new Error(externalJobStillRunningMessage(target.runId));
1594
+ return { source: "async", ...target };
1595
+ }
1596
+
1597
+ function readNestedRunStatus(asyncDir: string, run: NestedRunSummary): AsyncStatus | null {
1598
+ try {
1599
+ return readStatus(asyncDir);
1600
+ } catch (error) {
1601
+ // A nested Pi run revives from its session file, so its unreadable status file must not block it.
1602
+ if (nestedRunSessionFile(run)) return null;
1603
+ throw error;
1604
+ }
1605
+ }
1606
+
1607
+ function externalJobStillRunningMessage(runId: string): string {
1608
+ return `External-job run '${runId}' is still running. Wait for completion, then use subagent({ action: "resume", id: "${runId}", message: "..." }).`;
1609
+ }
1610
+
1611
+ function externalJobWithoutMetadataMessage(runId: string): string {
1612
+ return `External-job run '${runId}' has no persisted provider metadata. Cannot follow up without the parent provider job id.`;
1613
+ }
1614
+
1565
1615
  async function waitForNestedControlResult(target: ResolvedSubagentRunId & { kind: "nested" }, requestId: string, ignoredFiles: ReadonlySet<string>, timeoutMs = 1_000) {
1566
1616
  const deadline = Date.now() + timeoutMs;
1567
1617
  while (Date.now() < deadline) {
@@ -1724,12 +1774,12 @@ async function resumeExternalJobFollowUp(input: {
1724
1774
  absoluteDeadlineAt?: number;
1725
1775
  }): Promise<AgentToolResult<Details>> {
1726
1776
  if (input.target.kind === "live" || input.target.state === "running" || input.target.state === "queued") {
1727
- return { content: [{ type: "text", text: `External-job run '${input.target.runId}' is still running. Wait for completion, then use subagent({ action: "resume", id: "${input.target.runId}", message: "..." }).` }], isError: true, details: { mode: "management", results: [] } };
1777
+ return { content: [{ type: "text", text: externalJobStillRunningMessage(input.target.runId) }], isError: true, details: { mode: "management", results: [] } };
1728
1778
  }
1729
1779
  const runner = input.target.runner;
1730
1780
  const externalJob = input.target.externalJob;
1731
1781
  if (runner?.type !== "external-job") return { content: [{ type: "text", text: "Internal error: external-job follow-up was requested for a non-external-job runner." }], isError: true, details: { mode: "management", results: [] } };
1732
- if (!externalJob) return { content: [{ type: "text", text: `External-job run '${input.target.runId}' has no persisted provider metadata. Cannot follow up without the parent provider job id.` }], isError: true, details: { mode: "management", results: [] } };
1782
+ if (!externalJob) return { content: [{ type: "text", text: externalJobWithoutMetadataMessage(input.target.runId) }], isError: true, details: { mode: "management", results: [] } };
1733
1783
  if (externalJob.provider !== runner.provider) return { content: [{ type: "text", text: `External-job run '${input.target.runId}' has mismatched provider metadata. Refusing to follow up.` }], isError: true, details: { mode: "management", results: [] } };
1734
1784
  if (!externalJobOptionsEqual(externalJob.options, runner.options)) return { content: [{ type: "text", text: `External-job run '${input.target.runId}' has mismatched provider options. Refusing to follow up.` }], isError: true, details: { mode: "management", results: [] } };
1735
1785
  if (!externalJob.providerJobId) return { content: [{ type: "text", text: `External-job run '${input.target.runId}' has no parent provider job id. Cannot follow up without reopening or redispatching, so this fails closed.` }], isError: true, details: { mode: "management", results: [] } };
@@ -1741,10 +1791,13 @@ async function resumeExternalJobFollowUp(input: {
1741
1791
  const requestDigest = externalJobFollowUpRequestDigest({ provider: runner.provider, parentProviderJobId: externalJob.providerJobId, promptDigest, options: runner.options });
1742
1792
  const requestId = externalJobFollowUpRequestId(requestDigest);
1743
1793
  const runId = externalJobFollowUpRunId(requestDigest);
1744
- const asyncDir = path.join(DIRS.async, runId);
1794
+ // A child launches the follow-up under its nested route, so look for an earlier one where it would be.
1795
+ const nestedRoute = inheritedNestedRoute(input.deps);
1796
+ const runRoots = nestedRoute ? nestedRunScope(nestedRoute.rootRunId) : { asyncDirRoot: DIRS.async, resultsDir: DIRS.results };
1797
+ const asyncDir = path.join(runRoots.asyncDirRoot, runId);
1745
1798
  const currentSessionId = input.deps.state.currentSessionId;
1746
1799
  if (!currentSessionId) return { content: [{ type: "text", text: "External-job follow-up requires an active parent session." }], isError: true, details: { mode: "management", results: [] } };
1747
- if (fs.existsSync(asyncDir) || fs.existsSync(resultFilePath(DIRS.results, runId))) {
1800
+ if (fs.existsSync(asyncDir) || fs.existsSync(resultFilePath(runRoots.resultsDir, runId))) {
1748
1801
  return externalJobFollowUpStarted({ sourceRunId: input.target.runId, runId, asyncDir, duplicate: true, interactive: input.ctx.hasUI });
1749
1802
  }
1750
1803
 
@@ -1837,6 +1890,8 @@ function resolveRequestedResumeTarget(params: SubagentParamsLike, deps: Executor
1837
1890
  if (resolved?.kind === "nested") {
1838
1891
  if (params.chain?.length) throw new Error("Attaching a running subagent as a chain root is currently available for top-level async runs only.");
1839
1892
  if (resolved.match.run.state === "running" || resolved.match.run.state === "queued") return { kind: "live-nested", target: resolved };
1893
+ const externalJobTarget = resolveNestedExternalJobResumeTarget(resolved, params, deps);
1894
+ if (externalJobTarget) return externalJobTarget;
1840
1895
  const trustedSessionRoots = [
1841
1896
  ...(deps.config.defaultSessionDir ? [path.resolve(deps.expandTilde(deps.config.defaultSessionDir))] : []),
1842
1897
  ...(parentSessionFile ? [deps.getSubagentSessionRoot(parentSessionFile)] : []),
@@ -1854,6 +1909,7 @@ async function resumeAsyncRun(input: {
1854
1909
  parentModel?: ParentModel;
1855
1910
  absoluteDeadlineAt?: number;
1856
1911
  signal?: AbortSignal;
1912
+ onLaunch?: (launch: { agent: string; sessionName?: string; sessionFile?: string; async: boolean; runId?: string }) => void;
1857
1913
  }): Promise<AgentToolResult<Details>> {
1858
1914
  const followUp = (input.params.message ?? input.params.task ?? "").trim();
1859
1915
  const attachChain = (input.params.chain?.length ?? 0) > 0 ? input.params.chain as ChainStep[] : undefined;
@@ -1922,7 +1978,7 @@ async function resumeAsyncRun(input: {
1922
1978
  const discoveredAgents = discovered.agents;
1923
1979
  const unknownAgentDiagnosticContext = diagnosticContextFromDiscovery(discovered, effectiveCwd, scope);
1924
1980
  const modelScope = discovered.modelScope;
1925
- const sessionName = resolveIntercomSessionTarget(input.deps.pi.getSessionName(), input.ctx.sessionManager.getSessionId());
1981
+ const sessionName = resolveIntercomSessionTarget(input.deps.childRuntime?.intercomSessionName ?? input.deps.pi.getSessionName(), input.ctx.sessionManager.getSessionId());
1926
1982
  const recoveryDescriptor = "recoveryDescriptor" in target ? target.recoveryDescriptor : undefined;
1927
1983
  const recoveryContext = recoveryDescriptor?.context ?? (input.params.context === "profile" ? undefined : input.params.context);
1928
1984
  const intercomBridge = resolveIntercomBridge({
@@ -1963,7 +2019,7 @@ async function resumeAsyncRun(input: {
1963
2019
  }
1964
2020
  if (target.source === "async" && target.runner?.type === "external-job") {
1965
2021
  if (attachChain) return { content: [{ type: "text", text: "External-job follow-up does not support chain attachment. Use action='resume' with message instead." }], isError: true, details: { mode: "management", results: [] } };
1966
- return resumeExternalJobFollowUp({
2022
+ const resumed = await resumeExternalJobFollowUp({
1967
2023
  target,
1968
2024
  followUp,
1969
2025
  baseAgentConfig,
@@ -1977,6 +2033,9 @@ async function resumeAsyncRun(input: {
1977
2033
  parentSessionFile,
1978
2034
  absoluteDeadlineAt: input.absoluteDeadlineAt,
1979
2035
  });
2036
+ const resumedRunId = resumed.details.runId ?? resumed.details.asyncId;
2037
+ if (!resumed.isError && resumedRunId) input.onLaunch?.({ agent: target.agent, async: true, runId: resumedRunId });
2038
+ return resumed;
1980
2039
  }
1981
2040
 
1982
2041
  if (attachChain) {
@@ -2043,13 +2102,13 @@ async function resumeAsyncRun(input: {
2043
2102
  currentModelProvider: parentModel?.provider,
2044
2103
  currentModel: parentModel,
2045
2104
  modelScope,
2046
- projectTrusted: currentProjectTrusted(input.ctx),
2047
- ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
2105
+ projectTrusted: currentProjectTrusted(input.ctx),
2106
+ ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
2048
2107
  modelResponseAliases: input.deps.config.modelResponseAliases,
2049
2108
  interactive: input.ctx.hasUI,
2050
- permissions: input.deps.config.permissions,
2109
+ permissions: input.deps.config.permissions,
2051
2110
  childRuntime: input.deps.childRuntime,
2052
- }),
2111
+ }),
2053
2112
  availableModels,
2054
2113
  cwd: effectiveCwd,
2055
2114
  maxOutput: input.params.maxOutput,
@@ -2085,6 +2144,7 @@ async function resumeAsyncRun(input: {
2085
2144
  return result;
2086
2145
  }
2087
2146
  const attachedId = result.details.asyncId ?? runId;
2147
+ input.onLaunch?.({ agent: target.agent, ...(target.sessionFile ? { sessionFile: target.sessionFile } : {}), async: true, runId: attachedId });
2088
2148
  const lines = [
2089
2149
  `Attached async subagent ${target.runId} as the first step of a new chain.`,
2090
2150
  `Chain run: ${attachedId}`,
@@ -2102,11 +2162,14 @@ async function resumeAsyncRun(input: {
2102
2162
  if (!revivalSessionFile) {
2103
2163
  return { content: [{ type: "text", text: `Async run '${target.runId}' child ${target.index} does not have a persisted session file to resume from.` }], isError: true, details: { mode: "management", results: [] } };
2104
2164
  }
2165
+ if (input.params.baseRef !== undefined && "managedWorktree" in target && target.managedWorktree === true) {
2166
+ return { content: [{ type: "text", text: "Cannot resume with baseRef: retained managed-worktree children continue in their existing worktree. Start a new worktree run from that base ref instead." }], isError: true, details: { mode: "management", results: [] } };
2167
+ }
2105
2168
  if (target.source === "async" && asyncReviveRequiresRecoveryDescriptor(target)) {
2106
2169
  return { content: [{ type: "text", text: `Async child '${target.runId}' is missing its required run fan-out recovery identity. Start a new run instead.` }], isError: true, details: { mode: "management", results: [] } };
2107
2170
  }
2108
- if (input.params.baseRef !== undefined && "managedWorktree" in target && target.managedWorktree === true) {
2109
- return { content: [{ type: "text", text: "Cannot resume with baseRef: retained managed-worktree children continue in their existing worktree. Start a new worktree run from that base ref instead." }], isError: true, details: { mode: "management", results: [] } };
2171
+ if (target.source === "nested" && !target.recoveryDescriptor) {
2172
+ return { content: [{ type: "text", text: `Nested child '${target.runId}' is missing its required recovery identity. Start a new run instead.` }], isError: true, details: { mode: "management", results: [] } };
2110
2173
  }
2111
2174
  const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : baseAgentConfig;
2112
2175
  const agentConfig = intercomBridge.active ? applyIntercomBridgeToAgent(recoveryAgentConfig, intercomBridge) : recoveryAgentConfig;
@@ -2160,7 +2223,7 @@ async function resumeAsyncRun(input: {
2160
2223
  goal: effectiveFollowUp,
2161
2224
  agentConfig,
2162
2225
  recoveryAgentConfig,
2163
- ...(recoveryDescriptor?.sandbox ?? ("sandbox" in target ? target.sandbox : undefined) ? { sandbox: recoveryDescriptor?.sandbox ?? ("sandbox" in target ? target.sandbox : undefined) } : {}),
2226
+ ...(recoveryDescriptor?.sandbox ?? ("sandbox" in target ? target.sandbox : undefined) ? { sandbox: recoveryDescriptor?.sandbox ?? ("sandbox" in target ? target.sandbox : undefined) } : {}),
2164
2227
  ctx: compactOptional<Parameters<typeof executeAsyncSingle>[1]["ctx"]>({
2165
2228
  pi: input.deps.pi,
2166
2229
  cwd: input.requestCwd,
@@ -2169,8 +2232,8 @@ async function resumeAsyncRun(input: {
2169
2232
  currentModelProvider: parentModel?.provider,
2170
2233
  currentModel: parentModel,
2171
2234
  modelScope,
2172
- projectTrusted: currentProjectTrusted(input.ctx),
2173
- ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
2235
+ projectTrusted: currentProjectTrusted(input.ctx),
2236
+ ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
2174
2237
  // Absence in the retained contract is meaningful; never acquire current aliases.
2175
2238
  modelResponseAliases: recoveryDescriptor ? recoveryDescriptor.modelResponseAliases : foregroundContract?.modelResponseAliases,
2176
2239
  interactive: input.ctx.hasUI,
@@ -2229,15 +2292,19 @@ async function resumeAsyncRun(input: {
2229
2292
  ...(input.params.timeoutMs !== undefined ? { timeoutMs: input.params.timeoutMs } : {}),
2230
2293
  ...(input.absoluteDeadlineAt !== undefined ? { absoluteDeadlineAt: input.absoluteDeadlineAt } : {}),
2231
2294
  ...(input.params.toolBudget !== undefined ? { toolBudget: input.params.toolBudget } : {}),
2232
- capabilityCeiling: intersectSubagentCapabilityCeilings("capabilityCeiling" in target ? target.capabilityCeiling : undefined, recoveryDescriptor?.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(input.deps.state.currentSessionId)),
2295
+ // Recovery descriptors, remembered foreground runs, and current workflow roots
2296
+ // preserve parent authority before the selected agent's descendant ceiling.
2297
+ capabilityCeiling: intersectSubagentCapabilityCeilings(recoveryDescriptor?.capabilityCeiling ?? (target.source === "foreground" || (target.source === "async" && target.mode === "workflow") ? target.capabilityCeiling : undefined), resolveCurrentSubagentCapabilityCeiling(input.deps.state.currentSessionId)),
2233
2298
  runFanoutBudget: input.params.runFanoutBudget ?? recoveryDescriptor?.runFanoutBudget ?? createRunFanoutBudget(runId, resolveMaxSubagentSpawnsPerRun(input.deps.config.maxSubagentSpawnsPerRun)),
2234
2299
  parentWorkflowRunId: input.params.workflowParentRunId,
2235
2300
  workflowKey: input.params.workflowKey,
2236
2301
  activeAsyncCapacity,
2237
2302
  }));
2303
+ const notifyLaunch = (): void => input.onLaunch?.({ agent: target.agent, sessionFile: revivalSessionFile, async: true, runId });
2238
2304
  if (result.isError) {
2239
2305
  const startedStatus = readStatus(revivalAsyncDir);
2240
2306
  if (input.params.workflowParentRunId !== undefined && startedStatus?.runId === runId && startedStatus.processTerminal?.runnerProcessInstanceId) {
2307
+ notifyLaunch();
2241
2308
  return {
2242
2309
  ...result,
2243
2310
  details: {
@@ -2252,6 +2319,7 @@ async function resumeAsyncRun(input: {
2252
2319
  activeAsyncCapacity?.rollback();
2253
2320
  return result;
2254
2321
  }
2322
+ notifyLaunch();
2255
2323
  for (const brief of queuedBriefs) fs.rmSync(brief.path, { force: true });
2256
2324
  if (queuedBriefs.length > 0 && sourceAsyncDir) {
2257
2325
  const sourceStatus = readStatus(sourceAsyncDir);
@@ -2275,6 +2343,7 @@ async function resumeAsyncRun(input: {
2275
2343
  input.signal?.removeEventListener("abort", stopOnAbort);
2276
2344
  }
2277
2345
  if (completed.importedPublication) removeWorkflowAwaitedResult(asyncDir, resultPath, revivedId, completed.importedPublication);
2346
+ emitWorkflowAwaitedChildComplete(input.deps.pi, input.deps.state, revivedId, asyncDir, input.params.workflowParentRunId, completed);
2278
2347
  const usage = importedAsyncRootUsage(completed);
2279
2348
  const childResult: SingleResult = {
2280
2349
  index: 0,
@@ -2575,11 +2644,15 @@ function validateExecutionInput(
2575
2644
  context: UnknownAgentDiagnosticContext,
2576
2645
  ): AgentToolResult<Details> | null {
2577
2646
  if (Number(hasChain) + Number(hasTasks) + Number(hasSingle) !== 1) {
2647
+ const agentList = agents.map((a) => a.name).join(", ") || "none";
2648
+ const noMode = !hasChain && !hasTasks && !hasSingle;
2578
2649
  return {
2579
2650
  content: [
2580
2651
  {
2581
2652
  type: "text",
2582
- text: `Provide exactly one mode. Agents: ${agents.map((a) => a.name).join(", ") || "none"}`,
2653
+ text: noMode && typeof params.workflowKey === "string"
2654
+ ? `Workflow child '${params.workflowKey}' has no agent. Pass { key, agent, task }. Agents: ${agentList}`
2655
+ : `Provide exactly one mode. Agents: ${agentList}`,
2583
2656
  },
2584
2657
  ],
2585
2658
  isError: true,
@@ -2832,6 +2905,19 @@ function buildRequestedModeError(params: SubagentParamsLike, message: string): A
2832
2905
  );
2833
2906
  }
2834
2907
 
2908
+ function buildWorkflowValidationResult(
2909
+ validation: ReturnType<typeof validateWorkflowScript>,
2910
+ mode: "management" | "workflow",
2911
+ preflight?: import("../../shared/types.ts").WorkflowPreflight,
2912
+ ): AgentToolResult<Details> {
2913
+ const payload = preflight ? { ...validation, preflight } : validation;
2914
+ return {
2915
+ content: [{ type: "text", text: JSON.stringify(payload) }],
2916
+ ...(validation.ok ? {} : { isError: true }),
2917
+ details: { mode, results: [] },
2918
+ };
2919
+ }
2920
+
2835
2921
  function applySingleAgentLaunchDefaults(params: SubagentParamsLike, agents: AgentConfig[]): SubagentParamsLike {
2836
2922
  if ((params.chain?.length ?? 0) > 0 || (params.tasks?.length ?? 0) > 0 || !params.agent) return params;
2837
2923
  const agent = agents.find((candidate) => candidate.name === params.agent);
@@ -3095,7 +3181,7 @@ function resolveStaticLaunchSummary(input: {
3095
3181
  agent: input.agent,
3096
3182
  ...(model ? { model } : {}),
3097
3183
  ...(thinking ? { thinking } : {}),
3098
- ...(agentConfig?.sandbox ? { sandbox: agentConfig.sandbox } : {}),
3184
+ ...(agentConfig?.sandbox ? { sandbox: agentConfig.sandbox } : {}),
3099
3185
  };
3100
3186
  }
3101
3187
 
@@ -3269,10 +3355,41 @@ function removeWorkflowAwaitedResult(asyncDir: string, resultPath: string, runId
3269
3355
  removeResultIndex(asyncDir, publication.sessionId, runId, publication.toolCallId);
3270
3356
  }
3271
3357
 
3358
+ function emitWorkflowAwaitedChildComplete(
3359
+ pi: ExtensionAPI,
3360
+ state: SubagentState,
3361
+ runId: string,
3362
+ asyncDir: string,
3363
+ parentWorkflowRunId: string | undefined,
3364
+ completed: Awaited<ReturnType<typeof waitForImportedAsyncRoot>>,
3365
+ ): void {
3366
+ let status: ReturnType<typeof readStatus> | undefined;
3367
+ try {
3368
+ status = readStatus(asyncDir);
3369
+ } catch (error) {
3370
+ console.error(`Failed to read awaited workflow child status for ${runId}; emitting completion with fallback metadata:`, error);
3371
+ }
3372
+ pi.events.emit(SUBAGENT_ASYNC_COMPLETE_EVENT, {
3373
+ id: runId,
3374
+ runId,
3375
+ sessionId: status?.sessionId ?? completed.importedPublication?.sessionId ?? state.currentSessionId,
3376
+ completionOwnerId: status?.completionOwnerId ?? state.completionOwnerId ?? currentCompletionOwnerId(),
3377
+ asyncDir,
3378
+ agent: completed.agent,
3379
+ mode: "single",
3380
+ state: completed.stopped ? "stopped" : completed.success ? "complete" : "failed",
3381
+ success: completed.success,
3382
+ timestamp: Date.now(),
3383
+ triggerTurn: false,
3384
+ awaitedByWorkflow: true,
3385
+ parentWorkflowRunId,
3386
+ });
3387
+ }
3388
+
3272
3389
  async function waitForWorkflowAsyncSingleResult(
3273
3390
  params: SubagentParamsLike,
3274
3391
  launchResult: AgentToolResult<Details>,
3275
- options: { runId: string; task: string; signal?: AbortSignal; state: SubagentState; kill?: ExecutorDeps["kill"] },
3392
+ options: { runId: string; task: string; signal?: AbortSignal; state: SubagentState; pi: ExtensionAPI; kill?: ExecutorDeps["kill"] },
3276
3393
  ): Promise<AgentToolResult<Details>> {
3277
3394
  if (params.workflowAwaitAsync !== true || !launchResult.details.asyncDir) return launchResult;
3278
3395
  const asyncDir = launchResult.details.asyncDir;
@@ -3290,6 +3407,7 @@ async function waitForWorkflowAsyncSingleResult(
3290
3407
  options.signal?.removeEventListener("abort", stopOnAbort);
3291
3408
  }
3292
3409
  if (completed.importedPublication) removeWorkflowAwaitedResult(asyncDir, resultPath, options.runId, completed.importedPublication);
3410
+ emitWorkflowAwaitedChildComplete(options.pi, options.state, options.runId, asyncDir, params.workflowParentRunId, completed);
3293
3411
  const usage = importedAsyncRootUsage(completed);
3294
3412
  const childResult: SingleResult = omitUndefinedProperties({
3295
3413
  index: 0,
@@ -3370,9 +3488,9 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3370
3488
  currentModelProvider: parentModel?.provider,
3371
3489
  currentModel: parentModel,
3372
3490
  modelScope: data.modelScope,
3373
- projectTrusted: currentProjectTrusted(ctx),
3374
- ...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
3375
- modelResponseAliases: deps.config.modelResponseAliases, interactive: ctx.hasUI,
3491
+ projectTrusted: currentProjectTrusted(ctx),
3492
+ ...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
3493
+ modelResponseAliases: deps.config.modelResponseAliases, interactive: ctx.hasUI,
3376
3494
  permissions: deps.config.permissions,
3377
3495
  childRuntime: deps.childRuntime,
3378
3496
  });
@@ -3392,18 +3510,18 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3392
3510
  details: { mode: "single" as const, results: [] },
3393
3511
  };
3394
3512
  }
3395
- const sandboxTrustError = params.worktree === true
3396
- ? sandboxProfileTrustError(a, ctx, path.join(effectiveCwd, ".pi-subagents-worktree"))
3397
- : sandboxProfileTrustError(a, ctx, effectiveCwd);
3398
- if (sandboxTrustError) {
3399
- return { content: [{ type: "text", text: sandboxTrustError }], isError: true, details: { mode: "single" as const, results: [] } };
3400
- }
3401
- const permissionProfileTrustErrorForAgent = params.worktree === true
3402
- ? permissionProfileTrustError(a, ctx, path.join(effectiveCwd, ".pi-subagents-worktree"))
3403
- : permissionProfileTrustError(a, ctx, effectiveCwd);
3404
- if (permissionProfileTrustErrorForAgent) {
3405
- return { content: [{ type: "text", text: permissionProfileTrustErrorForAgent }], isError: true, details: { mode: "single" as const, results: [] } };
3406
- }
3513
+ const sandboxTrustError = params.worktree === true
3514
+ ? sandboxProfileTrustError(a, ctx, path.join(effectiveCwd, ".pi-subagents-worktree"))
3515
+ : sandboxProfileTrustError(a, ctx, effectiveCwd);
3516
+ if (sandboxTrustError) {
3517
+ return { content: [{ type: "text", text: sandboxTrustError }], isError: true, details: { mode: "single" as const, results: [] } };
3518
+ }
3519
+ const permissionProfileTrustErrorForAgent = params.worktree === true
3520
+ ? permissionProfileTrustError(a, ctx, path.join(effectiveCwd, ".pi-subagents-worktree"))
3521
+ : permissionProfileTrustError(a, ctx, effectiveCwd);
3522
+ if (permissionProfileTrustErrorForAgent) {
3523
+ return { content: [{ type: "text", text: permissionProfileTrustErrorForAgent }], isError: true, details: { mode: "single" as const, results: [] } };
3524
+ }
3407
3525
  const rawOutput = params.output !== undefined ? params.output : a.output;
3408
3526
  const effectiveOutput = normalizeSingleOutputOverride(rawOutput, a.output);
3409
3527
  const effectiveOutputMode = params.outputMode ?? a.outputMode ?? "inline";
@@ -3497,7 +3615,7 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3497
3615
  lane: params.lane,
3498
3616
  workflowAwaitAsync: params.workflowAwaitAsync,
3499
3617
  }));
3500
- return waitForWorkflowAsyncSingleResult(params, asyncResult, { runId: id, task: params.task ?? "", signal: data.signal, state: deps.state, kill: deps.kill });
3618
+ return waitForWorkflowAsyncSingleResult(params, asyncResult, { runId: id, task: params.task ?? "", signal: data.signal, state: deps.state, pi: deps.pi, kill: deps.kill });
3501
3619
  }
3502
3620
 
3503
3621
  return null;
@@ -3964,16 +4082,16 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3964
4082
  return worktreeSetupError;
3965
4083
  }
3966
4084
  const singleCwd = worktreeSetup?.worktrees[0]?.agentCwd ?? sourceCwd;
3967
- const sandboxTrustError = sandboxProfileTrustError(agentConfig, ctx, singleCwd);
3968
- if (sandboxTrustError) {
3969
- if (worktreeSetup) cleanupWorktrees(worktreeSetup);
3970
- return { content: [{ type: "text", text: sandboxTrustError }], isError: true, details: { mode: "single", results: [] } };
3971
- }
3972
- const permissionProfileTrustErrorForLaunch = permissionProfileTrustError(agentConfig, ctx, singleCwd);
3973
- if (permissionProfileTrustErrorForLaunch) {
3974
- if (worktreeSetup) cleanupWorktrees(worktreeSetup);
3975
- return { content: [{ type: "text", text: permissionProfileTrustErrorForLaunch }], isError: true, details: { mode: "single", results: [] } };
3976
- }
4085
+ const sandboxTrustError = sandboxProfileTrustError(agentConfig, ctx, singleCwd);
4086
+ if (sandboxTrustError) {
4087
+ if (worktreeSetup) cleanupWorktrees(worktreeSetup);
4088
+ return { content: [{ type: "text", text: sandboxTrustError }], isError: true, details: { mode: "single", results: [] } };
4089
+ }
4090
+ const permissionProfileTrustErrorForLaunch = permissionProfileTrustError(agentConfig, ctx, singleCwd);
4091
+ if (permissionProfileTrustErrorForLaunch) {
4092
+ if (worktreeSetup) cleanupWorktrees(worktreeSetup);
4093
+ return { content: [{ type: "text", text: permissionProfileTrustErrorForLaunch }], isError: true, details: { mode: "single", results: [] } };
4094
+ }
3977
4095
  const cleanupSingleWorktree = async () => {
3978
4096
  if (!worktreeSetup) return;
3979
4097
  let admitted = false;
@@ -4089,12 +4207,10 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4089
4207
  remoteReads: foregroundMachine ? readsOverride : undefined,
4090
4208
  permissions: deps.config.permissions,
4091
4209
  runtimeSnapshotHost: deps.pi,
4092
- hostAvailableBuiltins: getHostBuiltinToolNames(deps.pi),
4093
4210
  parentSessionId: ctx.sessionManager.getSessionId() ?? undefined,
4094
- projectTrusted: currentProjectTrusted(ctx),
4095
- ...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
4211
+ projectTrusted: currentProjectTrusted(ctx),
4212
+ ...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
4096
4213
  requiredExtensions,
4097
- llmIntentArbiter: createTaskMutationArbiter({ model: ctx.model, modelRegistry: ctx.modelRegistry, sessionId: ctx.sessionManager.getSessionId() }),
4098
4214
  childRuntime: deps.childRuntime,
4099
4215
  onChildSession: (controls) => { childSessionControls = controls; },
4100
4216
  context: data.contextPolicy.contextForAgent(params.agent!),
@@ -4390,12 +4506,13 @@ export function bindMissionWorkflowChildAsyncLaunch(
4390
4506
  binding: MissionLaunchBinding | undefined,
4391
4507
  asyncByDefault: boolean,
4392
4508
  asyncId: string = randomUUID(),
4509
+ nestedRootRunId?: string,
4393
4510
  ): SubagentParamsLike {
4394
4511
  const requestedAsync = params.async ?? asyncByDefault;
4395
4512
  if (!binding || !requestedAsync || params.clarify === true) return params;
4396
4513
  const id = asyncId.trim();
4397
4514
  if (!id || path.basename(id) !== id) throw new Error("workflow child async id must be a single path segment");
4398
- writeMissionAsyncBinding(path.join(DIRS.async, id), binding);
4515
+ writeMissionAsyncBinding(path.join(nestedRootRunId ? nestedRunScope(nestedRootRunId).asyncDirRoot : DIRS.async, id), binding);
4399
4516
  return { ...params, workflowChildAsyncId: id };
4400
4517
  }
4401
4518
 
@@ -4406,8 +4523,9 @@ function workflowChildResult(
4406
4523
  resumeState?: SubagentState,
4407
4524
  forcedTerminalOutcome?: WorkflowTerminalOutcome,
4408
4525
  ): WorkflowScriptChildResult {
4526
+ const running = missionWorkflowChildStatus(result) === "running";
4409
4527
  const receiptOutput = result.content.map((part) => part.type === "text" ? part.text : "").filter(Boolean).join("\n");
4410
- const output = result.details.results.length === 1 && result.details.results[0]?.finalOutput !== undefined
4528
+ const output = running ? "" : result.details.results.length === 1 && result.details.results[0]?.finalOutput !== undefined
4411
4529
  ? result.details.results[0].finalOutput
4412
4530
  : receiptOutput;
4413
4531
  const childError = result.details.results.map((child) => child.error).find((error): error is string => Boolean(error));
@@ -4428,7 +4546,7 @@ function workflowChildResult(
4428
4546
  ? { state: "partial" as const, reason: "budget_exhausted" as const }
4429
4547
  : undefined);
4430
4548
  const acceptanceRecovery = result.details.results.find((child) => child.acceptance?.recovery)?.acceptance?.recovery;
4431
- const ok = result.isError !== true && !detached && !interrupted && !stopped && acceptanceRecovery === undefined;
4549
+ const ok = result.isError !== true && !running && !detached && !interrupted && !stopped && acceptanceRecovery === undefined;
4432
4550
  const artifactPaths = new Set<string>();
4433
4551
  if (result.details.asyncDir) artifactPaths.add(result.details.asyncDir);
4434
4552
  if (result.details.parallelHandoff?.path) artifactPaths.add(result.details.parallelHandoff.path);
@@ -4458,6 +4576,8 @@ function workflowChildResult(
4458
4576
  const resolvedContext = result.details.context ?? (resolvedContexts.length === 1 ? resolvedContexts[0] : resolvedContexts.length > 1 ? "mixed" : undefined);
4459
4577
  const outputReference = result.details.results.find((child) => child.savedOutputPath)?.savedOutputPath
4460
4578
  ?? result.details.results.find((child) => child.outputReference?.path)?.outputReference?.path;
4579
+ const outputArtifactPath = running ? undefined : result.details.parallelHandoff?.path
4580
+ ?? result.details.results.find((child) => child.artifactPaths?.outputPath)?.artifactPaths?.outputPath;
4461
4581
  const outputPathMapping = typeof childParams.task === "string" ? outputPathMappingFromTask(childParams.task, outputReference) : undefined;
4462
4582
  const externalResult = result.details.results.length === 1 && result.details.results[0]?.runner?.type === "external-cli" ? result.details.results[0] : undefined;
4463
4583
  const externalStatus = result.details.asyncDir ? readStatus(result.details.asyncDir) : undefined;
@@ -4471,12 +4591,14 @@ function workflowChildResult(
4471
4591
  return {
4472
4592
  key,
4473
4593
  ok,
4594
+ ...(running ? { state: "running" as const } : {}),
4595
+ ...(result.details.asyncDir ? { asyncDir: result.details.asyncDir } : {}),
4474
4596
  ...(lane ? { lane } : {}),
4475
4597
  ...(terminalOutcome ? { terminalOutcome } : {}),
4476
4598
  ...(resolvedAgents.length === 1 ? { agent: resolvedAgents[0] } : {}),
4477
4599
  ...(runId ? { runId } : {}),
4478
4600
  output,
4479
- ...(!ok ? { error: failureError } : {}),
4601
+ ...(!ok && !running ? { error: failureError } : {}),
4480
4602
  ...(detached ? { detached: true } : {}),
4481
4603
  ...(interrupted ? { interrupted: true } : {}),
4482
4604
  ...(stopped ? { stopped: true } : {}),
@@ -4484,6 +4606,7 @@ function workflowChildResult(
4484
4606
  ...(requestedContext ? { requestedContext } : {}),
4485
4607
  ...(resolvedContext ? { resolvedContext } : {}),
4486
4608
  ...(outputReference ? { outputReference } : {}),
4609
+ ...(outputArtifactPath ? { outputArtifactPath } : {}),
4487
4610
  ...(acceptanceRecovery ? { recovery: acceptanceRecovery } : {}),
4488
4611
  ...(outputPathMapping ? { outputPathMapping } : {}),
4489
4612
  ...(externalAdapter ? { externalAdapter } : {}),
@@ -4505,6 +4628,18 @@ function workflowChildAccountingFields(child: WorkflowScriptChildResult): { usag
4505
4628
  };
4506
4629
  }
4507
4630
 
4631
+ function workflowRunningChildrenSummary(children: WorkflowScriptChildResult[]): string {
4632
+ const running = children.filter((child) => child.state === "running");
4633
+ return running.length ? `${running.length} child ${running.length === 1 ? "run remains" : "runs remain"} running or uncollected: ${running.map((child) => `${child.key}=${child.runId}`).join(", ")}. These launch receipts contain no final child results.` : "";
4634
+ }
4635
+
4636
+ function workflowResultChildren(children: WorkflowScriptChildResult[], status: AsyncStatus, includeFailureFields: boolean) {
4637
+ return children.map((child) => {
4638
+ const sessionName = status.steps?.find((step) => step.workflowKey === child.key)?.sessionName;
4639
+ return { workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), ...(sessionName ? { sessionName } : {}), ...workflowChildAccountingFields(child), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, ...(child.state === "running" ? { state: "running" } : { success: child.ok }), ...(child.asyncDir ? { asyncDir: child.asyncDir } : {}), ...(child.outputReference ? { outputReference: child.outputReference } : {}), ...(includeFailureFields && child.terminalOutcome ? { terminalOutcome: child.terminalOutcome } : {}), ...(child.outputPathMapping ? { outputPathMapping: child.outputPathMapping } : {}), ...(child.stopped ? { stopped: true } : {}), ...(child.interrupted ? { interrupted: true } : {}), ...(includeFailureFields && child.detached && status.state !== "complete" ? { detached: true } : {}), ...(child.outputArtifactPath || child.outputReference ? { artifactPaths: { outputPath: child.outputArtifactPath ?? child.outputReference } } : {}) };
4640
+ });
4641
+ }
4642
+
4508
4643
  function workflowOutputPathMappingSummary(children: WorkflowScriptChildResult[]): string {
4509
4644
  const mappings = children.flatMap((child) => child.outputPathMapping
4510
4645
  ? [`'${child.key}': requested ${child.outputPathMapping.requestedPath} -> saved ${child.outputPathMapping.savedPath}`]
@@ -4672,7 +4807,7 @@ function workflowFailureMessage(error: unknown, workflowRunId: string, children:
4672
4807
  if (children.length === 0 && text.includes(validationPrefix)) {
4673
4808
  return `Workflow '${workflowRunId}' validation failed before child launch; no children launched.${text.slice(text.indexOf(validationPrefix) + validationPrefix.length)}`;
4674
4809
  }
4675
- return text;
4810
+ return [text, workflowRunningChildrenSummary(children)].filter(Boolean).join(" ");
4676
4811
  }
4677
4812
 
4678
4813
  export async function steerWorkflowChildByKey(input: {
@@ -4889,6 +5024,15 @@ function normalizeGateParams(params: SubagentParamsLike): GateParamsNormalizatio
4889
5024
  return { ok: true, params: { ...rest, ...(normalized.acceptance !== undefined ? { acceptance: normalized.acceptance } : {}) } };
4890
5025
  }
4891
5026
 
5027
+ function describeTypedVerifyOutputSchemaConflict(effective: SubagentParamsLike, requested: SubagentParamsLike): string | undefined {
5028
+ if (!acceptanceHasTypedVerify(effective.acceptance)) return undefined;
5029
+ if (effective.outputSchema === undefined || effective.outputSchema === false) return undefined;
5030
+ const agent = effective.agent ?? "?";
5031
+ const schemaSource = requested.outputSchema !== undefined && requested.outputSchema !== false ? "outputSchema" : `agent '${agent}' outputSchema`;
5032
+ const verifySource = requested.gate !== undefined ? "gate.output" : requested.acceptance !== undefined ? "acceptance.verify" : `agent '${agent}' defaultAcceptance`;
5033
+ return `${verifySource}: ${TYPED_VERIFY_OUTPUT_SCHEMA_CONFLICT.replace("with outputSchema", `with ${schemaSource}`)}`;
5034
+ }
5035
+
4892
5036
  function formatWorkflowValue(value: unknown): string {
4893
5037
  if (value === undefined) return "(undefined)";
4894
5038
  if (typeof value === "string") return value;
@@ -5131,12 +5275,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5131
5275
  const validation = validateWorkflowScript(requestParams.workflowScript ?? "", {
5132
5276
  maxSubagentSpawnsPerRun: requestParams.maxSubagentSpawnsPerRun ?? resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun),
5133
5277
  });
5134
- const payload = workflowPreflight ? { ...validation, preflight: workflowPreflight } : validation;
5135
- return {
5136
- content: [{ type: "text", text: JSON.stringify(payload) }],
5137
- ...(validation.ok ? {} : { isError: true }),
5138
- details: { mode: "management", results: [] },
5139
- };
5278
+ return buildWorkflowValidationResult(validation, "management", workflowPreflight);
5140
5279
  }
5141
5280
  const normalizedAction = typeof requestParams.action === "string" ? requestParams.action.trim() : requestParams.action;
5142
5281
  if (normalizedAction === "resume" && requestParams.extensionBindings !== undefined) return buildRequestedModeError(requestParams, "extensionBindings is not supported with action='resume'; resume uses the original retained child binding.");
@@ -5151,14 +5290,15 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5151
5290
  const workflowArgsEvidence = requestParams.args === undefined ? undefined : { args: requestParams.args, argsDigest: stableJsonDigest(requestParams.args) };
5152
5291
  const workflowArgs = workflowArgsEvidence?.args;
5153
5292
  const workflowArgsDigest = workflowArgsEvidence?.argsDigest;
5154
- const spawnBudgetValidation = validateWorkflowScript(requestParams.workflowScript, {
5293
+ const workflowValidation = validateWorkflowScript(requestParams.workflowScript, {
5155
5294
  maxSubagentSpawnsPerRun: requestParams.maxSubagentSpawnsPerRun ?? resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun),
5156
5295
  });
5157
- const spawnBudgetErrors = spawnBudgetValidation.errors.filter((error) => error.kind === "spawn-budget");
5296
+ if (!workflowValidation.ok && publicExecution) return buildWorkflowValidationResult(workflowValidation, "workflow", workflowPreflight);
5297
+ const spawnBudgetErrors = workflowValidation.errors.filter((error) => error.kind === "spawn-budget");
5158
5298
  if (spawnBudgetErrors.length > 0) {
5159
- return buildRequestedModeError(requestParams, `workflowScript validation failed before child launch; no children launched. ${spawnBudgetErrors.map((error) => error.message).join(" ")}`);
5299
+ return buildRequestedModeError(requestParams, `Workflow '${_id}' validation failed before child launch; no children launched. ${spawnBudgetErrors.map((error) => error.message).join(" ")}`);
5160
5300
  }
5161
- for (const warning of spawnBudgetValidation.warnings ?? []) console.warn(`[pi-subagents] ${warning.message}`);
5301
+ for (const warning of workflowValidation.warnings ?? []) console.warn(`[pi-subagents] ${warning.message}`);
5162
5302
  const acceptanceErrors = validateAcceptanceInput(requestParams.acceptance);
5163
5303
  if (acceptanceErrors.length > 0) return buildRequestedModeError(requestParams, acceptanceErrors.join(" "));
5164
5304
  const foregroundWorkflowRunId = encodeIndexSegment(_id);
@@ -5316,6 +5456,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5316
5456
  ...(workflowSessionRoot ? { sessionRoot: workflowSessionRoot } : {}),
5317
5457
  ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}),
5318
5458
  pid: process.pid,
5459
+ ...(workflowCapabilityCeiling ? { admissionCapabilityCeiling: workflowCapabilityCeiling } : {}),
5319
5460
  steps: [],
5320
5461
  ...(workflowPreflight ? { preflight: workflowPreflight } : {}),
5321
5462
  workflow: { trace: [], emits: [], console: [], ...(workflowArgsEvidence ?? {}), ...(workflowResource ? { resource: workflowResource.provenance } : {}) },
@@ -5380,10 +5521,15 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5380
5521
  deps.refreshResultDelivery?.();
5381
5522
  return false;
5382
5523
  };
5524
+ const pendingWorkflowChildAnnouncements = new Map<string, NonNullable<AsyncStatus["steps"]>[number]>();
5525
+ let announcePersistedWorkflowChildren = (): void => {};
5383
5526
  const runPersistence = createCapacityResilientJsonWriter({
5384
5527
  keepAlive: true,
5385
5528
  onSuccess: (filePath, payload) => {
5386
- if (filePath === statusPath) queueActiveRunIndex(payload as AsyncStatus);
5529
+ if (filePath === statusPath) {
5530
+ announcePersistedWorkflowChildren();
5531
+ queueActiveRunIndex(payload as AsyncStatus);
5532
+ }
5387
5533
  if (filePath === resultPath) settleResultPublication?.(true);
5388
5534
  },
5389
5535
  onError: (error, filePath) => {
@@ -5404,7 +5550,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5404
5550
  // terminal writes stay fail-fast on purpose: no child work is at risk by then, and
5405
5551
  // silently dropping a terminal write would leave status.json and the active-run
5406
5552
  // index pinned at "running" after the result already says complete.
5407
- const persist = (options: { tolerateStatusWriteFailure?: boolean } = {}) => {
5553
+ const persist = (options: { tolerateStatusWriteFailure?: boolean } = {}): void => {
5408
5554
  if (persistClosed) return;
5409
5555
  const liveJob = deps.state.asyncJobs.get(workflowRunId);
5410
5556
  if (liveJob && (liveJob.status === "complete" || liveJob.status === "failed") && status.state !== "complete" && status.state !== "failed") return;
@@ -5418,7 +5564,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5418
5564
  } else if (options.tolerateStatusWriteFailure) {
5419
5565
  try {
5420
5566
  runPersistence.write(statusPath, { ...status });
5421
- statusPersistenceDegraded = false;
5567
+ if (runPersistence.pendingCount() === 0) statusPersistenceDegraded = false;
5422
5568
  } catch (error) {
5423
5569
  const message = `Failed to persist async workflow state ${statusPath}: ${error instanceof Error ? error.message : String(error)}`;
5424
5570
  console.error(message, error);
@@ -5507,6 +5653,24 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5507
5653
  return { content: [{ type: "text", text: `Failed to create async workflow storage: ${error instanceof Error ? error.message : String(error)}` }], isError: true, details: { mode: "workflow", results: [] } };
5508
5654
  }
5509
5655
  appendWorkflowEvent({ type: "subagent.workflow.started", ...(workflowArgsDigest ? { argsDigest: workflowArgsDigest } : {}) });
5656
+ try {
5657
+ deps.pi.events.emit(SUBAGENT_ASYNC_STARTED_EVENT, {
5658
+ lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
5659
+ id: workflowRunId,
5660
+ asyncDir,
5661
+ cwd: workflowCwd,
5662
+ ...(workflowSessionRoot ? { sessionRoot: workflowSessionRoot } : {}),
5663
+ pid: process.pid,
5664
+ sessionId: currentSessionId ?? undefined,
5665
+ completionOwnerId,
5666
+ mode: "workflow",
5667
+ agent: "workflow",
5668
+ goal: derivedObjective.trim() ? PROMPT_REDACTED : undefined,
5669
+ ...(timeout !== undefined ? { timeoutMs: timeout, deadlineAt: startedAt + timeout } : {}),
5670
+ });
5671
+ } catch (error) {
5672
+ console.error("Failed to emit async workflow start event:", error);
5673
+ }
5510
5674
  // The runner does not execute workflow scripts: this active owner must consume its own
5511
5675
  // durable steer inbox, deliver through in-process child controls, and persist receipts.
5512
5676
  const emitWorkflowSteerEvent = (type: string, requestId: string, index?: number, extra: Record<string, unknown> = {}): void => {
@@ -5662,6 +5826,41 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5662
5826
  const childOutputClaimPaths = new Map<string, string>();
5663
5827
  const producedChildOutputPaths = new Set<string>();
5664
5828
  const workflowSteps = new Map<string, NonNullable<AsyncStatus["steps"]>[number]>();
5829
+ const announcedWorkflowChildren = new Set<string>();
5830
+ const announceWorkflowChild = (key: string, step: NonNullable<AsyncStatus["steps"]>[number]): void => {
5831
+ if (announcedWorkflowChildren.has(key)) return;
5832
+ announcedWorkflowChildren.add(key);
5833
+ const stepIndex = status.steps?.indexOf(step);
5834
+ const childEvent: SubagentChildStatusEvent = {
5835
+ type: "subagent.child-status",
5836
+ version: 1,
5837
+ runId: workflowRunId,
5838
+ childId: key,
5839
+ status: "started",
5840
+ ts: Date.now(),
5841
+ source: "async",
5842
+ asyncDir,
5843
+ ...(stepIndex !== undefined ? { stepIndex } : {}),
5844
+ agent: step.agent,
5845
+ ...(step.runId ? { childRunId: step.runId } : {}),
5846
+ workflowKey: key,
5847
+ ...(step.phase ? { phase: step.phase } : {}),
5848
+ ...(step.label ? { label: step.label } : {}),
5849
+ };
5850
+ appendWorkflowEvent({ ...childEvent });
5851
+ try {
5852
+ deps.pi.events.emit(SUBAGENT_CHILD_STATUS_EVENT, childEvent);
5853
+ } catch (error) {
5854
+ console.error("Failed to emit workflow child status event:", error);
5855
+ }
5856
+ };
5857
+ announcePersistedWorkflowChildren = () => {
5858
+ for (const [key, step] of pendingWorkflowChildAnnouncements) {
5859
+ if (!step.runId) continue;
5860
+ announceWorkflowChild(key, step);
5861
+ pendingWorkflowChildAnnouncements.delete(key);
5862
+ }
5863
+ };
5665
5864
  const runHostCommand = workflowHostCommandRunner({
5666
5865
  workflowCwd,
5667
5866
  artifactsDir: workflowArtifactsDir,
@@ -5865,6 +6064,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5865
6064
  { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: workflowRunId, workflowKey: key, ctxCwd: parentCwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), outputClaimPath: childOutputClaimPaths.get(key), options: { missionDetached: detachWorkflowChildMissions, awaitDetachedChild: true, runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt, capabilityCeiling: workflowCapabilityCeiling } }), runFanoutAdmitted: admission.admitted },
5866
6065
  missionBinding,
5867
6066
  deps.asyncByDefault,
6067
+ undefined,
6068
+ inheritedNestedRoute(deps)?.rootRunId,
5868
6069
  );
5869
6070
  preparedChildParams = childRequest;
5870
6071
  if (workflowUsageBudget.budget) workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
@@ -5877,6 +6078,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5877
6078
  step.async = launch.async;
5878
6079
  if (launch.runId) step.runId = launch.runId;
5879
6080
  if (childRequest.lane) step.lane = childRequest.lane;
6081
+ if (step.runId) pendingWorkflowChildAnnouncements.set(key, step);
5880
6082
  persist({ tolerateStatusWriteFailure: true });
5881
6083
  }
5882
6084
  recordMissionWorkflowChild(missionBinding, workflowRunId, key, { status: "running", agent: launch.agent, ...(launch.sessionFile ? { sessionPath: launch.sessionFile } : {}) });
@@ -5945,7 +6147,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5945
6147
  const finalPreflightTrace = annotateWorkflowPreflightTrace(workflow.trace, workflowPreflight);
5946
6148
  const returnPreview = formatWorkflowValue(workflow.value).slice(0, 1_000);
5947
6149
  const emitPreview = workflow.emits.length > 0 ? ` Emitted: ${workflow.emits.map(formatWorkflowValue).join(", ").slice(0, 1_000)}` : "";
5948
- const summary = `Workflow completed with ${workflow.children.length} child run(s). Return: ${returnPreview}${emitPreview} Trace: ${workflow.trace.length} event(s).${workflowOutputPathMappingSummary(workflow.children)}${finalPreflightWarnings.length ? ` ${finalPreflightWarnings.join(" ")}` : ""}`;
6150
+ const runningSummary = workflowRunningChildrenSummary(workflow.children);
6151
+ const summary = `${runningSummary ? `Workflow dispatch completed; ${runningSummary}` : `Workflow completed with ${workflow.children.length} child run(s).`} Return: ${returnPreview}${emitPreview} Trace: ${workflow.trace.length} event(s).${workflowOutputPathMappingSummary(workflow.children)}${finalPreflightWarnings.length ? ` ${finalPreflightWarnings.join(" ")}` : ""}`;
5949
6152
  const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, summary, producedChildOutputPaths);
5950
6153
  const resultSummary = appendWorkflowOutputWarning(summary, outputWarning);
5951
6154
  const workflowUsage = sumResultsUsage(workflowResults);
@@ -5961,7 +6164,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5961
6164
  } catch (receiptError) {
5962
6165
  appendWorkflowEvent({ type: "subagent.workflow.receipt_write_failed", error: `Failed to persist async workflow receipt: ${receiptError instanceof Error ? receiptError.message : String(receiptError)}` });
5963
6166
  }
5964
- if (!writeWorkflowResult({ id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: true, state: "complete", summary: resultSummary, output: resultSummary, workflowChildren, results: workflow.children.map((child) => ({ workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), ...(status.steps?.find((step) => step.workflowKey === child.key)?.sessionName ? { sessionName: status.steps?.find((step) => step.workflowKey === child.key)?.sessionName } : {}), ...workflowChildAccountingFields(child), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, success: child.ok, ...(child.outputReference ? { outputReference: child.outputReference } : {}), ...(child.outputPathMapping ? { outputPathMapping: child.outputPathMapping } : {}), ...(child.stopped ? { stopped: true } : {}), ...(child.interrupted ? { interrupted: true } : {}), ...(child.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}) })), workflow: status.workflow, ...(workflowReceipt ? { workflowReceipt } : {}), asyncDir, cwd: workflowCwd, sessionId: currentSessionId, completionOwnerId, ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
6167
+ if (!writeWorkflowResult({ id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: true, state: "complete", summary: resultSummary, output: resultSummary, workflowChildren, results: workflowResultChildren(workflow.children, status, false), workflow: status.workflow, ...(workflowCapabilityCeiling ? { admissionCapabilityCeiling: workflowCapabilityCeiling } : {}), ...(workflowReceipt ? { workflowReceipt } : {}), asyncDir, cwd: workflowCwd, sessionId: currentSessionId, completionOwnerId, ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
5965
6168
  if (pendingResultPublication && !await pendingResultPublication) return;
5966
6169
  persist();
5967
6170
  deps.refreshResultDelivery?.();
@@ -5971,7 +6174,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5971
6174
  const partial = error instanceof WorkflowScriptError ? error.partial : { trace: [], emits: [], console: [], children: [] };
5972
6175
  const stopped = controller.signal.aborted;
5973
6176
  const detachedChildKeys = new Set(partial.children.filter((child) => child.detached).map((child) => child.key));
5974
- const hasRealFailedChild = partial.children.some((child) => !child.ok && !child.detached);
6177
+ const hasRealFailedChild = partial.children.some((child) => !child.ok && child.state !== "running" && !child.detached);
5975
6178
  const pauseForDetached = !stopped && error instanceof WorkflowScriptError && error.errorKind === "detached-child" && detachedChildKeys.size > 0 && !hasRealFailedChild;
5976
6179
  const state = stopped ? "stopped" : pauseForDetached ? "paused" : "failed";
5977
6180
  for (const step of status.steps ?? []) {
@@ -6011,7 +6214,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6011
6214
  } catch (receiptError) {
6012
6215
  appendWorkflowEvent({ type: "subagent.workflow.receipt_write_failed", error: `Failed to persist async workflow receipt: ${receiptError instanceof Error ? receiptError.message : String(receiptError)}` });
6013
6216
  }
6014
- if (!writeWorkflowResult({ id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: status.state === "complete", state: status.state, summary: resultSummary, error: status.state === "complete" ? undefined : status.error, stopped: status.stopped, activityState: status.activityState, workflowChildren, ...(terminalOutcome ? { terminalOutcome } : {}), results: partial.children.map((child) => ({ workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), ...(status.steps?.find((step) => step.workflowKey === child.key)?.sessionName ? { sessionName: status.steps?.find((step) => step.workflowKey === child.key)?.sessionName } : {}), ...workflowChildAccountingFields(child), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, success: child.ok, ...(child.outputReference ? { outputReference: child.outputReference } : {}), ...(child.terminalOutcome ? { terminalOutcome: child.terminalOutcome } : {}), ...(child.outputPathMapping ? { outputPathMapping: child.outputPathMapping } : {}), ...(child.stopped ? { stopped: true } : {}), ...(child.interrupted ? { interrupted: true } : {}), ...(child.detached && status.state !== "complete" ? { detached: true } : {}), ...(child.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}) })), workflow: status.workflow, ...(workflowReceipt ? { workflowReceipt } : {}), asyncDir, cwd: workflowCwd, sessionId: currentSessionId, completionOwnerId, ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
6217
+ if (!writeWorkflowResult({ id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: status.state === "complete", state: status.state, summary: resultSummary, error: status.state === "complete" ? undefined : status.error, stopped: status.stopped, activityState: status.activityState, workflowChildren, ...(terminalOutcome ? { terminalOutcome } : {}), results: workflowResultChildren(partial.children, status, true), workflow: status.workflow, ...(workflowCapabilityCeiling ? { admissionCapabilityCeiling: workflowCapabilityCeiling } : {}), ...(workflowReceipt ? { workflowReceipt } : {}), asyncDir, cwd: workflowCwd, sessionId: currentSessionId, completionOwnerId, ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
6015
6218
  if (pendingResultPublication && !await pendingResultPublication) return;
6016
6219
  persist();
6017
6220
  deps.refreshResultDelivery?.();
@@ -6134,6 +6337,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6134
6337
  { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams: delegatedWorkflowPermit ? { ...childParams, async: false } : childParams, parentWorkflowRunId: foregroundWorkflowRunId, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), outputClaimPath: childOutputClaimPaths.get(key), options: { missionDetached: detachWorkflowChildMissions, suppressRoutineResultIntercom: chatProgress.mode === "live-card", runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt, capabilityCeiling: workflowCapabilityCeiling } }), runFanoutAdmitted: admission.admitted },
6135
6338
  missionBinding,
6136
6339
  deps.asyncByDefault,
6340
+ undefined,
6341
+ inheritedNestedRoute(deps)?.rootRunId,
6137
6342
  );
6138
6343
  preparedChildParams = childRequest;
6139
6344
  if (workflowUsageBudget.budget) workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
@@ -6198,9 +6403,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6198
6403
  const workflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: foregroundWorkflowRunId, workflowState: "completed", inventoryComplete: true, trace: workflow.trace, children: workflow.children });
6199
6404
  const receipt = terminalWorkflowReceipt(foregroundWorkflowRunId, "complete", workflow.children, workflowChildren, undefined, [...workflowHostSteps.values()], workflowResource?.provenance, workflowArgsDigest);
6200
6405
  const traceLines = finalPreflightTrace.map((entry) => `- ${entry.operation} ${entry.key}: ${entry.state}${entry.runId ? ` (${entry.runId})` : ""}${entry.durationMs !== undefined ? ` in ${entry.durationMs}ms` : ""}${entry.warning ? ` — ${entry.warning}` : ""}${entry.error ? ` — ${entry.error}` : ""}`);
6406
+ const runningSummary = workflowRunningChildrenSummary(workflow.children);
6201
6407
  const sections = [
6202
6408
  ...(workflowPreflight ? [formatWorkflowPreflight(workflowPreflight)] : []),
6203
- "Workflow completed.",
6409
+ runningSummary ? `Workflow dispatch completed; ${runningSummary}` : "Workflow completed.",
6204
6410
  `Return:\n${formatWorkflowValue(workflow.value)}`,
6205
6411
  ];
6206
6412
  if (workflow.emits.length > 0) sections.push(`Emitted:\n${workflow.emits.map(formatWorkflowValue).join("\n")}`);
@@ -6401,7 +6607,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6401
6607
  cwd: requestCwd,
6402
6608
  ...(deps.config.missions ? { missions: deps.config.missions } : {}),
6403
6609
  ...(deps.config.authorityPolicy ? { authorityPolicy: deps.config.authorityPolicy } : {}),
6404
- plugins: createBuiltinInspectorPlugins(),
6610
+ plugins: getInspectorPlugins(deps.pi),
6405
6611
  signal,
6406
6612
  });
6407
6613
  }
@@ -6559,7 +6765,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6559
6765
  }
6560
6766
  let orchestratorTarget: string | undefined;
6561
6767
  try {
6562
- orchestratorTarget = resolveIntercomSessionTarget(deps.pi.getSessionName(), ctx.sessionManager.getSessionId());
6768
+ orchestratorTarget = resolveIntercomSessionTarget(deps.childRuntime?.intercomSessionName ?? deps.pi.getSessionName(), ctx.sessionManager.getSessionId());
6563
6769
  } catch (error) {
6564
6770
  if (!sessionError) sessionError = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
6565
6771
  }
@@ -6635,7 +6841,18 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6635
6841
  return withBudget(inspectSubagentStatus(paramsWithResolvedCwd, omitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots, abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) })));
6636
6842
  }
6637
6843
  if (action === "resume") {
6638
- return resumeAsyncRun(omitUndefinedProperties({ params: paramsWithResolvedCwd, requestCwd, ctx, deps, parentModel: requestParentModel, signal }));
6844
+ return resumeAsyncRun(omitUndefinedProperties({
6845
+ params: paramsWithResolvedCwd,
6846
+ requestCwd,
6847
+ ctx,
6848
+ deps,
6849
+ parentModel: requestParentModel,
6850
+ signal,
6851
+ ...(workflowLaunchObserver ? { onLaunch: (launch: Parameters<NonNullable<typeof workflowLaunchObserver>>[0]) => {
6852
+ workflowLaunchObservers.delete(params);
6853
+ workflowLaunchObserver(launch);
6854
+ } } : {}),
6855
+ }));
6639
6856
  }
6640
6857
  if (action === "steer") {
6641
6858
  if (paramsWithResolvedCwd.mode !== undefined && resolveSteerDeliveryMode(paramsWithResolvedCwd.mode) === undefined) {
@@ -6906,6 +7123,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6906
7123
  cwd: requestCwd,
6907
7124
  config: deps.config,
6908
7125
  currentSessionId: deps.state.currentSessionId ?? ctx.sessionManager.getSessionId() ?? undefined,
7126
+ discoverAgentsAll: deps.discoverAgentsAll,
6909
7127
  runtimeAgentOwner: deps.pi,
6910
7128
  onAgentsChanged: deps.onAgentsChanged,
6911
7129
  });
@@ -6964,6 +7182,12 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6964
7182
  }
6965
7183
  const modelScope = discovered.modelScope;
6966
7184
  effectiveParams = applySingleAgentLaunchDefaults(effectiveParams, discoveredAgents);
7185
+ // The gate shorthand, an explicit acceptance.verify list, and an agent's
7186
+ // defaultAcceptance all normalize to verify commands, and the agent's
7187
+ // frontmatter outputSchema has been merged by now, so this one check keeps
7188
+ // a run to a single structured-output source regardless of spelling.
7189
+ const typedVerifyConflict = describeTypedVerifyOutputSchemaConflict(effectiveParams, params);
7190
+ if (typedVerifyConflict) return buildRequestedModeError(effectiveParams, typedVerifyConflict);
6967
7191
  // An agent-level defaultContext is a preference, unlike an explicit request.
6968
7192
  // Prefer fork only when the parent session is persisted and has a current leaf;
6969
7193
  // otherwise use fresh immediately instead of launching a guaranteed-to-fail fork.
@@ -6977,7 +7201,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6977
7201
  if ("error" in contextPolicyResult) return buildRequestedModeError(effectiveParams, contextPolicyResult.error);
6978
7202
  const contextPolicy = contextPolicyResult;
6979
7203
  effectiveParams = contextPolicy.params;
6980
- const sessionName = resolveIntercomSessionTarget(deps.pi.getSessionName(), ctx.sessionManager.getSessionId());
7204
+ const sessionName = resolveIntercomSessionTarget(deps.childRuntime?.intercomSessionName ?? deps.pi.getSessionName(), ctx.sessionManager.getSessionId());
6981
7205
  const intercomBridge = resolveIntercomBridge({
6982
7206
  config: deps.config.intercomBridge,
6983
7207
  override: effectiveParams.intercomBridge,
@@ -6987,7 +7211,6 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6987
7211
  orchestratorTarget: sessionName,
6988
7212
  });
6989
7213
  const agents = applyScopedIntercomBridgeToAgents(discoveredAgents, intercomBridge, contextPolicy);
6990
- const runId = randomUUID();
6991
7214
  const inheritedNestedRouteValue = inheritedNestedRoute(deps);
6992
7215
  const nestedParentAddress = inheritedNestedRouteValue ? inheritedNestedParentAddress(deps) : undefined;
6993
7216
  const shareEnabled = effectiveParams.share === true;
@@ -7022,10 +7245,30 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7022
7245
 
7023
7246
  let forkSessionFileForIndex: (idx?: number) => string | undefined = () => undefined;
7024
7247
  let prepareForkSessionForIndex: (idx?: number) => Promise<void> = async () => {};
7248
+ // Check before pruner/session preparation, then recheck immediately before each fork
7249
+ // because the session capability ceiling can tighten while preparation awaits.
7250
+ const launchCapabilityCeiling = () => intersectSubagentCapabilityCeilings(
7251
+ intersectSubagentCapabilityCeilings(effectiveParams.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(requestSessionId)),
7252
+ deps.childRuntime?.capabilityCeiling,
7253
+ );
7254
+ const assertLaunchableAgentsAllowedBeforeFork = (): void => {
7255
+ if (!contextPolicy.usesFork) return;
7256
+ const ceiling = launchCapabilityCeiling();
7257
+ const launchable = hasSingle
7258
+ ? [effectiveParams.agent!]
7259
+ : hasTasks
7260
+ ? (effectiveParams.tasks ?? []).map((task) => task.agent)
7261
+ : (effectiveParams.chain ?? []).flatMap((step) => isDynamicParallelStep(step)
7262
+ && (step.expand.maxItems ?? deps.config.chain?.dynamicFanout?.maxItems ?? 0) === 0
7263
+ ? []
7264
+ : getStepAgents(step));
7265
+ for (const agent of launchable) assertAgentAllowedByCapabilityCeiling(agent, ceiling);
7266
+ };
7025
7267
  // Forked children keep their requested thinking level. Signed Anthropic thinking
7026
7268
  // blocks are stripped from the inherited transcript by the resolver (they are bound
7027
7269
  // to the parent session), which is not a reason to disable the child's own reasoning.
7028
7270
  try {
7271
+ assertLaunchableAgentsAllowedBeforeFork();
7029
7272
  const pruneSession = contextPolicy.usesFork && deps.config.forkContext?.mode === "pruned"
7030
7273
  ? await createPrunedForkSessionWriter(ctx, deps.config.forkContext, signal)
7031
7274
  : undefined;
@@ -7054,6 +7297,14 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7054
7297
  if (externalAgent && (!effectiveAsync || effectiveParams.foregroundOnly === true)) {
7055
7298
  return buildRequestedModeError(effectiveParams, `Agent '${externalAgent.name}' uses runner.type='${externalAgent.runner?.type}', which currently supports async/background execution only. Omit async or pass async:true; clarify and foregroundOnly are unsupported.`);
7056
7299
  }
7300
+ if (effectiveAsync && hasSingle && effectiveParams.resume === undefined && effectiveParams.worktree === true) {
7301
+ try {
7302
+ await preflightWorktreeSource(effectiveCwd, { signal });
7303
+ } catch (error) {
7304
+ return toExecutionErrorResult(effectiveParams, error, contextPolicy.contextSummary);
7305
+ }
7306
+ }
7307
+ const runId = randomUUID();
7057
7308
  const foregroundTimeout = resolveSingleAgentLaunchTimeout(
7058
7309
  effectiveParams,
7059
7310
  effectiveAsync,
@@ -7152,8 +7403,15 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7152
7403
  const childSessionFileForIndex = (idx?: number) =>
7153
7404
  path.join(sessionDirForIndex(idx), "session.jsonl");
7154
7405
  try {
7406
+ // The ceiling can change while the pruned writer is built; clarify skips preflight but
7407
+ // still branches the parent session at launch.
7408
+ assertLaunchableAgentsAllowedBeforeFork();
7155
7409
  if (!(effectiveParams.clarify === true && ctx.hasUI) || deps.config.forkContext?.mode === "pruned") {
7156
- await preflightForkSessionsForStaticTasks(effectiveParams, contextPolicy, prepareForkSessionForTask, deps.config.chain?.dynamicFanout?.maxItems);
7410
+ const prepareAllowedForkSession: PrepareForkSessionForTask = async (agent, ...rest) => {
7411
+ assertAgentAllowedByCapabilityCeiling(agent, launchCapabilityCeiling());
7412
+ await prepareForkSessionForTask(agent, ...rest);
7413
+ };
7414
+ await preflightForkSessionsForStaticTasks(effectiveParams, contextPolicy, prepareAllowedForkSession, deps.config.chain?.dynamicFanout?.maxItems);
7157
7415
  }
7158
7416
  } catch (error) {
7159
7417
  activeAsyncCapacity?.rollback();
@@ -7383,7 +7641,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7383
7641
  agents: agentsForSummary,
7384
7642
  ...(agentsForSummary.length === 1 && (type === "subagent.nested.started" ? startedLaunches[0]?.model : details?.results[0]?.model) ? { model: type === "subagent.nested.started" ? startedLaunches[0]?.model : details?.results[0]?.model } : {}),
7385
7643
  ...(agentsForSummary.length === 1 && (type === "subagent.nested.started" ? startedLaunches[0]?.thinking : details?.results[0]?.thinking) ? { thinking: type === "subagent.nested.started" ? startedLaunches[0]?.thinking : details?.results[0]?.thinking } : {}),
7386
- ...(agentsForSummary.length === 1 && (type === "subagent.nested.started" ? startedLaunches[0]?.sandbox : details?.results[0]?.sandbox) ? { sandbox: type === "subagent.nested.started" ? startedLaunches[0]?.sandbox : details?.results[0]?.sandbox } : {}),
7644
+ ...(agentsForSummary.length === 1 && (type === "subagent.nested.started" ? startedLaunches[0]?.sandbox : details?.results[0]?.sandbox) ? { sandbox: type === "subagent.nested.started" ? startedLaunches[0]?.sandbox : details?.results[0]?.sandbox } : {}),
7387
7645
  startedAt: foregroundControl?.startedAt ?? now,
7388
7646
  ...(state !== "running" ? { endedAt: now } : {}),
7389
7647
  lastUpdate: now,
@@ -7395,7 +7653,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7395
7653
  status: "running" as const,
7396
7654
  ...(launch.model ? { model: launch.model } : {}),
7397
7655
  ...(launch.thinking ? { thinking: launch.thinking } : {}),
7398
- ...(launch.sandbox ? { sandbox: launch.sandbox } : {}),
7656
+ ...(launch.sandbox ? { sandbox: launch.sandbox } : {}),
7399
7657
  })) }
7400
7658
  : details?.results.length
7401
7659
  ? { steps: details.results.map((child) => ({
@@ -7404,7 +7662,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7404
7662
  status: child.interrupted || child.detached ? "paused" as const : child.exitCode === 0 ? "complete" as const : "failed" as const,
7405
7663
  ...(child.model ? { model: child.model } : {}),
7406
7664
  ...(child.thinking ? { thinking: child.thinking } : {}),
7407
- ...(child.sandbox ? { sandbox: child.sandbox } : {}),
7665
+ ...(child.sandbox ? { sandbox: child.sandbox } : {}),
7408
7666
  ...(child.sessionFile ? { sessionFile: child.sessionFile } : {}),
7409
7667
  ...(child.error ? { error: child.error } : {}),
7410
7668
  })) }