@fitchmultz/pi-subagents 0.0.0-stage → 0.44.4
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 +1645 -0
- package/LICENSE +21 -0
- package/README.md +1529 -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 +194 -0
- package/dist/history/ingest.js +447 -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 +461 -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/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 +77 -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 +139 -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 +103 -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 +320 -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.md +579 -0
- package/docs/performance.md +121 -0
- package/package.json +101 -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/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 +205 -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 +152 -0
- package/src/history/ingest.ts +332 -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 +317 -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/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 +70 -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 +121 -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 +93 -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 +372 -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 +1259 -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,501 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { resolveExecutionAgentScope } from "../../agents/agent-scope.ts";
|
|
6
|
+
import { handleManagementAction } from "../../agents/agent-management.ts";
|
|
7
|
+
import { buildDoctorReport } from "../../extension/doctor.ts";
|
|
8
|
+
import { providerQualifiedModelId, toModelInfo, type ModelInfo } from "../../shared/model-info.ts";
|
|
9
|
+
import { resolveModelCandidate } from "../shared/model-fallback.ts";
|
|
10
|
+
import { getArtifactsDir } from "../../shared/artifacts.ts";
|
|
11
|
+
import {
|
|
12
|
+
collectInvocationAgentNames,
|
|
13
|
+
isParallelStep,
|
|
14
|
+
isDynamicParallelStep,
|
|
15
|
+
} from "../../shared/settings.ts";
|
|
16
|
+
import {
|
|
17
|
+
buildFlatAgentNameResolver,
|
|
18
|
+
createPerAgentForkContextResolver,
|
|
19
|
+
invocationUsesForkContext,
|
|
20
|
+
resolveAgentContext,
|
|
21
|
+
validateForkContextModelPolicy,
|
|
22
|
+
} from "../../shared/agent-context-policy.ts";
|
|
23
|
+
import { resolveCurrentSessionId } from "../../shared/session-identity.ts";
|
|
24
|
+
import { resolveExecutionCwd } from "../../shared/execution-cwd.ts";
|
|
25
|
+
import { resolveIntercomBridge, resolveIntercomSessionTarget, resolveOrchestratorIntercomTarget } from "../../intercom/intercom-bridge.ts";
|
|
26
|
+
import { resolveControlConfig } from "../shared/subagent-control.ts";
|
|
27
|
+
import { createNestedRoute, resolveInheritedNestedRouteFromEnv } from "../shared/nested-events.ts";
|
|
28
|
+
import { resolveSubagentRunId, type ResolvedSubagentRunId } from "../background/run-id-resolver.ts";
|
|
29
|
+
import { inspectSubagentStatus } from "../background/run-status.ts";
|
|
30
|
+
import { applyForceTopLevelAsyncOverride } from "../background/top-level-async.ts";
|
|
31
|
+
import { queryLiveIntercomHealth, queryLiveIntercomStatus } from "../../intercom/live-intercom.ts";
|
|
32
|
+
import { saveQuestionOwner } from "../shared/supervisor-questions.ts";
|
|
33
|
+
import { buildWorkflowGraphSnapshot, workflowAgentNodes } from "../shared/workflow-graph.ts";
|
|
34
|
+
import { ownedRunList, ownedRunStatusResult, ownedRunView, rememberOwnedRun, resolveOwnedRun, workflowChildren } from "../shared/run-records.ts";
|
|
35
|
+
import { ownedHistoryQuery } from "../shared/run-history-queries.ts";
|
|
36
|
+
import { cancelSupervisorInput, controlSupervisorQuestion, projectSupervisorQuestions } from "./question-control.ts";
|
|
37
|
+
import {
|
|
38
|
+
type AgentScope,
|
|
39
|
+
} from "../../agents/agents.ts";
|
|
40
|
+
import {
|
|
41
|
+
type SubagentExecutionResult,
|
|
42
|
+
SUBAGENT_ACTIONS,
|
|
43
|
+
checkSubagentDepth,
|
|
44
|
+
} from "../../shared/types.ts";
|
|
45
|
+
import {
|
|
46
|
+
type ExecutionContextData,
|
|
47
|
+
type ExecutorDeps,
|
|
48
|
+
type SubagentParamsLike,
|
|
49
|
+
resolveAsyncExecutionMode,
|
|
50
|
+
} from "./subagent-params.ts";
|
|
51
|
+
import {
|
|
52
|
+
MUTATING_MANAGEMENT_ACTIONS,
|
|
53
|
+
extendAsyncTimeoutResult,
|
|
54
|
+
interruptAsyncRun,
|
|
55
|
+
interruptNestedRun,
|
|
56
|
+
nestedResolutionScopeForExecutor,
|
|
57
|
+
nudgeSubagentRun,
|
|
58
|
+
rememberedForegroundStatusResult,
|
|
59
|
+
resolveRememberedForegroundRun,
|
|
60
|
+
resolveRequestedCwd,
|
|
61
|
+
resumeAsyncRun,
|
|
62
|
+
} from "./foreground-control.ts";
|
|
63
|
+
import {
|
|
64
|
+
buildRequestedModeError,
|
|
65
|
+
normalizeRepeatedParallelCounts,
|
|
66
|
+
normalizeRoleForegroundTimeout,
|
|
67
|
+
resolveForegroundTimeoutMs,
|
|
68
|
+
toExecutionErrorResult,
|
|
69
|
+
validateExecutionInput,
|
|
70
|
+
withForkContext,
|
|
71
|
+
} from "./execution-input.ts";
|
|
72
|
+
import { runAsyncPath } from "./run-async-path.ts";
|
|
73
|
+
import { clarifyInvocation } from "./clarify-invocation.ts";
|
|
74
|
+
import { waitForOwnedRun } from "./wait-run.ts";
|
|
75
|
+
|
|
76
|
+
export type { SubagentParamsLike } from "./subagent-params.ts";
|
|
77
|
+
export { normalizeSubagentParamsLike, resolveAsyncExecutionMode } from "./subagent-params.ts";
|
|
78
|
+
export { writeAsyncInterruptRequest } from "./foreground-control.ts";
|
|
79
|
+
|
|
80
|
+
type ExecuteSubagent = (id: string, params: SubagentParamsLike, signal: AbortSignal | undefined,
|
|
81
|
+
onUpdate: ((r: SubagentExecutionResult) => void) | undefined, ctx: ExtensionContext, executionCwd?: string) => Promise<SubagentExecutionResult>;
|
|
82
|
+
|
|
83
|
+
export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
84
|
+
execute: ExecuteSubagent;
|
|
85
|
+
} {
|
|
86
|
+
const execute = async (
|
|
87
|
+
_id: string,
|
|
88
|
+
params: SubagentParamsLike,
|
|
89
|
+
signal: AbortSignal | undefined,
|
|
90
|
+
onUpdate: ((r: SubagentExecutionResult) => void) | undefined,
|
|
91
|
+
ctx: ExtensionContext,
|
|
92
|
+
executionCwd?: string,
|
|
93
|
+
): Promise<SubagentExecutionResult> => {
|
|
94
|
+
const needsExecutionCwd = !params.action || params.cwd !== undefined || ["list", "get", "create", "update", "delete", "doctor"].includes(params.action);
|
|
95
|
+
const invocationCwd = needsExecutionCwd ? executionCwd ?? resolveExecutionCwd(deps.pi, ctx) : ctx.cwd;
|
|
96
|
+
await deps.ensureSessionState?.(ctx);
|
|
97
|
+
if (needsExecutionCwd) deps.state.baseCwd = invocationCwd;
|
|
98
|
+
deps.state.foregroundRuns ??= new Map();
|
|
99
|
+
const requestCwd = resolveRequestedCwd(invocationCwd, params.cwd);
|
|
100
|
+
const paramsWithResolvedCwd = params.cwd === undefined ? params : { ...params, cwd: requestCwd };
|
|
101
|
+
if (params.action) {
|
|
102
|
+
if (params.action === "review") {
|
|
103
|
+
try {
|
|
104
|
+
if (!(params.id ?? params.runId) || (params.decision !== "accepted" && params.decision !== "needs_changes")) throw new Error("action='review' requires id and decision ('accepted' or 'needs_changes').");
|
|
105
|
+
const run = resolveOwnedRun(deps.state, (params.id ?? params.runId)!);
|
|
106
|
+
if (!run) throw new Error("Run not found in this parent session.");
|
|
107
|
+
if (ownedRunView(run, deps.state).state === "live") throw new Error("The run is still live. Use nudge for guidance, or stop it before reviewing its result.");
|
|
108
|
+
const reviewed = { ...run, review: { decision: params.decision, ...(params.message ? { message: params.message } : {}), reviewedAt: Date.now() } };
|
|
109
|
+
rememberOwnedRun(deps.state, reviewed);
|
|
110
|
+
const result = ownedRunStatusResult(reviewed, deps.state, undefined, { childSafe: Boolean(nestedResolutionScopeForExecutor(deps)) });
|
|
111
|
+
return { ...result, content: [{ type: "text", text: `Saved parent review for ${run.runId}: ${params.decision}.\nThe review note is parent-only and was not sent to the child. Put actionable instructions in ${deps.allowMutatingManagementActions === false && deps.config.compactChildTools === false ? "subagent resume/nudge" : "agent_runs continue/nudge"}. No work started.` }] };
|
|
112
|
+
} catch (error) {
|
|
113
|
+
return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "management", results: [] } };
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (params.action === "history" || params.action === "search") {
|
|
117
|
+
try { return await ownedHistoryQuery(deps.state, params, signal); }
|
|
118
|
+
catch (error) {
|
|
119
|
+
return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "management", results: [] } };
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if (params.action === "questions" || params.action === "answer") {
|
|
123
|
+
return controlSupervisorQuestion({ params: paramsWithResolvedCwd, requestCwd, ctx, deps });
|
|
124
|
+
}
|
|
125
|
+
if (params.action === "doctor") {
|
|
126
|
+
let currentSessionFile: string | null = null;
|
|
127
|
+
let currentSessionId = deps.state.currentSessionId;
|
|
128
|
+
let sessionError: string | undefined;
|
|
129
|
+
try {
|
|
130
|
+
currentSessionFile = ctx.sessionManager.getSessionFile() ?? null;
|
|
131
|
+
currentSessionId = ctx.sessionManager.getSessionId();
|
|
132
|
+
} catch (error) {
|
|
133
|
+
sessionError = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
134
|
+
}
|
|
135
|
+
let orchestratorTarget: string | undefined;
|
|
136
|
+
try {
|
|
137
|
+
const fallbackTarget = resolveIntercomSessionTarget(deps.pi.getSessionName(), ctx.sessionManager.getSessionId());
|
|
138
|
+
orchestratorTarget = resolveOrchestratorIntercomTarget(deps.pi.events, fallbackTarget);
|
|
139
|
+
} catch {}
|
|
140
|
+
const { connection } = await queryLiveIntercomStatus(deps.pi.events);
|
|
141
|
+
return {
|
|
142
|
+
content: [{
|
|
143
|
+
type: "text",
|
|
144
|
+
text: buildDoctorReport({
|
|
145
|
+
cwd: requestCwd,
|
|
146
|
+
nativeSessionCwd: ctx.cwd,
|
|
147
|
+
config: deps.config,
|
|
148
|
+
state: deps.state,
|
|
149
|
+
requestedSessionDir: paramsWithResolvedCwd.sessionDir,
|
|
150
|
+
currentSessionFile,
|
|
151
|
+
currentSessionId,
|
|
152
|
+
orchestratorTarget,
|
|
153
|
+
connection,
|
|
154
|
+
sessionError,
|
|
155
|
+
projectTrusted: ctx.isProjectTrusted(),
|
|
156
|
+
expandTilde: deps.expandTilde,
|
|
157
|
+
}),
|
|
158
|
+
}],
|
|
159
|
+
details: { mode: "management", results: [] },
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
if (params.action === "status") {
|
|
163
|
+
const targetRunId = paramsWithResolvedCwd.id ?? paramsWithResolvedCwd.runId;
|
|
164
|
+
if (!targetRunId && !params.dir && deps.state.ownedRuns && deps.allowMutatingManagementActions !== false) {
|
|
165
|
+
try { return await ownedRunList(deps.state, { ...params, signal }); } catch (error) {
|
|
166
|
+
return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "management", results: [] } };
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
let includeRunHeader = true;
|
|
170
|
+
if (targetRunId) {
|
|
171
|
+
try {
|
|
172
|
+
includeRunHeader = Boolean(params.dir) || !resolveOwnedRun(deps.state, targetRunId);
|
|
173
|
+
} catch (error) {
|
|
174
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
175
|
+
return { content: [{ type: "text", text: message }], isError: true, details: { mode: "management", results: [] } };
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
let inspected = inspectSubagentStatus({ ...paramsWithResolvedCwd, action: "status" }, { state: deps.state, nested: nestedResolutionScopeForExecutor(deps), includeRunHeader });
|
|
179
|
+
const targets = inspected.details.intercomTargets ?? [];
|
|
180
|
+
if (!inspected.isError && targets.length) {
|
|
181
|
+
const intercomHealth = await queryLiveIntercomHealth(deps.pi.events, targets);
|
|
182
|
+
if (intercomHealth.size) inspected = inspectSubagentStatus({ ...paramsWithResolvedCwd, action: "status" }, { state: deps.state, nested: nestedResolutionScopeForExecutor(deps), intercomHealth, includeRunHeader });
|
|
183
|
+
}
|
|
184
|
+
if (targetRunId && inspected.isError && inspected.content[0]?.type === "text" && inspected.content[0].text.startsWith("Async run not found.")) {
|
|
185
|
+
try {
|
|
186
|
+
const remembered = resolveRememberedForegroundRun(targetRunId, deps.state);
|
|
187
|
+
if (remembered) return rememberedForegroundStatusResult(remembered, Boolean(nestedResolutionScopeForExecutor(deps)));
|
|
188
|
+
} catch (error) {
|
|
189
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
190
|
+
return { content: [{ type: "text", text: message }], isError: true, details: { mode: "management", results: [] } };
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
if (!targetRunId && !params.dir && deps.allowMutatingManagementActions !== false) {
|
|
194
|
+
const foreground = [...(deps.state.foregroundRuns?.values() ?? [])]
|
|
195
|
+
.sort((a, b) => b.updatedAt - a.updatedAt)
|
|
196
|
+
.map((run) => rememberedForegroundStatusResult(run));
|
|
197
|
+
if (foreground.length) {
|
|
198
|
+
inspected = {
|
|
199
|
+
...inspected,
|
|
200
|
+
content: [...foreground.flatMap((result) => result.content), ...inspected.content],
|
|
201
|
+
details: {
|
|
202
|
+
...inspected.details,
|
|
203
|
+
managementControls: [...foreground.flatMap((result) => result.details.managementControl ? [result.details.managementControl] : []), ...(inspected.details.managementControls ?? [])],
|
|
204
|
+
},
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return inspected;
|
|
209
|
+
}
|
|
210
|
+
if (params.action === "nudge") {
|
|
211
|
+
return nudgeSubagentRun({ params: paramsWithResolvedCwd, deps, ctx });
|
|
212
|
+
}
|
|
213
|
+
if (params.action === "resume") {
|
|
214
|
+
return resumeAsyncRun({ params: paramsWithResolvedCwd, requestCwd, ctx, deps });
|
|
215
|
+
}
|
|
216
|
+
if (params.action === "extend") {
|
|
217
|
+
const targetRunId = paramsWithResolvedCwd.runId ?? paramsWithResolvedCwd.id;
|
|
218
|
+
let resolved: ResolvedSubagentRunId | undefined;
|
|
219
|
+
if (targetRunId) {
|
|
220
|
+
try {
|
|
221
|
+
resolved = resolveSubagentRunId(targetRunId, { state: deps.state, nested: nestedResolutionScopeForExecutor(deps) });
|
|
222
|
+
} catch (error) {
|
|
223
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
224
|
+
return { content: [{ type: "text", text: message }], isError: true, details: { mode: "management", results: [] } };
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return extendAsyncTimeoutResult(deps.state, resolved?.id ?? targetRunId, paramsWithResolvedCwd.extendMs ?? paramsWithResolvedCwd.timeoutMs ?? paramsWithResolvedCwd.maxRuntimeMs ?? 0);
|
|
228
|
+
}
|
|
229
|
+
if (params.action === "interrupt") {
|
|
230
|
+
const targetRunId = paramsWithResolvedCwd.runId ?? paramsWithResolvedCwd.id;
|
|
231
|
+
let resolved: ResolvedSubagentRunId | undefined;
|
|
232
|
+
if (targetRunId) {
|
|
233
|
+
try {
|
|
234
|
+
resolved = resolveSubagentRunId(targetRunId, { state: deps.state, nested: nestedResolutionScopeForExecutor(deps) });
|
|
235
|
+
} catch (error) {
|
|
236
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
237
|
+
return { content: [{ type: "text", text: message }], isError: true, details: { mode: "management", results: [] } };
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
if (resolved?.kind === "nested") return interruptNestedRun(resolved, paramsWithResolvedCwd.index);
|
|
241
|
+
const asyncInterruptResult = interruptAsyncRun(deps.state, resolved?.kind === "async" ? resolved.id : targetRunId, paramsWithResolvedCwd.index);
|
|
242
|
+
if (asyncInterruptResult) return asyncInterruptResult;
|
|
243
|
+
return {
|
|
244
|
+
content: [{ type: "text", text: "No interrupt-capable run found in this session." }],
|
|
245
|
+
isError: true,
|
|
246
|
+
details: { mode: "management", results: [] },
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
if (!(SUBAGENT_ACTIONS as readonly string[]).includes(params.action)) {
|
|
250
|
+
return {
|
|
251
|
+
content: [{ type: "text", text: `Unknown action: ${params.action}. Valid: ${SUBAGENT_ACTIONS.join(", ")}` }],
|
|
252
|
+
isError: true,
|
|
253
|
+
details: { mode: "management" as const, results: [] },
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
if (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(params.action)) {
|
|
257
|
+
return {
|
|
258
|
+
content: [{ type: "text", text: `Action '${params.action}' is not available from child-safe subagent fanout mode.` }],
|
|
259
|
+
isError: true,
|
|
260
|
+
details: { mode: "management" as const, results: [] },
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
return handleManagementAction(params.action, paramsWithResolvedCwd, { ...ctx, cwd: requestCwd });
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const { blocked, depth, maxDepth } = checkSubagentDepth(deps.config.maxSubagentDepth);
|
|
267
|
+
if (blocked) {
|
|
268
|
+
return {
|
|
269
|
+
content: [
|
|
270
|
+
{
|
|
271
|
+
type: "text",
|
|
272
|
+
text:
|
|
273
|
+
`Nested subagent call blocked (depth=${depth}, max=${maxDepth}). ` +
|
|
274
|
+
"You are running at the maximum subagent nesting depth. " +
|
|
275
|
+
"Complete your current task directly without delegating to further subagents.",
|
|
276
|
+
},
|
|
277
|
+
],
|
|
278
|
+
isError: true,
|
|
279
|
+
details: { mode: "single" as const, results: [] },
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const normalized = normalizeRepeatedParallelCounts(paramsWithResolvedCwd);
|
|
284
|
+
if (normalized.error) return normalized.error;
|
|
285
|
+
const normalizedParams = normalized.params!;
|
|
286
|
+
|
|
287
|
+
let effectiveParams = applyForceTopLevelAsyncOverride(
|
|
288
|
+
normalizedParams,
|
|
289
|
+
depth,
|
|
290
|
+
deps.config.forceTopLevelAsync === true,
|
|
291
|
+
);
|
|
292
|
+
|
|
293
|
+
const scope: AgentScope = resolveExecutionAgentScope(effectiveParams.agentScope);
|
|
294
|
+
const effectiveCwd = effectiveParams.cwd ?? invocationCwd;
|
|
295
|
+
const parentSessionFile = ctx.sessionManager.getSessionFile() ?? null;
|
|
296
|
+
deps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
|
|
297
|
+
const inheritedModel = providerQualifiedModelId(ctx.model?.provider, ctx.model?.id);
|
|
298
|
+
const discoveredAgents = deps.discoverAgents(effectiveCwd, scope, { projectTrusted: ctx.isProjectTrusted() }).agents
|
|
299
|
+
.map((agent) => agent.model || !inheritedModel ? agent : { ...agent, model: inheritedModel });
|
|
300
|
+
const invocationAgentNames = collectInvocationAgentNames(effectiveParams);
|
|
301
|
+
const invocationContext: SubagentParamsLike["context"] = invocationUsesForkContext(
|
|
302
|
+
effectiveParams.context,
|
|
303
|
+
invocationAgentNames,
|
|
304
|
+
discoveredAgents,
|
|
305
|
+
)
|
|
306
|
+
? "fork"
|
|
307
|
+
: undefined;
|
|
308
|
+
const fallbackTarget = resolveIntercomSessionTarget(deps.pi.getSessionName(), ctx.sessionManager.getSessionId());
|
|
309
|
+
const orchestratorTarget = resolveOrchestratorIntercomTarget(deps.pi.events, fallbackTarget);
|
|
310
|
+
const intercomBridge = resolveIntercomBridge(orchestratorTarget);
|
|
311
|
+
const runId = randomUUID();
|
|
312
|
+
const agentNameAtIndex = buildFlatAgentNameResolver(effectiveParams);
|
|
313
|
+
const resolveContextForAgent = (agentName: string | undefined) =>
|
|
314
|
+
resolveAgentContext(effectiveParams.context, agentName, discoveredAgents);
|
|
315
|
+
const resolveContextForIndex = (index?: number) =>
|
|
316
|
+
resolveContextForAgent(agentNameAtIndex(index ?? 0));
|
|
317
|
+
const agents = discoveredAgents.map((agent) => ({ ...agent, defaultContext: resolveContextForAgent(agent.name) }));
|
|
318
|
+
const inheritedNestedRoute = resolveInheritedNestedRouteFromEnv();
|
|
319
|
+
const nestedRoute = inheritedNestedRoute ?? createNestedRoute(runId);
|
|
320
|
+
const shareEnabled = effectiveParams.share === true;
|
|
321
|
+
const hasChain = (effectiveParams.chain?.length ?? 0) > 0;
|
|
322
|
+
const hasTasks = (effectiveParams.tasks?.length ?? 0) > 0;
|
|
323
|
+
const hasSingle = !hasChain && !hasTasks && Boolean(effectiveParams.agent);
|
|
324
|
+
const allowClarifyTaskPrompt = hasChain
|
|
325
|
+
&& effectiveParams.clarify === true
|
|
326
|
+
&& ctx.hasUI
|
|
327
|
+
&& !(effectiveParams.chain?.some(isParallelStep) ?? false);
|
|
328
|
+
|
|
329
|
+
const validationError = validateExecutionInput(
|
|
330
|
+
effectiveParams,
|
|
331
|
+
agents,
|
|
332
|
+
hasChain,
|
|
333
|
+
hasTasks,
|
|
334
|
+
hasSingle,
|
|
335
|
+
allowClarifyTaskPrompt,
|
|
336
|
+
);
|
|
337
|
+
if (validationError) return validationError;
|
|
338
|
+
if (invocationContext === "fork") {
|
|
339
|
+
let availableModels: ModelInfo[];
|
|
340
|
+
try {
|
|
341
|
+
availableModels = ctx.modelRegistry.getAvailable().map(toModelInfo);
|
|
342
|
+
} catch (error) {
|
|
343
|
+
return toExecutionErrorResult(effectiveParams, error, invocationContext);
|
|
344
|
+
}
|
|
345
|
+
const forkModelPolicyError = validateForkContextModelPolicy(
|
|
346
|
+
effectiveParams,
|
|
347
|
+
discoveredAgents,
|
|
348
|
+
(model) => resolveModelCandidate(model, availableModels, ctx.model?.provider),
|
|
349
|
+
);
|
|
350
|
+
if (forkModelPolicyError) {
|
|
351
|
+
return toExecutionErrorResult(effectiveParams, new Error(forkModelPolicyError), invocationContext);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
try {
|
|
356
|
+
const clarified = await clarifyInvocation({ params: effectiveParams, agents, ctx, cwd: effectiveCwd, runId });
|
|
357
|
+
if (!clarified) return { content: [{ type: "text", text: "Cancelled" }], details: { mode: hasChain ? "chain" : hasTasks ? "parallel" : "single", results: [] } };
|
|
358
|
+
effectiveParams = clarified;
|
|
359
|
+
} catch (error) {
|
|
360
|
+
return toExecutionErrorResult(effectiveParams, error, invocationContext);
|
|
361
|
+
}
|
|
362
|
+
if (signal?.aborted) return toExecutionErrorResult(effectiveParams, new Error("Subagent cancelled before launch."), invocationContext);
|
|
363
|
+
|
|
364
|
+
let sessionFileForIndex: (idx?: number) => string | undefined = () => undefined;
|
|
365
|
+
let forkSessionFileForAgentIndex: (agentName: string | undefined, idx?: number) => string | undefined = () => undefined;
|
|
366
|
+
try {
|
|
367
|
+
const forkContextResolver = createPerAgentForkContextResolver(ctx.sessionManager, resolveContextForIndex, {
|
|
368
|
+
resolveContextForAgentIndex: (agentName) => resolveContextForAgent(agentName),
|
|
369
|
+
});
|
|
370
|
+
sessionFileForIndex = forkContextResolver.sessionFileForIndex;
|
|
371
|
+
forkSessionFileForAgentIndex = forkContextResolver.sessionFileForAgentIndex;
|
|
372
|
+
} catch (error) {
|
|
373
|
+
return toExecutionErrorResult(effectiveParams, error, invocationContext);
|
|
374
|
+
}
|
|
375
|
+
const asyncMode = resolveAsyncExecutionMode(effectiveParams, deps.asyncByDefault);
|
|
376
|
+
const backgroundRequestedWhileClarifying = (hasChain || hasTasks) && asyncMode.backgroundRequestedWhileClarifying;
|
|
377
|
+
const effectiveAsync = asyncMode.effectiveAsync;
|
|
378
|
+
const foregroundTimeout = resolveForegroundTimeoutMs(effectiveParams);
|
|
379
|
+
if (foregroundTimeout.error) return buildRequestedModeError(effectiveParams, foregroundTimeout.error);
|
|
380
|
+
if (effectiveAsync && foregroundTimeout.timeoutMs !== undefined) {
|
|
381
|
+
return buildRequestedModeError(effectiveParams, "timeoutMs/maxRuntimeMs only applies to foreground subagent runs. Set async:false or use action:'interrupt' for background runs.");
|
|
382
|
+
}
|
|
383
|
+
if (!effectiveAsync) foregroundTimeout.timeoutMs = normalizeRoleForegroundTimeout(effectiveParams, foregroundTimeout.timeoutMs);
|
|
384
|
+
const controlConfig = resolveControlConfig(deps.config.control, effectiveParams.control);
|
|
385
|
+
|
|
386
|
+
const artifactsEnabled = effectiveParams.artifacts !== false;
|
|
387
|
+
const artifactsDir = effectiveAsync ? deps.tempArtifactsDir : getArtifactsDir(parentSessionFile);
|
|
388
|
+
|
|
389
|
+
let sessionRoot: string;
|
|
390
|
+
if (effectiveParams.sessionDir) {
|
|
391
|
+
sessionRoot = path.resolve(deps.expandTilde(effectiveParams.sessionDir));
|
|
392
|
+
} else {
|
|
393
|
+
const baseSessionRoot = deps.config.defaultSessionDir
|
|
394
|
+
? path.resolve(deps.expandTilde(deps.config.defaultSessionDir))
|
|
395
|
+
: deps.getSubagentSessionRoot(parentSessionFile);
|
|
396
|
+
sessionRoot = path.join(baseSessionRoot, runId);
|
|
397
|
+
}
|
|
398
|
+
try {
|
|
399
|
+
fs.mkdirSync(sessionRoot, { recursive: true });
|
|
400
|
+
} catch (error) {
|
|
401
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
402
|
+
return toExecutionErrorResult(
|
|
403
|
+
effectiveParams,
|
|
404
|
+
new Error(`Failed to create session directory '${sessionRoot}': ${message}`),
|
|
405
|
+
invocationContext,
|
|
406
|
+
);
|
|
407
|
+
}
|
|
408
|
+
const sessionDirForIndex = (idx?: number) =>
|
|
409
|
+
path.join(sessionRoot, `run-${idx ?? 0}`);
|
|
410
|
+
const childSessionFileForIndex = (idx?: number) =>
|
|
411
|
+
sessionFileForIndex(idx) ?? path.join(sessionDirForIndex(idx), "session.jsonl");
|
|
412
|
+
const childSessionFileForAgentIndex = (agentName: string | undefined, idx?: number) =>
|
|
413
|
+
forkSessionFileForAgentIndex(agentName, idx) ?? path.join(sessionDirForIndex(idx), "session.jsonl");
|
|
414
|
+
|
|
415
|
+
const workflowGraph = effectiveParams.chain ? buildWorkflowGraphSnapshot({ runId, steps: effectiveParams.chain }) : undefined;
|
|
416
|
+
const assignmentNodes = workflowGraph && workflowAgentNodes(workflowGraph);
|
|
417
|
+
const onUpdateWithContext = (r: SubagentExecutionResult) => {
|
|
418
|
+
const owned = deps.state.ownedRuns?.get(runId);
|
|
419
|
+
if (owned && r.details.workflowGraph) rememberOwnedRun(deps.state, { ...owned, children: workflowChildren(owned.children, r.details.workflowGraph) });
|
|
420
|
+
|
|
421
|
+
onUpdate?.(withForkContext(r, invocationContext));
|
|
422
|
+
};
|
|
423
|
+
const assignments = effectiveParams.tasks ?? effectiveParams.chain?.flatMap((step) =>
|
|
424
|
+
isParallelStep(step) ? step.parallel : isDynamicParallelStep(step) ? [step.parallel] : [step])
|
|
425
|
+
?? [{ agent: effectiveParams.agent!, task: effectiveParams.task, label: effectiveParams.label }];
|
|
426
|
+
|
|
427
|
+
saveQuestionOwner(runId, ctx.sessionManager.getSessionId());
|
|
428
|
+
const execData: ExecutionContextData = {
|
|
429
|
+
params: effectiveParams,
|
|
430
|
+
effectiveCwd,
|
|
431
|
+
ctx,
|
|
432
|
+
signal,
|
|
433
|
+
onUpdate: onUpdateWithContext,
|
|
434
|
+
agents,
|
|
435
|
+
runId,
|
|
436
|
+
shareEnabled,
|
|
437
|
+
sessionRoot,
|
|
438
|
+
sessionDirForIndex,
|
|
439
|
+
sessionFileForIndex: childSessionFileForIndex,
|
|
440
|
+
sessionFileForAgentIndex: childSessionFileForAgentIndex,
|
|
441
|
+
artifactsEnabled,
|
|
442
|
+
artifactsDir,
|
|
443
|
+
backgroundRequestedWhileClarifying,
|
|
444
|
+
effectiveAsync,
|
|
445
|
+
...(foregroundTimeout.timeoutMs !== undefined ? { foregroundTimeoutMs: foregroundTimeout.timeoutMs } : {}),
|
|
446
|
+
controlConfig,
|
|
447
|
+
intercomBridge,
|
|
448
|
+
nestedRoute,
|
|
449
|
+
};
|
|
450
|
+
|
|
451
|
+
try {
|
|
452
|
+
const result = runAsyncPath(execData, deps);
|
|
453
|
+
if (!result) throw new Error("Invalid subagent execution mode.");
|
|
454
|
+
if (result.isError) return withForkContext(result, invocationContext);
|
|
455
|
+
rememberOwnedRun(deps.state, {
|
|
456
|
+
runId, ownerSessionId: ctx.sessionManager.getSessionId(), rootRunId: runId,
|
|
457
|
+
source: "async", mode: hasChain ? "chain" : hasTasks ? "parallel" : "single",
|
|
458
|
+
cwd: effectiveCwd, task: effectiveParams.task ?? effectiveParams.tasks?.map((task) => task.task).join("\n") ?? "Delegated workflow",
|
|
459
|
+
asyncDir: result.details.asyncDir, pid: result.details.asyncPid ?? deps.state.asyncJobs.get(runId)?.pid,
|
|
460
|
+
startedAt: Date.now(), children: assignments.map(({ agent, task, label }, index) => ({ agent, index, task, label, ...(assignmentNodes?.[index] ? { workflowNodeId: assignmentNodes[index]!.id } : {}) })),
|
|
461
|
+
});
|
|
462
|
+
if (!effectiveAsync && result.details.asyncId) {
|
|
463
|
+
return withForkContext(await waitForOwnedRun({ id: runId, deps, ctx, signal, onUpdate: onUpdateWithContext,
|
|
464
|
+
cancelNewRun: !effectiveAsync, executionResult: true, includeProgress: effectiveParams.includeProgress }), invocationContext);
|
|
465
|
+
}
|
|
466
|
+
return withForkContext(result, invocationContext);
|
|
467
|
+
} catch (error) {
|
|
468
|
+
const result = toExecutionErrorResult(effectiveParams, error, invocationContext);
|
|
469
|
+
const owned = deps.state.ownedRuns?.get(runId);
|
|
470
|
+
if (owned) rememberOwnedRun(deps.state, { ...owned, error: result.content.filter((part) => part.type === "text").map((part) => part.text).join("\n") });
|
|
471
|
+
return result;
|
|
472
|
+
}
|
|
473
|
+
};
|
|
474
|
+
|
|
475
|
+
return { execute: async (...args) => {
|
|
476
|
+
const [id, params, signal, onUpdate, ctx, executionCwd] = args;
|
|
477
|
+
const waiting = params.async === false && (params.action === "resume" || params.action === "answer");
|
|
478
|
+
const before = waiting ? new Set(deps.state.ownedRuns?.keys()) : undefined;
|
|
479
|
+
let result = await execute(id, params, signal, onUpdate, ctx, executionCwd);
|
|
480
|
+
// Launch/answer receipts and claims are saved before waiting; execution failure must not undo a successful launch.
|
|
481
|
+
if (waiting && !result.isError) {
|
|
482
|
+
const question = result.details.questions?.find((question) => question.delivery || question.state === "answer_pending");
|
|
483
|
+
const id = result.details.asyncId ?? result.details.managementControl?.runId ?? question?.delivery?.runId ?? question?.runId ?? params.id ?? params.runId;
|
|
484
|
+
const index = result.details.asyncId || question?.delivery?.kind === "revive" ? 0
|
|
485
|
+
: result.details.managementControl?.nextActions.find((action) => action.index !== undefined)?.index ?? question?.index ?? params.index;
|
|
486
|
+
if (id) return waitForOwnedRun({ id, index, deps, ctx, signal, onUpdate, cancelNewRun: params.async === false && !before?.has(id) && deps.state.ownedRuns?.has(id), executionResult: true, includeProgress: params.includeProgress });
|
|
487
|
+
}
|
|
488
|
+
if (args[1].action === "interrupt") return cancelSupervisorInput(result, args[1], args[4].sessionManager.getSessionId(), deps.pi.events);
|
|
489
|
+
if (args[1].action !== "status" || result.details.runList) return result;
|
|
490
|
+
const requested = args[1].id ?? args[1].runId;
|
|
491
|
+
if (requested && !args[1].dir) {
|
|
492
|
+
try {
|
|
493
|
+
const owned = resolveOwnedRun(deps.state, requested);
|
|
494
|
+
if (owned) result = ownedRunStatusResult(owned, deps.state, result, { full: args[1].full, childSafe: Boolean(nestedResolutionScopeForExecutor(deps)) });
|
|
495
|
+
} catch (error) {
|
|
496
|
+
return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "management", results: [] } };
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
return projectSupervisorQuestions(result, args[1], args[4].sessionManager.getSessionId(), Boolean(nestedResolutionScopeForExecutor(deps)));
|
|
500
|
+
} };
|
|
501
|
+
}
|