@selesai/code 0.1.5 → 0.1.7
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/dist/config.d.ts +23 -4
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +100 -5
- package/dist/config.js.map +1 -1
- package/dist/core/package-manager.d.ts +1 -0
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +6 -1
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +3 -2
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/settings-manager.d.ts +1 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/defaults/settings.json +2 -4
- package/dist/extensions/pi-intercom/LICENSE +21 -0
- package/dist/extensions/pi-intercom/README.md +484 -0
- package/dist/extensions/pi-intercom/broker/broker.ts +345 -0
- package/dist/extensions/pi-intercom/broker/client.ts +535 -0
- package/dist/extensions/pi-intercom/broker/framing.ts +57 -0
- package/dist/extensions/pi-intercom/broker/paths.ts +20 -0
- package/dist/extensions/pi-intercom/broker/spawn.ts +307 -0
- package/dist/extensions/pi-intercom/config.ts +108 -0
- package/dist/extensions/pi-intercom/index.ts +1778 -0
- package/dist/extensions/pi-intercom/package.json +38 -0
- package/dist/extensions/pi-intercom/reply-tracker.ts +102 -0
- package/dist/extensions/pi-intercom/skills/pi-intercom/SKILL.md +512 -0
- package/dist/extensions/pi-intercom/types.ts +46 -0
- package/dist/extensions/pi-intercom/ui/compose.ts +139 -0
- package/dist/extensions/pi-intercom/ui/inline-message.ts +76 -0
- package/dist/extensions/pi-intercom/ui/session-list.ts +162 -0
- package/dist/extensions/pi-rewind-hook/README.md +245 -0
- package/dist/extensions/pi-rewind-hook/index.ts +1445 -0
- package/dist/extensions/pi-rewind-hook/package.json +29 -0
- package/dist/extensions/pi-subagents/README.md +1290 -0
- package/dist/extensions/pi-subagents/agents/context-builder.md +46 -0
- package/dist/extensions/pi-subagents/agents/delegate.md +12 -0
- package/dist/extensions/pi-subagents/agents/oracle.md +73 -0
- package/dist/extensions/pi-subagents/agents/planner.md +55 -0
- package/dist/extensions/pi-subagents/agents/researcher.md +52 -0
- package/dist/extensions/pi-subagents/agents/reviewer.md +79 -0
- package/dist/extensions/pi-subagents/agents/scout.md +50 -0
- package/dist/extensions/pi-subagents/agents/worker.md +55 -0
- package/dist/extensions/pi-subagents/package.json +83 -0
- package/dist/extensions/pi-subagents/prompts/gather-context-and-clarify.md +13 -0
- package/dist/extensions/pi-subagents/prompts/parallel-cleanup.md +59 -0
- package/dist/extensions/pi-subagents/prompts/parallel-context-build.md +55 -0
- package/dist/extensions/pi-subagents/prompts/parallel-handoff-plan.md +61 -0
- package/dist/extensions/pi-subagents/prompts/parallel-research.md +50 -0
- package/dist/extensions/pi-subagents/prompts/parallel-review.md +54 -0
- package/dist/extensions/pi-subagents/prompts/review-loop.md +41 -0
- package/dist/extensions/pi-subagents/skills/pi-subagents/SKILL.md +855 -0
- package/dist/extensions/pi-subagents/src/agents/agent-management.ts +875 -0
- package/dist/extensions/pi-subagents/src/agents/agent-scope.ts +6 -0
- package/dist/extensions/pi-subagents/src/agents/agent-selection.ts +25 -0
- package/dist/extensions/pi-subagents/src/agents/agent-serializer.ts +110 -0
- package/dist/extensions/pi-subagents/src/agents/agents.ts +1379 -0
- package/dist/extensions/pi-subagents/src/agents/chain-serializer.ts +252 -0
- package/dist/extensions/pi-subagents/src/agents/frontmatter.ts +93 -0
- package/dist/extensions/pi-subagents/src/agents/identity.ts +30 -0
- package/dist/extensions/pi-subagents/src/agents/proactive-skills.ts +191 -0
- package/dist/extensions/pi-subagents/src/agents/skills.ts +729 -0
- package/dist/extensions/pi-subagents/src/extension/config.ts +16 -0
- package/dist/extensions/pi-subagents/src/extension/control-notices.ts +92 -0
- package/dist/extensions/pi-subagents/src/extension/doctor.ts +220 -0
- package/dist/extensions/pi-subagents/src/extension/fanout-child.ts +171 -0
- package/dist/extensions/pi-subagents/src/extension/index.ts +627 -0
- package/dist/extensions/pi-subagents/src/extension/schemas.ts +265 -0
- package/dist/extensions/pi-subagents/src/intercom/intercom-bridge.ts +412 -0
- package/dist/extensions/pi-subagents/src/intercom/result-intercom.ts +377 -0
- package/dist/extensions/pi-subagents/src/profiles/profiles.ts +637 -0
- package/dist/extensions/pi-subagents/src/runs/background/async-execution.ts +916 -0
- package/dist/extensions/pi-subagents/src/runs/background/async-job-tracker.ts +355 -0
- package/dist/extensions/pi-subagents/src/runs/background/async-resume.ts +391 -0
- package/dist/extensions/pi-subagents/src/runs/background/async-status.ts +338 -0
- package/dist/extensions/pi-subagents/src/runs/background/chain-append.ts +282 -0
- package/dist/extensions/pi-subagents/src/runs/background/chain-root-attachment.ts +161 -0
- package/dist/extensions/pi-subagents/src/runs/background/completion-dedupe.ts +63 -0
- package/dist/extensions/pi-subagents/src/runs/background/control-channel.ts +177 -0
- package/dist/extensions/pi-subagents/src/runs/background/notify.ts +108 -0
- package/dist/extensions/pi-subagents/src/runs/background/parallel-groups.ts +45 -0
- package/dist/extensions/pi-subagents/src/runs/background/result-watcher.ts +316 -0
- package/dist/extensions/pi-subagents/src/runs/background/run-id-resolver.ts +83 -0
- package/dist/extensions/pi-subagents/src/runs/background/run-status.ts +273 -0
- package/dist/extensions/pi-subagents/src/runs/background/stale-run-reconciler.ts +341 -0
- package/dist/extensions/pi-subagents/src/runs/background/subagent-runner.ts +2458 -0
- package/dist/extensions/pi-subagents/src/runs/background/top-level-async.ts +13 -0
- package/dist/extensions/pi-subagents/src/runs/foreground/chain-clarify.ts +1333 -0
- package/dist/extensions/pi-subagents/src/runs/foreground/chain-execution.ts +1217 -0
- package/dist/extensions/pi-subagents/src/runs/foreground/execution.ts +1092 -0
- package/dist/extensions/pi-subagents/src/runs/foreground/subagent-executor.ts +3125 -0
- package/dist/extensions/pi-subagents/src/runs/shared/acceptance.ts +856 -0
- package/dist/extensions/pi-subagents/src/runs/shared/chain-outputs.ts +116 -0
- package/dist/extensions/pi-subagents/src/runs/shared/completion-guard.ts +147 -0
- package/dist/extensions/pi-subagents/src/runs/shared/dynamic-fanout.ts +295 -0
- package/dist/extensions/pi-subagents/src/runs/shared/long-running-guard.ts +175 -0
- package/dist/extensions/pi-subagents/src/runs/shared/mcp-direct-tool-allowlist.ts +365 -0
- package/dist/extensions/pi-subagents/src/runs/shared/model-fallback.ts +141 -0
- package/dist/extensions/pi-subagents/src/runs/shared/nested-events.ts +819 -0
- package/dist/extensions/pi-subagents/src/runs/shared/nested-path.ts +52 -0
- package/dist/extensions/pi-subagents/src/runs/shared/nested-render.ts +115 -0
- package/dist/extensions/pi-subagents/src/runs/shared/parallel-utils.ts +149 -0
- package/dist/extensions/pi-subagents/src/runs/shared/pi-args.ts +240 -0
- package/dist/extensions/pi-subagents/src/runs/shared/pi-spawn.ts +115 -0
- package/dist/extensions/pi-subagents/src/runs/shared/run-history.ts +60 -0
- package/dist/extensions/pi-subagents/src/runs/shared/single-output.ts +178 -0
- package/dist/extensions/pi-subagents/src/runs/shared/structured-output.ts +77 -0
- package/dist/extensions/pi-subagents/src/runs/shared/subagent-control.ts +223 -0
- package/dist/extensions/pi-subagents/src/runs/shared/subagent-prompt-runtime.ts +222 -0
- package/dist/extensions/pi-subagents/src/runs/shared/workflow-graph.ts +206 -0
- package/dist/extensions/pi-subagents/src/runs/shared/worktree.ts +577 -0
- package/dist/extensions/pi-subagents/src/shared/artifacts.ts +98 -0
- package/dist/extensions/pi-subagents/src/shared/atomic-json.ts +73 -0
- package/dist/extensions/pi-subagents/src/shared/file-coalescer.ts +40 -0
- package/dist/extensions/pi-subagents/src/shared/fork-context.ts +76 -0
- package/dist/extensions/pi-subagents/src/shared/formatters.ts +133 -0
- package/dist/extensions/pi-subagents/src/shared/jsonl-writer.ts +81 -0
- package/dist/extensions/pi-subagents/src/shared/model-info.ts +78 -0
- package/dist/extensions/pi-subagents/src/shared/post-exit-stdio-guard.ts +85 -0
- package/dist/extensions/pi-subagents/src/shared/session-identity.ts +10 -0
- package/dist/extensions/pi-subagents/src/shared/session-tokens.ts +44 -0
- package/dist/extensions/pi-subagents/src/shared/settings.ts +448 -0
- package/dist/extensions/pi-subagents/src/shared/status-format.ts +49 -0
- package/dist/extensions/pi-subagents/src/shared/types.ts +1064 -0
- package/dist/extensions/pi-subagents/src/shared/utils.ts +469 -0
- package/dist/extensions/pi-subagents/src/slash/prompt-template-bridge.ts +420 -0
- package/dist/extensions/pi-subagents/src/slash/slash-bridge.ts +176 -0
- package/dist/extensions/pi-subagents/src/slash/slash-commands.ts +1165 -0
- package/dist/extensions/pi-subagents/src/slash/slash-live-state.ts +292 -0
- package/dist/extensions/pi-subagents/src/tui/render-helpers.ts +80 -0
- package/dist/extensions/pi-subagents/src/tui/render.ts +1728 -0
- package/dist/extensions/quick.ts +630 -0
- package/dist/modes/index.d.ts +1 -1
- package/dist/modes/index.d.ts.map +1 -1
- package/dist/modes/index.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +4 -3
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +3 -2
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,1217 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Chain execution logic for subagent tool
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import * as fs from "node:fs";
|
|
6
|
+
import * as path from "node:path";
|
|
7
|
+
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
8
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
9
|
+
import type { AgentConfig } from "../../agents/agents.ts";
|
|
10
|
+
import { ChainClarifyComponent, type ChainClarifyResult, type BehaviorOverride } from "./chain-clarify.ts";
|
|
11
|
+
import { toModelInfo, type ModelInfo } from "../../shared/model-info.ts";
|
|
12
|
+
import {
|
|
13
|
+
resolveChainTemplates,
|
|
14
|
+
createChainDir,
|
|
15
|
+
removeChainDir,
|
|
16
|
+
resolveStepBehavior,
|
|
17
|
+
resolveParallelBehaviors,
|
|
18
|
+
buildChainInstructions,
|
|
19
|
+
writeInitialProgressFile,
|
|
20
|
+
createParallelDirs,
|
|
21
|
+
suppressProgressForReadOnlyTask,
|
|
22
|
+
aggregateParallelOutputs,
|
|
23
|
+
isDynamicParallelStep,
|
|
24
|
+
isParallelStep,
|
|
25
|
+
type StepOverrides,
|
|
26
|
+
type ChainStep,
|
|
27
|
+
type ParallelStep,
|
|
28
|
+
type SequentialStep,
|
|
29
|
+
type ParallelTaskResult,
|
|
30
|
+
type ResolvedStepBehavior,
|
|
31
|
+
type ResolvedTemplates,
|
|
32
|
+
} from "../../shared/settings.ts";
|
|
33
|
+
import { discoverAvailableSkills, normalizeSkillInput } from "../../agents/skills.ts";
|
|
34
|
+
import { INTERCOM_BRIDGE_MARKER } from "../../intercom/intercom-bridge.ts";
|
|
35
|
+
import { runSync } from "./execution.ts";
|
|
36
|
+
import { buildChainSummary } from "../../shared/formatters.ts";
|
|
37
|
+
import { compactForegroundDetails, getSingleResultOutput, mapConcurrent, resolveChildCwd } from "../../shared/utils.ts";
|
|
38
|
+
import { recordRun } from "../shared/run-history.ts";
|
|
39
|
+
import {
|
|
40
|
+
cleanupWorktrees,
|
|
41
|
+
createWorktrees,
|
|
42
|
+
diffWorktrees,
|
|
43
|
+
findWorktreeTaskCwdConflict,
|
|
44
|
+
formatWorktreeDiffSummary,
|
|
45
|
+
formatWorktreeTaskCwdConflict,
|
|
46
|
+
type WorktreeSetup,
|
|
47
|
+
} from "../shared/worktree.ts";
|
|
48
|
+
import {
|
|
49
|
+
type ActivityState,
|
|
50
|
+
type AgentProgress,
|
|
51
|
+
type ArtifactConfig,
|
|
52
|
+
type ArtifactPaths,
|
|
53
|
+
type ControlEvent,
|
|
54
|
+
type Details,
|
|
55
|
+
type IntercomEventBus,
|
|
56
|
+
type NestedRouteInfo,
|
|
57
|
+
type ResolvedControlConfig,
|
|
58
|
+
type SingleResult,
|
|
59
|
+
MAX_CONCURRENCY,
|
|
60
|
+
resolveChildMaxSubagentDepth,
|
|
61
|
+
} from "../../shared/types.ts";
|
|
62
|
+
import { resolveSubagentModelOverride } from "../shared/model-fallback.ts";
|
|
63
|
+
import { validateFileOnlyOutputMode } from "../shared/single-output.ts";
|
|
64
|
+
import { buildWorkflowGraphSnapshot } from "../shared/workflow-graph.ts";
|
|
65
|
+
import { ChainOutputValidationError, outputEntryFromResult, resolveOutputReferences, validateChainOutputBindings } from "../shared/chain-outputs.ts";
|
|
66
|
+
import { createStructuredOutputRuntime } from "../shared/structured-output.ts";
|
|
67
|
+
import { collectDynamicResults, DynamicFanoutError, materializeDynamicParallelStep, validateDynamicCollection, type DynamicCollectedResult } from "../shared/dynamic-fanout.ts";
|
|
68
|
+
import { acceptanceFailureMessage, aggregateAcceptanceReport, evaluateAcceptance, resolveEffectiveAcceptance } from "../shared/acceptance.ts";
|
|
69
|
+
import type { ChainOutputMap } from "../../shared/types.ts";
|
|
70
|
+
|
|
71
|
+
interface ChainExecutionDetailsInput {
|
|
72
|
+
results: SingleResult[];
|
|
73
|
+
includeProgress?: boolean;
|
|
74
|
+
allProgress: AgentProgress[];
|
|
75
|
+
allArtifactPaths: ArtifactPaths[];
|
|
76
|
+
artifactsDir: string;
|
|
77
|
+
chainAgents: string[];
|
|
78
|
+
chainSteps: ChainStep[];
|
|
79
|
+
totalSteps: number;
|
|
80
|
+
currentStepIndex?: number;
|
|
81
|
+
runId: string;
|
|
82
|
+
outputs?: ChainOutputMap;
|
|
83
|
+
currentFlatIndex?: number;
|
|
84
|
+
dynamicChildren?: Record<number, Array<{ agent: string; label?: string; flatIndex: number; itemKey: string; outputName?: string; structured?: boolean; error?: string }>>;
|
|
85
|
+
dynamicGroupStatuses?: Record<number, { status: "pending" | "running" | "completed" | "failed" | "paused" | "detached"; error?: string; acceptance?: SingleResult["acceptance"] }>;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
interface ParallelChainRunInput {
|
|
89
|
+
step: ParallelStep;
|
|
90
|
+
parallelTemplates: string[];
|
|
91
|
+
parallelBehaviors: ResolvedStepBehavior[];
|
|
92
|
+
agents: AgentConfig[];
|
|
93
|
+
stepIndex: number;
|
|
94
|
+
availableModels: ModelInfo[];
|
|
95
|
+
chainDir: string;
|
|
96
|
+
prev: string;
|
|
97
|
+
originalTask: string;
|
|
98
|
+
ctx: ExtensionContext;
|
|
99
|
+
intercomEvents?: IntercomEventBus;
|
|
100
|
+
cwd?: string;
|
|
101
|
+
runId: string;
|
|
102
|
+
globalTaskIndex: number;
|
|
103
|
+
sessionDirForIndex: (idx?: number) => string | undefined;
|
|
104
|
+
sessionFileForIndex?: (idx?: number) => string | undefined;
|
|
105
|
+
sessionFileForTask?: (agentName: string, idx?: number) => string | undefined;
|
|
106
|
+
shareEnabled: boolean;
|
|
107
|
+
artifactConfig: ArtifactConfig;
|
|
108
|
+
artifactsDir: string;
|
|
109
|
+
signal?: AbortSignal;
|
|
110
|
+
onUpdate?: (r: AgentToolResult<Details>) => void;
|
|
111
|
+
onControlEvent?: (event: ControlEvent) => void;
|
|
112
|
+
controlConfig: ResolvedControlConfig;
|
|
113
|
+
childIntercomTarget?: (agent: string, index: number) => string | undefined;
|
|
114
|
+
orchestratorIntercomTarget?: string;
|
|
115
|
+
foregroundControl?: {
|
|
116
|
+
updatedAt: number;
|
|
117
|
+
currentAgent?: string;
|
|
118
|
+
currentIndex?: number;
|
|
119
|
+
currentActivityState?: ActivityState;
|
|
120
|
+
lastActivityAt?: number;
|
|
121
|
+
currentTool?: string;
|
|
122
|
+
currentToolStartedAt?: number;
|
|
123
|
+
currentPath?: string;
|
|
124
|
+
turnCount?: number;
|
|
125
|
+
tokens?: number;
|
|
126
|
+
toolCount?: number;
|
|
127
|
+
interrupt?: () => boolean;
|
|
128
|
+
};
|
|
129
|
+
results: SingleResult[];
|
|
130
|
+
allProgress: AgentProgress[];
|
|
131
|
+
outputs: ChainOutputMap;
|
|
132
|
+
chainAgents: string[];
|
|
133
|
+
chainSteps: ChainStep[];
|
|
134
|
+
totalSteps: number;
|
|
135
|
+
dynamicChildren?: ChainExecutionDetailsInput["dynamicChildren"];
|
|
136
|
+
dynamicGroupStatuses?: ChainExecutionDetailsInput["dynamicGroupStatuses"];
|
|
137
|
+
worktreeSetup?: WorktreeSetup;
|
|
138
|
+
maxSubagentDepth: number;
|
|
139
|
+
nestedRoute?: NestedRouteInfo;
|
|
140
|
+
timeoutMs?: number;
|
|
141
|
+
deadlineAt?: number;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function buildChainExecutionDetails(input: ChainExecutionDetailsInput): Details {
|
|
145
|
+
return compactForegroundDetails({
|
|
146
|
+
mode: "chain",
|
|
147
|
+
results: input.results,
|
|
148
|
+
progress: input.includeProgress ? input.allProgress : undefined,
|
|
149
|
+
artifacts: input.allArtifactPaths.length ? { dir: input.artifactsDir, files: input.allArtifactPaths } : undefined,
|
|
150
|
+
chainAgents: input.chainAgents,
|
|
151
|
+
totalSteps: input.totalSteps,
|
|
152
|
+
currentStepIndex: input.currentStepIndex,
|
|
153
|
+
outputs: input.outputs,
|
|
154
|
+
workflowGraph: buildWorkflowGraphSnapshot({
|
|
155
|
+
runId: input.runId,
|
|
156
|
+
mode: "chain",
|
|
157
|
+
steps: input.chainSteps,
|
|
158
|
+
results: input.results,
|
|
159
|
+
currentStepIndex: input.currentStepIndex,
|
|
160
|
+
currentFlatIndex: input.currentFlatIndex,
|
|
161
|
+
dynamicChildren: input.dynamicChildren,
|
|
162
|
+
dynamicGroupStatuses: input.dynamicGroupStatuses,
|
|
163
|
+
}),
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function buildChainExecutionErrorResult(message: string, input: ChainExecutionDetailsInput): ChainExecutionResult {
|
|
168
|
+
return {
|
|
169
|
+
content: [{ type: "text", text: message }],
|
|
170
|
+
isError: true,
|
|
171
|
+
details: buildChainExecutionDetails(input),
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function ensureParallelProgressFile(
|
|
176
|
+
chainDir: string,
|
|
177
|
+
progressCreated: boolean,
|
|
178
|
+
parallelBehaviors: ResolvedStepBehavior[],
|
|
179
|
+
): boolean {
|
|
180
|
+
if (progressCreated || !parallelBehaviors.some((behavior) => behavior.progress)) {
|
|
181
|
+
return progressCreated;
|
|
182
|
+
}
|
|
183
|
+
writeInitialProgressFile(chainDir);
|
|
184
|
+
return true;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function appendParallelWorktreeSummary(
|
|
188
|
+
output: string,
|
|
189
|
+
worktreeSetup: WorktreeSetup | undefined,
|
|
190
|
+
diffsDir: string,
|
|
191
|
+
agents: string[],
|
|
192
|
+
): string {
|
|
193
|
+
if (!worktreeSetup) return output;
|
|
194
|
+
const diffs = diffWorktrees(worktreeSetup, agents, diffsDir);
|
|
195
|
+
const diffSummary = formatWorktreeDiffSummary(diffs);
|
|
196
|
+
if (!diffSummary) return output;
|
|
197
|
+
return `${output}\n\n${diffSummary}`;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async function runParallelChainTasks(input: ParallelChainRunInput): Promise<SingleResult[]> {
|
|
201
|
+
const concurrency = input.step.concurrency ?? MAX_CONCURRENCY;
|
|
202
|
+
const failFast = input.step.failFast ?? false;
|
|
203
|
+
let aborted = false;
|
|
204
|
+
|
|
205
|
+
const parallelResults = await mapConcurrent(
|
|
206
|
+
input.step.parallel,
|
|
207
|
+
concurrency,
|
|
208
|
+
async (task, taskIndex) => {
|
|
209
|
+
if (aborted && failFast) {
|
|
210
|
+
return {
|
|
211
|
+
agent: task.agent,
|
|
212
|
+
task: "(skipped)",
|
|
213
|
+
exitCode: -1,
|
|
214
|
+
messages: [],
|
|
215
|
+
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 },
|
|
216
|
+
error: "Skipped due to fail-fast",
|
|
217
|
+
} as SingleResult;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const taskTemplate = input.parallelTemplates[taskIndex] ?? "{previous}";
|
|
221
|
+
const behavior = suppressProgressForReadOnlyTask(input.parallelBehaviors[taskIndex]!, taskTemplate, input.originalTask);
|
|
222
|
+
const templateHasPrevious = taskTemplate.includes("{previous}");
|
|
223
|
+
const { prefix, suffix } = buildChainInstructions(
|
|
224
|
+
behavior,
|
|
225
|
+
input.chainDir,
|
|
226
|
+
false,
|
|
227
|
+
templateHasPrevious ? undefined : input.prev,
|
|
228
|
+
);
|
|
229
|
+
|
|
230
|
+
let taskStr = resolveOutputReferences(taskTemplate, input.outputs);
|
|
231
|
+
taskStr = taskStr.replace(/\{task\}/g, input.originalTask);
|
|
232
|
+
taskStr = taskStr.replace(/\{previous\}/g, input.prev);
|
|
233
|
+
taskStr = taskStr.replace(/\{chain_dir\}/g, input.chainDir);
|
|
234
|
+
const cleanTask = taskStr;
|
|
235
|
+
taskStr = prefix + taskStr + suffix;
|
|
236
|
+
|
|
237
|
+
const taskAgentConfig = input.agents.find((agent) => agent.name === task.agent);
|
|
238
|
+
const effectiveModel = resolveSubagentModelOverride(
|
|
239
|
+
task.model ?? taskAgentConfig?.model,
|
|
240
|
+
input.ctx.model,
|
|
241
|
+
input.availableModels,
|
|
242
|
+
input.ctx.model?.provider,
|
|
243
|
+
);
|
|
244
|
+
const maxSubagentDepth = resolveChildMaxSubagentDepth(input.maxSubagentDepth, taskAgentConfig?.maxSubagentDepth);
|
|
245
|
+
|
|
246
|
+
const taskCwd = input.worktreeSetup
|
|
247
|
+
? input.worktreeSetup.worktrees[taskIndex]!.agentCwd
|
|
248
|
+
: resolveChildCwd(input.cwd ?? input.ctx.cwd, task.cwd);
|
|
249
|
+
|
|
250
|
+
const outputPath = typeof behavior.output === "string"
|
|
251
|
+
? (path.isAbsolute(behavior.output) ? behavior.output : path.join(input.chainDir, behavior.output))
|
|
252
|
+
: undefined;
|
|
253
|
+
const interruptController = new AbortController();
|
|
254
|
+
if (input.foregroundControl) {
|
|
255
|
+
input.foregroundControl.currentAgent = task.agent;
|
|
256
|
+
input.foregroundControl.currentIndex = input.globalTaskIndex + taskIndex;
|
|
257
|
+
input.foregroundControl.currentActivityState = undefined;
|
|
258
|
+
input.foregroundControl.updatedAt = Date.now();
|
|
259
|
+
input.foregroundControl.interrupt = () => {
|
|
260
|
+
if (interruptController.signal.aborted) return false;
|
|
261
|
+
interruptController.abort();
|
|
262
|
+
input.foregroundControl!.currentActivityState = undefined;
|
|
263
|
+
input.foregroundControl!.updatedAt = Date.now();
|
|
264
|
+
return true;
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
const structuredRuntime = task.outputSchema
|
|
269
|
+
? createStructuredOutputRuntime(task.outputSchema, path.join(input.chainDir, "structured-output"))
|
|
270
|
+
: undefined;
|
|
271
|
+
const result = await runSync(input.ctx.cwd, input.agents, task.agent, taskStr, {
|
|
272
|
+
parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
|
|
273
|
+
cwd: taskCwd,
|
|
274
|
+
signal: input.signal,
|
|
275
|
+
interruptSignal: interruptController.signal,
|
|
276
|
+
allowIntercomDetach: taskAgentConfig?.systemPrompt?.includes(INTERCOM_BRIDGE_MARKER) === true,
|
|
277
|
+
intercomEvents: input.intercomEvents,
|
|
278
|
+
runId: input.runId,
|
|
279
|
+
index: input.globalTaskIndex + taskIndex,
|
|
280
|
+
sessionDir: input.sessionDirForIndex(input.globalTaskIndex + taskIndex),
|
|
281
|
+
sessionFile: input.sessionFileForTask?.(task.agent, input.globalTaskIndex + taskIndex)
|
|
282
|
+
?? input.sessionFileForIndex?.(input.globalTaskIndex + taskIndex),
|
|
283
|
+
share: input.shareEnabled,
|
|
284
|
+
artifactsDir: input.artifactConfig.enabled ? input.artifactsDir : undefined,
|
|
285
|
+
artifactConfig: input.artifactConfig,
|
|
286
|
+
outputPath,
|
|
287
|
+
outputMode: behavior.outputMode,
|
|
288
|
+
maxSubagentDepth,
|
|
289
|
+
controlConfig: input.controlConfig,
|
|
290
|
+
onControlEvent: input.onControlEvent,
|
|
291
|
+
intercomSessionName: input.childIntercomTarget?.(task.agent, input.globalTaskIndex + taskIndex),
|
|
292
|
+
orchestratorIntercomTarget: input.orchestratorIntercomTarget,
|
|
293
|
+
nestedRoute: input.nestedRoute,
|
|
294
|
+
modelOverride: effectiveModel,
|
|
295
|
+
availableModels: input.availableModels,
|
|
296
|
+
preferredModelProvider: input.ctx.model?.provider,
|
|
297
|
+
skills: behavior.skills === false ? [] : behavior.skills,
|
|
298
|
+
structuredOutput: structuredRuntime,
|
|
299
|
+
acceptance: task.acceptance,
|
|
300
|
+
acceptanceContext: { mode: "chain" },
|
|
301
|
+
timeoutMs: input.timeoutMs,
|
|
302
|
+
deadlineAt: input.deadlineAt,
|
|
303
|
+
onUpdate: input.onUpdate
|
|
304
|
+
? (progressUpdate) => {
|
|
305
|
+
const stepResults = progressUpdate.details?.results || [];
|
|
306
|
+
const stepProgress = progressUpdate.details?.progress || [];
|
|
307
|
+
if (input.foregroundControl && stepProgress.length > 0) {
|
|
308
|
+
const current = stepProgress[0];
|
|
309
|
+
input.foregroundControl.currentAgent = task.agent;
|
|
310
|
+
input.foregroundControl.currentIndex = input.globalTaskIndex + taskIndex;
|
|
311
|
+
input.foregroundControl.currentActivityState = current?.activityState;
|
|
312
|
+
input.foregroundControl.lastActivityAt = current?.lastActivityAt;
|
|
313
|
+
input.foregroundControl.currentTool = current?.currentTool;
|
|
314
|
+
input.foregroundControl.currentToolStartedAt = current?.currentToolStartedAt;
|
|
315
|
+
input.foregroundControl.currentPath = current?.currentPath;
|
|
316
|
+
input.foregroundControl.turnCount = current?.turnCount;
|
|
317
|
+
input.foregroundControl.tokens = current?.tokens;
|
|
318
|
+
input.foregroundControl.toolCount = current?.toolCount;
|
|
319
|
+
input.foregroundControl.updatedAt = Date.now();
|
|
320
|
+
}
|
|
321
|
+
input.onUpdate?.({
|
|
322
|
+
...progressUpdate,
|
|
323
|
+
details: {
|
|
324
|
+
mode: "chain",
|
|
325
|
+
results: input.results.concat(stepResults),
|
|
326
|
+
progress: input.allProgress.concat(stepProgress),
|
|
327
|
+
controlEvents: progressUpdate.details?.controlEvents,
|
|
328
|
+
chainAgents: input.chainAgents,
|
|
329
|
+
totalSteps: input.totalSteps,
|
|
330
|
+
currentStepIndex: input.stepIndex,
|
|
331
|
+
outputs: input.outputs,
|
|
332
|
+
workflowGraph: buildWorkflowGraphSnapshot({
|
|
333
|
+
runId: input.runId,
|
|
334
|
+
mode: "chain",
|
|
335
|
+
steps: input.chainSteps,
|
|
336
|
+
results: input.results.concat(stepResults),
|
|
337
|
+
currentStepIndex: input.stepIndex,
|
|
338
|
+
currentFlatIndex: input.globalTaskIndex + taskIndex,
|
|
339
|
+
dynamicChildren: input.dynamicChildren,
|
|
340
|
+
dynamicGroupStatuses: input.dynamicGroupStatuses,
|
|
341
|
+
}),
|
|
342
|
+
},
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
: undefined,
|
|
346
|
+
});
|
|
347
|
+
if (input.foregroundControl?.currentIndex === input.globalTaskIndex + taskIndex) {
|
|
348
|
+
input.foregroundControl.interrupt = undefined;
|
|
349
|
+
input.foregroundControl.updatedAt = Date.now();
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
if (result.exitCode !== 0 && failFast) {
|
|
353
|
+
aborted = true;
|
|
354
|
+
}
|
|
355
|
+
recordRun(task.agent, cleanTask, result.exitCode, result.progressSummary?.durationMs ?? 0);
|
|
356
|
+
return result;
|
|
357
|
+
},
|
|
358
|
+
);
|
|
359
|
+
|
|
360
|
+
return parallelResults;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
interface ChainExecutionParams {
|
|
364
|
+
chain: ChainStep[];
|
|
365
|
+
task?: string;
|
|
366
|
+
agents: AgentConfig[];
|
|
367
|
+
ctx: ExtensionContext;
|
|
368
|
+
intercomEvents?: IntercomEventBus;
|
|
369
|
+
signal?: AbortSignal;
|
|
370
|
+
runId: string;
|
|
371
|
+
cwd?: string;
|
|
372
|
+
shareEnabled: boolean;
|
|
373
|
+
sessionDirForIndex: (idx?: number) => string | undefined;
|
|
374
|
+
sessionFileForIndex?: (idx?: number) => string | undefined;
|
|
375
|
+
sessionFileForTask?: (agentName: string, idx?: number) => string | undefined;
|
|
376
|
+
artifactsDir: string;
|
|
377
|
+
artifactConfig: ArtifactConfig;
|
|
378
|
+
includeProgress?: boolean;
|
|
379
|
+
clarify?: boolean;
|
|
380
|
+
onUpdate?: (r: AgentToolResult<Details>) => void;
|
|
381
|
+
onControlEvent?: (event: ControlEvent) => void;
|
|
382
|
+
controlConfig: ResolvedControlConfig;
|
|
383
|
+
childIntercomTarget?: (agent: string, index: number) => string | undefined;
|
|
384
|
+
orchestratorIntercomTarget?: string;
|
|
385
|
+
foregroundControl?: {
|
|
386
|
+
updatedAt: number;
|
|
387
|
+
currentAgent?: string;
|
|
388
|
+
currentIndex?: number;
|
|
389
|
+
currentActivityState?: ActivityState;
|
|
390
|
+
lastActivityAt?: number;
|
|
391
|
+
currentTool?: string;
|
|
392
|
+
currentToolStartedAt?: number;
|
|
393
|
+
currentPath?: string;
|
|
394
|
+
turnCount?: number;
|
|
395
|
+
tokens?: number;
|
|
396
|
+
toolCount?: number;
|
|
397
|
+
interrupt?: () => boolean;
|
|
398
|
+
};
|
|
399
|
+
chainSkills?: string[];
|
|
400
|
+
chainDir?: string;
|
|
401
|
+
dynamicFanoutMaxItems?: number;
|
|
402
|
+
maxSubagentDepth: number;
|
|
403
|
+
nestedRoute?: NestedRouteInfo;
|
|
404
|
+
worktreeSetupHook?: string;
|
|
405
|
+
worktreeSetupHookTimeoutMs?: number;
|
|
406
|
+
timeoutMs?: number;
|
|
407
|
+
deadlineAt?: number;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
interface ChainExecutionResult {
|
|
411
|
+
content: Array<{ type: "text"; text: string }>;
|
|
412
|
+
details: Details;
|
|
413
|
+
isError?: boolean;
|
|
414
|
+
/** User requested async execution via TUI - caller should dispatch to executeAsyncChain */
|
|
415
|
+
requestedAsync?: {
|
|
416
|
+
chain: ChainStep[];
|
|
417
|
+
chainSkills: string[];
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* Execute a chain of subagent steps
|
|
423
|
+
*/
|
|
424
|
+
export async function executeChain(params: ChainExecutionParams): Promise<ChainExecutionResult> {
|
|
425
|
+
const {
|
|
426
|
+
chain: chainSteps,
|
|
427
|
+
agents,
|
|
428
|
+
ctx,
|
|
429
|
+
signal,
|
|
430
|
+
runId,
|
|
431
|
+
cwd,
|
|
432
|
+
shareEnabled,
|
|
433
|
+
sessionDirForIndex,
|
|
434
|
+
sessionFileForIndex,
|
|
435
|
+
sessionFileForTask,
|
|
436
|
+
artifactsDir,
|
|
437
|
+
artifactConfig,
|
|
438
|
+
includeProgress,
|
|
439
|
+
clarify,
|
|
440
|
+
onUpdate,
|
|
441
|
+
onControlEvent,
|
|
442
|
+
controlConfig,
|
|
443
|
+
childIntercomTarget,
|
|
444
|
+
orchestratorIntercomTarget,
|
|
445
|
+
foregroundControl,
|
|
446
|
+
intercomEvents,
|
|
447
|
+
chainSkills: chainSkillsParam,
|
|
448
|
+
chainDir: chainDirBase,
|
|
449
|
+
} = params;
|
|
450
|
+
const chainSkills = chainSkillsParam ?? [];
|
|
451
|
+
|
|
452
|
+
const results: SingleResult[] = [];
|
|
453
|
+
const outputs: ChainOutputMap = {};
|
|
454
|
+
const dynamicChildren: ChainExecutionDetailsInput["dynamicChildren"] = {};
|
|
455
|
+
const dynamicGroupStatuses: ChainExecutionDetailsInput["dynamicGroupStatuses"] = {};
|
|
456
|
+
const allProgress: AgentProgress[] = [];
|
|
457
|
+
const allArtifactPaths: ArtifactPaths[] = [];
|
|
458
|
+
|
|
459
|
+
const chainAgents: string[] = chainSteps.map((step) =>
|
|
460
|
+
isParallelStep(step)
|
|
461
|
+
? `[${step.parallel.map((t) => t.agent).join("+")}]`
|
|
462
|
+
: isDynamicParallelStep(step)
|
|
463
|
+
? `expand:${step.parallel.agent}`
|
|
464
|
+
: (step as SequentialStep).agent,
|
|
465
|
+
);
|
|
466
|
+
const totalSteps = chainSteps.length;
|
|
467
|
+
|
|
468
|
+
const makeDetailsInput = (overrides: Pick<Partial<ChainExecutionDetailsInput>, "currentStepIndex" | "currentFlatIndex"> = {}): ChainExecutionDetailsInput => ({
|
|
469
|
+
results,
|
|
470
|
+
...(includeProgress !== undefined ? { includeProgress } : {}),
|
|
471
|
+
allProgress,
|
|
472
|
+
allArtifactPaths,
|
|
473
|
+
artifactsDir,
|
|
474
|
+
chainAgents,
|
|
475
|
+
chainSteps,
|
|
476
|
+
totalSteps,
|
|
477
|
+
runId,
|
|
478
|
+
outputs,
|
|
479
|
+
dynamicChildren,
|
|
480
|
+
dynamicGroupStatuses,
|
|
481
|
+
...overrides,
|
|
482
|
+
});
|
|
483
|
+
|
|
484
|
+
const firstStep = chainSteps[0]!;
|
|
485
|
+
const originalTask = params.task
|
|
486
|
+
?? (isParallelStep(firstStep)
|
|
487
|
+
? firstStep.parallel[0]!.task!
|
|
488
|
+
: isDynamicParallelStep(firstStep)
|
|
489
|
+
? firstStep.parallel.task!
|
|
490
|
+
: (firstStep as SequentialStep).task!);
|
|
491
|
+
try {
|
|
492
|
+
validateChainOutputBindings(chainSteps, { maxItems: params.dynamicFanoutMaxItems });
|
|
493
|
+
} catch (error) {
|
|
494
|
+
if (error instanceof ChainOutputValidationError) {
|
|
495
|
+
return {
|
|
496
|
+
content: [{ type: "text", text: error.message }],
|
|
497
|
+
isError: true,
|
|
498
|
+
details: buildChainExecutionDetails(makeDetailsInput()),
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
throw error;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
const chainDir = createChainDir(runId, chainDirBase);
|
|
505
|
+
const hasParallelSteps = chainSteps.some((step) => isParallelStep(step) || isDynamicParallelStep(step));
|
|
506
|
+
let templates: ResolvedTemplates = resolveChainTemplates(chainSteps);
|
|
507
|
+
const shouldClarify = clarify !== false && ctx.hasUI && !hasParallelSteps;
|
|
508
|
+
let tuiBehaviorOverrides: (BehaviorOverride | undefined)[] | undefined;
|
|
509
|
+
const availableModels: ModelInfo[] = ctx.modelRegistry.getAvailable().map(toModelInfo);
|
|
510
|
+
const availableSkills = discoverAvailableSkills(cwd ?? ctx.cwd);
|
|
511
|
+
|
|
512
|
+
if (shouldClarify) {
|
|
513
|
+
const seqSteps = chainSteps as SequentialStep[];
|
|
514
|
+
const agentConfigs: AgentConfig[] = [];
|
|
515
|
+
for (const step of seqSteps) {
|
|
516
|
+
const config = agents.find((a) => a.name === step.agent);
|
|
517
|
+
if (!config) {
|
|
518
|
+
removeChainDir(chainDir);
|
|
519
|
+
return {
|
|
520
|
+
content: [{ type: "text", text: `Unknown agent: ${step.agent}` }],
|
|
521
|
+
isError: true,
|
|
522
|
+
details: buildChainExecutionDetails(makeDetailsInput({ currentStepIndex: seqSteps.indexOf(step) })),
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
agentConfigs.push(config);
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
const stepOverrides: StepOverrides[] = seqSteps.map((step) => ({
|
|
529
|
+
output: step.output,
|
|
530
|
+
outputMode: step.outputMode,
|
|
531
|
+
reads: step.reads,
|
|
532
|
+
progress: step.progress,
|
|
533
|
+
skills: normalizeSkillInput(step.skill),
|
|
534
|
+
model: step.model,
|
|
535
|
+
}));
|
|
536
|
+
|
|
537
|
+
const resolvedBehaviors = agentConfigs.map((config, i) =>
|
|
538
|
+
resolveStepBehavior(config, stepOverrides[i]!, chainSkills),
|
|
539
|
+
);
|
|
540
|
+
const flatTemplates = templates as string[];
|
|
541
|
+
|
|
542
|
+
const result = await ctx.ui.custom<ChainClarifyResult>(
|
|
543
|
+
(tui, theme, _kb, done) =>
|
|
544
|
+
new ChainClarifyComponent(
|
|
545
|
+
tui,
|
|
546
|
+
theme,
|
|
547
|
+
agentConfigs,
|
|
548
|
+
flatTemplates,
|
|
549
|
+
originalTask,
|
|
550
|
+
chainDir,
|
|
551
|
+
resolvedBehaviors,
|
|
552
|
+
availableModels,
|
|
553
|
+
ctx.model?.provider,
|
|
554
|
+
availableSkills,
|
|
555
|
+
done,
|
|
556
|
+
),
|
|
557
|
+
{
|
|
558
|
+
overlay: true,
|
|
559
|
+
overlayOptions: { anchor: "center", width: 84, maxHeight: "80%" },
|
|
560
|
+
},
|
|
561
|
+
);
|
|
562
|
+
|
|
563
|
+
if (!result || !result.confirmed) {
|
|
564
|
+
removeChainDir(chainDir);
|
|
565
|
+
return {
|
|
566
|
+
content: [{ type: "text", text: "Chain cancelled" }],
|
|
567
|
+
details: buildChainExecutionDetails(makeDetailsInput()),
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
if (result.runInBackground) {
|
|
572
|
+
removeChainDir(chainDir);
|
|
573
|
+
const updatedChain: ChainStep[] = chainSteps.map((step, i) => {
|
|
574
|
+
if (isParallelStep(step)) return step;
|
|
575
|
+
const override = result.behaviorOverrides[i];
|
|
576
|
+
return {
|
|
577
|
+
...step,
|
|
578
|
+
task: result.templates[i]!,
|
|
579
|
+
...(override?.model ? { model: override.model } : {}),
|
|
580
|
+
...(override?.output !== undefined ? { output: override.output } : {}),
|
|
581
|
+
...("outputMode" in step && step.outputMode !== undefined ? { outputMode: step.outputMode } : {}),
|
|
582
|
+
...(override?.reads !== undefined ? { reads: override.reads } : {}),
|
|
583
|
+
...(override?.progress !== undefined ? { progress: override.progress } : {}),
|
|
584
|
+
...(override?.skills !== undefined ? { skill: override.skills } : {}),
|
|
585
|
+
};
|
|
586
|
+
});
|
|
587
|
+
return {
|
|
588
|
+
content: [{ type: "text", text: "Launching in background..." }],
|
|
589
|
+
details: buildChainExecutionDetails(makeDetailsInput()),
|
|
590
|
+
requestedAsync: { chain: updatedChain, chainSkills },
|
|
591
|
+
};
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
templates = result.templates;
|
|
595
|
+
tuiBehaviorOverrides = result.behaviorOverrides;
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
const deadlineAt = params.deadlineAt ?? (params.timeoutMs !== undefined ? Date.now() + params.timeoutMs : undefined);
|
|
599
|
+
let prev = "";
|
|
600
|
+
let globalTaskIndex = 0;
|
|
601
|
+
let progressCreated = false;
|
|
602
|
+
|
|
603
|
+
for (let stepIndex = 0; stepIndex < chainSteps.length; stepIndex++) {
|
|
604
|
+
const step = chainSteps[stepIndex]!;
|
|
605
|
+
const stepTemplates = templates[stepIndex]!;
|
|
606
|
+
|
|
607
|
+
if (isParallelStep(step)) {
|
|
608
|
+
const parallelTemplates = stepTemplates as string[];
|
|
609
|
+
const parallelCwd = resolveChildCwd(cwd ?? ctx.cwd, step.cwd);
|
|
610
|
+
let worktreeSetup: WorktreeSetup | undefined;
|
|
611
|
+
if (step.worktree) {
|
|
612
|
+
const worktreeTaskCwdConflict = findWorktreeTaskCwdConflict(step.parallel, parallelCwd);
|
|
613
|
+
if (worktreeTaskCwdConflict) {
|
|
614
|
+
return buildChainExecutionErrorResult(
|
|
615
|
+
`parallel chain step ${stepIndex + 1}: ${formatWorktreeTaskCwdConflict(worktreeTaskCwdConflict, parallelCwd)}`,
|
|
616
|
+
makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex }),
|
|
617
|
+
);
|
|
618
|
+
}
|
|
619
|
+
try {
|
|
620
|
+
worktreeSetup = createWorktrees(parallelCwd, `${runId}-s${stepIndex}`, step.parallel.length, {
|
|
621
|
+
agents: step.parallel.map((task) => task.agent),
|
|
622
|
+
setupHook: params.worktreeSetupHook
|
|
623
|
+
? { hookPath: params.worktreeSetupHook, timeoutMs: params.worktreeSetupHookTimeoutMs }
|
|
624
|
+
: undefined,
|
|
625
|
+
});
|
|
626
|
+
} catch (error) {
|
|
627
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
628
|
+
return buildChainExecutionErrorResult(message, makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex }));
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
try {
|
|
633
|
+
const agentNames = step.parallel.map((task) => task.agent);
|
|
634
|
+
const parallelBehaviors = resolveParallelBehaviors(step.parallel, agents, stepIndex, chainSkills)
|
|
635
|
+
.map((behavior, taskIndex) => suppressProgressForReadOnlyTask(behavior, parallelTemplates[taskIndex] ?? step.parallel[taskIndex]?.task, originalTask));
|
|
636
|
+
for (let taskIndex = 0; taskIndex < step.parallel.length; taskIndex++) {
|
|
637
|
+
const behavior = parallelBehaviors[taskIndex]!;
|
|
638
|
+
const outputPath = typeof behavior.output === "string"
|
|
639
|
+
? (path.isAbsolute(behavior.output) ? behavior.output : path.join(chainDir, behavior.output))
|
|
640
|
+
: undefined;
|
|
641
|
+
const validationError = validateFileOnlyOutputMode(behavior.outputMode, outputPath, `Parallel chain step ${stepIndex + 1} task ${taskIndex + 1} (${step.parallel[taskIndex]!.agent})`);
|
|
642
|
+
if (validationError) return buildChainExecutionErrorResult(validationError, makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex + taskIndex }));
|
|
643
|
+
}
|
|
644
|
+
progressCreated = ensureParallelProgressFile(chainDir, progressCreated, parallelBehaviors);
|
|
645
|
+
createParallelDirs(chainDir, stepIndex, step.parallel.length, agentNames);
|
|
646
|
+
|
|
647
|
+
const parallelResults = await runParallelChainTasks({
|
|
648
|
+
step,
|
|
649
|
+
parallelTemplates,
|
|
650
|
+
parallelBehaviors,
|
|
651
|
+
agents,
|
|
652
|
+
stepIndex,
|
|
653
|
+
availableModels,
|
|
654
|
+
chainDir,
|
|
655
|
+
prev,
|
|
656
|
+
originalTask,
|
|
657
|
+
ctx,
|
|
658
|
+
intercomEvents,
|
|
659
|
+
cwd,
|
|
660
|
+
runId,
|
|
661
|
+
globalTaskIndex,
|
|
662
|
+
sessionDirForIndex,
|
|
663
|
+
sessionFileForIndex,
|
|
664
|
+
sessionFileForTask,
|
|
665
|
+
shareEnabled,
|
|
666
|
+
artifactConfig,
|
|
667
|
+
artifactsDir,
|
|
668
|
+
signal,
|
|
669
|
+
onUpdate,
|
|
670
|
+
results,
|
|
671
|
+
allProgress,
|
|
672
|
+
outputs,
|
|
673
|
+
chainAgents,
|
|
674
|
+
chainSteps,
|
|
675
|
+
totalSteps,
|
|
676
|
+
dynamicChildren,
|
|
677
|
+
dynamicGroupStatuses,
|
|
678
|
+
controlConfig,
|
|
679
|
+
onControlEvent,
|
|
680
|
+
childIntercomTarget,
|
|
681
|
+
orchestratorIntercomTarget,
|
|
682
|
+
foregroundControl,
|
|
683
|
+
nestedRoute: params.nestedRoute,
|
|
684
|
+
worktreeSetup,
|
|
685
|
+
maxSubagentDepth: params.maxSubagentDepth,
|
|
686
|
+
timeoutMs: params.timeoutMs,
|
|
687
|
+
deadlineAt,
|
|
688
|
+
});
|
|
689
|
+
globalTaskIndex += step.parallel.length;
|
|
690
|
+
|
|
691
|
+
for (const result of parallelResults) {
|
|
692
|
+
results.push(result);
|
|
693
|
+
if (result.progress) allProgress.push(result.progress);
|
|
694
|
+
if (result.artifactPaths) allArtifactPaths.push(result.artifactPaths);
|
|
695
|
+
}
|
|
696
|
+
const interruptedIndexInStep = parallelResults.findIndex((result) => result.interrupted);
|
|
697
|
+
const interrupted = interruptedIndexInStep >= 0 ? parallelResults[interruptedIndexInStep] : undefined;
|
|
698
|
+
if (interrupted) {
|
|
699
|
+
return {
|
|
700
|
+
content: [{ type: "text", text: `Chain paused after interrupt at step ${stepIndex + 1} (${interrupted.agent}). Waiting for explicit next action.` }],
|
|
701
|
+
details: buildChainExecutionDetails(makeDetailsInput({
|
|
702
|
+
currentStepIndex: stepIndex,
|
|
703
|
+
currentFlatIndex: globalTaskIndex - step.parallel.length + interruptedIndexInStep,
|
|
704
|
+
})),
|
|
705
|
+
};
|
|
706
|
+
}
|
|
707
|
+
const detachedIndexInStep = parallelResults.findIndex((result) => result.detached);
|
|
708
|
+
const detached = detachedIndexInStep >= 0 ? parallelResults[detachedIndexInStep] : undefined;
|
|
709
|
+
if (detached) {
|
|
710
|
+
return {
|
|
711
|
+
content: [{ type: "text", text: `Chain detached for intercom coordination at step ${stepIndex + 1} (${detached.agent}). Reply to the supervisor request first. After the child exits, start a fresh follow-up if needed.` }],
|
|
712
|
+
details: buildChainExecutionDetails(makeDetailsInput({
|
|
713
|
+
currentStepIndex: stepIndex,
|
|
714
|
+
currentFlatIndex: globalTaskIndex - step.parallel.length + detachedIndexInStep,
|
|
715
|
+
})),
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
const failures = parallelResults
|
|
720
|
+
.map((result, originalIndex) => ({ ...result, originalIndex }))
|
|
721
|
+
.filter((result) => result.exitCode !== 0 && result.exitCode !== -1);
|
|
722
|
+
if (failures.length > 0) {
|
|
723
|
+
const failureSummary = failures
|
|
724
|
+
.map((failure) => `- Task ${failure.originalIndex + 1} (${failure.agent}): ${failure.error || "failed"}`)
|
|
725
|
+
.join("\n");
|
|
726
|
+
const errorMsg = `Parallel step ${stepIndex + 1} failed:\n${failureSummary}`;
|
|
727
|
+
const summary = buildChainSummary(chainSteps, results, chainDir, "failed", {
|
|
728
|
+
index: stepIndex,
|
|
729
|
+
error: errorMsg,
|
|
730
|
+
});
|
|
731
|
+
return {
|
|
732
|
+
content: [{ type: "text", text: summary }],
|
|
733
|
+
isError: true,
|
|
734
|
+
details: buildChainExecutionDetails(makeDetailsInput({
|
|
735
|
+
currentStepIndex: stepIndex,
|
|
736
|
+
currentFlatIndex: globalTaskIndex - step.parallel.length + failures[0]!.originalIndex,
|
|
737
|
+
})),
|
|
738
|
+
};
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
for (let taskIndex = 0; taskIndex < parallelResults.length; taskIndex++) {
|
|
742
|
+
const outputName = step.parallel[taskIndex]?.as;
|
|
743
|
+
if (outputName) outputs[outputName] = outputEntryFromResult(parallelResults[taskIndex]!, stepIndex);
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
const taskResults: ParallelTaskResult[] = parallelResults.map((result, i) => {
|
|
747
|
+
const outputTarget = parallelBehaviors[i]?.output;
|
|
748
|
+
const outputTargetPath = typeof outputTarget === "string"
|
|
749
|
+
? (path.isAbsolute(outputTarget) ? outputTarget : path.join(chainDir, outputTarget))
|
|
750
|
+
: undefined;
|
|
751
|
+
return {
|
|
752
|
+
agent: result.agent,
|
|
753
|
+
taskIndex: i,
|
|
754
|
+
output: getSingleResultOutput(result),
|
|
755
|
+
exitCode: result.exitCode,
|
|
756
|
+
error: result.error,
|
|
757
|
+
timedOut: result.timedOut,
|
|
758
|
+
outputTargetPath,
|
|
759
|
+
outputTargetExists: outputTargetPath ? fs.existsSync(outputTargetPath) : undefined,
|
|
760
|
+
};
|
|
761
|
+
});
|
|
762
|
+
prev = aggregateParallelOutputs(taskResults);
|
|
763
|
+
prev = appendParallelWorktreeSummary(
|
|
764
|
+
prev,
|
|
765
|
+
worktreeSetup,
|
|
766
|
+
path.join(chainDir, "worktree-diffs", `step-${stepIndex}`),
|
|
767
|
+
agentNames,
|
|
768
|
+
);
|
|
769
|
+
} finally {
|
|
770
|
+
if (worktreeSetup) cleanupWorktrees(worktreeSetup);
|
|
771
|
+
}
|
|
772
|
+
} else if (isDynamicParallelStep(step)) {
|
|
773
|
+
let materialized: ReturnType<typeof materializeDynamicParallelStep>;
|
|
774
|
+
try {
|
|
775
|
+
materialized = materializeDynamicParallelStep(step, outputs, stepIndex, { maxItems: params.dynamicFanoutMaxItems });
|
|
776
|
+
} catch (error) {
|
|
777
|
+
const message = error instanceof DynamicFanoutError ? error.message : error instanceof Error ? error.message : String(error);
|
|
778
|
+
dynamicGroupStatuses[stepIndex] = { status: "failed", error: message };
|
|
779
|
+
return buildChainExecutionErrorResult(message, makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex }));
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
dynamicChildren[stepIndex] = materialized.items.map((item, itemIndex) => ({
|
|
783
|
+
agent: step.parallel.agent,
|
|
784
|
+
label: materialized.parallel[itemIndex]?.label,
|
|
785
|
+
flatIndex: globalTaskIndex + itemIndex,
|
|
786
|
+
itemKey: item.key,
|
|
787
|
+
structured: Boolean(step.parallel.outputSchema),
|
|
788
|
+
}));
|
|
789
|
+
|
|
790
|
+
if (materialized.parallel.length === 0) {
|
|
791
|
+
const collection: DynamicCollectedResult[] = [];
|
|
792
|
+
try {
|
|
793
|
+
validateDynamicCollection(step.collect.outputSchema, collection);
|
|
794
|
+
} catch (error) {
|
|
795
|
+
const message = error instanceof DynamicFanoutError ? error.message : error instanceof Error ? error.message : String(error);
|
|
796
|
+
dynamicGroupStatuses[stepIndex] = { status: "failed", error: message };
|
|
797
|
+
return buildChainExecutionErrorResult(message, makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex }));
|
|
798
|
+
}
|
|
799
|
+
outputs[step.collect.as] = {
|
|
800
|
+
text: JSON.stringify(collection),
|
|
801
|
+
structured: collection,
|
|
802
|
+
agent: step.parallel.agent,
|
|
803
|
+
stepIndex,
|
|
804
|
+
};
|
|
805
|
+
dynamicGroupStatuses[stepIndex] = { status: "completed" };
|
|
806
|
+
if (step.acceptance !== undefined) {
|
|
807
|
+
const effectiveGroupAcceptance = resolveEffectiveAcceptance({
|
|
808
|
+
explicit: step.acceptance,
|
|
809
|
+
agentName: step.parallel.agent,
|
|
810
|
+
task: step.parallel.task ?? originalTask,
|
|
811
|
+
mode: "chain",
|
|
812
|
+
dynamicGroup: true,
|
|
813
|
+
});
|
|
814
|
+
const groupAcceptance = await evaluateAcceptance({
|
|
815
|
+
acceptance: effectiveGroupAcceptance,
|
|
816
|
+
output: "",
|
|
817
|
+
report: aggregateAcceptanceReport({
|
|
818
|
+
results: [],
|
|
819
|
+
notes: "Dynamic fanout produced 0 results.",
|
|
820
|
+
}),
|
|
821
|
+
cwd: cwd ?? ctx.cwd,
|
|
822
|
+
});
|
|
823
|
+
dynamicGroupStatuses[stepIndex].acceptance = groupAcceptance;
|
|
824
|
+
const groupAcceptanceFailure = acceptanceFailureMessage(groupAcceptance);
|
|
825
|
+
if (groupAcceptanceFailure) {
|
|
826
|
+
dynamicGroupStatuses[stepIndex] = { status: "failed", error: groupAcceptanceFailure, acceptance: groupAcceptance };
|
|
827
|
+
return buildChainExecutionErrorResult(groupAcceptanceFailure, makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex }));
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
prev = "Dynamic fanout produced 0 results.";
|
|
831
|
+
continue;
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
const dynamicParallelStep: ParallelStep = {
|
|
835
|
+
parallel: materialized.parallel,
|
|
836
|
+
concurrency: step.concurrency,
|
|
837
|
+
failFast: step.failFast,
|
|
838
|
+
};
|
|
839
|
+
const parallelTemplates = materialized.parallel.map((task) => task.task ?? "{previous}");
|
|
840
|
+
const parallelBehaviors = resolveParallelBehaviors(dynamicParallelStep.parallel, agents, stepIndex, chainSkills)
|
|
841
|
+
.map((behavior, taskIndex) => suppressProgressForReadOnlyTask(behavior, parallelTemplates[taskIndex] ?? dynamicParallelStep.parallel[taskIndex]?.task, originalTask));
|
|
842
|
+
|
|
843
|
+
for (let taskIndex = 0; taskIndex < dynamicParallelStep.parallel.length; taskIndex++) {
|
|
844
|
+
const behavior = parallelBehaviors[taskIndex]!;
|
|
845
|
+
const outputPath = typeof behavior.output === "string"
|
|
846
|
+
? (path.isAbsolute(behavior.output) ? behavior.output : path.join(chainDir, behavior.output))
|
|
847
|
+
: undefined;
|
|
848
|
+
const validationError = validateFileOnlyOutputMode(behavior.outputMode, outputPath, `Dynamic chain step ${stepIndex + 1} item ${taskIndex + 1} (${dynamicParallelStep.parallel[taskIndex]!.agent})`);
|
|
849
|
+
if (validationError) {
|
|
850
|
+
dynamicGroupStatuses[stepIndex] = { status: "failed", error: validationError };
|
|
851
|
+
return buildChainExecutionErrorResult(validationError, makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex + taskIndex }));
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
progressCreated = ensureParallelProgressFile(chainDir, progressCreated, parallelBehaviors);
|
|
856
|
+
createParallelDirs(chainDir, stepIndex, dynamicParallelStep.parallel.length, dynamicParallelStep.parallel.map((task) => task.agent));
|
|
857
|
+
const parallelResults = await runParallelChainTasks({
|
|
858
|
+
step: dynamicParallelStep,
|
|
859
|
+
parallelTemplates,
|
|
860
|
+
parallelBehaviors,
|
|
861
|
+
agents,
|
|
862
|
+
stepIndex,
|
|
863
|
+
availableModels,
|
|
864
|
+
chainDir,
|
|
865
|
+
prev,
|
|
866
|
+
originalTask,
|
|
867
|
+
ctx,
|
|
868
|
+
intercomEvents,
|
|
869
|
+
cwd,
|
|
870
|
+
runId,
|
|
871
|
+
globalTaskIndex,
|
|
872
|
+
sessionDirForIndex,
|
|
873
|
+
sessionFileForIndex,
|
|
874
|
+
sessionFileForTask,
|
|
875
|
+
shareEnabled,
|
|
876
|
+
artifactConfig,
|
|
877
|
+
artifactsDir,
|
|
878
|
+
signal,
|
|
879
|
+
onUpdate,
|
|
880
|
+
results,
|
|
881
|
+
allProgress,
|
|
882
|
+
outputs,
|
|
883
|
+
chainAgents,
|
|
884
|
+
chainSteps,
|
|
885
|
+
totalSteps,
|
|
886
|
+
dynamicChildren,
|
|
887
|
+
dynamicGroupStatuses,
|
|
888
|
+
controlConfig,
|
|
889
|
+
onControlEvent,
|
|
890
|
+
childIntercomTarget,
|
|
891
|
+
orchestratorIntercomTarget,
|
|
892
|
+
foregroundControl,
|
|
893
|
+
nestedRoute: params.nestedRoute,
|
|
894
|
+
maxSubagentDepth: params.maxSubagentDepth,
|
|
895
|
+
timeoutMs: params.timeoutMs,
|
|
896
|
+
deadlineAt,
|
|
897
|
+
});
|
|
898
|
+
globalTaskIndex += dynamicParallelStep.parallel.length;
|
|
899
|
+
|
|
900
|
+
for (const result of parallelResults) {
|
|
901
|
+
results.push(result);
|
|
902
|
+
if (result.progress) allProgress.push(result.progress);
|
|
903
|
+
if (result.artifactPaths) allArtifactPaths.push(result.artifactPaths);
|
|
904
|
+
}
|
|
905
|
+
const collected = collectDynamicResults(step, materialized.items, parallelResults);
|
|
906
|
+
const interruptedIndexInStep = parallelResults.findIndex((result) => result.interrupted);
|
|
907
|
+
const interrupted = interruptedIndexInStep >= 0 ? parallelResults[interruptedIndexInStep] : undefined;
|
|
908
|
+
if (interrupted) {
|
|
909
|
+
return {
|
|
910
|
+
content: [{ type: "text", text: `Chain paused after interrupt at step ${stepIndex + 1} (${interrupted.agent}). Waiting for explicit next action.` }],
|
|
911
|
+
details: buildChainExecutionDetails(makeDetailsInput({
|
|
912
|
+
currentStepIndex: stepIndex,
|
|
913
|
+
currentFlatIndex: globalTaskIndex - dynamicParallelStep.parallel.length + interruptedIndexInStep,
|
|
914
|
+
})),
|
|
915
|
+
};
|
|
916
|
+
}
|
|
917
|
+
const detachedIndexInStep = parallelResults.findIndex((result) => result.detached);
|
|
918
|
+
const detached = detachedIndexInStep >= 0 ? parallelResults[detachedIndexInStep] : undefined;
|
|
919
|
+
if (detached) {
|
|
920
|
+
return {
|
|
921
|
+
content: [{ type: "text", text: `Chain detached for intercom coordination at step ${stepIndex + 1} (${detached.agent}). Reply to the supervisor request first. After the child exits, start a fresh follow-up if needed.` }],
|
|
922
|
+
details: buildChainExecutionDetails(makeDetailsInput({
|
|
923
|
+
currentStepIndex: stepIndex,
|
|
924
|
+
currentFlatIndex: globalTaskIndex - dynamicParallelStep.parallel.length + detachedIndexInStep,
|
|
925
|
+
})),
|
|
926
|
+
};
|
|
927
|
+
}
|
|
928
|
+
const failures = parallelResults
|
|
929
|
+
.map((result, originalIndex) => ({ ...result, originalIndex }))
|
|
930
|
+
.filter((result) => result.exitCode !== 0 && result.exitCode !== -1);
|
|
931
|
+
if (failures.length > 0) {
|
|
932
|
+
const failureSummary = failures
|
|
933
|
+
.map((failure) => `- Item ${failure.originalIndex + 1} (${failure.agent}, key ${materialized.items[failure.originalIndex]?.key ?? failure.originalIndex}): ${failure.error || "failed"}`)
|
|
934
|
+
.join("\n");
|
|
935
|
+
const errorMsg = `Dynamic step ${stepIndex + 1} failed:\n${failureSummary}`;
|
|
936
|
+
dynamicGroupStatuses[stepIndex] = { status: "failed", error: errorMsg };
|
|
937
|
+
const summary = buildChainSummary(chainSteps, results, chainDir, "failed", {
|
|
938
|
+
index: stepIndex,
|
|
939
|
+
error: errorMsg,
|
|
940
|
+
});
|
|
941
|
+
return {
|
|
942
|
+
content: [{ type: "text", text: summary }],
|
|
943
|
+
isError: true,
|
|
944
|
+
details: buildChainExecutionDetails(makeDetailsInput({
|
|
945
|
+
currentStepIndex: stepIndex,
|
|
946
|
+
currentFlatIndex: globalTaskIndex - dynamicParallelStep.parallel.length + failures[0]!.originalIndex,
|
|
947
|
+
})),
|
|
948
|
+
};
|
|
949
|
+
}
|
|
950
|
+
try {
|
|
951
|
+
validateDynamicCollection(step.collect.outputSchema, collected);
|
|
952
|
+
} catch (error) {
|
|
953
|
+
const message = error instanceof DynamicFanoutError ? error.message : error instanceof Error ? error.message : String(error);
|
|
954
|
+
dynamicGroupStatuses[stepIndex] = { status: "failed", error: message };
|
|
955
|
+
return buildChainExecutionErrorResult(message, makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex - dynamicParallelStep.parallel.length }));
|
|
956
|
+
}
|
|
957
|
+
outputs[step.collect.as] = {
|
|
958
|
+
text: JSON.stringify(collected),
|
|
959
|
+
structured: collected,
|
|
960
|
+
agent: step.parallel.agent,
|
|
961
|
+
stepIndex,
|
|
962
|
+
};
|
|
963
|
+
dynamicGroupStatuses[stepIndex] = { status: "completed" };
|
|
964
|
+
const effectiveGroupAcceptance = resolveEffectiveAcceptance({
|
|
965
|
+
explicit: step.acceptance,
|
|
966
|
+
agentName: step.parallel.agent,
|
|
967
|
+
task: step.parallel.task ?? originalTask,
|
|
968
|
+
mode: "chain",
|
|
969
|
+
dynamicGroup: true,
|
|
970
|
+
});
|
|
971
|
+
const groupAcceptance = await evaluateAcceptance({
|
|
972
|
+
acceptance: effectiveGroupAcceptance,
|
|
973
|
+
output: "",
|
|
974
|
+
report: aggregateAcceptanceReport({
|
|
975
|
+
results: parallelResults,
|
|
976
|
+
notes: `Dynamic fanout collected ${collected.length} result(s) into ${step.collect.as}.`,
|
|
977
|
+
}),
|
|
978
|
+
cwd: cwd ?? ctx.cwd,
|
|
979
|
+
});
|
|
980
|
+
dynamicGroupStatuses[stepIndex].acceptance = groupAcceptance;
|
|
981
|
+
const groupAcceptanceFailure = acceptanceFailureMessage(groupAcceptance);
|
|
982
|
+
if (groupAcceptanceFailure) {
|
|
983
|
+
dynamicGroupStatuses[stepIndex] = { status: "failed", error: groupAcceptanceFailure, acceptance: groupAcceptance };
|
|
984
|
+
return buildChainExecutionErrorResult(groupAcceptanceFailure, makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex - dynamicParallelStep.parallel.length }));
|
|
985
|
+
}
|
|
986
|
+
const taskResults: ParallelTaskResult[] = parallelResults.map((result, i) => ({
|
|
987
|
+
agent: result.agent,
|
|
988
|
+
taskIndex: i,
|
|
989
|
+
output: getSingleResultOutput(result),
|
|
990
|
+
exitCode: result.exitCode,
|
|
991
|
+
error: result.error,
|
|
992
|
+
timedOut: result.timedOut,
|
|
993
|
+
}));
|
|
994
|
+
prev = aggregateParallelOutputs(taskResults, (i, agent) => `=== Dynamic Item ${i + 1} (${agent}, key ${materialized.items[i]?.key ?? i}) ===`);
|
|
995
|
+
} else {
|
|
996
|
+
const seqStep = step as SequentialStep;
|
|
997
|
+
const stepTemplate = stepTemplates as string;
|
|
998
|
+
|
|
999
|
+
const agentConfig = agents.find((a) => a.name === seqStep.agent);
|
|
1000
|
+
if (!agentConfig) {
|
|
1001
|
+
removeChainDir(chainDir);
|
|
1002
|
+
return {
|
|
1003
|
+
content: [{ type: "text", text: `Unknown agent: ${seqStep.agent}` }],
|
|
1004
|
+
isError: true,
|
|
1005
|
+
details: buildChainExecutionDetails(makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex })),
|
|
1006
|
+
};
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
const tuiOverride = tuiBehaviorOverrides?.[stepIndex];
|
|
1010
|
+
const stepOverride: StepOverrides = {
|
|
1011
|
+
output: tuiOverride?.output !== undefined ? tuiOverride.output : seqStep.output,
|
|
1012
|
+
outputMode: seqStep.outputMode,
|
|
1013
|
+
reads: tuiOverride?.reads !== undefined ? tuiOverride.reads : seqStep.reads,
|
|
1014
|
+
progress: tuiOverride?.progress !== undefined ? tuiOverride.progress : seqStep.progress,
|
|
1015
|
+
skills:
|
|
1016
|
+
tuiOverride?.skills !== undefined
|
|
1017
|
+
? tuiOverride.skills
|
|
1018
|
+
: normalizeSkillInput(seqStep.skill),
|
|
1019
|
+
};
|
|
1020
|
+
const behavior = suppressProgressForReadOnlyTask(resolveStepBehavior(agentConfig, stepOverride, chainSkills), stepTemplate, originalTask);
|
|
1021
|
+
|
|
1022
|
+
const isFirstProgress = behavior.progress && !progressCreated;
|
|
1023
|
+
if (isFirstProgress) {
|
|
1024
|
+
progressCreated = true;
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
const templateHasPrevious = stepTemplate.includes("{previous}");
|
|
1028
|
+
const { prefix, suffix } = buildChainInstructions(
|
|
1029
|
+
behavior,
|
|
1030
|
+
chainDir,
|
|
1031
|
+
isFirstProgress,
|
|
1032
|
+
templateHasPrevious ? undefined : prev,
|
|
1033
|
+
);
|
|
1034
|
+
|
|
1035
|
+
let stepTask = resolveOutputReferences(stepTemplate, outputs);
|
|
1036
|
+
stepTask = stepTask.replace(/\{task\}/g, originalTask);
|
|
1037
|
+
stepTask = stepTask.replace(/\{previous\}/g, prev);
|
|
1038
|
+
stepTask = stepTask.replace(/\{chain_dir\}/g, chainDir);
|
|
1039
|
+
const cleanTask = stepTask;
|
|
1040
|
+
stepTask = prefix + stepTask + suffix;
|
|
1041
|
+
|
|
1042
|
+
const effectiveModel = tuiOverride?.model
|
|
1043
|
+
?? resolveSubagentModelOverride(
|
|
1044
|
+
seqStep.model ?? agentConfig.model,
|
|
1045
|
+
ctx.model,
|
|
1046
|
+
availableModels,
|
|
1047
|
+
ctx.model?.provider,
|
|
1048
|
+
);
|
|
1049
|
+
|
|
1050
|
+
const outputPath = typeof behavior.output === "string"
|
|
1051
|
+
? (path.isAbsolute(behavior.output) ? behavior.output : path.join(chainDir, behavior.output))
|
|
1052
|
+
: undefined;
|
|
1053
|
+
const validationError = validateFileOnlyOutputMode(behavior.outputMode, outputPath, `Chain step ${stepIndex + 1} (${seqStep.agent})`);
|
|
1054
|
+
if (validationError) {
|
|
1055
|
+
return buildChainExecutionErrorResult(validationError, makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex }));
|
|
1056
|
+
}
|
|
1057
|
+
const maxSubagentDepth = resolveChildMaxSubagentDepth(params.maxSubagentDepth, agentConfig.maxSubagentDepth);
|
|
1058
|
+
const interruptController = new AbortController();
|
|
1059
|
+
if (foregroundControl) {
|
|
1060
|
+
foregroundControl.currentAgent = seqStep.agent;
|
|
1061
|
+
foregroundControl.currentIndex = globalTaskIndex;
|
|
1062
|
+
foregroundControl.currentActivityState = undefined;
|
|
1063
|
+
foregroundControl.updatedAt = Date.now();
|
|
1064
|
+
foregroundControl.interrupt = () => {
|
|
1065
|
+
if (interruptController.signal.aborted) return false;
|
|
1066
|
+
interruptController.abort();
|
|
1067
|
+
foregroundControl.currentActivityState = undefined;
|
|
1068
|
+
foregroundControl.updatedAt = Date.now();
|
|
1069
|
+
return true;
|
|
1070
|
+
};
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
const structuredRuntime = seqStep.outputSchema
|
|
1074
|
+
? createStructuredOutputRuntime(seqStep.outputSchema, path.join(chainDir, "structured-output"))
|
|
1075
|
+
: undefined;
|
|
1076
|
+
const r = await runSync(ctx.cwd, agents, seqStep.agent, stepTask, {
|
|
1077
|
+
parentSessionId: ctx.sessionManager.getSessionId() ?? undefined,
|
|
1078
|
+
cwd: resolveChildCwd(cwd ?? ctx.cwd, seqStep.cwd),
|
|
1079
|
+
signal,
|
|
1080
|
+
interruptSignal: interruptController.signal,
|
|
1081
|
+
allowIntercomDetach: agentConfig.systemPrompt?.includes(INTERCOM_BRIDGE_MARKER) === true,
|
|
1082
|
+
intercomEvents,
|
|
1083
|
+
runId,
|
|
1084
|
+
index: globalTaskIndex,
|
|
1085
|
+
sessionDir: sessionDirForIndex(globalTaskIndex),
|
|
1086
|
+
sessionFile: sessionFileForTask?.(seqStep.agent, globalTaskIndex)
|
|
1087
|
+
?? sessionFileForIndex?.(globalTaskIndex),
|
|
1088
|
+
share: shareEnabled,
|
|
1089
|
+
artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
|
|
1090
|
+
artifactConfig,
|
|
1091
|
+
outputPath,
|
|
1092
|
+
outputMode: behavior.outputMode,
|
|
1093
|
+
maxSubagentDepth,
|
|
1094
|
+
controlConfig,
|
|
1095
|
+
onControlEvent,
|
|
1096
|
+
intercomSessionName: childIntercomTarget?.(seqStep.agent, globalTaskIndex),
|
|
1097
|
+
orchestratorIntercomTarget,
|
|
1098
|
+
nestedRoute: params.nestedRoute,
|
|
1099
|
+
modelOverride: effectiveModel,
|
|
1100
|
+
availableModels,
|
|
1101
|
+
preferredModelProvider: ctx.model?.provider,
|
|
1102
|
+
skills: behavior.skills === false ? [] : behavior.skills,
|
|
1103
|
+
structuredOutput: structuredRuntime,
|
|
1104
|
+
acceptance: seqStep.acceptance,
|
|
1105
|
+
acceptanceContext: { mode: "chain" },
|
|
1106
|
+
timeoutMs: params.timeoutMs,
|
|
1107
|
+
deadlineAt,
|
|
1108
|
+
onUpdate: onUpdate
|
|
1109
|
+
? (p) => {
|
|
1110
|
+
const stepResults = p.details?.results || [];
|
|
1111
|
+
const stepProgress = p.details?.progress || [];
|
|
1112
|
+
if (foregroundControl && stepProgress.length > 0) {
|
|
1113
|
+
const current = stepProgress[0];
|
|
1114
|
+
foregroundControl.currentAgent = seqStep.agent;
|
|
1115
|
+
foregroundControl.currentIndex = globalTaskIndex;
|
|
1116
|
+
foregroundControl.currentActivityState = current?.activityState;
|
|
1117
|
+
foregroundControl.lastActivityAt = current?.lastActivityAt;
|
|
1118
|
+
foregroundControl.currentTool = current?.currentTool;
|
|
1119
|
+
foregroundControl.currentToolStartedAt = current?.currentToolStartedAt;
|
|
1120
|
+
foregroundControl.currentPath = current?.currentPath;
|
|
1121
|
+
foregroundControl.turnCount = current?.turnCount;
|
|
1122
|
+
foregroundControl.tokens = current?.tokens;
|
|
1123
|
+
foregroundControl.toolCount = current?.toolCount;
|
|
1124
|
+
foregroundControl.updatedAt = Date.now();
|
|
1125
|
+
}
|
|
1126
|
+
onUpdate({
|
|
1127
|
+
...p,
|
|
1128
|
+
details: {
|
|
1129
|
+
mode: "chain",
|
|
1130
|
+
results: results.concat(stepResults),
|
|
1131
|
+
progress: allProgress.concat(stepProgress),
|
|
1132
|
+
controlEvents: p.details?.controlEvents,
|
|
1133
|
+
chainAgents,
|
|
1134
|
+
totalSteps,
|
|
1135
|
+
currentStepIndex: stepIndex,
|
|
1136
|
+
outputs,
|
|
1137
|
+
workflowGraph: buildWorkflowGraphSnapshot({
|
|
1138
|
+
runId,
|
|
1139
|
+
mode: "chain",
|
|
1140
|
+
steps: chainSteps,
|
|
1141
|
+
results: results.concat(stepResults),
|
|
1142
|
+
currentStepIndex: stepIndex,
|
|
1143
|
+
currentFlatIndex: globalTaskIndex,
|
|
1144
|
+
dynamicChildren,
|
|
1145
|
+
dynamicGroupStatuses,
|
|
1146
|
+
}),
|
|
1147
|
+
},
|
|
1148
|
+
});
|
|
1149
|
+
}
|
|
1150
|
+
: undefined,
|
|
1151
|
+
});
|
|
1152
|
+
if (foregroundControl?.currentIndex === globalTaskIndex) {
|
|
1153
|
+
foregroundControl.interrupt = undefined;
|
|
1154
|
+
foregroundControl.updatedAt = Date.now();
|
|
1155
|
+
}
|
|
1156
|
+
recordRun(seqStep.agent, cleanTask, r.exitCode, r.progressSummary?.durationMs ?? 0);
|
|
1157
|
+
|
|
1158
|
+
globalTaskIndex++;
|
|
1159
|
+
results.push(r);
|
|
1160
|
+
if (r.progress) allProgress.push(r.progress);
|
|
1161
|
+
if (r.artifactPaths) allArtifactPaths.push(r.artifactPaths);
|
|
1162
|
+
|
|
1163
|
+
if (r.interrupted) {
|
|
1164
|
+
return {
|
|
1165
|
+
content: [{ type: "text", text: `Chain paused after interrupt at step ${stepIndex + 1} (${r.agent}). Waiting for explicit next action.` }],
|
|
1166
|
+
details: buildChainExecutionDetails(makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex - 1 })),
|
|
1167
|
+
};
|
|
1168
|
+
}
|
|
1169
|
+
if (r.detached) {
|
|
1170
|
+
return {
|
|
1171
|
+
content: [{ type: "text", text: `Chain detached for intercom coordination at step ${stepIndex + 1} (${r.agent}). Reply to the supervisor request first. After the child exits, start a fresh follow-up if needed.` }],
|
|
1172
|
+
details: buildChainExecutionDetails(makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex - 1 })),
|
|
1173
|
+
};
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
if (r.exitCode !== 0) {
|
|
1177
|
+
const summary = buildChainSummary(chainSteps, results, chainDir, "failed", {
|
|
1178
|
+
index: stepIndex,
|
|
1179
|
+
error: r.error || "Chain failed",
|
|
1180
|
+
});
|
|
1181
|
+
return {
|
|
1182
|
+
content: [{ type: "text", text: summary }],
|
|
1183
|
+
details: buildChainExecutionDetails(makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex - 1 })),
|
|
1184
|
+
isError: true,
|
|
1185
|
+
};
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
if (behavior.output) {
|
|
1189
|
+
try {
|
|
1190
|
+
const expectedPath = path.isAbsolute(behavior.output)
|
|
1191
|
+
? behavior.output
|
|
1192
|
+
: path.join(chainDir, behavior.output);
|
|
1193
|
+
if (!fs.existsSync(expectedPath)) {
|
|
1194
|
+
const dirFiles = fs.readdirSync(chainDir);
|
|
1195
|
+
const mdFiles = dirFiles.filter((file) => file.endsWith(".md") && file !== "progress.md");
|
|
1196
|
+
const warning = mdFiles.length > 0
|
|
1197
|
+
? `Agent wrote to different file(s): ${mdFiles.join(", ")} instead of ${behavior.output}`
|
|
1198
|
+
: `Agent did not create expected output file: ${behavior.output}`;
|
|
1199
|
+
r.error = r.error ? `${r.error}\n${warning}` : warning;
|
|
1200
|
+
}
|
|
1201
|
+
} catch {
|
|
1202
|
+
// Ignore validation errors; this diagnostic should not mask successful chain output.
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
if (seqStep.as) outputs[seqStep.as] = outputEntryFromResult(r, stepIndex);
|
|
1207
|
+
prev = getSingleResultOutput(r);
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
const summary = buildChainSummary(chainSteps, results, chainDir, "completed");
|
|
1212
|
+
|
|
1213
|
+
return {
|
|
1214
|
+
content: [{ type: "text", text: summary }],
|
|
1215
|
+
details: buildChainExecutionDetails(makeDetailsInput()),
|
|
1216
|
+
};
|
|
1217
|
+
}
|