@fitchmultz/pi-subagents 0.0.0-stage → 0.44.5
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 +1654 -0
- package/LICENSE +21 -0
- package/README.md +1533 -2
- package/agents/context-builder.md +97 -0
- package/agents/debugger.md +51 -0
- package/agents/delegate.md +13 -0
- package/agents/fixer.md +37 -0
- package/agents/oracle.md +71 -0
- package/agents/planner.md +72 -0
- package/agents/researcher.md +51 -0
- package/agents/reviewer-claude.md +69 -0
- package/agents/reviewer-gpt.md +68 -0
- package/agents/reviewer-ponytail.md +82 -0
- package/agents/reviewer-security.md +81 -0
- package/agents/reviewer.md +69 -0
- package/agents/scout.md +66 -0
- package/agents/ui-designer.md +51 -0
- package/agents/watcher.md +26 -0
- package/agents/worker.md +46 -0
- package/agents/writer.md +36 -0
- package/dist/agents/agent-management.js +923 -0
- package/dist/agents/agent-scope.js +7 -0
- package/dist/agents/agent-selection.js +20 -0
- package/dist/agents/agent-serializer.js +100 -0
- package/dist/agents/agents.js +752 -0
- package/dist/agents/chain-serializer.js +367 -0
- package/dist/agents/frontmatter.js +21 -0
- package/dist/agents/identity.js +29 -0
- package/dist/agents/skills.js +570 -0
- package/dist/extension/build-info.js +1 -0
- package/dist/extension/compact-tools.js +112 -0
- package/dist/extension/config.js +22 -0
- package/dist/extension/control-notices.js +29 -0
- package/dist/extension/doctor.js +143 -0
- package/dist/extension/fanout-child.js +326 -0
- package/dist/extension/index.js +577 -0
- package/dist/extension/schemas.js +416 -0
- package/dist/extension/tool-input.js +20 -0
- package/dist/extension/tool-result.js +14 -0
- package/dist/history/canonical-result.js +81 -0
- package/dist/history/database.js +72 -0
- package/dist/history/index.js +199 -0
- package/dist/history/ingest.js +468 -0
- package/dist/history/queries.js +350 -0
- package/dist/history/store.js +216 -0
- package/dist/history/types.js +4 -0
- package/dist/history/worker.js +466 -0
- package/dist/intercom/intercom-bridge.js +112 -0
- package/dist/intercom/live-intercom.js +94 -0
- package/dist/intercom/result-intercom.js +373 -0
- package/dist/pi-intercom/agent-dir.js +10 -0
- package/dist/pi-intercom/bridge.js +750 -0
- package/dist/pi-intercom/broker/broker.js +426 -0
- package/dist/pi-intercom/broker/client.js +492 -0
- package/dist/pi-intercom/broker/framing.js +65 -0
- package/dist/pi-intercom/broker/paths.js +42 -0
- package/dist/pi-intercom/broker/pid.js +66 -0
- package/dist/pi-intercom/broker/spawn.js +221 -0
- package/dist/pi-intercom/config.js +102 -0
- package/dist/pi-intercom/index.js +2942 -0
- package/dist/pi-intercom/reply-tracker.js +182 -0
- package/dist/pi-intercom/session-targets.js +128 -0
- package/dist/pi-intercom/subagent-live-events.js +132 -0
- package/dist/pi-intercom/topics.js +157 -0
- package/dist/pi-intercom/types.js +163 -0
- package/dist/pi-intercom/ui/compose.js +269 -0
- package/dist/pi-intercom/ui/inline-message.js +80 -0
- package/dist/pi-intercom/ui/session-list.js +124 -0
- package/dist/runs/background/async-control.js +95 -0
- package/dist/runs/background/async-execution.js +676 -0
- package/dist/runs/background/async-job-tracker.js +383 -0
- package/dist/runs/background/async-result-file.js +58 -0
- package/dist/runs/background/async-resume.js +305 -0
- package/dist/runs/background/async-status.js +442 -0
- package/dist/runs/background/completion-dedupe.js +69 -0
- package/dist/runs/background/completion-delivery.js +245 -0
- package/dist/runs/background/notify.js +71 -0
- package/dist/runs/background/parallel-groups.js +55 -0
- package/dist/runs/background/result-watcher.js +426 -0
- package/dist/runs/background/run-id-resolver.js +64 -0
- package/dist/runs/background/run-status.js +382 -0
- package/dist/runs/background/stale-run-reconciler.js +335 -0
- package/dist/runs/background/subagent-runner-launcher.js +55 -0
- package/dist/runs/background/subagent-runner.js +1872 -0
- package/dist/runs/background/top-level-async.js +5 -0
- package/dist/runs/foreground/chain-clarify.js +1152 -0
- package/dist/runs/foreground/clarify-invocation.js +72 -0
- package/dist/runs/foreground/execution-input.js +423 -0
- package/dist/runs/foreground/foreground-control.js +817 -0
- package/dist/runs/foreground/question-control.js +88 -0
- package/dist/runs/foreground/run-async-path.js +205 -0
- package/dist/runs/foreground/subagent-executor.js +442 -0
- package/dist/runs/foreground/subagent-params.js +165 -0
- package/dist/runs/foreground/wait-run.js +141 -0
- package/dist/runs/shared/acceptance-contract.js +253 -0
- package/dist/runs/shared/acceptance-evaluation.js +256 -0
- package/dist/runs/shared/acceptance-finalization.js +280 -0
- package/dist/runs/shared/acceptance-reports.js +147 -0
- package/dist/runs/shared/acceptance.js +4 -0
- package/dist/runs/shared/chain-outputs.js +110 -0
- package/dist/runs/shared/child-attempt.js +693 -0
- package/dist/runs/shared/child-execution-cwd.js +96 -0
- package/dist/runs/shared/child-observations.js +114 -0
- package/dist/runs/shared/claude-code.js +199 -0
- package/dist/runs/shared/completion-guard.js +31 -0
- package/dist/runs/shared/dynamic-fanout.js +274 -0
- package/dist/runs/shared/history-index.js +72 -0
- package/dist/runs/shared/mcp-direct-tool-allowlist.js +334 -0
- package/dist/runs/shared/model-fallback.js +185 -0
- package/dist/runs/shared/mutating-tool-guard.js +170 -0
- package/dist/runs/shared/native-finalization.js +101 -0
- package/dist/runs/shared/native-usage.js +153 -0
- package/dist/runs/shared/nested-events.js +700 -0
- package/dist/runs/shared/nested-path.js +48 -0
- package/dist/runs/shared/nested-render.js +108 -0
- package/dist/runs/shared/parallel-utils.js +61 -0
- package/dist/runs/shared/parent-receipts.js +68 -0
- package/dist/runs/shared/parent-usage.js +121 -0
- package/dist/runs/shared/pi-args.js +310 -0
- package/dist/runs/shared/pi-spawn.js +52 -0
- package/dist/runs/shared/run-history-queries.js +45 -0
- package/dist/runs/shared/run-history.js +110 -0
- package/dist/runs/shared/run-id-ambiguity.js +4 -0
- package/dist/runs/shared/run-records.js +679 -0
- package/dist/runs/shared/session-cwd-preload.js +33 -0
- package/dist/runs/shared/single-output.js +222 -0
- package/dist/runs/shared/streaming-text.js +15 -0
- package/dist/runs/shared/structured-output.js +55 -0
- package/dist/runs/shared/subagent-control.js +179 -0
- package/dist/runs/shared/subagent-prompt-runtime.js +197 -0
- package/dist/runs/shared/subagent-tool-loop-guard.js +66 -0
- package/dist/runs/shared/supervisor-questions.js +350 -0
- package/dist/runs/shared/workflow-graph.js +214 -0
- package/dist/runs/shared/workflow-policy.js +84 -0
- package/dist/runs/shared/worktree.js +525 -0
- package/dist/shared/agent-context-policy.js +126 -0
- package/dist/shared/artifacts.js +96 -0
- package/dist/shared/atomic-json.js +13 -0
- package/dist/shared/cooperative.js +20 -0
- package/dist/shared/execution-cwd.js +14 -0
- package/dist/shared/file-coalescer.js +21 -0
- package/dist/shared/fork-context.js +49 -0
- package/dist/shared/formatters.js +85 -0
- package/dist/shared/journal-reader.js +407 -0
- package/dist/shared/lazy-tools.js +32 -0
- package/dist/shared/model-info.js +68 -0
- package/dist/shared/native-session.js +15 -0
- package/dist/shared/native-tui.js +18 -0
- package/dist/shared/native-typebox.js +20 -0
- package/dist/shared/post-exit-stdio-guard.js +197 -0
- package/dist/shared/prompt-sections.js +8 -0
- package/dist/shared/session-entries.js +52 -0
- package/dist/shared/session-identity.js +14 -0
- package/dist/shared/settings.js +254 -0
- package/dist/shared/status-format.js +111 -0
- package/dist/shared/temp-root.js +114 -0
- package/dist/shared/types.js +207 -0
- package/dist/shared/ui-mode.js +3 -0
- package/dist/shared/utils.js +334 -0
- package/dist/slash/prompt-template-bridge.js +298 -0
- package/dist/slash/slash-bridge.js +116 -0
- package/dist/slash/slash-commands.js +607 -0
- package/dist/slash/slash-live-state.js +246 -0
- package/dist/tui/action-hints.js +75 -0
- package/dist/tui/agent-history.js +197 -0
- package/dist/tui/agent-view.js +1656 -0
- package/dist/tui/render.js +1515 -0
- package/docs/intercom-bridge.md +212 -0
- package/docs/intercom.md +581 -0
- package/docs/performance.md +121 -0
- package/package.json +102 -4
- package/prompts/gather-context-and-clarify.md +14 -0
- package/prompts/parallel-cleanup.md +62 -0
- package/prompts/parallel-context-build.md +56 -0
- package/prompts/parallel-handoff-plan.md +62 -0
- package/prompts/parallel-research.md +51 -0
- package/prompts/parallel-review.md +59 -0
- package/prompts/review-loop.md +42 -0
- package/scripts/build.mjs +134 -0
- package/scripts/check-compat.mjs +48 -0
- package/scripts/compat-host.mjs +19 -0
- package/scripts/intercom-bridge-credentials.mjs +143 -0
- package/scripts/intercom-remote.mjs +103 -0
- package/scripts/linux-smoke.sh +51 -0
- package/scripts/local-install-smoke.mjs +66 -0
- package/scripts/native-package-smoke.mjs +82 -0
- package/scripts/package-smoke.mjs +209 -0
- package/scripts/prepare.mjs +67 -0
- package/scripts/real-pi-smoke.mjs +415 -0
- package/scripts/run-tests.mjs +149 -0
- package/skills/pi-intercom/SKILL.md +113 -0
- package/skills/pi-intercom/evals/evals.json +29 -0
- package/skills/pi-intercom/evals/trigger-evals.json +47 -0
- package/skills/pi-intercom/references/peer-sessions.md +69 -0
- package/skills/pi-subagents/SKILL.md +76 -0
- package/skills/pi-subagents/evals/evals.json +29 -0
- package/skills/pi-subagents/evals/trigger-evals.json +42 -0
- package/skills/pi-subagents/references/full-orchestration-guide.md +863 -0
- package/src/agents/agent-management.ts +813 -0
- package/src/agents/agent-scope.ts +7 -0
- package/src/agents/agent-selection.ts +23 -0
- package/src/agents/agent-serializer.ts +99 -0
- package/src/agents/agents.ts +916 -0
- package/src/agents/chain-serializer.ts +329 -0
- package/src/agents/frontmatter.ts +21 -0
- package/src/agents/identity.ts +30 -0
- package/src/agents/skills.ts +637 -0
- package/src/extension/build-info.ts +2 -0
- package/src/extension/compact-tools.ts +114 -0
- package/src/extension/config.ts +23 -0
- package/src/extension/control-notices.ts +47 -0
- package/src/extension/doctor.ts +171 -0
- package/src/extension/fanout-child.ts +312 -0
- package/src/extension/index.ts +649 -0
- package/src/extension/schemas.ts +444 -0
- package/src/extension/tool-input.ts +19 -0
- package/src/extension/tool-result.ts +16 -0
- package/src/history/canonical-result.ts +62 -0
- package/src/history/database.ts +59 -0
- package/src/history/index.ts +156 -0
- package/src/history/ingest.ts +349 -0
- package/src/history/queries.ts +241 -0
- package/src/history/store.ts +203 -0
- package/src/history/types.ts +166 -0
- package/src/history/worker.ts +321 -0
- package/src/intercom/intercom-bridge.ts +123 -0
- package/src/intercom/live-intercom.ts +104 -0
- package/src/intercom/result-intercom.ts +429 -0
- package/src/pi-intercom/agent-dir.ts +9 -0
- package/src/pi-intercom/bridge.ts +668 -0
- package/src/pi-intercom/broker/broker.ts +463 -0
- package/src/pi-intercom/broker/client.ts +558 -0
- package/src/pi-intercom/broker/framing.ts +77 -0
- package/src/pi-intercom/broker/paths.ts +47 -0
- package/src/pi-intercom/broker/pid.ts +59 -0
- package/src/pi-intercom/broker/spawn.ts +248 -0
- package/src/pi-intercom/config.ts +142 -0
- package/src/pi-intercom/index.ts +2929 -0
- package/src/pi-intercom/reply-tracker.ts +211 -0
- package/src/pi-intercom/session-targets.ts +172 -0
- package/src/pi-intercom/subagent-live-events.ts +133 -0
- package/src/pi-intercom/topics.ts +125 -0
- package/src/pi-intercom/types.ts +271 -0
- package/src/pi-intercom/ui/compose.ts +289 -0
- package/src/pi-intercom/ui/inline-message.ts +92 -0
- package/src/pi-intercom/ui/session-list.ts +139 -0
- package/src/runs/background/async-control.ts +89 -0
- package/src/runs/background/async-execution.ts +850 -0
- package/src/runs/background/async-job-tracker.ts +385 -0
- package/src/runs/background/async-result-file.ts +62 -0
- package/src/runs/background/async-resume.ts +333 -0
- package/src/runs/background/async-status.ts +481 -0
- package/src/runs/background/completion-dedupe.ts +79 -0
- package/src/runs/background/completion-delivery.ts +195 -0
- package/src/runs/background/notify.ts +123 -0
- package/src/runs/background/parallel-groups.ts +53 -0
- package/src/runs/background/result-watcher.ts +423 -0
- package/src/runs/background/run-id-resolver.ts +69 -0
- package/src/runs/background/run-status.ts +384 -0
- package/src/runs/background/stale-run-reconciler.ts +369 -0
- package/src/runs/background/subagent-runner-launcher.ts +56 -0
- package/src/runs/background/subagent-runner.ts +2053 -0
- package/src/runs/background/top-level-async.ts +13 -0
- package/src/runs/foreground/chain-clarify.ts +1340 -0
- package/src/runs/foreground/clarify-invocation.ts +77 -0
- package/src/runs/foreground/execution-input.ts +467 -0
- package/src/runs/foreground/foreground-control.ts +821 -0
- package/src/runs/foreground/question-control.ts +82 -0
- package/src/runs/foreground/run-async-path.ts +243 -0
- package/src/runs/foreground/subagent-executor.ts +501 -0
- package/src/runs/foreground/subagent-params.ts +320 -0
- package/src/runs/foreground/wait-run.ts +124 -0
- package/src/runs/shared/acceptance-contract.ts +257 -0
- package/src/runs/shared/acceptance-evaluation.ts +275 -0
- package/src/runs/shared/acceptance-finalization.ts +353 -0
- package/src/runs/shared/acceptance-reports.ts +152 -0
- package/src/runs/shared/acceptance.ts +33 -0
- package/src/runs/shared/chain-outputs.ts +114 -0
- package/src/runs/shared/child-attempt.ts +623 -0
- package/src/runs/shared/child-execution-cwd.ts +91 -0
- package/src/runs/shared/child-observations.ts +99 -0
- package/src/runs/shared/claude-code.ts +243 -0
- package/src/runs/shared/completion-guard.ts +35 -0
- package/src/runs/shared/dynamic-fanout.ts +295 -0
- package/src/runs/shared/history-index.ts +69 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +376 -0
- package/src/runs/shared/model-fallback.ts +219 -0
- package/src/runs/shared/mutating-tool-guard.ts +194 -0
- package/src/runs/shared/native-finalization.ts +128 -0
- package/src/runs/shared/native-usage.ts +113 -0
- package/src/runs/shared/nested-events.ts +752 -0
- package/src/runs/shared/nested-path.ts +52 -0
- package/src/runs/shared/nested-render.ts +119 -0
- package/src/runs/shared/parallel-utils.ts +153 -0
- package/src/runs/shared/parent-receipts.ts +59 -0
- package/src/runs/shared/parent-usage.ts +121 -0
- package/src/runs/shared/pi-args.ts +350 -0
- package/src/runs/shared/pi-spawn.ts +52 -0
- package/src/runs/shared/run-history-queries.ts +44 -0
- package/src/runs/shared/run-history.ts +100 -0
- package/src/runs/shared/run-id-ambiguity.ts +4 -0
- package/src/runs/shared/run-records.ts +607 -0
- package/src/runs/shared/session-cwd-preload.ts +27 -0
- package/src/runs/shared/single-output.ts +267 -0
- package/src/runs/shared/streaming-text.ts +18 -0
- package/src/runs/shared/structured-output.ts +68 -0
- package/src/runs/shared/subagent-control.ts +219 -0
- package/src/runs/shared/subagent-prompt-runtime.ts +201 -0
- package/src/runs/shared/subagent-tool-loop-guard.ts +89 -0
- package/src/runs/shared/supervisor-questions.ts +415 -0
- package/src/runs/shared/workflow-graph.ts +220 -0
- package/src/runs/shared/workflow-policy.ts +125 -0
- package/src/runs/shared/worktree.ts +635 -0
- package/src/shared/agent-context-policy.ts +184 -0
- package/src/shared/artifacts.ts +95 -0
- package/src/shared/atomic-json.ts +16 -0
- package/src/shared/cooperative.ts +21 -0
- package/src/shared/execution-cwd.ts +14 -0
- package/src/shared/file-coalescer.ts +29 -0
- package/src/shared/fork-context.ts +68 -0
- package/src/shared/formatters.ts +84 -0
- package/src/shared/journal-reader.ts +333 -0
- package/src/shared/lazy-tools.ts +36 -0
- package/src/shared/model-info.ts +81 -0
- package/src/shared/native-session.ts +8 -0
- package/src/shared/native-tui.ts +10 -0
- package/src/shared/native-typebox.ts +14 -0
- package/src/shared/post-exit-stdio-guard.ts +204 -0
- package/src/shared/prompt-sections.ts +10 -0
- package/src/shared/session-entries.ts +49 -0
- package/src/shared/session-identity.ts +18 -0
- package/src/shared/settings.ts +384 -0
- package/src/shared/status-format.ts +123 -0
- package/src/shared/temp-root.ts +107 -0
- package/src/shared/types.ts +1260 -0
- package/src/shared/ui-mode.ts +5 -0
- package/src/shared/utils.ts +342 -0
- package/src/slash/prompt-template-bridge.ts +408 -0
- package/src/slash/slash-bridge.ts +178 -0
- package/src/slash/slash-commands.ts +617 -0
- package/src/slash/slash-live-state.ts +292 -0
- package/src/tui/action-hints.ts +69 -0
- package/src/tui/agent-history.ts +210 -0
- package/src/tui/agent-view.ts +1323 -0
- package/src/tui/render.ts +1550 -0
- package/tsconfig.build.json +12 -0
- package/tsconfig.json +19 -0
|
@@ -0,0 +1,676 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Async execution logic for subagent tool
|
|
3
|
+
*/
|
|
4
|
+
import { spawn } from "node:child_process";
|
|
5
|
+
import * as fs from "node:fs";
|
|
6
|
+
import * as path from "node:path";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { applyThinkingSuffix, SUBAGENT_CHILD_ENV, SUBAGENT_FANOUT_CHILD_ENV } from "../shared/pi-args.js";
|
|
9
|
+
import { findDuplicateOutputPath, injectSingleOutputInstruction, materializeAgentDefaultOutputPath, normalizeSingleOutputOverride, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.js";
|
|
10
|
+
import { buildChainInstructions, createChainDir, isDynamicParallelStep, isParallelStep, resolveChainTemplates, resolveParallelBehaviors, resolveStepBehavior, suppressProgressForReadOnlyTask, writeInitialProgressFile } from "../../shared/settings.js";
|
|
11
|
+
import { resolvePiPackageRoot } from "../shared/pi-spawn.js";
|
|
12
|
+
import { buildSkillInjection, normalizeSkillInput, resolveSkillsWithFallback } from "../../agents/skills.js";
|
|
13
|
+
import { resolveChildCwd } from "../../shared/utils.js";
|
|
14
|
+
import { buildModelCandidates, resolveModelCandidate } from "../shared/model-fallback.js";
|
|
15
|
+
import { resolveEffectiveThinking } from "../../shared/model-info.js";
|
|
16
|
+
import { resolveExpectedWorktreeAgentCwd } from "../shared/worktree.js";
|
|
17
|
+
import { buildWorkflowGraphSnapshot } from "../shared/workflow-graph.js";
|
|
18
|
+
import { ChainOutputValidationError, validateChainOutputBindings } from "../shared/chain-outputs.js";
|
|
19
|
+
import { createStructuredOutputRuntime } from "../shared/structured-output.js";
|
|
20
|
+
import { resolveEffectiveAcceptance } from "../shared/acceptance.js";
|
|
21
|
+
import { DEFAULT_MAX_OUTPUT, RESULTS_DIR, RUNNER_ERROR_LOG_FILE, SUBAGENT_ASYNC_STARTED_EVENT, resolveChildMaxSubagentDepth, } from "../../shared/types.js";
|
|
22
|
+
import { nestedResultsPath, resolveInheritedNestedRouteFromEnv, resolveNestedParentAddressFromEnv, writeNestedEvent } from "../shared/nested-events.js";
|
|
23
|
+
import { formatRunAction } from "../../shared/status-format.js";
|
|
24
|
+
import { ensureTempRoot } from "../../shared/temp-root.js";
|
|
25
|
+
import { getRunMetadataDir } from "../shared/supervisor-questions.js";
|
|
26
|
+
const piPackageRoot = resolvePiPackageRoot();
|
|
27
|
+
function usesAgentDefaultOutput(output) {
|
|
28
|
+
return output === undefined || output === true || output === "true";
|
|
29
|
+
}
|
|
30
|
+
function materializeAsyncDefaultOutput(params) {
|
|
31
|
+
return materializeAgentDefaultOutputPath({
|
|
32
|
+
output: params.output,
|
|
33
|
+
artifactsDir: params.artifactsDir ?? params.asyncDir,
|
|
34
|
+
runId: params.runId,
|
|
35
|
+
agent: params.agent,
|
|
36
|
+
index: params.index,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
function resolveAsyncOutput(params) {
|
|
40
|
+
const effectiveOutput = usesAgentDefaultOutput(params.requestedOutput)
|
|
41
|
+
? normalizeSingleOutputOverride(true, params.agentDefaultOutput)
|
|
42
|
+
: normalizeSingleOutputOverride(params.requestedOutput, params.agentDefaultOutput);
|
|
43
|
+
return usesAgentDefaultOutput(params.requestedOutput)
|
|
44
|
+
? materializeAsyncDefaultOutput({ output: effectiveOutput, artifactsDir: params.artifactsDir, asyncDir: params.asyncDir, runId: params.runId, agent: params.agent, index: params.index })
|
|
45
|
+
: effectiveOutput;
|
|
46
|
+
}
|
|
47
|
+
function withSavedLaunch(step, agent, params, generatedOutputFilename) {
|
|
48
|
+
return { ...step, launch: {
|
|
49
|
+
agent, model: step.model, thinking: step.thinking, modelCandidates: step.modelCandidates ?? [],
|
|
50
|
+
artifacts: params.artifactsDir !== undefined, artifactsDir: params.artifactsDir, share: params.shareEnabled,
|
|
51
|
+
systemPrompt: step.systemPrompt ?? "", skills: step.skills ?? [], cwd: step.cwd ?? params.ctx.cwd,
|
|
52
|
+
context: agent.defaultContext ?? "fresh", output: step.outputPath ?? false, outputMode: step.outputMode ?? "inline",
|
|
53
|
+
...(generatedOutputFilename ? { generatedOutputFilename } : step.outputPathFromAgentDefault && step.outputPath && typeof agent.output === "string" && !path.isAbsolute(agent.output) ? { generatedOutputFilename: path.basename(agent.output) } : {}),
|
|
54
|
+
outputSchema: step.structuredOutputSchema, effectiveAcceptance: step.effectiveAcceptance,
|
|
55
|
+
maxOutput: { ...DEFAULT_MAX_OUTPUT, ...params.maxOutput }, maxSubagentDepth: step.maxSubagentDepth,
|
|
56
|
+
maxExecutionTimeMs: step.maxExecutionTimeMs, maxTokens: step.maxTokens,
|
|
57
|
+
controlConfig: params.controlConfig, projectTrust: params.projectTrust, projectTrusted: params.ctx.projectTrusted,
|
|
58
|
+
} };
|
|
59
|
+
}
|
|
60
|
+
function resolveLaunchModel(agent, modelOverride, availableModels, preferredProvider, savedLaunch) {
|
|
61
|
+
const primary = modelOverride ?? savedLaunch?.model ?? agent.model;
|
|
62
|
+
const thinking = savedLaunch?.thinking ?? agent.thinking;
|
|
63
|
+
const model = applyThinkingSuffix(resolveModelCandidate(primary, availableModels, preferredProvider), thinking);
|
|
64
|
+
// Only caller selections pin the route; persisted candidates already encode the saved policy.
|
|
65
|
+
const fallbacks = modelOverride ? [] : savedLaunch?.modelCandidates ?? agent.fallbackModels;
|
|
66
|
+
return {
|
|
67
|
+
model,
|
|
68
|
+
thinking: resolveEffectiveThinking(model, thinking),
|
|
69
|
+
modelCandidates: buildModelCandidates(primary, fallbacks, availableModels, preferredProvider)
|
|
70
|
+
.map((candidate) => applyThinkingSuffix(candidate, thinking))
|
|
71
|
+
.filter((candidate) => typeof candidate === "string"),
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
export function formatAsyncStartedMessage(headline, childSafe = process.env[SUBAGENT_CHILD_ENV] === "1" && process.env[SUBAGENT_FANOUT_CHILD_ENV] === "1") {
|
|
75
|
+
return [
|
|
76
|
+
headline,
|
|
77
|
+
"",
|
|
78
|
+
"The async run is detached. Do not run sleep timers or polling loops just to wait for it.",
|
|
79
|
+
"If you have independent work, continue that work. If you have nothing else to do until the async result arrives, end your turn now; Pi will deliver the completion when the run finishes.",
|
|
80
|
+
`Use ${formatRunAction("status", "...", {}, childSafe)} when you need the current status/result, or to inspect a blocked/stale run. Do not poll just to wait.`,
|
|
81
|
+
].join("\n");
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Spawn the async runner process
|
|
85
|
+
*/
|
|
86
|
+
function spawnRunner(cfg, cwd, asyncDir) {
|
|
87
|
+
try {
|
|
88
|
+
const cwdStats = fs.statSync(cwd);
|
|
89
|
+
if (!cwdStats.isDirectory()) {
|
|
90
|
+
return { error: `cwd is not a directory: ${cwd}` };
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return { error: `cwd does not exist: ${cwd}` };
|
|
95
|
+
}
|
|
96
|
+
ensureTempRoot();
|
|
97
|
+
const cfgPath = path.join(asyncDir, "launch.json");
|
|
98
|
+
fs.writeFileSync(cfgPath, JSON.stringify({ ...cfg, runtimeVersion: 2 }), { mode: 0o600, flag: "wx" });
|
|
99
|
+
const runnerDir = path.dirname(fileURLToPath(import.meta.url));
|
|
100
|
+
const moduleExtension = import.meta.url.endsWith(".ts") ? ".ts" : ".js";
|
|
101
|
+
const launcher = path.join(runnerDir, `subagent-runner-launcher${moduleExtension}`);
|
|
102
|
+
const runner = path.join(runnerDir, `subagent-runner${moduleExtension}`);
|
|
103
|
+
const errorLogFd = fs.openSync(path.join(asyncDir, RUNNER_ERROR_LOG_FILE), "a");
|
|
104
|
+
try {
|
|
105
|
+
const proc = spawn(process.execPath, [launcher, runner, cfgPath], {
|
|
106
|
+
cwd,
|
|
107
|
+
detached: true,
|
|
108
|
+
stdio: ["ignore", "ignore", errorLogFd],
|
|
109
|
+
});
|
|
110
|
+
proc.on("error", (error) => {
|
|
111
|
+
console.error(`[pi-subagents] async spawn failed: ${error.message}`);
|
|
112
|
+
});
|
|
113
|
+
if (typeof proc.pid !== "number") {
|
|
114
|
+
return { error: `async runner did not produce a pid for cwd: ${cwd}` };
|
|
115
|
+
}
|
|
116
|
+
proc.unref();
|
|
117
|
+
return { pid: proc.pid };
|
|
118
|
+
}
|
|
119
|
+
finally {
|
|
120
|
+
fs.closeSync(errorLogFd);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
function formatAsyncStartError(mode, message) {
|
|
124
|
+
return {
|
|
125
|
+
content: [{ type: "text", text: message }],
|
|
126
|
+
isError: true,
|
|
127
|
+
details: { mode, results: [] },
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
const UNAVAILABLE_SUBAGENT_SKILL_ERROR = "Skills not found: pi-subagents";
|
|
131
|
+
class UnavailableSubagentSkillError extends Error {
|
|
132
|
+
}
|
|
133
|
+
class AsyncStartValidationError extends Error {
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Execute a chain asynchronously
|
|
137
|
+
*/
|
|
138
|
+
export function executeAsyncChain(id, params) {
|
|
139
|
+
const { chain, agents, ctx, cwd, maxOutput, artifactsDir, shareEnabled, sessionRoot, sessionFilesByFlatIndex, maxSubagentDepth, worktreeSetupHook, worktreeSetupHookTimeoutMs, controlConfig, controlIntercomTarget, childIntercomTarget, nestedRoute, } = params;
|
|
140
|
+
const resultMode = params.resultMode ?? "chain";
|
|
141
|
+
const chainSkills = params.chainSkills ?? [];
|
|
142
|
+
const availableModels = params.availableModels;
|
|
143
|
+
const runnerCwd = resolveChildCwd(ctx.cwd, cwd);
|
|
144
|
+
const chainDir = resultMode === "chain" ? createChainDir(id, params.chainDir, runnerCwd) : runnerCwd;
|
|
145
|
+
const firstStep = chain[0];
|
|
146
|
+
const originalTask = params.task ?? (firstStep
|
|
147
|
+
? (isParallelStep(firstStep)
|
|
148
|
+
? firstStep.parallel[0]?.task
|
|
149
|
+
: isDynamicParallelStep(firstStep)
|
|
150
|
+
? firstStep.parallel.task
|
|
151
|
+
: firstStep.task)
|
|
152
|
+
: undefined);
|
|
153
|
+
try {
|
|
154
|
+
validateChainOutputBindings(chain, { maxItems: params.dynamicFanoutMaxItems });
|
|
155
|
+
}
|
|
156
|
+
catch (error) {
|
|
157
|
+
if (error instanceof ChainOutputValidationError)
|
|
158
|
+
return formatAsyncStartError(resultMode, error.message);
|
|
159
|
+
throw error;
|
|
160
|
+
}
|
|
161
|
+
const workflowGraph = buildWorkflowGraphSnapshot({ runId: id, mode: resultMode, steps: chain });
|
|
162
|
+
const templates = resolveChainTemplates(chain);
|
|
163
|
+
for (const s of chain) {
|
|
164
|
+
const stepAgents = isParallelStep(s)
|
|
165
|
+
? s.parallel.map((t) => t.agent)
|
|
166
|
+
: isDynamicParallelStep(s)
|
|
167
|
+
? [s.parallel.agent]
|
|
168
|
+
: [s.agent];
|
|
169
|
+
for (const agentName of stepAgents) {
|
|
170
|
+
if (!agents.find((x) => x.name === agentName)) {
|
|
171
|
+
return {
|
|
172
|
+
content: [{ type: "text", text: `Unknown agent: ${agentName}` }],
|
|
173
|
+
isError: true,
|
|
174
|
+
details: { mode: resultMode, results: [] },
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
const inheritedNestedRoute = resolveInheritedNestedRouteFromEnv();
|
|
180
|
+
const nestedAddress = inheritedNestedRoute ? resolveNestedParentAddressFromEnv() : undefined;
|
|
181
|
+
const asyncDir = getRunMetadataDir(id);
|
|
182
|
+
try {
|
|
183
|
+
fs.mkdirSync(asyncDir, { recursive: true });
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
187
|
+
return {
|
|
188
|
+
content: [{ type: "text", text: `Failed to create async run directory '${asyncDir}': ${message}` }],
|
|
189
|
+
isError: true,
|
|
190
|
+
details: { mode: resultMode, results: [] },
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
let progressInstructionCreated = false;
|
|
194
|
+
let outputMaterializationIndex = 0;
|
|
195
|
+
const buildStepOverrides = (s) => {
|
|
196
|
+
const stepSkillInput = normalizeSkillInput(s.skill);
|
|
197
|
+
return {
|
|
198
|
+
...(s.output !== undefined ? { output: s.output } : {}),
|
|
199
|
+
...(s.outputMode !== undefined ? { outputMode: s.outputMode } : {}),
|
|
200
|
+
...(s.reads !== undefined ? { reads: s.reads } : {}),
|
|
201
|
+
...(s.progress !== undefined ? { progress: s.progress } : {}),
|
|
202
|
+
...(stepSkillInput !== undefined ? { skills: stepSkillInput } : {}),
|
|
203
|
+
};
|
|
204
|
+
};
|
|
205
|
+
const buildSeqStep = (s, sessionFile, behaviorCwd, progressPrecreated = false, resolvedBehavior) => {
|
|
206
|
+
const a = agents.find((x) => x.name === s.agent);
|
|
207
|
+
const outputIndex = outputMaterializationIndex++;
|
|
208
|
+
const stepCwd = resolveChildCwd(runnerCwd, s.cwd);
|
|
209
|
+
const instructionCwd = behaviorCwd ?? (resultMode === "chain" ? chainDir : stepCwd);
|
|
210
|
+
const behavior = suppressProgressForReadOnlyTask(resolvedBehavior ?? resolveStepBehavior(a, buildStepOverrides(s), chainSkills), s.task, originalTask);
|
|
211
|
+
const launchAgent = behavior.skills === false ? { ...a, inheritSkills: false } : a;
|
|
212
|
+
const outputUsesAgentDefault = usesAgentDefaultOutput(s.output) || s.outputFromAgentDefault === true;
|
|
213
|
+
const output = outputUsesAgentDefault && resultMode !== "chain"
|
|
214
|
+
? materializeAsyncDefaultOutput({ output: behavior.output, artifactsDir, asyncDir, runId: id, agent: s.agent, index: outputIndex })
|
|
215
|
+
: behavior.output;
|
|
216
|
+
const skillNames = behavior.skills === false ? [] : behavior.skills;
|
|
217
|
+
const { resolved: resolvedSkills, missing: missingSkills } = resolveSkillsWithFallback(skillNames, stepCwd, ctx.cwd, { projectTrusted: ctx.projectTrusted ?? true });
|
|
218
|
+
if (missingSkills.includes("pi-subagents"))
|
|
219
|
+
throw new UnavailableSubagentSkillError(UNAVAILABLE_SUBAGENT_SKILL_ERROR);
|
|
220
|
+
let systemPrompt = a.systemPrompt?.trim() ?? "";
|
|
221
|
+
if (resolvedSkills.length > 0) {
|
|
222
|
+
const injection = buildSkillInjection(resolvedSkills);
|
|
223
|
+
systemPrompt = systemPrompt ? `${systemPrompt}\n\n${injection}` : injection;
|
|
224
|
+
}
|
|
225
|
+
const readInstructions = buildChainInstructions({ ...behavior, output: false, progress: false }, instructionCwd, false);
|
|
226
|
+
const isFirstProgressAgent = behavior.progress && !progressPrecreated && (resultMode !== "chain" || !progressInstructionCreated);
|
|
227
|
+
if (behavior.progress && resultMode === "chain")
|
|
228
|
+
progressInstructionCreated = true;
|
|
229
|
+
const progressInstructions = buildChainInstructions({ ...behavior, output: false, reads: false }, instructionCwd, isFirstProgressAgent);
|
|
230
|
+
const outputPath = resolveSingleOutputPath(output, ctx.cwd, instructionCwd);
|
|
231
|
+
const validationError = validateFileOnlyOutputMode(behavior.outputMode, outputPath, `Async step (${s.agent})`);
|
|
232
|
+
if (validationError)
|
|
233
|
+
throw new AsyncStartValidationError(validationError);
|
|
234
|
+
const taskTemplate = s.task ?? "{previous}";
|
|
235
|
+
const task = injectSingleOutputInstruction(`${readInstructions.prefix}${taskTemplate}${progressInstructions.suffix}`, outputPath);
|
|
236
|
+
return withSavedLaunch({
|
|
237
|
+
agent: s.agent,
|
|
238
|
+
task,
|
|
239
|
+
phase: s.phase,
|
|
240
|
+
label: s.label,
|
|
241
|
+
outputName: s.as,
|
|
242
|
+
structured: Boolean(s.outputSchema),
|
|
243
|
+
cwd: stepCwd,
|
|
244
|
+
...resolveLaunchModel(a, s.model, availableModels, ctx.currentModelProvider),
|
|
245
|
+
tools: a.tools,
|
|
246
|
+
allowSubagents: a.allowSubagents,
|
|
247
|
+
extensions: a.extensions,
|
|
248
|
+
mcpDirectTools: a.mcpDirectTools,
|
|
249
|
+
completionGuard: a.completionGuard,
|
|
250
|
+
systemPrompt,
|
|
251
|
+
systemPromptMode: a.systemPromptMode,
|
|
252
|
+
inheritProjectContext: a.inheritProjectContext,
|
|
253
|
+
inheritSkills: launchAgent.inheritSkills,
|
|
254
|
+
skills: resolvedSkills.map((r) => r.name),
|
|
255
|
+
outputPath,
|
|
256
|
+
output: behavior.output,
|
|
257
|
+
outputMode: behavior.outputMode,
|
|
258
|
+
...(outputUsesAgentDefault && outputPath && typeof a.output === "string" && !path.isAbsolute(a.output) ? { outputPathFromAgentDefault: true } : {}),
|
|
259
|
+
sessionFile,
|
|
260
|
+
maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, a.maxSubagentDepth),
|
|
261
|
+
maxExecutionTimeMs: a.maxExecutionTimeMs,
|
|
262
|
+
maxTokens: a.maxTokens,
|
|
263
|
+
effectiveAcceptance: resolveEffectiveAcceptance({ explicit: s.acceptance }),
|
|
264
|
+
...(s.outputSchema ? { structuredOutputSchema: s.outputSchema } : {}),
|
|
265
|
+
...(s.outputSchema ? { structuredOutput: createStructuredOutputRuntime(s.outputSchema, path.join(asyncDir, "structured-output")) } : {}),
|
|
266
|
+
}, launchAgent, params);
|
|
267
|
+
};
|
|
268
|
+
let flatStepIndex = 0;
|
|
269
|
+
const nextSessionFile = () => {
|
|
270
|
+
const sessionFile = sessionFilesByFlatIndex?.[flatStepIndex];
|
|
271
|
+
flatStepIndex++;
|
|
272
|
+
return sessionFile;
|
|
273
|
+
};
|
|
274
|
+
const takeDynamicSessionFiles = (count) => {
|
|
275
|
+
if (!sessionFilesByFlatIndex || count <= 0)
|
|
276
|
+
return undefined;
|
|
277
|
+
const sessionFiles = sessionFilesByFlatIndex.slice(flatStepIndex, flatStepIndex + count);
|
|
278
|
+
flatStepIndex += count;
|
|
279
|
+
return sessionFiles;
|
|
280
|
+
};
|
|
281
|
+
let steps;
|
|
282
|
+
try {
|
|
283
|
+
steps = chain.map((s, stepIndex) => {
|
|
284
|
+
if (isParallelStep(s)) {
|
|
285
|
+
const groupCwd = resolveChildCwd(runnerCwd, s.cwd);
|
|
286
|
+
const behaviors = resultMode === "chain"
|
|
287
|
+
? resolveParallelBehaviors(s.parallel, agents, stepIndex, chainSkills)
|
|
288
|
+
: s.parallel.map((task) => resolveStepBehavior(agents.find((agent) => agent.name === task.agent), buildStepOverrides(task), chainSkills));
|
|
289
|
+
const parallelBehaviors = behaviors.map((behavior, index) => suppressProgressForReadOnlyTask(behavior, s.parallel[index]?.task, originalTask));
|
|
290
|
+
const progressPrecreated = resultMode === "chain" && parallelBehaviors.some((behavior) => behavior.progress);
|
|
291
|
+
if (progressPrecreated) {
|
|
292
|
+
if (!s.worktree)
|
|
293
|
+
writeInitialProgressFile(chainDir);
|
|
294
|
+
progressInstructionCreated = true;
|
|
295
|
+
}
|
|
296
|
+
const parallelSteps = s.parallel.map((t, taskIndex) => {
|
|
297
|
+
let behaviorCwd;
|
|
298
|
+
if (s.worktree && resultMode !== "chain") {
|
|
299
|
+
try {
|
|
300
|
+
behaviorCwd = resolveExpectedWorktreeAgentCwd(groupCwd, `${id}-s${stepIndex}`, taskIndex);
|
|
301
|
+
}
|
|
302
|
+
catch {
|
|
303
|
+
behaviorCwd = undefined;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
const taskProgressPrecreated = progressPrecreated || (resultMode !== "chain" && parallelBehaviors[taskIndex]?.progress === true && !s.worktree);
|
|
307
|
+
if (taskProgressPrecreated && !progressPrecreated) {
|
|
308
|
+
const progressCwd = resolveChildCwd(groupCwd, t.cwd);
|
|
309
|
+
try {
|
|
310
|
+
writeInitialProgressFile(progressCwd);
|
|
311
|
+
}
|
|
312
|
+
catch (error) {
|
|
313
|
+
throw new AsyncStartValidationError(`Failed to initialize progress in '${progressCwd}': ${error instanceof Error ? error.message : String(error)}`);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
return buildSeqStep({ ...t, task: templates[stepIndex][taskIndex], cwd: resolveChildCwd(groupCwd, t.cwd) }, nextSessionFile(), behaviorCwd, taskProgressPrecreated, parallelBehaviors[taskIndex]);
|
|
317
|
+
});
|
|
318
|
+
const duplicateOutputError = findDuplicateOutputPath(parallelSteps);
|
|
319
|
+
if (duplicateOutputError)
|
|
320
|
+
throw new AsyncStartValidationError(duplicateOutputError);
|
|
321
|
+
return {
|
|
322
|
+
parallel: parallelSteps,
|
|
323
|
+
cwd: groupCwd,
|
|
324
|
+
concurrency: s.concurrency,
|
|
325
|
+
failFast: s.failFast,
|
|
326
|
+
worktree: s.worktree,
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
if (isDynamicParallelStep(s)) {
|
|
330
|
+
const agent = agents.find((candidate) => candidate.name === s.parallel.agent);
|
|
331
|
+
const behavior = suppressProgressForReadOnlyTask(resolveStepBehavior(agent, buildStepOverrides(s.parallel), chainSkills), s.parallel.task, originalTask);
|
|
332
|
+
const progressPrecreated = behavior.progress;
|
|
333
|
+
if (progressPrecreated) {
|
|
334
|
+
writeInitialProgressFile(chainDir);
|
|
335
|
+
progressInstructionCreated = true;
|
|
336
|
+
}
|
|
337
|
+
const maxItems = s.expand.maxItems ?? params.dynamicFanoutMaxItems ?? 0;
|
|
338
|
+
return {
|
|
339
|
+
expand: s.expand,
|
|
340
|
+
parallel: buildSeqStep({ ...s.parallel, task: templates[stepIndex] }, undefined, undefined, progressPrecreated, behavior),
|
|
341
|
+
collect: s.collect,
|
|
342
|
+
concurrency: s.concurrency,
|
|
343
|
+
failFast: s.failFast,
|
|
344
|
+
phase: s.phase,
|
|
345
|
+
label: s.label,
|
|
346
|
+
sessionFiles: takeDynamicSessionFiles(maxItems),
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
return buildSeqStep({ ...s, task: templates[stepIndex] }, nextSessionFile());
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
catch (error) {
|
|
353
|
+
if (error instanceof UnavailableSubagentSkillError || error instanceof AsyncStartValidationError)
|
|
354
|
+
return formatAsyncStartError(resultMode, error.message);
|
|
355
|
+
throw error;
|
|
356
|
+
}
|
|
357
|
+
let childTargetIndex = 0;
|
|
358
|
+
const childIntercomTargets = childIntercomTarget ? steps.flatMap((step) => {
|
|
359
|
+
if ("parallel" in step) {
|
|
360
|
+
if (!Array.isArray(step.parallel)) {
|
|
361
|
+
return [childIntercomTarget(step.parallel.agent, childTargetIndex++)];
|
|
362
|
+
}
|
|
363
|
+
return step.parallel.map((task) => childIntercomTarget(task.agent, childTargetIndex++));
|
|
364
|
+
}
|
|
365
|
+
return [childIntercomTarget(step.agent, childTargetIndex++)];
|
|
366
|
+
}) : undefined;
|
|
367
|
+
let spawnResult = {};
|
|
368
|
+
try {
|
|
369
|
+
spawnResult = spawnRunner({
|
|
370
|
+
id,
|
|
371
|
+
steps,
|
|
372
|
+
chainDir,
|
|
373
|
+
originalTask,
|
|
374
|
+
resultPath: inheritedNestedRoute ? nestedResultsPath(inheritedNestedRoute.rootRunId, id) : path.join(RESULTS_DIR, `${id}.json`),
|
|
375
|
+
cwd: runnerCwd,
|
|
376
|
+
placeholder: "{previous}",
|
|
377
|
+
maxOutput,
|
|
378
|
+
timeoutMs: params.timeoutMs,
|
|
379
|
+
artifactsDir,
|
|
380
|
+
share: shareEnabled,
|
|
381
|
+
sessionDir: sessionRoot ? path.join(sessionRoot, `async-${id}`) : undefined,
|
|
382
|
+
asyncDir,
|
|
383
|
+
sessionId: ctx.currentSessionId,
|
|
384
|
+
rootSessionId: ctx.rootSessionId,
|
|
385
|
+
piPackageRoot,
|
|
386
|
+
worktreeSetupHook,
|
|
387
|
+
worktreeSetupHookTimeoutMs,
|
|
388
|
+
controlConfig,
|
|
389
|
+
controlIntercomTarget,
|
|
390
|
+
childIntercomTargets,
|
|
391
|
+
resultMode,
|
|
392
|
+
dynamicFanoutMaxItems: params.dynamicFanoutMaxItems,
|
|
393
|
+
workflowGraph,
|
|
394
|
+
nestedRoute: nestedRoute ?? inheritedNestedRoute,
|
|
395
|
+
nestedSelf: inheritedNestedRoute && nestedAddress ? {
|
|
396
|
+
parentRunId: nestedAddress.parentRunId,
|
|
397
|
+
parentStepIndex: nestedAddress.parentStepIndex,
|
|
398
|
+
depth: nestedAddress.depth,
|
|
399
|
+
path: nestedAddress.path,
|
|
400
|
+
} : undefined,
|
|
401
|
+
projectTrust: params.projectTrust,
|
|
402
|
+
}, runnerCwd, asyncDir);
|
|
403
|
+
}
|
|
404
|
+
catch (error) {
|
|
405
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
406
|
+
return formatAsyncStartError(resultMode, `Failed to start async ${resultMode} '${id}': ${message}`);
|
|
407
|
+
}
|
|
408
|
+
if (spawnResult.error) {
|
|
409
|
+
return formatAsyncStartError(resultMode, `Failed to start async ${resultMode} '${id}': ${spawnResult.error}`);
|
|
410
|
+
}
|
|
411
|
+
if (spawnResult.pid) {
|
|
412
|
+
const firstStep = chain[0];
|
|
413
|
+
const firstAgents = isParallelStep(firstStep)
|
|
414
|
+
? firstStep.parallel.map((t) => t.agent)
|
|
415
|
+
: isDynamicParallelStep(firstStep)
|
|
416
|
+
? [firstStep.parallel.agent]
|
|
417
|
+
: [firstStep.agent];
|
|
418
|
+
const parallelGroups = [];
|
|
419
|
+
const flatAgents = [];
|
|
420
|
+
let flatStepStart = 0;
|
|
421
|
+
for (let stepIndex = 0; stepIndex < chain.length; stepIndex++) {
|
|
422
|
+
const step = chain[stepIndex];
|
|
423
|
+
if (isParallelStep(step)) {
|
|
424
|
+
parallelGroups.push({ start: flatStepStart, count: step.parallel.length, stepIndex });
|
|
425
|
+
flatAgents.push(...step.parallel.map((task) => task.agent));
|
|
426
|
+
flatStepStart += step.parallel.length;
|
|
427
|
+
}
|
|
428
|
+
else if (isDynamicParallelStep(step)) {
|
|
429
|
+
parallelGroups.push({ start: flatStepStart, count: 1, stepIndex });
|
|
430
|
+
flatAgents.push(step.parallel.agent);
|
|
431
|
+
flatStepStart++;
|
|
432
|
+
}
|
|
433
|
+
else {
|
|
434
|
+
flatAgents.push(step.agent);
|
|
435
|
+
flatStepStart++;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
if (inheritedNestedRoute && nestedAddress) {
|
|
439
|
+
const now = Date.now();
|
|
440
|
+
try {
|
|
441
|
+
writeNestedEvent(inheritedNestedRoute, {
|
|
442
|
+
type: "subagent.nested.started",
|
|
443
|
+
ts: now,
|
|
444
|
+
parentRunId: nestedAddress.parentRunId,
|
|
445
|
+
parentStepIndex: nestedAddress.parentStepIndex,
|
|
446
|
+
child: {
|
|
447
|
+
id,
|
|
448
|
+
parentRunId: nestedAddress.parentRunId,
|
|
449
|
+
parentStepIndex: nestedAddress.parentStepIndex,
|
|
450
|
+
depth: nestedAddress.depth,
|
|
451
|
+
path: nestedAddress.path,
|
|
452
|
+
asyncDir,
|
|
453
|
+
pid: spawnResult.pid,
|
|
454
|
+
ownerIntercomTarget: process.env.PI_SUBAGENT_INTERCOM_SESSION_NAME,
|
|
455
|
+
leafIntercomTarget: childIntercomTargets?.[0],
|
|
456
|
+
intercomTarget: childIntercomTargets?.[0],
|
|
457
|
+
ownerState: "live",
|
|
458
|
+
mode: resultMode,
|
|
459
|
+
state: "running",
|
|
460
|
+
agent: firstAgents[0],
|
|
461
|
+
agents: flatAgents,
|
|
462
|
+
chainStepCount: chain.length,
|
|
463
|
+
parallelGroups,
|
|
464
|
+
startedAt: now,
|
|
465
|
+
lastUpdate: now,
|
|
466
|
+
},
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
catch (error) {
|
|
470
|
+
console.error("Failed to emit nested async start event:", error);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
ctx.pi.events.emit(SUBAGENT_ASYNC_STARTED_EVENT, {
|
|
474
|
+
id,
|
|
475
|
+
pid: spawnResult.pid,
|
|
476
|
+
sessionId: ctx.currentSessionId,
|
|
477
|
+
mode: resultMode,
|
|
478
|
+
agent: firstAgents[0],
|
|
479
|
+
agents: flatAgents,
|
|
480
|
+
task: isParallelStep(firstStep)
|
|
481
|
+
? firstStep.parallel[0]?.task?.slice(0, 50)
|
|
482
|
+
: isDynamicParallelStep(firstStep)
|
|
483
|
+
? firstStep.parallel.task?.slice(0, 50)
|
|
484
|
+
: firstStep.task?.slice(0, 50),
|
|
485
|
+
chain: chain.map((s) => isParallelStep(s) ? `[${s.parallel.map((t) => t.agent).join("+")}]` : isDynamicParallelStep(s) ? `expand:${s.parallel.agent}` : s.agent),
|
|
486
|
+
chainStepCount: chain.length,
|
|
487
|
+
parallelGroups,
|
|
488
|
+
workflowGraph,
|
|
489
|
+
cwd: runnerCwd,
|
|
490
|
+
asyncDir,
|
|
491
|
+
nestedRoute,
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
const chainDesc = chain
|
|
495
|
+
.map((s) => isParallelStep(s) ? `[${s.parallel.map((t) => t.agent).join("+")}]` : isDynamicParallelStep(s) ? `expand:${s.parallel.agent}` : s.agent)
|
|
496
|
+
.join(" -> ");
|
|
497
|
+
return {
|
|
498
|
+
content: [{ type: "text", text: formatAsyncStartedMessage(`Async ${resultMode}: ${chainDesc} [${id}]`) }],
|
|
499
|
+
details: { mode: resultMode, runId: id, results: [], asyncId: id, asyncDir, asyncPid: spawnResult.pid, workflowGraph },
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* Execute a single agent asynchronously
|
|
504
|
+
*/
|
|
505
|
+
export function executeAsyncSingle(id, params) {
|
|
506
|
+
const { agent, agentConfig, ctx, cwd, maxOutput, artifactsDir, shareEnabled, sessionRoot, sessionFile, maxSubagentDepth, worktreeSetupHook, worktreeSetupHookTimeoutMs, controlConfig, controlIntercomTarget, childIntercomTarget, nestedRoute, } = params;
|
|
507
|
+
const task = params.task ?? "";
|
|
508
|
+
const runnerCwd = resolveChildCwd(ctx.cwd, cwd);
|
|
509
|
+
const skillNames = params.skills === false ? [] : params.skills ?? agentConfig.skills ?? [];
|
|
510
|
+
const launchAgent = params.skills === false ? { ...agentConfig, inheritSkills: false } : agentConfig;
|
|
511
|
+
const availableModels = params.availableModels;
|
|
512
|
+
const { resolved: resolvedSkills, missing: missingSkills } = params.savedLaunch && params.skills === undefined
|
|
513
|
+
? { resolved: [], missing: [] }
|
|
514
|
+
: resolveSkillsWithFallback(skillNames, runnerCwd, ctx.cwd, { projectTrusted: ctx.projectTrusted ?? true });
|
|
515
|
+
if (missingSkills.includes("pi-subagents"))
|
|
516
|
+
return formatAsyncStartError("single", UNAVAILABLE_SUBAGENT_SKILL_ERROR);
|
|
517
|
+
let systemPrompt = params.savedLaunch && params.skills === undefined ? params.savedLaunch.systemPrompt : agentConfig.systemPrompt?.trim() ?? "";
|
|
518
|
+
if (resolvedSkills.length > 0) {
|
|
519
|
+
const injection = buildSkillInjection(resolvedSkills);
|
|
520
|
+
systemPrompt = systemPrompt ? `${systemPrompt}\n\n${injection}` : injection;
|
|
521
|
+
}
|
|
522
|
+
const inheritedNestedRoute = resolveInheritedNestedRouteFromEnv();
|
|
523
|
+
const nestedAddress = inheritedNestedRoute ? resolveNestedParentAddressFromEnv() : undefined;
|
|
524
|
+
const asyncDir = getRunMetadataDir(id);
|
|
525
|
+
try {
|
|
526
|
+
fs.mkdirSync(asyncDir, { recursive: true });
|
|
527
|
+
}
|
|
528
|
+
catch (error) {
|
|
529
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
530
|
+
return {
|
|
531
|
+
content: [{ type: "text", text: `Failed to create async run directory '${asyncDir}': ${message}` }],
|
|
532
|
+
isError: true,
|
|
533
|
+
details: { mode: "single", results: [] },
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
const outputUsesAgentDefault = usesAgentDefaultOutput(params.output) || params.outputFromAgentDefault === true;
|
|
537
|
+
const agentDefaultOutput = params.generatedOutputFilename ?? agentConfig.output;
|
|
538
|
+
const effectiveOutput = resolveAsyncOutput({
|
|
539
|
+
requestedOutput: params.output,
|
|
540
|
+
agentDefaultOutput,
|
|
541
|
+
artifactsDir,
|
|
542
|
+
asyncDir,
|
|
543
|
+
runId: id,
|
|
544
|
+
agent,
|
|
545
|
+
index: 0,
|
|
546
|
+
});
|
|
547
|
+
const outputPath = resolveSingleOutputPath(effectiveOutput, ctx.cwd, runnerCwd);
|
|
548
|
+
const outputMode = params.outputMode ?? "inline";
|
|
549
|
+
const validationError = validateFileOnlyOutputMode(outputMode, outputPath, `Async single run (${agent})`);
|
|
550
|
+
if (validationError)
|
|
551
|
+
return formatAsyncStartError("single", validationError);
|
|
552
|
+
let taskWithOutputInstruction = task;
|
|
553
|
+
if (params.progress) {
|
|
554
|
+
writeInitialProgressFile(runnerCwd);
|
|
555
|
+
taskWithOutputInstruction += buildChainInstructions({ output: false, outputMode: "inline", reads: false, progress: true, skills: false }, runnerCwd, true).suffix;
|
|
556
|
+
}
|
|
557
|
+
taskWithOutputInstruction = injectSingleOutputInstruction(taskWithOutputInstruction, outputPath);
|
|
558
|
+
let spawnResult = {};
|
|
559
|
+
try {
|
|
560
|
+
spawnResult = spawnRunner({
|
|
561
|
+
id,
|
|
562
|
+
steps: [
|
|
563
|
+
withSavedLaunch({
|
|
564
|
+
agent,
|
|
565
|
+
task: taskWithOutputInstruction,
|
|
566
|
+
cwd: runnerCwd,
|
|
567
|
+
...resolveLaunchModel(agentConfig, params.modelOverride, availableModels, ctx.currentModelProvider, params.savedLaunch),
|
|
568
|
+
tools: agentConfig.tools,
|
|
569
|
+
allowSubagents: agentConfig.allowSubagents,
|
|
570
|
+
extensions: agentConfig.extensions,
|
|
571
|
+
mcpDirectTools: agentConfig.mcpDirectTools,
|
|
572
|
+
completionGuard: agentConfig.completionGuard,
|
|
573
|
+
systemPrompt,
|
|
574
|
+
systemPromptMode: agentConfig.systemPromptMode,
|
|
575
|
+
inheritProjectContext: agentConfig.inheritProjectContext,
|
|
576
|
+
inheritSkills: launchAgent.inheritSkills,
|
|
577
|
+
skills: params.savedLaunch && params.skills === undefined ? params.savedLaunch.skills : resolvedSkills.map((r) => r.name),
|
|
578
|
+
outputPath,
|
|
579
|
+
outputMode,
|
|
580
|
+
...(outputUsesAgentDefault && outputPath && typeof agentDefaultOutput === "string" && !path.isAbsolute(agentDefaultOutput) ? { outputPathFromAgentDefault: true } : {}),
|
|
581
|
+
...(params.outputSchema ? { structuredOutputSchema: params.outputSchema } : {}),
|
|
582
|
+
...(params.outputSchema ? { structuredOutput: createStructuredOutputRuntime(params.outputSchema, path.join(asyncDir, "structured-output")) } : {}),
|
|
583
|
+
sessionFile,
|
|
584
|
+
maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, agentConfig.maxSubagentDepth),
|
|
585
|
+
maxExecutionTimeMs: agentConfig.maxExecutionTimeMs,
|
|
586
|
+
maxTokens: agentConfig.maxTokens,
|
|
587
|
+
effectiveAcceptance: resolveEffectiveAcceptance({ explicit: params.acceptance }),
|
|
588
|
+
}, launchAgent, params, params.generatedOutputFilename),
|
|
589
|
+
],
|
|
590
|
+
resultPath: inheritedNestedRoute ? nestedResultsPath(inheritedNestedRoute.rootRunId, id) : path.join(RESULTS_DIR, `${id}.json`),
|
|
591
|
+
cwd: runnerCwd,
|
|
592
|
+
placeholder: "{previous}",
|
|
593
|
+
maxOutput,
|
|
594
|
+
timeoutMs: params.timeoutMs,
|
|
595
|
+
artifactsDir,
|
|
596
|
+
share: shareEnabled,
|
|
597
|
+
sessionDir: sessionRoot ? path.join(sessionRoot, `async-${id}`) : undefined,
|
|
598
|
+
asyncDir,
|
|
599
|
+
sessionId: ctx.currentSessionId,
|
|
600
|
+
rootSessionId: ctx.rootSessionId,
|
|
601
|
+
piPackageRoot,
|
|
602
|
+
worktreeSetupHook,
|
|
603
|
+
worktreeSetupHookTimeoutMs,
|
|
604
|
+
controlConfig,
|
|
605
|
+
controlIntercomTarget,
|
|
606
|
+
childIntercomTargets: childIntercomTarget ? [childIntercomTarget(agent, 0)] : undefined,
|
|
607
|
+
resultMode: "single",
|
|
608
|
+
nestedRoute: nestedRoute ?? inheritedNestedRoute,
|
|
609
|
+
nestedSelf: inheritedNestedRoute && nestedAddress ? {
|
|
610
|
+
parentRunId: nestedAddress.parentRunId,
|
|
611
|
+
parentStepIndex: nestedAddress.parentStepIndex,
|
|
612
|
+
depth: nestedAddress.depth,
|
|
613
|
+
path: nestedAddress.path,
|
|
614
|
+
} : undefined,
|
|
615
|
+
projectTrust: params.projectTrust,
|
|
616
|
+
}, runnerCwd, asyncDir);
|
|
617
|
+
}
|
|
618
|
+
catch (error) {
|
|
619
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
620
|
+
return formatAsyncStartError("single", `Failed to start async run '${id}': ${message}`);
|
|
621
|
+
}
|
|
622
|
+
if (spawnResult.error) {
|
|
623
|
+
return formatAsyncStartError("single", `Failed to start async run '${id}': ${spawnResult.error}`);
|
|
624
|
+
}
|
|
625
|
+
if (spawnResult.pid) {
|
|
626
|
+
if (inheritedNestedRoute && nestedAddress) {
|
|
627
|
+
const now = Date.now();
|
|
628
|
+
try {
|
|
629
|
+
writeNestedEvent(inheritedNestedRoute, {
|
|
630
|
+
type: "subagent.nested.started",
|
|
631
|
+
ts: now,
|
|
632
|
+
parentRunId: nestedAddress.parentRunId,
|
|
633
|
+
parentStepIndex: nestedAddress.parentStepIndex,
|
|
634
|
+
child: {
|
|
635
|
+
id,
|
|
636
|
+
parentRunId: nestedAddress.parentRunId,
|
|
637
|
+
parentStepIndex: nestedAddress.parentStepIndex,
|
|
638
|
+
depth: nestedAddress.depth,
|
|
639
|
+
path: nestedAddress.path,
|
|
640
|
+
asyncDir,
|
|
641
|
+
pid: spawnResult.pid,
|
|
642
|
+
ownerIntercomTarget: process.env.PI_SUBAGENT_INTERCOM_SESSION_NAME,
|
|
643
|
+
leafIntercomTarget: childIntercomTarget?.(agent, 0),
|
|
644
|
+
intercomTarget: childIntercomTarget?.(agent, 0),
|
|
645
|
+
ownerState: "live",
|
|
646
|
+
mode: "single",
|
|
647
|
+
state: "running",
|
|
648
|
+
agent,
|
|
649
|
+
agents: [agent],
|
|
650
|
+
chainStepCount: 1,
|
|
651
|
+
startedAt: now,
|
|
652
|
+
lastUpdate: now,
|
|
653
|
+
},
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
catch (error) {
|
|
657
|
+
console.error("Failed to emit nested async start event:", error);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
ctx.pi.events.emit(SUBAGENT_ASYNC_STARTED_EVENT, {
|
|
661
|
+
id,
|
|
662
|
+
pid: spawnResult.pid,
|
|
663
|
+
sessionId: ctx.currentSessionId,
|
|
664
|
+
mode: "single",
|
|
665
|
+
agent,
|
|
666
|
+
task: task?.slice(0, 50),
|
|
667
|
+
cwd: runnerCwd,
|
|
668
|
+
asyncDir,
|
|
669
|
+
nestedRoute,
|
|
670
|
+
});
|
|
671
|
+
}
|
|
672
|
+
return {
|
|
673
|
+
content: [{ type: "text", text: formatAsyncStartedMessage(`Async: ${agent} [${id}]`) }],
|
|
674
|
+
details: { mode: "single", runId: id, results: [], asyncId: id, asyncDir, asyncPid: spawnResult.pid },
|
|
675
|
+
};
|
|
676
|
+
}
|