pi-subagents 0.83.1 → 0.85.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 (206) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-5YIITCPD.js → chunk-3UZ5FVVJ.js} +322 -110
  5. package/bundle/{chunk-F4ASL6OV.js → chunk-7MAE3DJV.js} +1 -1
  6. package/bundle/{chunk-YXFJVCOL.js → chunk-CS4O36CZ.js} +11 -156
  7. package/bundle/{chunk-AHIFYGR3.js → chunk-DV2NCNPR.js} +22 -11
  8. package/bundle/{chunk-G2Z6ZH26.js → chunk-GCSLVFCX.js} +1 -1
  9. package/bundle/{chunk-2S4K53MV.js → chunk-H2NLFTC5.js} +1 -1
  10. package/bundle/{chunk-MABL3FUM.js → chunk-HFTBF7SG.js} +2 -1
  11. package/bundle/chunk-HXRB42AF.js +108 -0
  12. package/bundle/{chunk-UFL7IYCW.js → chunk-IQIWF2VX.js} +190 -1177
  13. package/bundle/{chunk-NPIYWVOD.js → chunk-JNXT3MPI.js} +15 -6
  14. package/bundle/{chunk-C7JMPU5F.js → chunk-JO67XSKD.js} +59 -27
  15. package/bundle/{chunk-UUP372DR.js → chunk-JWYG26RE.js} +223 -93
  16. package/bundle/{chunk-C5P5CHYK.js → chunk-KDMFBYFM.js} +1 -1
  17. package/bundle/{chunk-V2BZYLEP.js → chunk-KEY3UQMQ.js} +7 -2
  18. package/bundle/{chunk-VLFZIN6D.js → chunk-KZ34KQQH.js} +9 -6
  19. package/bundle/{chunk-ZVOAMTUQ.js → chunk-L2ENOFVZ.js} +76 -58
  20. package/bundle/{chunk-RNIZLSEA.js → chunk-LGMILZNE.js} +323 -18
  21. package/bundle/{chunk-UYK5MZWE.js → chunk-LTPH2DXH.js} +247 -153
  22. package/bundle/{chunk-2D52JFLF.js → chunk-N7B2KD74.js} +41 -117
  23. package/bundle/{chunk-IPGZMQXV.js → chunk-O7CPL6H4.js} +183 -28
  24. package/bundle/{chunk-D3JAFGMO.js → chunk-PHZP3KHB.js} +1 -1
  25. package/bundle/{chunk-2DHZTCOL.js → chunk-PVIVCDG2.js} +2 -2
  26. package/bundle/{chunk-LFDBD4PW.js → chunk-QO75KJBT.js} +2 -2
  27. package/bundle/{chunk-SSG7IEP5.js → chunk-RQAUNAWG.js} +2 -2
  28. package/bundle/{chunk-QP5ZWNIS.js → chunk-RV5OGHLO.js} +6 -3
  29. package/bundle/chunk-T5V5BRCL.js +1067 -0
  30. package/bundle/{chunk-LNRJCP2Y.js → chunk-UX4SCV5N.js} +337 -207
  31. package/bundle/{chunk-F5DBXJ2G.js → chunk-WOVMHDES.js} +234 -182
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +1 -1
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +8 -8
  36. package/bundle/project-panes.js +3 -3
  37. package/docs/agents.md +17 -2
  38. package/docs/configuration.md +2 -2
  39. package/docs/extension-api.md +16 -1
  40. package/docs/workflows.md +30 -2
  41. package/package.json +1 -1
  42. package/src/agents/agent-management.js +27 -11
  43. package/src/agents/agent-memory.d.ts +1 -4
  44. package/src/agents/agent-memory.js +1 -4
  45. package/src/agents/agents.d.ts +1 -3
  46. package/src/agents/agents.js +7 -6
  47. package/src/agents/frontmatter.js +1 -8
  48. package/src/agents/global-npm-root.d.ts +1 -0
  49. package/src/agents/global-npm-root.js +11 -3
  50. package/src/agents/skills.d.ts +0 -3
  51. package/src/agents/skills.js +0 -3
  52. package/src/extension/config.js +7 -1
  53. package/src/extension/herdr-pi-bridge.js +10 -2
  54. package/src/extension/index.d.ts +0 -13
  55. package/src/extension/index.js +43 -32
  56. package/src/extension/public-execution.d.ts +1 -0
  57. package/src/extension/public-execution.js +4 -0
  58. package/src/extension/reply-workflow-script.js +24 -4
  59. package/src/extension/schemas.d.ts +8 -3
  60. package/src/extension/schemas.js +5 -3
  61. package/src/extension/session-switch.d.ts +25 -0
  62. package/src/extension/session-switch.js +138 -0
  63. package/src/extension/subagent-guide.d.ts +1 -1
  64. package/src/extension/subagent-guide.js +1 -1
  65. package/src/extension/subagent-launch-tool.d.ts +25 -0
  66. package/src/extension/subagent-launch-tool.js +48 -0
  67. package/src/extension/tool-activation.js +25 -11
  68. package/src/extension/tool-description.js +6 -0
  69. package/src/inspectors/herdr/actions.d.ts +0 -1
  70. package/src/inspectors/herdr/actions.js +0 -1
  71. package/src/inspectors/session-roots-codec.d.ts +0 -1
  72. package/src/inspectors/session-roots-codec.js +0 -1
  73. package/src/inspectors/tmux/actions.d.ts +0 -1
  74. package/src/inspectors/tmux/actions.js +0 -1
  75. package/src/integrations/herdr-status.js +3 -8
  76. package/src/intercom/native-supervisor-channel.js +65 -9
  77. package/src/runs/background/async-execution.d.ts +8 -9
  78. package/src/runs/background/async-execution.js +77 -27
  79. package/src/runs/background/async-job-tracker.js +12 -0
  80. package/src/runs/background/async-resume.d.ts +2 -1
  81. package/src/runs/background/async-resume.js +112 -39
  82. package/src/runs/background/async-retention.d.ts +1 -0
  83. package/src/runs/background/async-retention.js +22 -11
  84. package/src/runs/background/auto-drain.js +2 -1
  85. package/src/runs/background/boot-id.d.ts +1 -3
  86. package/src/runs/background/boot-id.js +1 -3
  87. package/src/runs/background/completion-batcher.d.ts +3 -4
  88. package/src/runs/background/completion-batcher.js +2 -3
  89. package/src/runs/background/control-channel.d.ts +0 -6
  90. package/src/runs/background/control-channel.js +0 -6
  91. package/src/runs/background/fleet-view.js +2 -3
  92. package/src/runs/background/notify.d.ts +0 -2
  93. package/src/runs/background/notify.js +0 -2
  94. package/src/runs/background/result-watcher.d.ts +1 -0
  95. package/src/runs/background/result-watcher.js +59 -29
  96. package/src/runs/background/resume-guidance.js +4 -2
  97. package/src/runs/background/retained-children.js +2 -1
  98. package/src/runs/background/run-child-session.d.ts +2 -1
  99. package/src/runs/background/run-child-session.js +10 -2
  100. package/src/runs/background/run-status.js +4 -3
  101. package/src/runs/background/scheduled-runs.d.ts +3 -1
  102. package/src/runs/background/scheduled-runs.js +13 -16
  103. package/src/runs/background/subagent-runner.d.ts +2 -4
  104. package/src/runs/background/subagent-runner.js +10 -6
  105. package/src/runs/background/subagent-wait.js +12 -15
  106. package/src/runs/background/wait-config.d.ts +2 -0
  107. package/src/runs/background/wait-config.js +17 -3
  108. package/src/runs/background/wait-tool.js +4 -2
  109. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  110. package/src/runs/background/workflow-terminal-proof.js +0 -1
  111. package/src/runs/foreground/execution.d.ts +0 -3
  112. package/src/runs/foreground/execution.js +17 -9
  113. package/src/runs/foreground/subagent-executor.d.ts +3 -2
  114. package/src/runs/foreground/subagent-executor.js +112 -26
  115. package/src/runs/shared/child-commands.js +15 -2
  116. package/src/runs/shared/child-hooks.d.ts +1 -7
  117. package/src/runs/shared/child-hooks.js +13 -5
  118. package/src/runs/shared/child-launch.js +6 -2
  119. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  120. package/src/runs/shared/child-session.d.ts +3 -1
  121. package/src/runs/shared/child-session.js +22 -2
  122. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  123. package/src/runs/shared/child-tool-plan.js +0 -1
  124. package/src/runs/shared/claude-code-adapter.js +11 -0
  125. package/src/runs/shared/external-cli-runner.js +26 -6
  126. package/src/runs/shared/herdr-connection.js +2 -1
  127. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  128. package/src/runs/shared/herdr-pane-host.js +17 -1
  129. package/src/runs/shared/herdr-placed-run.js +48 -22
  130. package/src/runs/shared/lane-metadata.d.ts +0 -1
  131. package/src/runs/shared/lane-metadata.js +0 -1
  132. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  133. package/src/runs/shared/model-resolution-diagnostic.d.ts +11 -1
  134. package/src/runs/shared/model-resolution-diagnostic.js +25 -0
  135. package/src/runs/shared/model-resolution.d.ts +2 -2
  136. package/src/runs/shared/model-resolution.js +7 -1
  137. package/src/runs/shared/model-scope.d.ts +1 -5
  138. package/src/runs/shared/model-scope.js +1 -5
  139. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  140. package/src/runs/shared/mutation-evidence.js +52 -7
  141. package/src/runs/shared/nested-events.d.ts +1 -0
  142. package/src/runs/shared/nested-events.js +1 -1
  143. package/src/runs/shared/parallel-utils.d.ts +2 -1
  144. package/src/runs/shared/permissions.js +5 -3
  145. package/src/runs/shared/placement-host.d.ts +5 -1
  146. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  147. package/src/runs/shared/rex-pane-host.js +0 -2
  148. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  149. package/src/runs/shared/run-launch-folder.js +21 -0
  150. package/src/runs/shared/runner-launcher.d.ts +12 -1
  151. package/src/runs/shared/runner-launcher.js +16 -0
  152. package/src/runs/shared/single-output.d.ts +3 -3
  153. package/src/runs/shared/single-output.js +5 -3
  154. package/src/runs/shared/structured-output.d.ts +8 -0
  155. package/src/runs/shared/structured-output.js +30 -2
  156. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  157. package/src/runs/shared/subagent-prompt-runtime.js +4 -2
  158. package/src/runs/shared/tool-timeout.js +2 -1
  159. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  160. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  161. package/src/runs/shared/worktree.d.ts +3 -0
  162. package/src/runs/shared/worktree.js +20 -0
  163. package/src/shared/capacity-resilient-json.d.ts +1 -1
  164. package/src/shared/child-cache-retention.d.ts +1 -2
  165. package/src/shared/child-cache-retention.js +1 -2
  166. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  167. package/src/shared/fleet-transcript-reader.js +333 -0
  168. package/src/shared/formatters.d.ts +0 -18
  169. package/src/shared/formatters.js +0 -18
  170. package/src/shared/session-succession.d.ts +16 -1
  171. package/src/shared/session-succession.js +41 -2
  172. package/src/shared/session-warnings.d.ts +7 -0
  173. package/src/shared/session-warnings.js +26 -0
  174. package/src/shared/settings.d.ts +0 -23
  175. package/src/shared/settings.js +3 -35
  176. package/src/shared/types.d.ts +28 -11
  177. package/src/shared/types.js +0 -12
  178. package/src/shared/utils.d.ts +0 -14
  179. package/src/shared/utils.js +0 -22
  180. package/src/shared/wait-tool-name.d.ts +8 -0
  181. package/src/shared/wait-tool-name.js +13 -0
  182. package/src/slash/slash-commands.js +2 -1
  183. package/src/slash/subagent-cost.d.ts +3 -2
  184. package/src/slash/subagent-cost.js +22 -3
  185. package/src/slash/subagents-admin.js +0 -1
  186. package/src/tui/fleet-status.d.ts +0 -5
  187. package/src/tui/fleet-status.js +4 -24
  188. package/src/tui/fleet-transcript.d.ts +1 -44
  189. package/src/tui/fleet-transcript.js +1 -327
  190. package/src/tui/fleet.js +6 -4
  191. package/src/tui/render.d.ts +0 -9
  192. package/src/tui/render.js +81 -47
  193. package/src/tui/subagent-messages.js +3 -2
  194. package/src/watchdog/register-child.d.ts +2 -3
  195. package/src/watchdog/register-child.js +2 -3
  196. package/src/watchdog/turn-delta.js +2 -1
  197. package/src/workflows/scripted-workflow.js +243 -20
  198. package/src/workflows/workflow-launch-record.d.ts +15 -6
  199. package/src/workflows/workflow-launch-record.js +30 -12
  200. package/src/workflows/workflow-resume-claim.js +2 -2
  201. package/src/workflows/workflow-resume.d.ts +1 -1
  202. package/src/workflows/workflow-resume.js +11 -8
  203. package/src/workflows/workflow-script-worker.d.ts +13 -0
  204. package/src/workflows/workflow-script-worker.js +79 -0
  205. package/workflow-script-process.cjs +36 -0
  206. package/workflow-script-worker.cjs +453 -176
@@ -5,7 +5,7 @@ import { discoverAgents, findBlockingAgentDiagnostic, formatAvailableAgentLines,
5
5
  import { getArtifactsDir, getProjectArtifactPackagingWarning, getProjectSubagentsDir } from "../../shared/artifacts.js";
6
6
  import { writeAtomicJson } from "../../shared/atomic-json.js";
7
7
  import { createCapacityResilientJsonWriter } from "../../shared/capacity-resilient-json.js";
8
- import { isStorageCapacityError } from "../../shared/file-system-retry.js";
8
+ import { reportSessionWarning } from "../../shared/session-warnings.js";
9
9
  import { resolveEffectiveThinking, toModelInfo } from "../../shared/model-info.js";
10
10
  import { beginForegroundChild, finishForegroundChild, foregroundSchedulingSettled, settleForegroundSchedulingOwner, updateForegroundChild, } from "./foreground-control.js";
11
11
  import { getLivePromptAudit, rewritePromptWithGuidance, updateLiveEffectivePrompt } from "./prompt-audit.js";
@@ -15,6 +15,7 @@ import { handleManagementAction } from "../../agents/agent-management.js";
15
15
  import { handleRefinementAction } from "../../agents/agent-refinements.js";
16
16
  import { buildDoctorReport } from "../../extension/doctor.js";
17
17
  import { readSubagentGuide } from "../../extension/subagent-guide.js";
18
+ import { approveWorkflowChildLaunch } from "../../extension/subagent-launch-tool.js";
18
19
  import { isWorkflowScriptPath, normalizePublicSubagentExecution, validateWorkflowCapacityOverrides } from "../../extension/public-execution.js";
19
20
  import { readReplyWorkflowScript } from "../../extension/reply-workflow-script.js";
20
21
  import { disabledFeatureNotice, disabledFeatureSectionNotice, disabledFeatureUseError, resolveDisabledFeatureSurface } from "../../shared/disabled-features.js";
@@ -37,7 +38,7 @@ import { isScheduledRunAction } from "../background/scheduled-runs.js";
37
38
  import { encodeIndexSegment } from "../background/index-segment.js";
38
39
  import { enqueueChainAppendRequest, readPendingChainAppendRequests, runnerStepOutputNames } from "../background/chain-append.js";
39
40
  import { ChainOutputValidationError, validateChainOutputBindingsWithContext } from "../shared/chain-outputs.js";
40
- import { acceptanceHasTypedVerify, normalizeGateAcceptance, resolveAcceptanceReportMode, TYPED_VERIFY_OUTPUT_SCHEMA_CONFLICT, validateAcceptanceInput, validateExecutionAcceptance, validateExecutionAcceptancePolicy } from "../shared/acceptance.js";
41
+ import { acceptanceHasTypedVerify, normalizeAcceptanceInput, normalizeGateAcceptance, resolveAcceptanceReportMode, TYPED_VERIFY_OUTPUT_SCHEMA_CONFLICT, validateAcceptanceInput, validateExecutionAcceptance, validateExecutionAcceptancePolicy } from "../shared/acceptance.js";
41
42
  import { canPreferFork, createForkContextResolver, resolveSubagentLaunchContext } from "../../shared/fork-context.js";
42
43
  import { createPrunedForkSessionWriter } from "../../shared/pruned-fork.js";
43
44
  import { resolveCurrentSessionId } from "../../shared/session-identity.js";
@@ -84,7 +85,7 @@ import { getExternalJobProvider } from "../../api/external-job-provider.js";
84
85
  import { externalJobFollowUpRequestDigest, externalJobFollowUpRequestId, externalJobFollowUpRunId, externalJobPromptDigest, externalJobStableJson } from "../shared/external-job-runner.js";
85
86
  import { externalCliReceiptMetadata, normalizeExternalCliRunnerStatus } from "../shared/external-cli-contract.js";
86
87
  import { formatHerdrMachineRunnerUnsupported, resolveMachinePlacement } from "../shared/herdr-machine.js";
87
- import { lookupRunnerLauncher, resolveAgentRunnerLauncher } from "../shared/runner-launcher.js";
88
+ import { checkRequiredRunnerLauncher, lookupRunnerLauncher, REQUIRE_LAUNCHER_SHAPE_ERROR, resolveAgentRunnerLauncher } from "../shared/runner-launcher.js";
88
89
  import { applyForceTopLevelAsyncOverride } from "../background/top-level-async.js";
89
90
  import { handleMissionAction, MISSION_ACTIONS } from "../../missions/actions.js";
90
91
  import { attachMissionToLaunchResult, missionAcceptanceStatus, prepareMissionLaunch, writeMissionAsyncBinding } from "../../missions/lifecycle.js";
@@ -111,13 +112,14 @@ import { annotateWorkflowPreflightTrace, formatWorkflowPreflight, formatWorkflow
111
112
  import { authorizeWorkflowResourceHost, claimWorkflowChildPermit, consumeWorkflowResourcePermit, validateWorkflowChildPermitRoot, } from "../../shared/workflow-child-permit.js";
112
113
  import { deepFreezeWorkflowArgs, normalizeWorkflowArgs, resolveStructuredWorkflowResource, resolveWorkflowResource } from "../../workflows/workflow-resources.js";
113
114
  import { writeWorkflowLaunchRecord } from "../../workflows/workflow-launch-record.js";
114
- import { stableJsonDigest } from "../../shared/launch-contract.js";
115
+ import { agentDefinitionDigest, stableJsonDigest } from "../../shared/launch-contract.js";
115
116
  import { cleanupWorktrees, createWorktrees, preflightWorktreeSource, withWorktreeTransaction, diffWorktrees, formatWorktreeDiffSummary, } from "../shared/worktree.js";
116
117
  import { applyReviewedCleanupPlan, formatCleanupReceipt, loadReviewedCleanupPlan } from "../shared/worktree-cleanup-apply.js";
117
118
  import { createWorktreeCleanupPlan, formatWorktreeCleanupPlan } from "../shared/worktree-cleanup-plan.js";
118
119
  import { DIRS, DEFAULT_ARTIFACT_CONFIG, DEFAULT_MAX_OUTPUT, DEFAULT_FORK_PREAMBLE, SUBAGENT_ACTIONS, SUBAGENT_ASYNC_STARTED_EVENT, SUBAGENT_CHILD_STATUS_EVENT, SUBAGENT_CONTROL_EVENT, SUBAGENT_CONTROL_INTERCOM_EVENT, SUBAGENT_FOREGROUND_COMPLETE_EVENT, SUBAGENT_LIFECYCLE_ARTIFACT_VERSION, checkSubagentDepth, resolveChildMaxSubagentDepth, resolveCurrentMaxSubagentDepth, resolveMaxSubagentSpawnsPerRun, truncateOutput, wrapForkTask, } from "../../shared/types.js";
119
120
  import { deriveChildSessionName } from "../../shared/child-session-name.js";
120
121
  import { editDistance, hasSingleAdjacentTransposition } from "../../shared/edit-distance.js";
122
+ import { waitToolName } from "../../shared/wait-tool-name.js";
121
123
  const MUTATING_MANAGEMENT_ACTIONS = new Set(["command.yield", "command.cancel", "create", "update", "delete", "eject", "disable", "enable", "reset", "grant-spawn-budget", "watchdog.configure", "mission.create", "mission.update", "mission.resolve-decision", "mission.attach-run", "mission.close", "inspector.open", "inspector.close", "project.open", "project.close", "worktree.discard", "worktree.cleanup", "lane.recordMerge", "lane.recordSupersession", "refine", "refine.rollback", "dismiss", "schedule.create", "schedule.pause", "schedule.resume", "schedule.run", "schedule.run-due", "schedule.delete"]);
122
124
  const DESTRUCTIVE_MANAGEMENT_ACTIONS = new Set(["command.cancel", "delete", "eject", "disable", "reset", "mission.close", "worktree.discard", "refine.rollback", "inspector.close", "project.close", "stop", "interrupt", "schedule.delete"]);
123
125
  function resolveSteerDeliveryMode(mode) {
@@ -177,6 +179,47 @@ function inheritedRunFanoutBudget(deps) {
177
179
  function resolveRequestedCwd(runtimeCwd, requestedCwd) {
178
180
  return requestedCwd ? path.resolve(runtimeCwd, requestedCwd) : runtimeCwd;
179
181
  }
182
+ function workflowChildLaunchArgs(workflowRunId, key, request, scriptAgent, ctxCwd, discoverAgents) {
183
+ // prepareWorkflowLaunchParams turns a retained resume into { action: "resume", id, message }.
184
+ const resume = request.action === "resume" && typeof request.id === "string" ? request.id : undefined;
185
+ const agent = request.agent ?? scriptAgent;
186
+ const task = resume !== undefined ? request.message : request.task;
187
+ // cwd is where execute runs a fresh local child. A resumed child keeps its retained directory, and a
188
+ // placed child's cwd names a directory on its machine, so neither gets a local cwd here.
189
+ const scope = resolveExecutionAgentScope(request.agentScope);
190
+ const findAgent = (dir) => typeof agent === "string" ? resolveAgentName(agent, discoverAgents(dir, scope).agents).agent : undefined;
191
+ const ctxAgent = request.machine === undefined ? findAgent(ctxCwd) : undefined;
192
+ const placed = request.machine !== undefined || ctxAgent?.machine !== undefined;
193
+ const runCwd = resolveRequestedCwd(ctxCwd, request.cwd);
194
+ const cwd = resume === undefined && !placed ? runCwd : undefined;
195
+ // Mirrors applySingleAgentLaunchDefaults: the agent's defaultAcceptance applies only to a fresh launch with no
196
+ // acceptance (gate is already acceptance here). A resume's retained commands were in the call that first launched it.
197
+ const acceptanceInput = request.acceptance !== undefined || resume !== undefined
198
+ ? request.acceptance
199
+ : (placed || runCwd === ctxCwd ? ctxAgent ?? findAgent(ctxCwd) : findAgent(runCwd))?.defaultAcceptance;
200
+ // An invalid acceptance fails the launch before anything runs. Verify commands run only at level
201
+ // "verified", which no inferred level reaches.
202
+ const acceptance = acceptanceInput !== undefined && validateAcceptanceInput(acceptanceInput).length === 0 ? normalizeAcceptanceInput(acceptanceInput) : undefined;
203
+ const commands = acceptance?.level === "verified" ? (acceptance.verify ?? []).map((verify) => ({
204
+ command: verify.command,
205
+ ...(cwd !== undefined ? { cwd: verify.cwd ? path.resolve(cwd, verify.cwd) : cwd } : {}),
206
+ ...(verify.env !== undefined ? { env: verify.env } : {}),
207
+ })) : [];
208
+ const output = resolveSingleOutputPath(request.output, ctxCwd);
209
+ return {
210
+ workflowRunId,
211
+ key,
212
+ ...(typeof agent === "string" ? { agent } : {}),
213
+ ...(typeof task === "string" ? { task } : {}),
214
+ ...(cwd !== undefined ? { cwd } : {}),
215
+ ...(typeof request.model === "string" ? { model: request.model } : {}),
216
+ ...(typeof request.async === "boolean" ? { async: request.async } : {}),
217
+ ...(typeof request.worktree === "boolean" ? { worktree: request.worktree } : {}),
218
+ ...(resume !== undefined ? { resume } : {}),
219
+ ...(commands.length > 0 ? { commands } : {}),
220
+ ...(output !== undefined ? { output } : {}),
221
+ };
222
+ }
180
223
  function readWorkflowScriptFile(requestedPath, requestedCwd, runtimeCwd) {
181
224
  const scriptPath = path.resolve(resolveRequestedCwd(runtimeCwd, requestedCwd), requestedPath);
182
225
  let script;
@@ -644,7 +687,7 @@ function resolveForegroundResumeTarget(params, state, options = {}) {
644
687
  throw new Error(`Ambiguous foreground run id prefix '${requested}' matched: ${matches.map((run) => run.runId).join(", ")}. Provide a longer id.`);
645
688
  const run = matches[0];
646
689
  if (run.children.some((child) => child.status === "detached"))
647
- throw new Error(`Foreground run '${run.runId}' is detached for intercom coordination and cannot be revived safely while any child may still be live. Reply to the supervisor request first, then wait with bg_wait({ id: "${run.runId}" }); use status to recover the result and do not launch a replacement while it remains detached.`);
690
+ throw new Error(`Foreground run '${run.runId}' is detached for intercom coordination and cannot be revived safely while any child may still be live. Reply to the supervisor request first, then wait with ${waitToolName()}({ id: "${run.runId}" }); use status to recover the result and do not launch a replacement while it remains detached.`);
648
691
  if (run.children.length > 1 && params.index === undefined)
649
692
  throw new Error(`Foreground run '${run.runId}' has ${run.children.length} children. Provide index to choose one.`);
650
693
  const index = params.index ?? 0;
@@ -795,9 +838,8 @@ function persistAsyncWorkflowControlEvent(input) {
795
838
  fs.appendFileSync(path.join(input.job.asyncDir, "events.jsonl"), `${JSON.stringify(record)}\n`, "utf-8");
796
839
  }
797
840
  catch (error) {
798
- if (!isStorageCapacityError(error))
799
- throw error;
800
- console.error("Failed to append async workflow control event while storage is full:", error);
841
+ // Called from the child's 1 s activity timer, where a throw would exit Pi; the notice itself is still sent.
842
+ reportSessionWarning(input.state, `Failed to record a control event for workflow ${input.job.asyncId}: ${error instanceof Error ? error.message : String(error)}`, "async-workflow-control-event");
801
843
  }
802
844
  }
803
845
  function emitControlNotification(input) {
@@ -1018,6 +1060,7 @@ function appendStepToAsyncChain(input) {
1018
1060
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
1019
1061
  parentSessionFile: input.ctx.sessionManager.getSessionFile() ?? undefined,
1020
1062
  currentModelProvider: parentModel?.provider,
1063
+ parentProviderRegistry: input.ctx.modelRegistry,
1021
1064
  currentModel: parentModel,
1022
1065
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
1023
1066
  modelScope: discoveredForAppend.modelScope,
@@ -1179,8 +1222,8 @@ function validateNestedSessionFile(run, trustedSessionRoots, resolveSource, visi
1179
1222
  }
1180
1223
  return realSessionFile;
1181
1224
  }
1182
- export function readNestedRecoveryDescriptor(asyncDir, runId, agent) {
1183
- const recoveryDescriptor = readAsyncRecoveryDescriptor(asyncDir);
1225
+ export function readNestedRecoveryDescriptor(rootRunId, runId, agent) {
1226
+ const recoveryDescriptor = readAsyncRecoveryDescriptor(nestedRunScope(rootRunId).asyncDirRoot, runId);
1184
1227
  if (!recoveryDescriptor)
1185
1228
  return undefined;
1186
1229
  if (recoveryDescriptor.sourceRunId !== runId)
@@ -1200,7 +1243,7 @@ function resolveNestedResumeTarget(match, trustedSessionRoots, resolveSource) {
1200
1243
  throw new Error(`Could not determine child agent for nested run '${run.id}'.`);
1201
1244
  const state = run.state === "complete" || run.state === "failed" || run.state === "paused" ? run.state : "failed";
1202
1245
  const asyncDir = resolveNestedAsyncDir(match.match.rootRunId, run);
1203
- const recoveryDescriptor = readNestedRecoveryDescriptor(asyncDir, run.id, agent);
1246
+ const recoveryDescriptor = asyncDir ? readNestedRecoveryDescriptor(match.match.rootRunId, run.id, agent) : undefined;
1204
1247
  return compactOptional({
1205
1248
  kind: "revive",
1206
1249
  source: "nested",
@@ -1505,6 +1548,7 @@ async function resumeExternalJobFollowUp(input) {
1505
1548
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
1506
1549
  parentSessionFile: input.ctx.sessionManager.getSessionFile() ?? undefined,
1507
1550
  currentModelProvider: parentModel?.provider,
1551
+ parentProviderRegistry: input.ctx.modelRegistry,
1508
1552
  currentModel: parentModel,
1509
1553
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
1510
1554
  modelScope: input.modelScope,
@@ -1686,6 +1730,20 @@ async function resumeAsyncRun(input) {
1686
1730
  details: { mode: "management", results: [] },
1687
1731
  };
1688
1732
  }
1733
+ // Before any worktree protection or chain attachment: a launch that required a launcher and agent definition
1734
+ // resumes only while both still hold.
1735
+ const requiredLauncher = recoveryDescriptor?.requiredLauncher;
1736
+ if (requiredLauncher) {
1737
+ const refuse = (text) => ({ content: [{ type: "text", text }], isError: true, details: { mode: "management", results: [] } });
1738
+ if (attachChain)
1739
+ return refuse(`Cannot attach a chain to run '${target.runId}': it was launched with requireLauncher, and appended steps would run inside its runner unchecked.`);
1740
+ const currentDigest = discoveredAgentConfig ? agentDefinitionDigest(discoveredAgentConfig) : undefined;
1741
+ const now = !discoveredAgentConfig ? "is missing"
1742
+ : recoveryDescriptor.launcher !== requiredLauncher.name || discoveredAgentConfig.launcher !== requiredLauncher.name ? `uses launcher '${discoveredAgentConfig.launcher ?? "none"}'`
1743
+ : currentDigest !== requiredLauncher.definitionDigest ? `has digest ${currentDigest}` : undefined;
1744
+ if (now)
1745
+ return refuse(`Cannot resume: run '${target.runId}' was launched requiring launcher '${requiredLauncher.name}' and agent definition ${requiredLauncher.definitionDigest}; agent '${target.agent}' now ${now}.`);
1746
+ }
1689
1747
  if (target.source === "async" && target.runner?.type === "external-cli") {
1690
1748
  const runner = normalizeExternalCliRunnerStatus(target.runner);
1691
1749
  const message = runner
@@ -1696,7 +1754,8 @@ async function resumeAsyncRun(input) {
1696
1754
  if (input.params.baseRef !== undefined && "managedWorktree" in target && target.managedWorktree === true) {
1697
1755
  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: [] } };
1698
1756
  }
1699
- if (target.source === "async" && target.managedWorktree && target.asyncDir) {
1757
+ // Without a handoff the resume runs in the worktree the descriptor recorded; there is no cleanup record to mark preserved.
1758
+ if (target.source === "async" && target.managedWorktree && target.asyncDir && fs.existsSync(parallelHandoffPath(target.asyncDir))) {
1700
1759
  try {
1701
1760
  const protectedCwd = await protectRetainedWorktreeForResume(parallelHandoffPath(target.asyncDir), target.runId, target.index, input.signal);
1702
1761
  if (path.resolve(protectedCwd) !== path.resolve(effectiveCwd))
@@ -1793,6 +1852,7 @@ async function resumeAsyncRun(input) {
1793
1852
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
1794
1853
  parentSessionFile: input.ctx.sessionManager.getSessionFile() ?? undefined,
1795
1854
  currentModelProvider: parentModel?.provider,
1855
+ parentProviderRegistry: input.ctx.modelRegistry,
1796
1856
  currentModel: parentModel,
1797
1857
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
1798
1858
  modelScope,
@@ -1861,8 +1921,8 @@ async function resumeAsyncRun(input) {
1861
1921
  if (target.source === "nested" && !target.recoveryDescriptor) {
1862
1922
  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: [] } };
1863
1923
  }
1864
- // Runs without a recovery descriptor were never wrapped; a launcher added to the agent file later does not apply.
1865
- const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : { ...baseAgentConfig, launcher: undefined };
1924
+ // Without a recovery descriptor nothing records how the run was wrapped, so the agent file's launcher applies.
1925
+ const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : baseAgentConfig;
1866
1926
  const agentConfig = intercomBridge.active ? applyIntercomBridgeToAgent(recoveryAgentConfig, intercomBridge) : recoveryAgentConfig;
1867
1927
  const foregroundContract = target.source === "foreground" ? target.resumeContract : undefined;
1868
1928
  const outputSchema = Object.hasOwn(input.params, "outputSchema")
@@ -1881,7 +1941,7 @@ async function resumeAsyncRun(input) {
1881
1941
  }
1882
1942
  // Refuse before capacity moves so the retained run stays resumable once the config is fixed.
1883
1943
  if (agentConfig.launcher !== undefined && !lookupRunnerLauncher(input.deps.config.runnerLaunchers, agentConfig.launcher)) {
1884
- return { content: [{ type: "text", text: `Cannot resume: run '${target.runId}' was launched with launcher '${agentConfig.launcher}', which is no longer defined in runnerLaunchers in the user subagent config.` }], isError: true, details: { mode: "management", results: [] } };
1944
+ return { content: [{ type: "text", text: `Cannot resume: run '${target.runId}' uses launcher '${agentConfig.launcher}', which is no longer defined in runnerLaunchers in the user subagent config.` }], isError: true, details: { mode: "management", results: [] } };
1885
1945
  }
1886
1946
  const runId = randomUUID();
1887
1947
  const topLevelResume = depth === 0 && !inheritedNestedRoute(input.deps) && !input.params.workflowParentRunId;
@@ -1927,6 +1987,7 @@ async function resumeAsyncRun(input) {
1927
1987
  goal: effectiveFollowUp,
1928
1988
  agentConfig,
1929
1989
  recoveryAgentConfig,
1990
+ carriedRequiredLauncher: recoveryDescriptor?.requiredLauncher,
1930
1991
  ctx: compactOptional({
1931
1992
  pi: input.deps.pi,
1932
1993
  cwd: input.requestCwd,
@@ -1934,6 +1995,7 @@ async function resumeAsyncRun(input) {
1934
1995
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
1935
1996
  parentSessionFile: input.ctx.sessionManager.getSessionFile() ?? undefined,
1936
1997
  currentModelProvider: parentModel?.provider,
1998
+ parentProviderRegistry: input.ctx.modelRegistry,
1937
1999
  currentModel: parentModel,
1938
2000
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
1939
2001
  modelScope,
@@ -2113,6 +2175,7 @@ function createForegroundControlNotifier(data, deps) {
2113
2175
  const enriched = workflowKey && !event.workflowKey ? { ...event, workflowKey } : event;
2114
2176
  if (asyncWorkflow) {
2115
2177
  persistAsyncWorkflowControlEvent({
2178
+ state: deps.state,
2116
2179
  job: asyncWorkflow,
2117
2180
  event: enriched,
2118
2181
  controlConfig: data.controlConfig,
@@ -3105,6 +3168,7 @@ async function runAsyncPath(data, deps) {
3105
3168
  parentSessionId: data.parentPiSessionId,
3106
3169
  parentSessionFile: ctx.sessionManager.getSessionFile() ?? undefined,
3107
3170
  currentModelProvider: parentModel?.provider,
3171
+ parentProviderRegistry: ctx.modelRegistry,
3108
3172
  currentModel: parentModel,
3109
3173
  scopedModelIds: data.scopedModelIds,
3110
3174
  modelScope: data.modelScope,
@@ -3172,6 +3236,7 @@ async function runAsyncPath(data, deps) {
3172
3236
  requestedCwd: data.requestedCwd,
3173
3237
  machine: params.machine,
3174
3238
  machineCwd: params.machineCwd,
3239
+ requireLauncher: params.requireLauncher,
3175
3240
  maxOutput: params.maxOutput,
3176
3241
  artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
3177
3242
  artifactConfig,
@@ -3672,7 +3737,7 @@ async function runSinglePath(data, deps) {
3672
3737
  ? `[Read from: ${readPaths.join(", ")}]\n\n`
3673
3738
  : "";
3674
3739
  task = readsInstruction + task;
3675
- task = injectSingleOutputInstruction(task, outputPath, agentConfig);
3740
+ task = injectSingleOutputInstruction(task, outputPath, agentConfig, foregroundMachine);
3676
3741
  let effectiveSkills;
3677
3742
  if (skillOverride === false) {
3678
3743
  effectiveSkills = [];
@@ -3824,6 +3889,7 @@ async function runSinglePath(data, deps) {
3824
3889
  suppressUnchangedDelegationUpdates,
3825
3890
  controlConfig,
3826
3891
  onControlEvent,
3892
+ onWarning: (message, key) => reportSessionWarning(deps.state, message, key),
3827
3893
  intercomSessionName: childIntercomTarget,
3828
3894
  orchestratorIntercomTarget: childBridgeActive ? data.intercomBridge.orchestratorTarget : undefined,
3829
3895
  nestedRoute: foregroundControl?.nestedRoute,
@@ -4012,11 +4078,11 @@ async function runSinglePath(data, deps) {
4012
4078
  const worktreeSuffix = worktreeHandoff?.suffix ? `\n\n${worktreeHandoff.suffix}` : "";
4013
4079
  if (r.detached) {
4014
4080
  const statusRecovery = `subagent({ action: "status", id: "${runId}" }) to recover the result; do not resume or launch a replacement while it remains detached.`;
4015
- const blockingRecovery = `bg_wait({ id: "${runId}" }). Use ${statusRecovery}`;
4081
+ const blockingRecovery = `${waitToolName()}({ id: "${runId}" }). Use ${statusRecovery}`;
4016
4082
  const message = r.detachedReason === "intercom coordination"
4017
4083
  ? `Detached for intercom coordination: ${params.agent}. Reply to the supervisor request first, then wait with ${blockingRecovery}`
4018
4084
  : r.detachedReason === "user request"
4019
- ? `Detached at user request: ${params.agent}. The child continues independently. Register a completion wake-up with bg_wait({ id: "${runId}", nonBlocking: true }), or use ${statusRecovery}`
4085
+ ? `Detached at user request: ${params.agent}. The child continues independently. Register a completion wake-up with ${waitToolName()}({ id: "${runId}", nonBlocking: true }), or use ${statusRecovery}`
4020
4086
  : `Detached before task completion: ${params.agent}. Wait with ${blockingRecovery}`;
4021
4087
  return {
4022
4088
  content: [{ type: "text", text: `${message}${worktreeSuffix}` }],
@@ -4496,6 +4562,9 @@ export async function preflightWorkflowWorktrees(input) {
4496
4562
  input.signal.throwIfAborted();
4497
4563
  }
4498
4564
  export function prepareWorkflowLaunchParams(workflowDefaults, childParams, parentWorkflowRunId, workflowKey, options = {}) {
4565
+ // Before the resume branch below, which rebuilds params field by field and would drop the requirement.
4566
+ if (childParams.requireLauncher !== undefined || workflowDefaults.requireLauncher !== undefined)
4567
+ throw new Error(REQUIRE_LAUNCHER_SHAPE_ERROR);
4499
4568
  const { globalConcurrencyLimit: _globalConcurrencyLimit, maxSubagentSpawnsPerRun: _maxSubagentSpawnsPerRun, ...workflowDefaultsWithoutCapacity } = workflowDefaults;
4500
4569
  const { globalConcurrencyLimit: _childGlobalConcurrencyLimit, maxSubagentSpawnsPerRun: _childMaxSubagentSpawnsPerRun, ...childParamsWithoutCapacity } = childParams;
4501
4570
  workflowDefaults = workflowDefaultsWithoutCapacity;
@@ -4774,11 +4843,12 @@ function savedWorkflowLaunchParams(params) {
4774
4843
  const { reuseFrom: _reuseFrom, scheduleOrigin: _scheduleOrigin, resumeOrigin: _resumeOrigin, ...saved } = params;
4775
4844
  return saved;
4776
4845
  }
4777
- function workflowLaunchRecord(launch, cwd, scriptDigest) {
4778
- if (launch.source === "structured")
4779
- return { version: 1, source: "structured", scriptDigest };
4846
+ function workflowLaunchRecord(launch, cwd, scriptDigest, sessionId, ceiling) {
4847
+ const owner = { version: 2, scriptDigest, sessionId, ...(ceiling ? { admissionCapabilityCeiling: ceiling } : {}) };
4848
+ if (launch.source === "structured" || launch.source === "internal")
4849
+ return { ...owner, source: launch.source };
4780
4850
  // The resolved cwd is saved: a relative one would resolve against a later session's cwd.
4781
- return { version: 1, source: launch.source, params: { ...launch.params, cwd }, scriptDigest };
4851
+ return { ...owner, source: launch.source, params: { ...launch.params, cwd } };
4782
4852
  }
4783
4853
  export function createSubagentExecutor(deps) {
4784
4854
  const executorDeps = deps;
@@ -5099,8 +5169,8 @@ export function createSubagentExecutor(deps) {
5099
5169
  try {
5100
5170
  fs.mkdirSync(asyncDir, { recursive: true });
5101
5171
  writeRunFanoutBudgetDescriptor(asyncDir, workflowFanoutBudget);
5102
- if (topLevelAsyncWorkflow && publicWorkflowLaunch)
5103
- writeWorkflowLaunchRecord(asyncDir, workflowLaunchRecord(publicWorkflowLaunch, workflowCwd, workflowScriptSourceDigest));
5172
+ if (topLevelAsyncWorkflow)
5173
+ writeWorkflowLaunchRecord(DIRS.async, workflowRunId, workflowLaunchRecord(publicWorkflowLaunch ?? { source: "internal" }, workflowCwd, workflowScriptSourceDigest, currentSessionId, workflowCapabilityCeiling));
5104
5174
  fs.mkdirSync(DIRS.results, { recursive: true });
5105
5175
  }
5106
5176
  catch (error) {
@@ -5860,9 +5930,12 @@ export function createSubagentExecutor(deps) {
5860
5930
  heartbeat: { status: "running", ...(childPhase ? { phase: childPhase } : {}) },
5861
5931
  });
5862
5932
  let preparedChildParams;
5863
- const result = await runMissionWorkflowChild(missionBinding, workflowRunId, key, childPhase, () => {
5933
+ const result = await runMissionWorkflowChild(missionBinding, workflowRunId, key, childPhase, async () => {
5864
5934
  const childRequest = bindMissionWorkflowChildAsyncLaunch({ ...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 }, missionBinding, deps.asyncByDefault, undefined, inheritedNestedRoute(deps)?.rootRunId);
5865
5935
  preparedChildParams = childRequest;
5936
+ const launchRefusal = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(workflowRunId, key, childRequest, childParams.agent, parentCwd, discoverWorkflowAgents), workflowSignal);
5937
+ if (launchRefusal)
5938
+ return buildRequestedModeError(childRequest, launchRefusal);
5866
5939
  if (workflowUsageBudget.budget)
5867
5940
  workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
5868
5941
  if (workflowRequiredExtensions)
@@ -6187,9 +6260,12 @@ export function createSubagentExecutor(deps) {
6187
6260
  heartbeat: { status: "running", ...(childPhase ? { phase: childPhase } : {}) },
6188
6261
  });
6189
6262
  let preparedChildParams;
6190
- const result = await runMissionWorkflowChild(missionBinding, foregroundWorkflowRunId, key, childPhase, () => {
6263
+ const result = await runMissionWorkflowChild(missionBinding, foregroundWorkflowRunId, key, childPhase, async () => {
6191
6264
  const childRequest = bindMissionWorkflowChildAsyncLaunch({ ...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 }, missionBinding, deps.asyncByDefault, undefined, inheritedNestedRoute(deps)?.rootRunId);
6192
6265
  preparedChildParams = childRequest;
6266
+ const launchRefusal = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(foregroundWorkflowRunId, key, childRequest, childParams.agent, ctx.cwd, discoverWorkflowAgents), workflowSignal);
6267
+ if (launchRefusal)
6268
+ return buildRequestedModeError(childRequest, launchRefusal);
6193
6269
  if (workflowUsageBudget.budget)
6194
6270
  workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
6195
6271
  if (workflowRequiredExtensions)
@@ -7257,6 +7333,16 @@ export function createSubagentExecutor(deps) {
7257
7333
  if (launcherError)
7258
7334
  return buildRequestedModeError(effectiveParams, launcherError);
7259
7335
  }
7336
+ // Refused here, before admission; executeAsyncSingle checks again on the exact agent and launcher it spawns.
7337
+ if (effectiveParams.requireLauncher !== undefined) {
7338
+ if (!effectiveParams.requireLauncher || typeof effectiveParams.requireLauncher !== "object")
7339
+ return buildRequestedModeError(effectiveParams, "requireLauncher must be { name, definitionDigest }.");
7340
+ if (!hasSingle || effectiveParams.resume !== undefined || effectiveParams.workflowParentRunId !== undefined)
7341
+ return buildRequestedModeError(effectiveParams, REQUIRE_LAUNCHER_SHAPE_ERROR);
7342
+ const required = selectedAgents[0] ? checkRequiredRunnerLauncher(selectedAgents[0], selectedAgents[0].launcher, effectiveParams.requireLauncher) : undefined;
7343
+ if (required?.error)
7344
+ return buildRequestedModeError(effectiveParams, required.error);
7345
+ }
7260
7346
  if (effectiveAsync && hasSingle && effectiveParams.resume === undefined && effectiveParams.worktree === true) {
7261
7347
  try {
7262
7348
  await preflightWorktreeSource(effectiveCwd, { signal });
@@ -135,8 +135,20 @@ export function createChildCommandRuntime(channelDir) {
135
135
  persist();
136
136
  startInbox();
137
137
  let timer;
138
+ let yieldSaveError;
139
+ // A throw from this timer would exit Pi. A closed controller is already cancelling the command; a failed
140
+ // save still yields, and the handle says the saved state is stale.
138
141
  if (typeof yieldTimeMs === "number")
139
- timer = setTimeout(() => operate("yield", toolCallId), yieldTimeMs);
142
+ timer = setTimeout(() => {
143
+ if (closed)
144
+ return;
145
+ try {
146
+ operate("yield", toolCallId);
147
+ }
148
+ catch (error) {
149
+ yieldSaveError = error;
150
+ }
151
+ }, yieldTimeMs);
140
152
  const execution = Promise.resolve().then(() => tool.execute(toolCallId, args, commandSignal, (update) => {
141
153
  job.snapshot.output = text(update);
142
154
  if (job.snapshot.state === "running")
@@ -163,7 +175,8 @@ export function createChildCommandRuntime(channelDir) {
163
175
  const result = await Promise.race([execution.then((value) => ({ value })), yielded.then(() => undefined)]);
164
176
  if (result)
165
177
  return result.value;
166
- return { content: [{ type: "text", text: `Command is still running (toolCallId: ${toolCallId}). This is not a successful exit. Use subagent_command({ action: "status", toolCallId: ${JSON.stringify(toolCallId)} }) to inspect or wait, or action: "cancel" to stop it.\n${job.snapshot.output}` }], details: { command: { ...job.snapshot } } };
178
+ const saveWarning = yieldSaveError === undefined ? "" : `\nThe command's saved state is out of date because it could not be saved: ${yieldSaveError instanceof Error ? yieldSaveError.message : String(yieldSaveError)}`;
179
+ return { content: [{ type: "text", text: `Command is still running (toolCallId: ${toolCallId}). This is not a successful exit. Use subagent_command({ action: "status", toolCallId: ${JSON.stringify(toolCallId)} }) to inspect or wait, or action: "cancel" to stop it.${saveWarning}\n${job.snapshot.output}` }], details: { command: { ...job.snapshot } } };
167
180
  },
168
181
  };
169
182
  },
@@ -1,13 +1,7 @@
1
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
1
  import type { ChildRuntimeConfig } from "./child-runtime-config.ts";
3
2
  import type { ChildToolDiagnostic } from "./tool-availability.ts";
4
- import type { ChildSessionLaunch } from "./child-session.ts";
3
+ import type { ChildHookExtension, ChildSessionLaunch } from "./child-session.ts";
5
4
  import type { ChildTranscriptWriter } from "../../shared/child-transcript.ts";
6
- /** Inline extension shape accepted by pi's resource loader (`extensionFactories`). */
7
- export interface ChildHookExtension {
8
- name: string;
9
- factory: (pi: ExtensionAPI) => void;
10
- }
11
5
  /** The host's mandatory transcript reporting, owned by the existing hook certificate. */
12
6
  export declare function withChildSessionErrorReporting(session: Omit<ChildSessionLaunch, "onExtensionError">, transcriptWriter: ChildTranscriptWriter | undefined): ChildSessionLaunch;
13
7
  export declare function isReadonlyChildSessionReporting(launch: ChildSessionLaunch): boolean;
@@ -3,6 +3,7 @@ import { ReadonlyDrainObservation } from "./readonly-drain-observation.js";
3
3
  import registerFanoutChildSubagentExtension, { createChildSafeState } from "../../extension/fanout-child.js";
4
4
  import registerSubagentFastModeExtension from "./fast-mode-extension.js";
5
5
  import registerSubagentPromptRuntime, { registerSubagentPromptBoundary } from "./subagent-prompt-runtime.js";
6
+ import { structuredOutputValidatorReady } from "./structured-output.js";
6
7
  import { projectRuntimeAcknowledgedExtensions } from "./runtime-acknowledged-extensions.js";
7
8
  const promptProofs = new WeakMap();
8
9
  function ownedProof(hooks) {
@@ -153,11 +154,18 @@ function childHooks(config, capture, holdFinalDrain) {
153
154
  }
154
155
  const hooks = [
155
156
  { name: "pi-subagents:prompt-runtime", factory: function promptRuntime(pi) {
156
- if (!proof?.observeNext)
157
- return registerSubagentPromptRuntime(pi, runtime);
158
- proof.observation = proof.observeNext;
159
- proof.observeNext = undefined;
160
- registerSubagentPromptRuntime(pi, runtime, proof.observation);
157
+ if (!proof?.observeNext) {
158
+ registerSubagentPromptRuntime(pi, runtime);
159
+ }
160
+ else {
161
+ proof.observation = proof.observeNext;
162
+ proof.observeNext = undefined;
163
+ registerSubagentPromptRuntime(pi, runtime, proof.observation);
164
+ }
165
+ // Pi awaits extension factories, so structured_output's synchronous prepareArguments has its
166
+ // validator before the model can call it.
167
+ if (runtime.structuredOutput)
168
+ return structuredOutputValidatorReady();
161
169
  } },
162
170
  ];
163
171
  if (config.fast)
@@ -14,6 +14,7 @@ import { intersectSubagentCapabilityCeilings } from "./capability-ceiling.js";
14
14
  import { isSubagentRuntimeExtensionPath, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan, supervisorChannelDir, } from "./child-tool-plan.js";
15
15
  import { createCapturedChildHooks, withChildSessionErrorReporting } from "./child-hooks.js";
16
16
  import { resolveRequiredChildExtensions } from "../../shared/required-child-extensions.js";
17
+ import { DEFAULT_WAIT_TOOL_NAME, waitToolName } from "../../shared/wait-tool-name.js";
17
18
  /** Environment variable pi-mcp-adapter reads for the tools a child may expose. */
18
19
  export const MCP_DIRECT_TOOLS_ENV = "MCP_DIRECT_TOOLS";
19
20
  export function inheritedChildRuntime(config) {
@@ -34,7 +35,6 @@ export function inheritedChildRuntime(config) {
34
35
  export function createReportedChildSessionInput(launch, transcriptWriter) {
35
36
  return withChildSessionErrorReporting(launch.session, transcriptWriter);
36
37
  }
37
- /** Escape XML-significant characters in a string for safe attribute interpolation. */
38
38
  function escapeXmlAttr(value) {
39
39
  return value
40
40
  .replace(/&/g, "&amp;")
@@ -75,7 +75,10 @@ function childStorage(input) {
75
75
  return { kind: "default" };
76
76
  }
77
77
  export function buildInProcessChildLaunch(input) {
78
- const requiredExtensions = input.requiredExtensions ?? input.inherited?.requiredExtensions ?? resolveRequiredChildExtensions(input.parentSessionId);
78
+ const resolvedRequiredExtensions = input.requiredExtensions ?? input.inherited?.requiredExtensions ?? resolveRequiredChildExtensions(input.parentSessionId);
79
+ // A placed child cannot load local extension paths, so it skips non-mandatory entries like an
80
+ // external runner does; a mandatory one stays and refuses the launch when it is serialized.
81
+ const requiredExtensions = input.machine ? resolvedRequiredExtensions.filter((entry) => entry.requireForAllRunners) : resolvedRequiredExtensions;
79
82
  const agentCapabilityCeiling = input.descendantAllowedAgents === undefined
80
83
  ? undefined
81
84
  : { version: 1, allowedAgents: [...input.descendantAllowedAgents], denyExtensions: false, sources: [`agent:${input.childAgentName}`] };
@@ -171,6 +174,7 @@ export function buildInProcessChildLaunch(input) {
171
174
  waitTool: {
172
175
  enabled: input.waitToolEnabled ?? true,
173
176
  ...(input.waitToolDefaultTimeoutMs !== undefined ? { defaultTimeoutMs: input.waitToolDefaultTimeoutMs } : {}),
177
+ ...(waitToolName() !== DEFAULT_WAIT_TOOL_NAME ? { name: waitToolName() } : {}),
174
178
  },
175
179
  ...(input.structuredOutput
176
180
  ? {
@@ -90,7 +90,6 @@ export interface ChildRuntimeConfig {
90
90
  permissions?: ChildPermissions;
91
91
  toolBudget?: ResolvedToolBudget;
92
92
  childWatchdog?: ChildWatchdogConfig;
93
- /** Receives child watchdog status events. */
94
93
  watchdogStatus?: (event: ChildWatchdogStatusEvent) => void;
95
94
  waitTool: ResolvedWaitToolConfig;
96
95
  runtimeState?: SubagentState;
@@ -16,7 +16,7 @@ export interface ChildSessionExtensionError {
16
16
  }
17
17
  export interface ChildHookExtension {
18
18
  name: string;
19
- factory: (pi: ExtensionAPI) => void;
19
+ factory: (pi: ExtensionAPI) => void | Promise<void>;
20
20
  }
21
21
  export type ChildSessionStorage = {
22
22
  kind: "file";
@@ -109,6 +109,8 @@ export interface ChildSession {
109
109
  readonly modelId: string | undefined;
110
110
  /** Provider id of the selected model when this child inherited that provider from the parent's registry instead of loading its extension. */
111
111
  readonly inheritedProvider?: string;
112
+ /** Provider id of the selected model when an extension in this child's model runtime registered that provider, at load or later (e.g. on `session_start`). */
113
+ readonly claimedProvider?: string;
112
114
  /** Live provider/id of the selected model when Pi marks it virtual (`api === "pi-virtual"`); assistant messages then name the dispatched physical model. */
113
115
  readonly virtualModelId?: string;
114
116
  readonly contextWindow?: number;
@@ -18,6 +18,7 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
18
18
  import * as fs from "node:fs";
19
19
  import * as path from "node:path";
20
20
  import { pathToFileURL } from "node:url";
21
+ import { cleanupSessionResources, registerSessionResourceCleanup } from "@earendil-works/pi-ai";
21
22
  import { CHILD_COMMAND_TOOL, createChildCommandRuntime } from "./child-commands.js";
22
23
  import { supervisorChannelDir } from "./child-tool-plan.js";
23
24
  import { pinChildCacheRetention } from "../../shared/child-cache-retention.js";
@@ -138,6 +139,24 @@ function prioritizeChildCommandRuntime(result) {
138
139
  extensions.unshift(commands);
139
140
  return { ...result, extensions };
140
141
  }
142
+ /**
143
+ * `dispose()` releases session resources only in the SDK's copy of pi-ai. Under Pi's bundled CLI, the host's
144
+ * extensions register theirs in a different copy: the one this module imports. The observer is registered per
145
+ * dispose because Pi reloads extensions without a module cache, so a module-level one would pile up on each reload.
146
+ */
147
+ function disposeChildSession(session) {
148
+ let released = false;
149
+ const unregister = registerSessionResourceCleanup((sessionId) => { if (sessionId === session.sessionId)
150
+ released = true; });
151
+ try {
152
+ session.dispose();
153
+ }
154
+ finally {
155
+ unregister();
156
+ if (!released)
157
+ cleanupSessionResources(session.sessionId);
158
+ }
159
+ }
141
160
  /** One launch at a time from env application through `session_start`, so parallel launches never observe each other's `processEnv` while their extensions load and start. */
142
161
  let loading = Promise.resolve();
143
162
  /**
@@ -472,7 +491,7 @@ export function createDefaultChildSessionFactory(options = {}) {
472
491
  launch.onExtensionError?.({ extensionPath: "<session>", event: "session_shutdown", error });
473
492
  }
474
493
  finally {
475
- session.dispose();
494
+ disposeChildSession(session);
476
495
  }
477
496
  };
478
497
  let inheritedProviders = new Set();
@@ -552,7 +571,7 @@ export function createDefaultChildSessionFactory(options = {}) {
552
571
  });
553
572
  }
554
573
  catch (error) {
555
- session.dispose();
574
+ disposeChildSession(session);
556
575
  throw error;
557
576
  }
558
577
  finally {
@@ -633,6 +652,7 @@ export function createDefaultChildSessionFactory(options = {}) {
633
652
  get sessionId() { return session.sessionId; },
634
653
  get modelId() { return session.model ? `${session.model.provider}/${session.model.id}` : undefined; },
635
654
  get inheritedProvider() { return session.model && inheritedProviders.has(session.model.provider) ? session.model.provider : undefined; },
655
+ get claimedProvider() { return session.model && !inheritedProviders.has(session.model.provider) && modelRuntime.getRegisteredProviderIds().includes(session.model.provider) ? session.model.provider : undefined; },
636
656
  get virtualModelId() { return session.model?.api === "pi-virtual" ? `${session.model.provider}/${session.model.id}` : undefined; },
637
657
  get contextWindow() { return session.model?.contextWindow; },
638
658
  };
@@ -74,7 +74,6 @@ export declare function formatRuntimeSnapshotMcpServersError(agentName: string |
74
74
  export declare function assertNoToolModifierEntries(agentName: string | undefined, tools: readonly string[]): void;
75
75
  export declare function projectLaunchResolvedChildExtensions(toolPlan: Pick<PiLaunchToolPlan, "runtimeExtensions" | "configuredExtensions" | "requiredExtensions" | "extensionArgs" | "disableAmbientExtensions">): LaunchResolvedChildExtensions;
76
76
  /**
77
- * Resolve the permission-system extension entry point when installed.
78
77
  * Returns the absolute path to the extension's main module, or undefined
79
78
  * when the package is not installed. Callers can check `autoInject` config
80
79
  * to decide whether to include it in child sessions.
@@ -138,7 +138,6 @@ export function projectLaunchResolvedChildExtensions(toolPlan) {
138
138
  };
139
139
  }
140
140
  /**
141
- * Resolve the permission-system extension entry point when installed.
142
141
  * Returns the absolute path to the extension's main module, or undefined
143
142
  * when the package is not installed. Callers can check `autoInject` config
144
143
  * to decide whether to include it in child sessions.
@@ -201,6 +201,17 @@ export function createClaudeCodeJsonlParser() {
201
201
  }
202
202
  return { phase: terminal ? terminal.state : "streaming", eventCount };
203
203
  },
204
+ /**
205
+ * Reading an image returns it as base64 in a user-role tool result, so that line can be far
206
+ * larger than the parser line limit. Only user lines are absorbed: a terminal `result` is
207
+ * never skipped, because dropping it would discard the answer. The runner bounds the size.
208
+ */
209
+ skipOversizedLine(prefix) {
210
+ if (terminal || !/^\s*\{\s*"type"\s*:\s*"user"\s*,/.test(prefix))
211
+ return undefined;
212
+ eventCount += 1;
213
+ return { phase: "streaming", eventCount };
214
+ },
204
215
  finish() {
205
216
  return terminal;
206
217
  },