@vicary/pi-subagents 0.84.0-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 (204) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-F4ASL6OV.js → chunk-7MAE3DJV.js} +1 -1
  5. package/bundle/{chunk-4MDR6V46.js → chunk-A7VJ5XXE.js} +190 -1177
  6. package/bundle/{chunk-LGLEH7B6.js → chunk-B3OOJJA6.js} +231 -182
  7. package/bundle/{chunk-4E7BKDTX.js → chunk-CS4O36CZ.js} +11 -156
  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-T44HVL5U.js → chunk-HFTBF7SG.js} +2 -1
  11. package/bundle/{chunk-F4AMYP5N.js → chunk-HS4WPO6B.js} +15 -6
  12. package/bundle/chunk-HXRB42AF.js +108 -0
  13. package/bundle/{chunk-4NIY3BE6.js → chunk-JHBQ7N2L.js} +2 -2
  14. package/bundle/{chunk-HKJLSMXV.js → chunk-JO67XSKD.js} +59 -27
  15. package/bundle/{chunk-C5P5CHYK.js → chunk-KDMFBYFM.js} +1 -1
  16. package/bundle/{chunk-V2BZYLEP.js → chunk-KEY3UQMQ.js} +7 -2
  17. package/bundle/{chunk-NENDSQUY.js → chunk-KZ34KQQH.js} +9 -6
  18. package/bundle/{chunk-AKOIVLA5.js → chunk-L2ENOFVZ.js} +76 -58
  19. package/bundle/{chunk-CGN2TVE7.js → chunk-LGMILZNE.js} +322 -18
  20. package/bundle/{chunk-L3WFKBEI.js → chunk-LTPH2DXH.js} +247 -153
  21. package/bundle/{chunk-2D52JFLF.js → chunk-N7B2KD74.js} +41 -117
  22. package/bundle/{chunk-PV63UFUR.js → chunk-O7CPL6H4.js} +183 -28
  23. package/bundle/{chunk-D3JAFGMO.js → chunk-PHZP3KHB.js} +1 -1
  24. package/bundle/{chunk-2DHZTCOL.js → chunk-PVIVCDG2.js} +2 -2
  25. package/bundle/{chunk-LFDBD4PW.js → chunk-QO75KJBT.js} +2 -2
  26. package/bundle/{chunk-67ENPDDA.js → chunk-QZL2ZZPM.js} +22 -11
  27. package/bundle/{chunk-PALJGGYC.js → chunk-RV5OGHLO.js} +6 -3
  28. package/bundle/chunk-T5V5BRCL.js +1067 -0
  29. package/bundle/{chunk-LNRJCP2Y.js → chunk-UX4SCV5N.js} +337 -207
  30. package/bundle/{chunk-TE4LHYHN.js → chunk-VEZMZDTW.js} +209 -93
  31. package/bundle/{chunk-X2MXCSA5.js → chunk-YZBCREP5.js} +310 -101
  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 +2 -2
  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 +5 -9
  78. package/src/runs/background/async-execution.js +62 -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.js +6 -1
  83. package/src/runs/background/auto-drain.js +2 -1
  84. package/src/runs/background/boot-id.d.ts +1 -3
  85. package/src/runs/background/boot-id.js +1 -3
  86. package/src/runs/background/completion-batcher.d.ts +3 -4
  87. package/src/runs/background/completion-batcher.js +2 -3
  88. package/src/runs/background/control-channel.d.ts +0 -6
  89. package/src/runs/background/control-channel.js +0 -6
  90. package/src/runs/background/fleet-view.js +2 -3
  91. package/src/runs/background/notify.d.ts +0 -2
  92. package/src/runs/background/notify.js +0 -2
  93. package/src/runs/background/result-watcher.d.ts +1 -0
  94. package/src/runs/background/result-watcher.js +59 -29
  95. package/src/runs/background/resume-guidance.js +4 -2
  96. package/src/runs/background/retained-children.js +2 -1
  97. package/src/runs/background/run-child-session.d.ts +0 -1
  98. package/src/runs/background/run-child-session.js +1 -1
  99. package/src/runs/background/run-status.js +4 -3
  100. package/src/runs/background/scheduled-runs.d.ts +3 -1
  101. package/src/runs/background/scheduled-runs.js +13 -16
  102. package/src/runs/background/subagent-runner.d.ts +2 -4
  103. package/src/runs/background/subagent-runner.js +9 -6
  104. package/src/runs/background/subagent-wait.js +12 -15
  105. package/src/runs/background/wait-config.d.ts +2 -0
  106. package/src/runs/background/wait-config.js +17 -3
  107. package/src/runs/background/wait-tool.js +4 -2
  108. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  109. package/src/runs/background/workflow-terminal-proof.js +0 -1
  110. package/src/runs/foreground/execution.d.ts +0 -3
  111. package/src/runs/foreground/execution.js +17 -9
  112. package/src/runs/foreground/subagent-executor.d.ts +3 -2
  113. package/src/runs/foreground/subagent-executor.js +107 -26
  114. package/src/runs/shared/child-commands.js +15 -2
  115. package/src/runs/shared/child-hooks.d.ts +1 -7
  116. package/src/runs/shared/child-hooks.js +13 -5
  117. package/src/runs/shared/child-launch.js +6 -2
  118. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  119. package/src/runs/shared/child-session.d.ts +1 -1
  120. package/src/runs/shared/child-session.js +21 -2
  121. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  122. package/src/runs/shared/child-tool-plan.js +0 -1
  123. package/src/runs/shared/claude-code-adapter.js +11 -0
  124. package/src/runs/shared/external-cli-runner.js +26 -6
  125. package/src/runs/shared/herdr-connection.js +2 -1
  126. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  127. package/src/runs/shared/herdr-pane-host.js +17 -1
  128. package/src/runs/shared/herdr-placed-run.js +48 -22
  129. package/src/runs/shared/lane-metadata.d.ts +0 -1
  130. package/src/runs/shared/lane-metadata.js +0 -1
  131. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  132. package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
  133. package/src/runs/shared/model-resolution.d.ts +2 -2
  134. package/src/runs/shared/model-resolution.js +7 -1
  135. package/src/runs/shared/model-scope.d.ts +1 -5
  136. package/src/runs/shared/model-scope.js +1 -5
  137. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  138. package/src/runs/shared/mutation-evidence.js +52 -7
  139. package/src/runs/shared/nested-events.d.ts +1 -0
  140. package/src/runs/shared/nested-events.js +1 -1
  141. package/src/runs/shared/parallel-utils.d.ts +0 -1
  142. package/src/runs/shared/permissions.js +5 -3
  143. package/src/runs/shared/placement-host.d.ts +5 -1
  144. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  145. package/src/runs/shared/rex-pane-host.js +0 -2
  146. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  147. package/src/runs/shared/run-launch-folder.js +21 -0
  148. package/src/runs/shared/runner-launcher.d.ts +12 -1
  149. package/src/runs/shared/runner-launcher.js +16 -0
  150. package/src/runs/shared/single-output.d.ts +3 -3
  151. package/src/runs/shared/single-output.js +5 -3
  152. package/src/runs/shared/structured-output.d.ts +8 -0
  153. package/src/runs/shared/structured-output.js +30 -2
  154. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  155. package/src/runs/shared/subagent-prompt-runtime.js +4 -2
  156. package/src/runs/shared/tool-timeout.js +2 -1
  157. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  158. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  159. package/src/runs/shared/worktree.d.ts +3 -0
  160. package/src/runs/shared/worktree.js +20 -0
  161. package/src/shared/capacity-resilient-json.d.ts +1 -1
  162. package/src/shared/child-cache-retention.d.ts +1 -2
  163. package/src/shared/child-cache-retention.js +1 -2
  164. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  165. package/src/shared/fleet-transcript-reader.js +333 -0
  166. package/src/shared/formatters.d.ts +0 -18
  167. package/src/shared/formatters.js +0 -18
  168. package/src/shared/session-succession.d.ts +16 -1
  169. package/src/shared/session-succession.js +41 -2
  170. package/src/shared/session-warnings.d.ts +7 -0
  171. package/src/shared/session-warnings.js +26 -0
  172. package/src/shared/settings.d.ts +0 -23
  173. package/src/shared/settings.js +3 -35
  174. package/src/shared/types.d.ts +28 -11
  175. package/src/shared/types.js +0 -12
  176. package/src/shared/utils.d.ts +0 -14
  177. package/src/shared/utils.js +0 -22
  178. package/src/shared/wait-tool-name.d.ts +8 -0
  179. package/src/shared/wait-tool-name.js +13 -0
  180. package/src/slash/slash-commands.js +2 -1
  181. package/src/slash/subagent-cost.d.ts +3 -2
  182. package/src/slash/subagent-cost.js +22 -3
  183. package/src/slash/subagents-admin.js +0 -1
  184. package/src/tui/fleet-status.d.ts +0 -5
  185. package/src/tui/fleet-status.js +4 -24
  186. package/src/tui/fleet-transcript.d.ts +1 -44
  187. package/src/tui/fleet-transcript.js +1 -327
  188. package/src/tui/fleet.js +6 -4
  189. package/src/tui/render.d.ts +0 -9
  190. package/src/tui/render.js +81 -47
  191. package/src/tui/subagent-messages.js +3 -2
  192. package/src/watchdog/register-child.d.ts +2 -3
  193. package/src/watchdog/register-child.js +2 -3
  194. package/src/watchdog/turn-delta.js +2 -1
  195. package/src/workflows/scripted-workflow.js +241 -20
  196. package/src/workflows/workflow-launch-record.d.ts +15 -6
  197. package/src/workflows/workflow-launch-record.js +30 -12
  198. package/src/workflows/workflow-resume-claim.js +2 -2
  199. package/src/workflows/workflow-resume.d.ts +1 -1
  200. package/src/workflows/workflow-resume.js +11 -8
  201. package/src/workflows/workflow-script-worker.d.ts +13 -0
  202. package/src/workflows/workflow-script-worker.js +79 -0
  203. package/workflow-script-process.cjs +36 -0
  204. package/workflow-script-worker.cjs +4 -1
@@ -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) {
@@ -1180,8 +1222,8 @@ function validateNestedSessionFile(run, trustedSessionRoots, resolveSource, visi
1180
1222
  }
1181
1223
  return realSessionFile;
1182
1224
  }
1183
- export function readNestedRecoveryDescriptor(asyncDir, runId, agent) {
1184
- const recoveryDescriptor = readAsyncRecoveryDescriptor(asyncDir);
1225
+ export function readNestedRecoveryDescriptor(rootRunId, runId, agent) {
1226
+ const recoveryDescriptor = readAsyncRecoveryDescriptor(nestedRunScope(rootRunId).asyncDirRoot, runId);
1185
1227
  if (!recoveryDescriptor)
1186
1228
  return undefined;
1187
1229
  if (recoveryDescriptor.sourceRunId !== runId)
@@ -1201,7 +1243,7 @@ function resolveNestedResumeTarget(match, trustedSessionRoots, resolveSource) {
1201
1243
  throw new Error(`Could not determine child agent for nested run '${run.id}'.`);
1202
1244
  const state = run.state === "complete" || run.state === "failed" || run.state === "paused" ? run.state : "failed";
1203
1245
  const asyncDir = resolveNestedAsyncDir(match.match.rootRunId, run);
1204
- const recoveryDescriptor = readNestedRecoveryDescriptor(asyncDir, run.id, agent);
1246
+ const recoveryDescriptor = asyncDir ? readNestedRecoveryDescriptor(match.match.rootRunId, run.id, agent) : undefined;
1205
1247
  return compactOptional({
1206
1248
  kind: "revive",
1207
1249
  source: "nested",
@@ -1688,6 +1730,20 @@ async function resumeAsyncRun(input) {
1688
1730
  details: { mode: "management", results: [] },
1689
1731
  };
1690
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
+ }
1691
1747
  if (target.source === "async" && target.runner?.type === "external-cli") {
1692
1748
  const runner = normalizeExternalCliRunnerStatus(target.runner);
1693
1749
  const message = runner
@@ -1698,7 +1754,8 @@ async function resumeAsyncRun(input) {
1698
1754
  if (input.params.baseRef !== undefined && "managedWorktree" in target && target.managedWorktree === true) {
1699
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: [] } };
1700
1756
  }
1701
- 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))) {
1702
1759
  try {
1703
1760
  const protectedCwd = await protectRetainedWorktreeForResume(parallelHandoffPath(target.asyncDir), target.runId, target.index, input.signal);
1704
1761
  if (path.resolve(protectedCwd) !== path.resolve(effectiveCwd))
@@ -1864,8 +1921,8 @@ async function resumeAsyncRun(input) {
1864
1921
  if (target.source === "nested" && !target.recoveryDescriptor) {
1865
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: [] } };
1866
1923
  }
1867
- // Runs without a recovery descriptor were never wrapped; a launcher added to the agent file later does not apply.
1868
- 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;
1869
1926
  const agentConfig = intercomBridge.active ? applyIntercomBridgeToAgent(recoveryAgentConfig, intercomBridge) : recoveryAgentConfig;
1870
1927
  const foregroundContract = target.source === "foreground" ? target.resumeContract : undefined;
1871
1928
  const outputSchema = Object.hasOwn(input.params, "outputSchema")
@@ -1884,7 +1941,7 @@ async function resumeAsyncRun(input) {
1884
1941
  }
1885
1942
  // Refuse before capacity moves so the retained run stays resumable once the config is fixed.
1886
1943
  if (agentConfig.launcher !== undefined && !lookupRunnerLauncher(input.deps.config.runnerLaunchers, agentConfig.launcher)) {
1887
- 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: [] } };
1888
1945
  }
1889
1946
  const runId = randomUUID();
1890
1947
  const topLevelResume = depth === 0 && !inheritedNestedRoute(input.deps) && !input.params.workflowParentRunId;
@@ -1930,6 +1987,7 @@ async function resumeAsyncRun(input) {
1930
1987
  goal: effectiveFollowUp,
1931
1988
  agentConfig,
1932
1989
  recoveryAgentConfig,
1990
+ carriedRequiredLauncher: recoveryDescriptor?.requiredLauncher,
1933
1991
  ctx: compactOptional({
1934
1992
  pi: input.deps.pi,
1935
1993
  cwd: input.requestCwd,
@@ -2117,6 +2175,7 @@ function createForegroundControlNotifier(data, deps) {
2117
2175
  const enriched = workflowKey && !event.workflowKey ? { ...event, workflowKey } : event;
2118
2176
  if (asyncWorkflow) {
2119
2177
  persistAsyncWorkflowControlEvent({
2178
+ state: deps.state,
2120
2179
  job: asyncWorkflow,
2121
2180
  event: enriched,
2122
2181
  controlConfig: data.controlConfig,
@@ -3165,6 +3224,7 @@ async function runAsyncPath(data, deps) {
3165
3224
  requestedCwd: data.requestedCwd,
3166
3225
  machine: params.machine,
3167
3226
  machineCwd: params.machineCwd,
3227
+ requireLauncher: params.requireLauncher,
3168
3228
  maxOutput: params.maxOutput,
3169
3229
  artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
3170
3230
  artifactConfig,
@@ -3665,7 +3725,7 @@ async function runSinglePath(data, deps) {
3665
3725
  ? `[Read from: ${readPaths.join(", ")}]\n\n`
3666
3726
  : "";
3667
3727
  task = readsInstruction + task;
3668
- task = injectSingleOutputInstruction(task, outputPath, agentConfig);
3728
+ task = injectSingleOutputInstruction(task, outputPath, agentConfig, foregroundMachine);
3669
3729
  let effectiveSkills;
3670
3730
  if (skillOverride === false) {
3671
3731
  effectiveSkills = [];
@@ -3817,6 +3877,7 @@ async function runSinglePath(data, deps) {
3817
3877
  suppressUnchangedDelegationUpdates,
3818
3878
  controlConfig,
3819
3879
  onControlEvent,
3880
+ onWarning: (message, key) => reportSessionWarning(deps.state, message, key),
3820
3881
  intercomSessionName: childIntercomTarget,
3821
3882
  orchestratorIntercomTarget: childBridgeActive ? data.intercomBridge.orchestratorTarget : undefined,
3822
3883
  nestedRoute: foregroundControl?.nestedRoute,
@@ -4005,11 +4066,11 @@ async function runSinglePath(data, deps) {
4005
4066
  const worktreeSuffix = worktreeHandoff?.suffix ? `\n\n${worktreeHandoff.suffix}` : "";
4006
4067
  if (r.detached) {
4007
4068
  const statusRecovery = `subagent({ action: "status", id: "${runId}" }) to recover the result; do not resume or launch a replacement while it remains detached.`;
4008
- const blockingRecovery = `bg_wait({ id: "${runId}" }). Use ${statusRecovery}`;
4069
+ const blockingRecovery = `${waitToolName()}({ id: "${runId}" }). Use ${statusRecovery}`;
4009
4070
  const message = r.detachedReason === "intercom coordination"
4010
4071
  ? `Detached for intercom coordination: ${params.agent}. Reply to the supervisor request first, then wait with ${blockingRecovery}`
4011
4072
  : r.detachedReason === "user request"
4012
- ? `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}`
4073
+ ? `Detached at user request: ${params.agent}. The child continues independently. Register a completion wake-up with ${waitToolName()}({ id: "${runId}", nonBlocking: true }), or use ${statusRecovery}`
4013
4074
  : `Detached before task completion: ${params.agent}. Wait with ${blockingRecovery}`;
4014
4075
  return {
4015
4076
  content: [{ type: "text", text: `${message}${worktreeSuffix}` }],
@@ -4489,6 +4550,9 @@ export async function preflightWorkflowWorktrees(input) {
4489
4550
  input.signal.throwIfAborted();
4490
4551
  }
4491
4552
  export function prepareWorkflowLaunchParams(workflowDefaults, childParams, parentWorkflowRunId, workflowKey, options = {}) {
4553
+ // Before the resume branch below, which rebuilds params field by field and would drop the requirement.
4554
+ if (childParams.requireLauncher !== undefined || workflowDefaults.requireLauncher !== undefined)
4555
+ throw new Error(REQUIRE_LAUNCHER_SHAPE_ERROR);
4492
4556
  const { globalConcurrencyLimit: _globalConcurrencyLimit, maxSubagentSpawnsPerRun: _maxSubagentSpawnsPerRun, ...workflowDefaultsWithoutCapacity } = workflowDefaults;
4493
4557
  const { globalConcurrencyLimit: _childGlobalConcurrencyLimit, maxSubagentSpawnsPerRun: _childMaxSubagentSpawnsPerRun, ...childParamsWithoutCapacity } = childParams;
4494
4558
  workflowDefaults = workflowDefaultsWithoutCapacity;
@@ -4767,11 +4831,12 @@ function savedWorkflowLaunchParams(params) {
4767
4831
  const { reuseFrom: _reuseFrom, scheduleOrigin: _scheduleOrigin, resumeOrigin: _resumeOrigin, ...saved } = params;
4768
4832
  return saved;
4769
4833
  }
4770
- function workflowLaunchRecord(launch, cwd, scriptDigest) {
4771
- if (launch.source === "structured")
4772
- return { version: 1, source: "structured", scriptDigest };
4834
+ function workflowLaunchRecord(launch, cwd, scriptDigest, sessionId, ceiling) {
4835
+ const owner = { version: 2, scriptDigest, sessionId, ...(ceiling ? { admissionCapabilityCeiling: ceiling } : {}) };
4836
+ if (launch.source === "structured" || launch.source === "internal")
4837
+ return { ...owner, source: launch.source };
4773
4838
  // The resolved cwd is saved: a relative one would resolve against a later session's cwd.
4774
- return { version: 1, source: launch.source, params: { ...launch.params, cwd }, scriptDigest };
4839
+ return { ...owner, source: launch.source, params: { ...launch.params, cwd } };
4775
4840
  }
4776
4841
  export function createSubagentExecutor(deps) {
4777
4842
  const executorDeps = deps;
@@ -5092,8 +5157,8 @@ export function createSubagentExecutor(deps) {
5092
5157
  try {
5093
5158
  fs.mkdirSync(asyncDir, { recursive: true });
5094
5159
  writeRunFanoutBudgetDescriptor(asyncDir, workflowFanoutBudget);
5095
- if (topLevelAsyncWorkflow && publicWorkflowLaunch)
5096
- writeWorkflowLaunchRecord(asyncDir, workflowLaunchRecord(publicWorkflowLaunch, workflowCwd, workflowScriptSourceDigest));
5160
+ if (topLevelAsyncWorkflow)
5161
+ writeWorkflowLaunchRecord(DIRS.async, workflowRunId, workflowLaunchRecord(publicWorkflowLaunch ?? { source: "internal" }, workflowCwd, workflowScriptSourceDigest, currentSessionId, workflowCapabilityCeiling));
5097
5162
  fs.mkdirSync(DIRS.results, { recursive: true });
5098
5163
  }
5099
5164
  catch (error) {
@@ -5853,9 +5918,12 @@ export function createSubagentExecutor(deps) {
5853
5918
  heartbeat: { status: "running", ...(childPhase ? { phase: childPhase } : {}) },
5854
5919
  });
5855
5920
  let preparedChildParams;
5856
- const result = await runMissionWorkflowChild(missionBinding, workflowRunId, key, childPhase, () => {
5921
+ const result = await runMissionWorkflowChild(missionBinding, workflowRunId, key, childPhase, async () => {
5857
5922
  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);
5858
5923
  preparedChildParams = childRequest;
5924
+ const launchRefusal = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(workflowRunId, key, childRequest, childParams.agent, parentCwd, discoverWorkflowAgents), workflowSignal);
5925
+ if (launchRefusal)
5926
+ return buildRequestedModeError(childRequest, launchRefusal);
5859
5927
  if (workflowUsageBudget.budget)
5860
5928
  workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
5861
5929
  if (workflowRequiredExtensions)
@@ -6180,9 +6248,12 @@ export function createSubagentExecutor(deps) {
6180
6248
  heartbeat: { status: "running", ...(childPhase ? { phase: childPhase } : {}) },
6181
6249
  });
6182
6250
  let preparedChildParams;
6183
- const result = await runMissionWorkflowChild(missionBinding, foregroundWorkflowRunId, key, childPhase, () => {
6251
+ const result = await runMissionWorkflowChild(missionBinding, foregroundWorkflowRunId, key, childPhase, async () => {
6184
6252
  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);
6185
6253
  preparedChildParams = childRequest;
6254
+ const launchRefusal = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(foregroundWorkflowRunId, key, childRequest, childParams.agent, ctx.cwd, discoverWorkflowAgents), workflowSignal);
6255
+ if (launchRefusal)
6256
+ return buildRequestedModeError(childRequest, launchRefusal);
6186
6257
  if (workflowUsageBudget.budget)
6187
6258
  workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
6188
6259
  if (workflowRequiredExtensions)
@@ -7254,6 +7325,16 @@ export function createSubagentExecutor(deps) {
7254
7325
  if (launcherError)
7255
7326
  return buildRequestedModeError(effectiveParams, launcherError);
7256
7327
  }
7328
+ // Refused here, before admission; executeAsyncSingle checks again on the exact agent and launcher it spawns.
7329
+ if (effectiveParams.requireLauncher !== undefined) {
7330
+ if (!effectiveParams.requireLauncher || typeof effectiveParams.requireLauncher !== "object")
7331
+ return buildRequestedModeError(effectiveParams, "requireLauncher must be { name, definitionDigest }.");
7332
+ if (!hasSingle || effectiveParams.resume !== undefined || effectiveParams.workflowParentRunId !== undefined)
7333
+ return buildRequestedModeError(effectiveParams, REQUIRE_LAUNCHER_SHAPE_ERROR);
7334
+ const required = selectedAgents[0] ? checkRequiredRunnerLauncher(selectedAgents[0], selectedAgents[0].launcher, effectiveParams.requireLauncher) : undefined;
7335
+ if (required?.error)
7336
+ return buildRequestedModeError(effectiveParams, required.error);
7337
+ }
7257
7338
  if (effectiveAsync && hasSingle && effectiveParams.resume === undefined && effectiveParams.worktree === true) {
7258
7339
  try {
7259
7340
  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";
@@ -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 {
@@ -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
  },