pi-subagents 0.84.0 → 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.
- package/CHANGELOG.md +62 -0
- package/bundle/agents.js +3 -3
- package/bundle/child-tool-plan.js +2 -2
- package/bundle/{chunk-235AWJUQ.js → chunk-3UZ5FVVJ.js} +310 -101
- package/bundle/{chunk-F4ASL6OV.js → chunk-7MAE3DJV.js} +1 -1
- package/bundle/{chunk-4E7BKDTX.js → chunk-CS4O36CZ.js} +11 -156
- package/bundle/{chunk-VQVVHSY6.js → chunk-DV2NCNPR.js} +22 -11
- package/bundle/{chunk-G2Z6ZH26.js → chunk-GCSLVFCX.js} +1 -1
- package/bundle/{chunk-2S4K53MV.js → chunk-H2NLFTC5.js} +1 -1
- package/bundle/{chunk-NKQ6JNAS.js → chunk-HFTBF7SG.js} +2 -1
- package/bundle/chunk-HXRB42AF.js +108 -0
- package/bundle/{chunk-7BWGNDNK.js → chunk-IQIWF2VX.js} +190 -1177
- package/bundle/{chunk-XDQORLZ5.js → chunk-JNXT3MPI.js} +15 -6
- package/bundle/{chunk-J5YL7LYR.js → chunk-JO67XSKD.js} +59 -27
- package/bundle/{chunk-JG4QKI5M.js → chunk-JWYG26RE.js} +209 -93
- package/bundle/{chunk-C5P5CHYK.js → chunk-KDMFBYFM.js} +1 -1
- package/bundle/{chunk-V2BZYLEP.js → chunk-KEY3UQMQ.js} +7 -2
- package/bundle/{chunk-NENDSQUY.js → chunk-KZ34KQQH.js} +9 -6
- package/bundle/{chunk-AKOIVLA5.js → chunk-L2ENOFVZ.js} +76 -58
- package/bundle/{chunk-CGN2TVE7.js → chunk-LGMILZNE.js} +322 -18
- package/bundle/{chunk-L3WFKBEI.js → chunk-LTPH2DXH.js} +247 -153
- package/bundle/{chunk-2D52JFLF.js → chunk-N7B2KD74.js} +41 -117
- package/bundle/{chunk-PV63UFUR.js → chunk-O7CPL6H4.js} +183 -28
- package/bundle/{chunk-D3JAFGMO.js → chunk-PHZP3KHB.js} +1 -1
- package/bundle/{chunk-2DHZTCOL.js → chunk-PVIVCDG2.js} +2 -2
- package/bundle/{chunk-LFDBD4PW.js → chunk-QO75KJBT.js} +2 -2
- package/bundle/{chunk-SSG7IEP5.js → chunk-RQAUNAWG.js} +2 -2
- package/bundle/{chunk-PALJGGYC.js → chunk-RV5OGHLO.js} +6 -3
- package/bundle/chunk-T5V5BRCL.js +1067 -0
- package/bundle/{chunk-LNRJCP2Y.js → chunk-UX4SCV5N.js} +337 -207
- package/bundle/{chunk-DZDETGRJ.js → chunk-WOVMHDES.js} +231 -182
- package/bundle/control-channel.js +2 -2
- package/bundle/index.js +1 -1
- package/bundle/intercom-bridge.js +2 -2
- package/bundle/preflight.js +8 -8
- package/bundle/project-panes.js +3 -3
- package/docs/agents.md +17 -2
- package/docs/configuration.md +2 -2
- package/docs/extension-api.md +16 -1
- package/docs/workflows.md +30 -2
- package/package.json +1 -1
- package/src/agents/agent-management.js +27 -11
- package/src/agents/agent-memory.d.ts +1 -4
- package/src/agents/agent-memory.js +1 -4
- package/src/agents/agents.d.ts +1 -3
- package/src/agents/agents.js +7 -6
- package/src/agents/frontmatter.js +1 -8
- package/src/agents/global-npm-root.d.ts +1 -0
- package/src/agents/global-npm-root.js +11 -3
- package/src/agents/skills.d.ts +0 -3
- package/src/agents/skills.js +0 -3
- package/src/extension/config.js +7 -1
- package/src/extension/herdr-pi-bridge.js +10 -2
- package/src/extension/index.d.ts +0 -13
- package/src/extension/index.js +43 -32
- package/src/extension/public-execution.d.ts +1 -0
- package/src/extension/public-execution.js +4 -0
- package/src/extension/reply-workflow-script.js +24 -4
- package/src/extension/schemas.d.ts +8 -3
- package/src/extension/schemas.js +5 -3
- package/src/extension/session-switch.d.ts +25 -0
- package/src/extension/session-switch.js +138 -0
- package/src/extension/subagent-guide.d.ts +1 -1
- package/src/extension/subagent-guide.js +1 -1
- package/src/extension/subagent-launch-tool.d.ts +25 -0
- package/src/extension/subagent-launch-tool.js +48 -0
- package/src/extension/tool-activation.js +25 -11
- package/src/extension/tool-description.js +6 -0
- package/src/inspectors/herdr/actions.d.ts +0 -1
- package/src/inspectors/herdr/actions.js +0 -1
- package/src/inspectors/session-roots-codec.d.ts +0 -1
- package/src/inspectors/session-roots-codec.js +0 -1
- package/src/inspectors/tmux/actions.d.ts +0 -1
- package/src/inspectors/tmux/actions.js +0 -1
- package/src/integrations/herdr-status.js +3 -8
- package/src/intercom/native-supervisor-channel.js +65 -9
- package/src/runs/background/async-execution.d.ts +5 -9
- package/src/runs/background/async-execution.js +62 -27
- package/src/runs/background/async-job-tracker.js +12 -0
- package/src/runs/background/async-resume.d.ts +2 -1
- package/src/runs/background/async-resume.js +112 -39
- package/src/runs/background/async-retention.js +6 -1
- package/src/runs/background/auto-drain.js +2 -1
- package/src/runs/background/boot-id.d.ts +1 -3
- package/src/runs/background/boot-id.js +1 -3
- package/src/runs/background/completion-batcher.d.ts +3 -4
- package/src/runs/background/completion-batcher.js +2 -3
- package/src/runs/background/control-channel.d.ts +0 -6
- package/src/runs/background/control-channel.js +0 -6
- package/src/runs/background/fleet-view.js +2 -3
- package/src/runs/background/notify.d.ts +0 -2
- package/src/runs/background/notify.js +0 -2
- package/src/runs/background/result-watcher.d.ts +1 -0
- package/src/runs/background/result-watcher.js +59 -29
- package/src/runs/background/resume-guidance.js +4 -2
- package/src/runs/background/retained-children.js +2 -1
- package/src/runs/background/run-child-session.d.ts +0 -1
- package/src/runs/background/run-child-session.js +1 -1
- package/src/runs/background/run-status.js +4 -3
- package/src/runs/background/scheduled-runs.d.ts +3 -1
- package/src/runs/background/scheduled-runs.js +13 -16
- package/src/runs/background/subagent-runner.d.ts +2 -4
- package/src/runs/background/subagent-runner.js +9 -6
- package/src/runs/background/subagent-wait.js +12 -15
- package/src/runs/background/wait-config.d.ts +2 -0
- package/src/runs/background/wait-config.js +17 -3
- package/src/runs/background/wait-tool.js +4 -2
- package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
- package/src/runs/background/workflow-terminal-proof.js +0 -1
- package/src/runs/foreground/execution.d.ts +0 -3
- package/src/runs/foreground/execution.js +17 -9
- package/src/runs/foreground/subagent-executor.d.ts +3 -2
- package/src/runs/foreground/subagent-executor.js +107 -26
- package/src/runs/shared/child-commands.js +15 -2
- package/src/runs/shared/child-hooks.d.ts +1 -7
- package/src/runs/shared/child-hooks.js +13 -5
- package/src/runs/shared/child-launch.js +6 -2
- package/src/runs/shared/child-runtime-config.d.ts +0 -1
- package/src/runs/shared/child-session.d.ts +1 -1
- package/src/runs/shared/child-session.js +21 -2
- package/src/runs/shared/child-tool-plan.d.ts +0 -1
- package/src/runs/shared/child-tool-plan.js +0 -1
- package/src/runs/shared/claude-code-adapter.js +11 -0
- package/src/runs/shared/external-cli-runner.js +26 -6
- package/src/runs/shared/herdr-connection.js +2 -1
- package/src/runs/shared/herdr-pane-host.d.ts +2 -2
- package/src/runs/shared/herdr-pane-host.js +17 -1
- package/src/runs/shared/herdr-placed-run.js +48 -22
- package/src/runs/shared/lane-metadata.d.ts +0 -1
- package/src/runs/shared/lane-metadata.js +0 -1
- package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
- package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
- package/src/runs/shared/model-resolution.d.ts +2 -2
- package/src/runs/shared/model-resolution.js +7 -1
- package/src/runs/shared/model-scope.d.ts +1 -5
- package/src/runs/shared/model-scope.js +1 -5
- package/src/runs/shared/mutation-evidence.d.ts +1 -1
- package/src/runs/shared/mutation-evidence.js +52 -7
- package/src/runs/shared/nested-events.d.ts +1 -0
- package/src/runs/shared/nested-events.js +1 -1
- package/src/runs/shared/parallel-utils.d.ts +0 -1
- package/src/runs/shared/permissions.js +5 -3
- package/src/runs/shared/placement-host.d.ts +5 -1
- package/src/runs/shared/rex-pane-host.d.ts +0 -1
- package/src/runs/shared/rex-pane-host.js +0 -2
- package/src/runs/shared/run-launch-folder.d.ts +12 -0
- package/src/runs/shared/run-launch-folder.js +21 -0
- package/src/runs/shared/runner-launcher.d.ts +12 -1
- package/src/runs/shared/runner-launcher.js +16 -0
- package/src/runs/shared/single-output.d.ts +3 -3
- package/src/runs/shared/single-output.js +5 -3
- package/src/runs/shared/structured-output.d.ts +8 -0
- package/src/runs/shared/structured-output.js +30 -2
- package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
- package/src/runs/shared/subagent-prompt-runtime.js +4 -2
- package/src/runs/shared/tool-timeout.js +2 -1
- package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
- package/src/runs/shared/worktree-cleanup-plan.js +0 -1
- package/src/runs/shared/worktree.d.ts +3 -0
- package/src/runs/shared/worktree.js +20 -0
- package/src/shared/capacity-resilient-json.d.ts +1 -1
- package/src/shared/child-cache-retention.d.ts +1 -2
- package/src/shared/child-cache-retention.js +1 -2
- package/src/shared/fleet-transcript-reader.d.ts +51 -0
- package/src/shared/fleet-transcript-reader.js +333 -0
- package/src/shared/formatters.d.ts +0 -18
- package/src/shared/formatters.js +0 -18
- package/src/shared/session-succession.d.ts +16 -1
- package/src/shared/session-succession.js +41 -2
- package/src/shared/session-warnings.d.ts +7 -0
- package/src/shared/session-warnings.js +26 -0
- package/src/shared/settings.d.ts +0 -23
- package/src/shared/settings.js +3 -35
- package/src/shared/types.d.ts +28 -11
- package/src/shared/types.js +0 -12
- package/src/shared/utils.d.ts +0 -14
- package/src/shared/utils.js +0 -22
- package/src/shared/wait-tool-name.d.ts +8 -0
- package/src/shared/wait-tool-name.js +13 -0
- package/src/slash/slash-commands.js +2 -1
- package/src/slash/subagent-cost.d.ts +3 -2
- package/src/slash/subagent-cost.js +22 -3
- package/src/slash/subagents-admin.js +0 -1
- package/src/tui/fleet-status.d.ts +0 -5
- package/src/tui/fleet-status.js +4 -24
- package/src/tui/fleet-transcript.d.ts +1 -44
- package/src/tui/fleet-transcript.js +1 -327
- package/src/tui/fleet.js +6 -4
- package/src/tui/render.d.ts +0 -9
- package/src/tui/render.js +81 -47
- package/src/tui/subagent-messages.js +3 -2
- package/src/watchdog/register-child.d.ts +2 -3
- package/src/watchdog/register-child.js +2 -3
- package/src/watchdog/turn-delta.js +2 -1
- package/src/workflows/scripted-workflow.js +241 -20
- package/src/workflows/workflow-launch-record.d.ts +15 -6
- package/src/workflows/workflow-launch-record.js +30 -12
- package/src/workflows/workflow-resume-claim.js +2 -2
- package/src/workflows/workflow-resume.d.ts +1 -1
- package/src/workflows/workflow-resume.js +11 -8
- package/src/workflows/workflow-script-worker.d.ts +13 -0
- package/src/workflows/workflow-script-worker.js +79 -0
- package/workflow-script-process.cjs +36 -0
- 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 {
|
|
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
|
|
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
|
-
|
|
799
|
-
|
|
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(
|
|
1184
|
-
const recoveryDescriptor = readAsyncRecoveryDescriptor(
|
|
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(
|
|
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
|
-
|
|
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
|
-
//
|
|
1868
|
-
const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) :
|
|
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}'
|
|
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,
|
|
@@ -3177,6 +3236,7 @@ async function runAsyncPath(data, deps) {
|
|
|
3177
3236
|
requestedCwd: data.requestedCwd,
|
|
3178
3237
|
machine: params.machine,
|
|
3179
3238
|
machineCwd: params.machineCwd,
|
|
3239
|
+
requireLauncher: params.requireLauncher,
|
|
3180
3240
|
maxOutput: params.maxOutput,
|
|
3181
3241
|
artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
|
|
3182
3242
|
artifactConfig,
|
|
@@ -3677,7 +3737,7 @@ async function runSinglePath(data, deps) {
|
|
|
3677
3737
|
? `[Read from: ${readPaths.join(", ")}]\n\n`
|
|
3678
3738
|
: "";
|
|
3679
3739
|
task = readsInstruction + task;
|
|
3680
|
-
task = injectSingleOutputInstruction(task, outputPath, agentConfig);
|
|
3740
|
+
task = injectSingleOutputInstruction(task, outputPath, agentConfig, foregroundMachine);
|
|
3681
3741
|
let effectiveSkills;
|
|
3682
3742
|
if (skillOverride === false) {
|
|
3683
3743
|
effectiveSkills = [];
|
|
@@ -3829,6 +3889,7 @@ async function runSinglePath(data, deps) {
|
|
|
3829
3889
|
suppressUnchangedDelegationUpdates,
|
|
3830
3890
|
controlConfig,
|
|
3831
3891
|
onControlEvent,
|
|
3892
|
+
onWarning: (message, key) => reportSessionWarning(deps.state, message, key),
|
|
3832
3893
|
intercomSessionName: childIntercomTarget,
|
|
3833
3894
|
orchestratorIntercomTarget: childBridgeActive ? data.intercomBridge.orchestratorTarget : undefined,
|
|
3834
3895
|
nestedRoute: foregroundControl?.nestedRoute,
|
|
@@ -4017,11 +4078,11 @@ async function runSinglePath(data, deps) {
|
|
|
4017
4078
|
const worktreeSuffix = worktreeHandoff?.suffix ? `\n\n${worktreeHandoff.suffix}` : "";
|
|
4018
4079
|
if (r.detached) {
|
|
4019
4080
|
const statusRecovery = `subagent({ action: "status", id: "${runId}" }) to recover the result; do not resume or launch a replacement while it remains detached.`;
|
|
4020
|
-
const blockingRecovery =
|
|
4081
|
+
const blockingRecovery = `${waitToolName()}({ id: "${runId}" }). Use ${statusRecovery}`;
|
|
4021
4082
|
const message = r.detachedReason === "intercom coordination"
|
|
4022
4083
|
? `Detached for intercom coordination: ${params.agent}. Reply to the supervisor request first, then wait with ${blockingRecovery}`
|
|
4023
4084
|
: r.detachedReason === "user request"
|
|
4024
|
-
? `Detached at user request: ${params.agent}. The child continues independently. Register a completion wake-up with
|
|
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}`
|
|
4025
4086
|
: `Detached before task completion: ${params.agent}. Wait with ${blockingRecovery}`;
|
|
4026
4087
|
return {
|
|
4027
4088
|
content: [{ type: "text", text: `${message}${worktreeSuffix}` }],
|
|
@@ -4501,6 +4562,9 @@ export async function preflightWorkflowWorktrees(input) {
|
|
|
4501
4562
|
input.signal.throwIfAborted();
|
|
4502
4563
|
}
|
|
4503
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);
|
|
4504
4568
|
const { globalConcurrencyLimit: _globalConcurrencyLimit, maxSubagentSpawnsPerRun: _maxSubagentSpawnsPerRun, ...workflowDefaultsWithoutCapacity } = workflowDefaults;
|
|
4505
4569
|
const { globalConcurrencyLimit: _childGlobalConcurrencyLimit, maxSubagentSpawnsPerRun: _childMaxSubagentSpawnsPerRun, ...childParamsWithoutCapacity } = childParams;
|
|
4506
4570
|
workflowDefaults = workflowDefaultsWithoutCapacity;
|
|
@@ -4779,11 +4843,12 @@ function savedWorkflowLaunchParams(params) {
|
|
|
4779
4843
|
const { reuseFrom: _reuseFrom, scheduleOrigin: _scheduleOrigin, resumeOrigin: _resumeOrigin, ...saved } = params;
|
|
4780
4844
|
return saved;
|
|
4781
4845
|
}
|
|
4782
|
-
function workflowLaunchRecord(launch, cwd, scriptDigest) {
|
|
4783
|
-
|
|
4784
|
-
|
|
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 };
|
|
4785
4850
|
// The resolved cwd is saved: a relative one would resolve against a later session's cwd.
|
|
4786
|
-
return {
|
|
4851
|
+
return { ...owner, source: launch.source, params: { ...launch.params, cwd } };
|
|
4787
4852
|
}
|
|
4788
4853
|
export function createSubagentExecutor(deps) {
|
|
4789
4854
|
const executorDeps = deps;
|
|
@@ -5104,8 +5169,8 @@ export function createSubagentExecutor(deps) {
|
|
|
5104
5169
|
try {
|
|
5105
5170
|
fs.mkdirSync(asyncDir, { recursive: true });
|
|
5106
5171
|
writeRunFanoutBudgetDescriptor(asyncDir, workflowFanoutBudget);
|
|
5107
|
-
if (topLevelAsyncWorkflow
|
|
5108
|
-
writeWorkflowLaunchRecord(
|
|
5172
|
+
if (topLevelAsyncWorkflow)
|
|
5173
|
+
writeWorkflowLaunchRecord(DIRS.async, workflowRunId, workflowLaunchRecord(publicWorkflowLaunch ?? { source: "internal" }, workflowCwd, workflowScriptSourceDigest, currentSessionId, workflowCapabilityCeiling));
|
|
5109
5174
|
fs.mkdirSync(DIRS.results, { recursive: true });
|
|
5110
5175
|
}
|
|
5111
5176
|
catch (error) {
|
|
@@ -5865,9 +5930,12 @@ export function createSubagentExecutor(deps) {
|
|
|
5865
5930
|
heartbeat: { status: "running", ...(childPhase ? { phase: childPhase } : {}) },
|
|
5866
5931
|
});
|
|
5867
5932
|
let preparedChildParams;
|
|
5868
|
-
const result = await runMissionWorkflowChild(missionBinding, workflowRunId, key, childPhase, () => {
|
|
5933
|
+
const result = await runMissionWorkflowChild(missionBinding, workflowRunId, key, childPhase, async () => {
|
|
5869
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);
|
|
5870
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);
|
|
5871
5939
|
if (workflowUsageBudget.budget)
|
|
5872
5940
|
workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
|
|
5873
5941
|
if (workflowRequiredExtensions)
|
|
@@ -6192,9 +6260,12 @@ export function createSubagentExecutor(deps) {
|
|
|
6192
6260
|
heartbeat: { status: "running", ...(childPhase ? { phase: childPhase } : {}) },
|
|
6193
6261
|
});
|
|
6194
6262
|
let preparedChildParams;
|
|
6195
|
-
const result = await runMissionWorkflowChild(missionBinding, foregroundWorkflowRunId, key, childPhase, () => {
|
|
6263
|
+
const result = await runMissionWorkflowChild(missionBinding, foregroundWorkflowRunId, key, childPhase, async () => {
|
|
6196
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);
|
|
6197
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);
|
|
6198
6269
|
if (workflowUsageBudget.budget)
|
|
6199
6270
|
workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
|
|
6200
6271
|
if (workflowRequiredExtensions)
|
|
@@ -7262,6 +7333,16 @@ export function createSubagentExecutor(deps) {
|
|
|
7262
7333
|
if (launcherError)
|
|
7263
7334
|
return buildRequestedModeError(effectiveParams, launcherError);
|
|
7264
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
|
+
}
|
|
7265
7346
|
if (effectiveAsync && hasSingle && effectiveParams.resume === undefined && effectiveParams.worktree === true) {
|
|
7266
7347
|
try {
|
|
7267
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(() =>
|
|
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
|
-
|
|
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
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
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, "&")
|
|
@@ -75,7 +75,10 @@ function childStorage(input) {
|
|
|
75
75
|
return { kind: "default" };
|
|
76
76
|
}
|
|
77
77
|
export function buildInProcessChildLaunch(input) {
|
|
78
|
-
const
|
|
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
|
|
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
|
|
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
|
},
|