@ashx-j/lunr-dev 0.2.40-dev.54.2 → 0.2.40-dev.55.1
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/builtin-extensions/pi-subagents/src/runs/foreground/async-run-control.d.ts +19 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/async-run-control.js +331 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution-input.d.ts +37 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution-input.js +321 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/executor-types.d.ts +124 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/executor-types.js +2 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/foreground-notifications.d.ts +17 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/foreground-notifications.js +98 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/foreground-run-registry.d.ts +40 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/foreground-run-registry.js +172 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/fork-policy.d.ts +14 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/fork-policy.js +161 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/nested-run-control.d.ts +46 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/nested-run-control.js +195 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/parallel-run.d.ts +10 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/parallel-run.js +537 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.d.ts +5 -81
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js +26 -1763
- package/dist/builtin-extensions/pi-subagents/src/shared/settings.d.ts +1 -1
- package/dist/node-runtime/{builtin-extensions-VQHK3YKF.js → builtin-extensions-YJ7F6GND.js} +1 -1
- package/dist/node-runtime/{chunk-YDY7A2WB.js → chunk-3UQ7ZNLI.js} +2 -2
- package/dist/node-runtime/{chunk-UZMXBZQT.js → chunk-5HVA5ECB.js} +3 -3
- package/dist/node-runtime/{chunk-VIYDTWDK.js → chunk-CDILDA4F.js} +604 -602
- package/dist/node-runtime/{chunk-MFDTF25H.js → chunk-G3PARFR4.js} +2 -2
- package/dist/node-runtime/{command-SRDEBPUR.js → command-H52R5R2G.js} +1 -1
- package/dist/node-runtime/{gateway-AMEMDTUT.js → gateway-OHPDCOOB.js} +1 -1
- package/dist/node-runtime/index.js +2 -2
- package/dist/node-runtime/{lunr-cron-OMQBN3UK.js → lunr-cron-SV2EXYKV.js} +1 -1
- package/dist/node-runtime/main.js +2 -2
- package/dist/node-runtime/{pi-subagents-36KOL5SV.js → pi-subagents-WS6OU5MG.js} +2 -2
- package/dist/node-runtime/rpc-entry.js +2 -2
- package/dist/node-runtime/{subagent-executor-D42G55F5.js → subagent-executor-LPVOWPMG.js} +1920 -1897
- package/install-lock/package-lock.json +24 -24
- package/install-lock/package.json +2 -2
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
|
@@ -16,95 +16,40 @@ import { clearPendingForegroundControlNotices } from "../../extension/control-no
|
|
|
16
16
|
import { runSync } from "./execution.js";
|
|
17
17
|
import { handleWatchdogToolAction, WATCHDOG_TOOL_ACTIONS } from "../../watchdog/tool-actions.js";
|
|
18
18
|
import { buildModelCandidates, captureModelSelection, resolveEffectiveSubagentModel, resolveExecutableChildModel } from "../shared/model-fallback.js";
|
|
19
|
-
import { aggregateParallelOutputs } from "../shared/parallel-utils.js";
|
|
20
19
|
import { recordRun } from "../shared/run-history.js";
|
|
21
|
-
import {
|
|
20
|
+
import { getStepAgents, isParallelStep, isDynamicParallelStep, resolveStepBehavior, } from "../../shared/settings.js";
|
|
22
21
|
import { discoverAvailableSkills, normalizeSkillInput } from "../../agents/skills.js";
|
|
23
|
-
import {
|
|
24
|
-
import { enqueueChainAppendRequest, readPendingChainAppendRequests, runnerStepOutputNames } from "../background/chain-append.js";
|
|
25
|
-
import { ChainOutputValidationError, validateChainOutputBindingsWithContext } from "../shared/chain-outputs.js";
|
|
22
|
+
import { executeAsyncChain, executeAsyncSingle, formatAsyncStartedMessage, isAsyncAvailable } from "../background/async-execution.js";
|
|
26
23
|
import { restorePersistedAcceptance, validateExecutionAcceptance } from "../shared/acceptance.js";
|
|
27
24
|
import { createForkContextResolver, forkedChildRequiresThinkingOff } from "../../shared/fork-context.js";
|
|
28
|
-
import { lunrContextPolicy } from "../../shared/lunr-child-context.js";
|
|
29
25
|
import { resolveCurrentSessionId } from "../../shared/session-identity.js";
|
|
30
|
-
import { applyIntercomBridgeToAgent,
|
|
31
|
-
import {
|
|
26
|
+
import { applyIntercomBridgeToAgent, resolveIntercomBridge, resolveIntercomSessionTarget, resolveSubagentIntercomTarget } from "../../intercom/intercom-bridge.js";
|
|
27
|
+
import { resolveControlConfig } from "../shared/subagent-control.js";
|
|
32
28
|
import { resolveTurnBudgetConfig } from "../shared/turn-budget.js";
|
|
33
|
-
import { validateToolBudgetConfig } from "../shared/tool-budget.js";
|
|
34
29
|
import { finalizeSingleOutput, injectSingleOutputInstruction, normalizeSingleOutputOverride, outputTargetError, readOnlyOutputError, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.js";
|
|
35
|
-
import { compactForegroundDetails, getSingleResultOutput,
|
|
36
|
-
import {
|
|
37
|
-
import { attachNestedChildrenToResultChildren, buildSubagentResultIntercomPayload, deliverSubagentIntercomMessageEvent, deliverSubagentResultIntercomEvent, formatSubagentResultReceipt, resolveSubagentResultStatus, stripDetailsOutputsForIntercomReceipt, } from "../../intercom/result-intercom.js";
|
|
30
|
+
import { compactForegroundDetails, getSingleResultOutput, readStatus, resolveChildCwd, sumResultsCost, sumResultsUsage } from "../../shared/utils.js";
|
|
31
|
+
import { deliverSubagentIntercomMessageEvent, } from "../../intercom/result-intercom.js";
|
|
38
32
|
import { buildRevivedAsyncTask, interruptLiveAsyncResumeTarget, resolveAsyncResumeTarget, resolveAsyncRunLocation } from "../background/async-resume.js";
|
|
39
|
-
import {
|
|
40
|
-
import { remainingSteeringRecoveryLimits, waitForSteeringAction } from "../background/steering.js";
|
|
33
|
+
import { remainingSteeringRecoveryLimits } from "../background/steering.js";
|
|
41
34
|
import { steerAsyncRun } from "./async-steering-action.js";
|
|
42
|
-
import { reconcileAsyncRun } from "../background/stale-run-reconciler.js";
|
|
43
35
|
import { resolveAsyncRootResultPath } from "../background/chain-root-attachment.js";
|
|
44
|
-
import { attachRootChildrenToSteps, createNestedRoute,
|
|
36
|
+
import { attachRootChildrenToSteps, createNestedRoute, resolveInheritedNestedRouteFromEnv, resolveNestedParentAddressFromEnv, updateForegroundNestedProjection, writeNestedEvent } from "../shared/nested-events.js";
|
|
45
37
|
import { resolveSubagentRunId } from "../background/run-id-resolver.js";
|
|
46
|
-
import { formatNestedRunStatusLines } from "../shared/nested-render.js";
|
|
47
38
|
import { inspectSubagentStatus } from "../background/run-status.js";
|
|
48
39
|
import { subagentLaunchRunsAsync } from "../background/top-level-async.js";
|
|
49
|
-
import {
|
|
50
|
-
import { ASYNC_DIR, DEFAULT_ARTIFACT_CONFIG, DEFAULT_FORK_PREAMBLE, RESULTS_DIR, SUBAGENT_ACTIONS,
|
|
40
|
+
import { findWorktreeTaskCwdConflict, formatWorktreeTaskCwdConflict, } from "../shared/worktree.js";
|
|
41
|
+
import { ASYNC_DIR, DEFAULT_ARTIFACT_CONFIG, DEFAULT_FORK_PREAMBLE, RESULTS_DIR, SUBAGENT_ACTIONS, checkSubagentDepth, resolveMaxSubagentSpawnsPerSession, resolveTopLevelParallelConcurrency, resolveTopLevelParallelMaxTasks, resolveChildMaxSubagentDepth, resolveCurrentMaxSubagentDepth, wrapForkTask, } from "../../shared/types.js";
|
|
42
|
+
import { appendStepToAsyncChain, stopAsyncRun, interruptAsyncRun } from "./async-run-control.js";
|
|
43
|
+
import { resolveToolBudget, resolveEffectiveToolBudget, toExecutionErrorResult, normalizeRepeatedParallelCounts, buildRequestedModeError, internalizePromptDrivenChildren, resolveForegroundTimeout, validateExecutionInput, validateExecutionChainBindings } from "./execution-input.js";
|
|
44
|
+
import { createForegroundControlNotifier, maybeBuildForegroundIntercomReceipt } from "./foreground-notifications.js";
|
|
45
|
+
import { updateRememberedForegroundChild, rememberForegroundRun, getForegroundControl, foregroundStatusResult } from "./foreground-run-registry.js";
|
|
46
|
+
import { resolveExplicitContextPolicy, wrapChainTasksForFork, shouldForkAgent, collectChainSessionFiles, collectChainThinkingOverrides, resolveAgentDefaultContextPolicy, preflightForkSessionsForStaticTasks, withForkContext, withForkThinkingNotes } from "./fork-policy.js";
|
|
47
|
+
import { nestedResolutionScopeForExecutor, resumeLiveNestedRun, resolveNestedResumeTarget, steerNestedRun, interruptNestedRun } from "./nested-run-control.js";
|
|
48
|
+
import { buildParallelModeError, buildParallelWorktreeTaskCwdError, runParallelPath } from "./parallel-run.js";
|
|
51
49
|
const MUTATING_MANAGEMENT_ACTIONS = new Set(["create", "update", "delete", "eject", "disable", "enable", "reset"]);
|
|
52
50
|
function resolveRequestedCwd(runtimeCwd, requestedCwd) {
|
|
53
51
|
return requestedCwd ? path.resolve(runtimeCwd, requestedCwd) : runtimeCwd;
|
|
54
52
|
}
|
|
55
|
-
function getForegroundControl(state, runId) {
|
|
56
|
-
if (runId)
|
|
57
|
-
return state.foregroundControls.get(runId);
|
|
58
|
-
if (state.lastForegroundControlId) {
|
|
59
|
-
const latest = state.foregroundControls.get(state.lastForegroundControlId);
|
|
60
|
-
if (latest)
|
|
61
|
-
return latest;
|
|
62
|
-
}
|
|
63
|
-
let newest;
|
|
64
|
-
for (const control of state.foregroundControls.values()) {
|
|
65
|
-
if (!newest || control.updatedAt > newest.updatedAt)
|
|
66
|
-
newest = control;
|
|
67
|
-
}
|
|
68
|
-
return newest;
|
|
69
|
-
}
|
|
70
|
-
function formatForegroundActivity(control) {
|
|
71
|
-
const facts = [];
|
|
72
|
-
if (control.currentTool && control.currentToolStartedAt)
|
|
73
|
-
facts.push(`tool ${control.currentTool} for ${Math.floor(Math.max(0, Date.now() - control.currentToolStartedAt) / 1000)}s`);
|
|
74
|
-
else if (control.currentTool)
|
|
75
|
-
facts.push(`tool ${control.currentTool}`);
|
|
76
|
-
if (control.currentPath)
|
|
77
|
-
facts.push(`path ${control.currentPath}`);
|
|
78
|
-
if (control.turnCount !== undefined)
|
|
79
|
-
facts.push(`${control.turnCount} turns`);
|
|
80
|
-
if (control.tokens !== undefined)
|
|
81
|
-
facts.push(`${control.tokens} tokens`);
|
|
82
|
-
if (control.toolCount !== undefined)
|
|
83
|
-
facts.push(`${control.toolCount} tools`);
|
|
84
|
-
if (!control.lastActivityAt) {
|
|
85
|
-
if (control.currentActivityState === "needs_attention")
|
|
86
|
-
return ["needs attention", ...facts].join(" | ");
|
|
87
|
-
if (control.currentActivityState === "active_long_running")
|
|
88
|
-
return ["active but long-running", ...facts].join(" | ");
|
|
89
|
-
return facts.length ? facts.join(" | ") : undefined;
|
|
90
|
-
}
|
|
91
|
-
const seconds = Math.floor(Math.max(0, Date.now() - control.lastActivityAt) / 1000);
|
|
92
|
-
if (control.currentActivityState === "needs_attention")
|
|
93
|
-
return [`no activity for ${seconds}s`, ...facts].join(" | ");
|
|
94
|
-
if (control.currentActivityState === "active_long_running")
|
|
95
|
-
return [`active but long-running; last activity ${seconds}s ago`, ...facts].join(" | ");
|
|
96
|
-
return [`active ${seconds}s ago`, ...facts].join(" | ");
|
|
97
|
-
}
|
|
98
|
-
function nestedResolutionScopeForExecutor(deps) {
|
|
99
|
-
if (deps.allowMutatingManagementActions !== false)
|
|
100
|
-
return undefined;
|
|
101
|
-
const route = resolveInheritedNestedRouteFromEnv();
|
|
102
|
-
const address = route ? resolveNestedParentAddressFromEnv() : undefined;
|
|
103
|
-
return {
|
|
104
|
-
routes: route ? [route] : [],
|
|
105
|
-
...(address ? { descendantOf: { parentRunId: address.parentRunId, ...(address.parentStepIndex !== undefined ? { parentStepIndex: address.parentStepIndex } : {}) } } : {}),
|
|
106
|
-
};
|
|
107
|
-
}
|
|
108
53
|
function trustedSessionRootsForStatus(ctx, deps) {
|
|
109
54
|
const roots = deps.config.defaultSessionDir ? [path.resolve(deps.expandTilde(deps.config.defaultSessionDir))] : [];
|
|
110
55
|
const parentSessionFile = ctx.sessionManager.getSessionFile() ?? null;
|
|
@@ -144,129 +89,6 @@ function countRequestedSubagentSpawns(params, config) {
|
|
|
144
89
|
}
|
|
145
90
|
return params.agent ? 1 : 0;
|
|
146
91
|
}
|
|
147
|
-
function foregroundStatusResult(control) {
|
|
148
|
-
let nestedWarning;
|
|
149
|
-
try {
|
|
150
|
-
updateForegroundNestedProjection(control);
|
|
151
|
-
}
|
|
152
|
-
catch (error) {
|
|
153
|
-
nestedWarning = `Nested status unavailable: ${error instanceof Error ? error.message : String(error)}`;
|
|
154
|
-
}
|
|
155
|
-
const activity = formatForegroundActivity(control);
|
|
156
|
-
const lines = [
|
|
157
|
-
`Run: ${control.runId}`,
|
|
158
|
-
"State: running",
|
|
159
|
-
`Mode: ${control.mode}`,
|
|
160
|
-
control.currentAgent ? `Current: ${control.currentAgent}${control.currentIndex !== undefined ? ` step ${control.currentIndex + 1}` : ""}` : undefined,
|
|
161
|
-
activity ? `Activity: ${activity}` : undefined,
|
|
162
|
-
].filter((line) => Boolean(line));
|
|
163
|
-
lines.push(...formatNestedRunStatusLines(control.nestedChildren, { indent: "", commandHints: true, maxLines: 20 }));
|
|
164
|
-
if (nestedWarning)
|
|
165
|
-
lines.push(`Warning: ${nestedWarning}`);
|
|
166
|
-
return { content: [{ type: "text", text: lines.join("\n") }], details: { mode: "management", results: [] } };
|
|
167
|
-
}
|
|
168
|
-
function trimRememberedForegroundRuns(state) {
|
|
169
|
-
if (!state.foregroundRuns)
|
|
170
|
-
return;
|
|
171
|
-
while (state.foregroundRuns.size > 50) {
|
|
172
|
-
const oldestTerminal = [...state.foregroundRuns.values()]
|
|
173
|
-
.filter((run) => !run.children.some((child) => child.status === "detached"))
|
|
174
|
-
.sort((left, right) => left.updatedAt - right.updatedAt)[0];
|
|
175
|
-
if (!oldestTerminal)
|
|
176
|
-
break;
|
|
177
|
-
state.foregroundRuns.delete(oldestTerminal.runId);
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
function rememberForegroundRun(state, input) {
|
|
181
|
-
state.foregroundRuns ??= new Map();
|
|
182
|
-
const previous = state.foregroundRuns.get(input.runId);
|
|
183
|
-
const updatedAt = Date.now();
|
|
184
|
-
state.foregroundRuns.set(input.runId, {
|
|
185
|
-
runId: input.runId,
|
|
186
|
-
mode: input.mode,
|
|
187
|
-
cwd: input.cwd,
|
|
188
|
-
...(input.sessionId ? { sessionId: input.sessionId } : {}),
|
|
189
|
-
updatedAt,
|
|
190
|
-
children: input.results.map((result, index) => {
|
|
191
|
-
const child = {
|
|
192
|
-
agent: result.agent,
|
|
193
|
-
index,
|
|
194
|
-
status: resolveSubagentResultStatus({ exitCode: result.exitCode, interrupted: result.interrupted, detached: result.detached }),
|
|
195
|
-
updatedAt,
|
|
196
|
-
...(result.exitCode !== undefined ? { exitCode: result.exitCode } : {}),
|
|
197
|
-
...(result.error ? { error: result.error } : {}),
|
|
198
|
-
...(result.finalOutput ? { finalOutput: result.finalOutput } : {}),
|
|
199
|
-
...(result.outputMode ? { outputMode: result.outputMode } : {}),
|
|
200
|
-
...(result.savedOutputPath ? { savedOutputPath: result.savedOutputPath } : {}),
|
|
201
|
-
...(result.outputSaveError ? { outputSaveError: result.outputSaveError } : {}),
|
|
202
|
-
...(result.sessionFile ? { sessionFile: result.sessionFile } : {}),
|
|
203
|
-
...(result.artifactPaths ? { artifactPaths: result.artifactPaths } : {}),
|
|
204
|
-
...(result.transcriptPath ? { transcriptPath: result.transcriptPath } : {}),
|
|
205
|
-
...(result.transcriptError ? { transcriptError: result.transcriptError } : {}),
|
|
206
|
-
...(result.detachedReason ? { detachedReason: result.detachedReason } : {}),
|
|
207
|
-
...(result.acceptance ? { acceptance: result.acceptance } : {}),
|
|
208
|
-
};
|
|
209
|
-
const recovered = previous?.children[index];
|
|
210
|
-
return child.status === "detached" && recovered && recovered.status !== "detached" ? recovered : child;
|
|
211
|
-
}),
|
|
212
|
-
});
|
|
213
|
-
trimRememberedForegroundRuns(state);
|
|
214
|
-
}
|
|
215
|
-
function updateRememberedForegroundChild(state, input) {
|
|
216
|
-
state.foregroundRuns ??= new Map();
|
|
217
|
-
const updatedAt = Date.now();
|
|
218
|
-
let run = state.foregroundRuns.get(input.runId);
|
|
219
|
-
if (!run) {
|
|
220
|
-
run = { runId: input.runId, mode: input.mode, cwd: input.cwd, ...(input.sessionId ? { sessionId: input.sessionId } : {}), updatedAt, children: [] };
|
|
221
|
-
state.foregroundRuns.set(input.runId, run);
|
|
222
|
-
}
|
|
223
|
-
run.updatedAt = updatedAt;
|
|
224
|
-
const child = run.children[input.index] ?? { agent: input.result.agent, index: input.index, status: "detached" };
|
|
225
|
-
run.children[input.index] = {
|
|
226
|
-
...child,
|
|
227
|
-
agent: input.result.agent,
|
|
228
|
-
index: input.index,
|
|
229
|
-
status: input.result.acceptance?.status === "rejected"
|
|
230
|
-
? "failed"
|
|
231
|
-
: resolveSubagentResultStatus({ exitCode: input.result.exitCode, interrupted: input.result.interrupted, detached: false }),
|
|
232
|
-
updatedAt,
|
|
233
|
-
...(input.result.exitCode !== undefined ? { exitCode: input.result.exitCode } : {}),
|
|
234
|
-
...(input.result.error ? { error: input.result.error } : {}),
|
|
235
|
-
...(input.result.finalOutput ? { finalOutput: input.result.finalOutput } : {}),
|
|
236
|
-
outputMode: input.result.outputMode,
|
|
237
|
-
savedOutputPath: input.result.savedOutputPath,
|
|
238
|
-
outputSaveError: input.result.outputSaveError,
|
|
239
|
-
...(input.result.sessionFile ? { sessionFile: input.result.sessionFile } : {}),
|
|
240
|
-
...(input.result.artifactPaths ? { artifactPaths: input.result.artifactPaths } : {}),
|
|
241
|
-
...(input.result.transcriptPath ? { transcriptPath: input.result.transcriptPath } : {}),
|
|
242
|
-
...(input.result.transcriptError ? { transcriptError: input.result.transcriptError } : {}),
|
|
243
|
-
...(input.result.detachedReason ? { detachedReason: input.result.detachedReason } : {}),
|
|
244
|
-
...(input.result.acceptance ? { acceptance: input.result.acceptance } : {}),
|
|
245
|
-
};
|
|
246
|
-
trimRememberedForegroundRuns(state);
|
|
247
|
-
const output = getSingleResultOutput(input.result).trim();
|
|
248
|
-
const success = input.result.exitCode === 0 && input.result.acceptance?.status !== "rejected";
|
|
249
|
-
const summary = !success && input.result.error
|
|
250
|
-
? `${input.result.error}${output ? `\n\nOutput:\n${output}` : ""}`
|
|
251
|
-
: output || input.result.error || "Detached child exited without final output.";
|
|
252
|
-
input.events.emit(SUBAGENT_FOREGROUND_COMPLETE_EVENT, {
|
|
253
|
-
id: `${input.runId}:${input.index}`,
|
|
254
|
-
runId: input.runId,
|
|
255
|
-
source: "foreground",
|
|
256
|
-
mode: input.mode,
|
|
257
|
-
agent: input.result.agent,
|
|
258
|
-
success,
|
|
259
|
-
summary,
|
|
260
|
-
exitCode: input.result.exitCode,
|
|
261
|
-
state: success ? "complete" : "failed",
|
|
262
|
-
timestamp: updatedAt,
|
|
263
|
-
cwd: input.cwd,
|
|
264
|
-
sessionFile: input.result.sessionFile,
|
|
265
|
-
sessionId: input.sessionId,
|
|
266
|
-
taskIndex: input.index,
|
|
267
|
-
results: [{ childId: input.result.childId, agent: input.result.agent, sessionFile: input.result.sessionFile, usage: input.result.usage, usageRequests: input.result.usageRequests, success, output: summary }],
|
|
268
|
-
});
|
|
269
|
-
}
|
|
270
92
|
function resolveForegroundResumeTarget(params, state) {
|
|
271
93
|
const requested = (params.id ?? params.runId)?.trim();
|
|
272
94
|
if (!requested || !state.foregroundRuns?.size || !state.currentSessionId)
|
|
@@ -366,514 +188,6 @@ function resolveResumeTarget(params, state, options = {}) {
|
|
|
366
188
|
throw asyncError;
|
|
367
189
|
throw new Error("Run not found. Provide id or runId.");
|
|
368
190
|
}
|
|
369
|
-
function getAsyncInterruptTarget(state, runId, location) {
|
|
370
|
-
if (location?.asyncDir) {
|
|
371
|
-
return {
|
|
372
|
-
asyncId: location.resolvedId ?? runId ?? path.basename(location.asyncDir),
|
|
373
|
-
asyncDir: location.asyncDir,
|
|
374
|
-
};
|
|
375
|
-
}
|
|
376
|
-
if (runId) {
|
|
377
|
-
const direct = state.asyncJobs.get(runId);
|
|
378
|
-
if (direct)
|
|
379
|
-
return { asyncId: direct.asyncId, asyncDir: direct.asyncDir };
|
|
380
|
-
return undefined;
|
|
381
|
-
}
|
|
382
|
-
let newest;
|
|
383
|
-
for (const job of state.asyncJobs.values()) {
|
|
384
|
-
if (job.status !== "running")
|
|
385
|
-
continue;
|
|
386
|
-
if (!newest || (job.updatedAt ?? 0) > newest.updatedAt) {
|
|
387
|
-
newest = { asyncId: job.asyncId, asyncDir: job.asyncDir, updatedAt: job.updatedAt ?? 0 };
|
|
388
|
-
}
|
|
389
|
-
}
|
|
390
|
-
return newest ? { asyncId: newest.asyncId, asyncDir: newest.asyncDir } : undefined;
|
|
391
|
-
}
|
|
392
|
-
function emitControlNotification(input) {
|
|
393
|
-
if (!shouldNotifyControlEvent(input.controlConfig, input.event))
|
|
394
|
-
return;
|
|
395
|
-
const childIntercomTarget = input.intercomBridge.active
|
|
396
|
-
? resolveSubagentIntercomTarget(input.event.runId, input.event.agent, input.event.index)
|
|
397
|
-
: undefined;
|
|
398
|
-
const payload = {
|
|
399
|
-
event: input.event,
|
|
400
|
-
source: "foreground",
|
|
401
|
-
childIntercomTarget,
|
|
402
|
-
noticeText: formatControlNoticeMessage(input.event, childIntercomTarget),
|
|
403
|
-
};
|
|
404
|
-
if (input.controlConfig.notifyChannels.includes("event")) {
|
|
405
|
-
input.pi.events.emit(SUBAGENT_CONTROL_EVENT, payload);
|
|
406
|
-
}
|
|
407
|
-
if (input.event.type !== "active_long_running" && input.controlConfig.notifyChannels.includes("intercom") && input.intercomBridge.active && input.intercomBridge.orchestratorTarget) {
|
|
408
|
-
input.pi.events.emit(SUBAGENT_CONTROL_INTERCOM_EVENT, {
|
|
409
|
-
...payload,
|
|
410
|
-
to: input.intercomBridge.orchestratorTarget,
|
|
411
|
-
message: formatControlIntercomMessage(input.event, childIntercomTarget),
|
|
412
|
-
});
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
function interruptAsyncRun(state, runId, kill, location) {
|
|
416
|
-
const target = getAsyncInterruptTarget(state, runId, location);
|
|
417
|
-
if (!target)
|
|
418
|
-
return null;
|
|
419
|
-
const status = reconcileAsyncRun(target.asyncDir, { kill }).status;
|
|
420
|
-
if (state.currentSessionId && status?.sessionId !== state.currentSessionId) {
|
|
421
|
-
return {
|
|
422
|
-
content: [{ type: "text", text: `Async run '${target.asyncId}' was not found in the active session.` }],
|
|
423
|
-
isError: true,
|
|
424
|
-
details: { mode: "management", results: [] },
|
|
425
|
-
};
|
|
426
|
-
}
|
|
427
|
-
if (!status || status.state !== "running" || typeof status.pid !== "number") {
|
|
428
|
-
return {
|
|
429
|
-
content: [{ type: "text", text: `No running async run with an interrupt-capable pid was found for '${runId ?? "current"}'.` }],
|
|
430
|
-
isError: true,
|
|
431
|
-
details: { mode: "management", results: [] },
|
|
432
|
-
};
|
|
433
|
-
}
|
|
434
|
-
try {
|
|
435
|
-
deliverInterruptRequest({ asyncDir: target.asyncDir, pid: status.pid, kill, source: "interrupt-action" });
|
|
436
|
-
const tracked = state.asyncJobs.get(target.asyncId);
|
|
437
|
-
if (tracked) {
|
|
438
|
-
tracked.activityState = undefined;
|
|
439
|
-
tracked.updatedAt = Date.now();
|
|
440
|
-
}
|
|
441
|
-
return {
|
|
442
|
-
content: [{ type: "text", text: `Interrupt requested for async run ${target.asyncId}.` }],
|
|
443
|
-
details: { mode: "management", results: [] },
|
|
444
|
-
};
|
|
445
|
-
}
|
|
446
|
-
catch (error) {
|
|
447
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
448
|
-
return {
|
|
449
|
-
content: [{ type: "text", text: `Failed to interrupt async run ${target.asyncId}: ${message}` }],
|
|
450
|
-
isError: true,
|
|
451
|
-
details: { mode: "management", results: [] },
|
|
452
|
-
};
|
|
453
|
-
}
|
|
454
|
-
}
|
|
455
|
-
function stopAsyncRun(state, runId, kill, location) {
|
|
456
|
-
const target = getAsyncInterruptTarget(state, runId, location);
|
|
457
|
-
if (!target)
|
|
458
|
-
return null;
|
|
459
|
-
const status = reconcileAsyncRun(target.asyncDir, { kill }).status;
|
|
460
|
-
if (state.currentSessionId && status?.sessionId !== state.currentSessionId) {
|
|
461
|
-
return {
|
|
462
|
-
content: [{ type: "text", text: `Async run '${target.asyncId}' was not found in the active session.` }],
|
|
463
|
-
isError: true,
|
|
464
|
-
details: { mode: "management", results: [] },
|
|
465
|
-
};
|
|
466
|
-
}
|
|
467
|
-
if (!status || (status.state !== "running" && status.state !== "queued")) {
|
|
468
|
-
return {
|
|
469
|
-
content: [{ type: "text", text: `No running or queued async run was found for '${runId ?? "current"}'.` }],
|
|
470
|
-
isError: true,
|
|
471
|
-
details: { mode: "management", results: [] },
|
|
472
|
-
};
|
|
473
|
-
}
|
|
474
|
-
try {
|
|
475
|
-
deliverStopRequest({ asyncDir: target.asyncDir, pid: typeof status.pid === "number" ? status.pid : undefined, kill, source: "stop-action" });
|
|
476
|
-
const tracked = state.asyncJobs.get(target.asyncId);
|
|
477
|
-
if (tracked) {
|
|
478
|
-
tracked.activityState = undefined;
|
|
479
|
-
tracked.updatedAt = Date.now();
|
|
480
|
-
}
|
|
481
|
-
return {
|
|
482
|
-
content: [{ type: "text", text: `Stop requested for async run ${target.asyncId}.` }],
|
|
483
|
-
details: { mode: "management", results: [] },
|
|
484
|
-
};
|
|
485
|
-
}
|
|
486
|
-
catch (error) {
|
|
487
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
488
|
-
return {
|
|
489
|
-
content: [{ type: "text", text: `Failed to stop async run ${target.asyncId}: ${message}` }],
|
|
490
|
-
isError: true,
|
|
491
|
-
details: { mode: "management", results: [] },
|
|
492
|
-
};
|
|
493
|
-
}
|
|
494
|
-
}
|
|
495
|
-
function duplicateNames(names) {
|
|
496
|
-
const seen = new Set();
|
|
497
|
-
const duplicates = new Set();
|
|
498
|
-
for (const name of names) {
|
|
499
|
-
if (seen.has(name))
|
|
500
|
-
duplicates.add(name);
|
|
501
|
-
else
|
|
502
|
-
seen.add(name);
|
|
503
|
-
}
|
|
504
|
-
return [...duplicates];
|
|
505
|
-
}
|
|
506
|
-
function appendStepToAsyncChain(input) {
|
|
507
|
-
const targetRunId = input.params.id ?? input.params.runId;
|
|
508
|
-
if (!targetRunId) {
|
|
509
|
-
return {
|
|
510
|
-
content: [{ type: "text", text: "action='append-step' requires id." }],
|
|
511
|
-
isError: true,
|
|
512
|
-
details: { mode: "management", results: [] },
|
|
513
|
-
};
|
|
514
|
-
}
|
|
515
|
-
if (!input.params.chain || input.params.chain.length !== 1) {
|
|
516
|
-
return {
|
|
517
|
-
content: [{ type: "text", text: "action='append-step' requires chain with exactly one step." }],
|
|
518
|
-
isError: true,
|
|
519
|
-
details: { mode: "management", results: [] },
|
|
520
|
-
};
|
|
521
|
-
}
|
|
522
|
-
// internalizePromptDrivenChildren would take the tasks branch and leave the chain step without its agent.
|
|
523
|
-
if ((input.params.tasks?.length ?? 0) > 0) {
|
|
524
|
-
return {
|
|
525
|
-
content: [{ type: "text", text: "action='append-step' takes chain only, not tasks." }],
|
|
526
|
-
isError: true,
|
|
527
|
-
details: { mode: "management", results: [] },
|
|
528
|
-
};
|
|
529
|
-
}
|
|
530
|
-
const acceptanceErrors = validateExecutionAcceptance(input.params);
|
|
531
|
-
if (acceptanceErrors.length > 0) {
|
|
532
|
-
return {
|
|
533
|
-
content: [{ type: "text", text: `Cannot append step: ${acceptanceErrors.join(" ")}` }],
|
|
534
|
-
isError: true,
|
|
535
|
-
details: { mode: "management", results: [] },
|
|
536
|
-
};
|
|
537
|
-
}
|
|
538
|
-
let resolved;
|
|
539
|
-
try {
|
|
540
|
-
resolved = resolveSubagentRunId(targetRunId, { state: input.deps.state, nested: nestedResolutionScopeForExecutor(input.deps) });
|
|
541
|
-
}
|
|
542
|
-
catch (error) {
|
|
543
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
544
|
-
return { content: [{ type: "text", text: message }], isError: true, details: { mode: "management", results: [] } };
|
|
545
|
-
}
|
|
546
|
-
if (!resolved) {
|
|
547
|
-
return {
|
|
548
|
-
content: [{ type: "text", text: `No async chain run found for '${targetRunId}'.` }],
|
|
549
|
-
isError: true,
|
|
550
|
-
details: { mode: "management", results: [] },
|
|
551
|
-
};
|
|
552
|
-
}
|
|
553
|
-
if (resolved.kind !== "async" || !resolved.location.asyncDir) {
|
|
554
|
-
return {
|
|
555
|
-
content: [{ type: "text", text: `Run '${resolved.id}' is not an append-capable async chain run.` }],
|
|
556
|
-
isError: true,
|
|
557
|
-
details: { mode: "management", results: [] },
|
|
558
|
-
};
|
|
559
|
-
}
|
|
560
|
-
const status = readStatus(resolved.location.asyncDir);
|
|
561
|
-
if (!status) {
|
|
562
|
-
return {
|
|
563
|
-
content: [{ type: "text", text: `No async run status found for '${resolved.id}'.` }],
|
|
564
|
-
isError: true,
|
|
565
|
-
details: { mode: "management", results: [] },
|
|
566
|
-
};
|
|
567
|
-
}
|
|
568
|
-
if (status.mode !== "chain") {
|
|
569
|
-
return {
|
|
570
|
-
content: [{ type: "text", text: `Run '${resolved.id}' is ${status.mode}; only active chain runs accept appended steps.` }],
|
|
571
|
-
isError: true,
|
|
572
|
-
details: { mode: "management", results: [] },
|
|
573
|
-
};
|
|
574
|
-
}
|
|
575
|
-
if (status.state !== "running") {
|
|
576
|
-
return {
|
|
577
|
-
content: [{ type: "text", text: `Run '${resolved.id}' is ${status.state}; only running chain runs accept appended steps.` }],
|
|
578
|
-
isError: true,
|
|
579
|
-
details: { mode: "management", results: [] },
|
|
580
|
-
};
|
|
581
|
-
}
|
|
582
|
-
const stillInProgress = (status.steps ?? []).some((step) => step.status === "running" || step.status === "pending") || (status.pendingAppends ?? 0) > 0;
|
|
583
|
-
if (!stillInProgress) {
|
|
584
|
-
return {
|
|
585
|
-
content: [{ type: "text", text: `Run '${resolved.id}' has no running or pending chain steps left; append-step must target an in-progress chain.` }],
|
|
586
|
-
isError: true,
|
|
587
|
-
details: { mode: "management", results: [] },
|
|
588
|
-
};
|
|
589
|
-
}
|
|
590
|
-
const pendingAppendRequests = readPendingChainAppendRequests(resolved.location.asyncDir);
|
|
591
|
-
const reservedOutputNames = new Set([
|
|
592
|
-
...Object.keys(status.outputs ?? {}),
|
|
593
|
-
...(status.steps ?? []).map((step) => step.outputName).filter((name) => Boolean(name)),
|
|
594
|
-
...pendingAppendRequests.flatMap((request) => runnerStepOutputNames(request.steps)),
|
|
595
|
-
]);
|
|
596
|
-
try {
|
|
597
|
-
validateChainOutputBindingsWithContext(input.params.chain, { maxItems: input.deps.config.chain?.dynamicFanout?.maxItems }, {
|
|
598
|
-
priorOutputNames: reservedOutputNames,
|
|
599
|
-
startStepIndex: status.chainStepCount ?? status.steps?.length ?? 0,
|
|
600
|
-
});
|
|
601
|
-
}
|
|
602
|
-
catch (error) {
|
|
603
|
-
if (!(error instanceof ChainOutputValidationError))
|
|
604
|
-
throw error;
|
|
605
|
-
return {
|
|
606
|
-
content: [{ type: "text", text: `Cannot append step to run '${resolved.id}': ${error.message}` }],
|
|
607
|
-
isError: true,
|
|
608
|
-
details: { mode: "management", results: [] },
|
|
609
|
-
};
|
|
610
|
-
}
|
|
611
|
-
let appendParams;
|
|
612
|
-
const appendChildRunId = `${resolved.id}-append-${randomUUID().slice(0, 8)}`;
|
|
613
|
-
try {
|
|
614
|
-
appendParams = internalizePromptDrivenChildren(input.params, {
|
|
615
|
-
runId: appendChildRunId,
|
|
616
|
-
parentMode: snapshotParentPermissionMode(input.ctx.sessionManager.getSessionId() ?? undefined),
|
|
617
|
-
dynamicFanoutMaxItems: input.deps.config.chain?.dynamicFanout?.maxItems,
|
|
618
|
-
}).params;
|
|
619
|
-
}
|
|
620
|
-
catch (error) {
|
|
621
|
-
return {
|
|
622
|
-
content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }],
|
|
623
|
-
isError: true,
|
|
624
|
-
details: { mode: "management", results: [] },
|
|
625
|
-
};
|
|
626
|
-
}
|
|
627
|
-
const contextPolicy = resolveExplicitContextPolicy(appendParams);
|
|
628
|
-
const chainSkillInput = normalizeSkillInput(appendParams.skill);
|
|
629
|
-
const chainSkills = chainSkillInput === false ? [] : (chainSkillInput ?? []);
|
|
630
|
-
const asyncCtx = {
|
|
631
|
-
pi: input.deps.pi,
|
|
632
|
-
cwd: input.ctx.cwd,
|
|
633
|
-
currentSessionId: resolveCurrentSessionId(input.ctx.sessionManager),
|
|
634
|
-
parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
|
|
635
|
-
currentModelProvider: input.ctx.model?.provider,
|
|
636
|
-
currentModel: input.ctx.model,
|
|
637
|
-
modelScope: undefined,
|
|
638
|
-
};
|
|
639
|
-
const built = buildAsyncRunnerSteps(resolved.id, {
|
|
640
|
-
chain: wrapChainTasksForFork(appendParams.chain, contextPolicy),
|
|
641
|
-
task: appendParams.task,
|
|
642
|
-
resultMode: "chain",
|
|
643
|
-
ctx: asyncCtx,
|
|
644
|
-
availableModels: input.ctx.modelRegistry.getAvailable().map(toModelInfo),
|
|
645
|
-
cwd: status.cwd ?? input.requestCwd,
|
|
646
|
-
chainSkills,
|
|
647
|
-
dynamicFanoutMaxItems: input.deps.config.chain?.dynamicFanout?.maxItems,
|
|
648
|
-
maxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth),
|
|
649
|
-
waitToolEnabled: input.deps.waitToolEnabled,
|
|
650
|
-
asyncDir: resolved.location.asyncDir,
|
|
651
|
-
childIdRunId: appendChildRunId,
|
|
652
|
-
validateOutputBindings: false,
|
|
653
|
-
});
|
|
654
|
-
if ("error" in built) {
|
|
655
|
-
return {
|
|
656
|
-
content: [{ type: "text", text: built.error }],
|
|
657
|
-
isError: true,
|
|
658
|
-
details: { mode: "management", results: [] },
|
|
659
|
-
};
|
|
660
|
-
}
|
|
661
|
-
const appendedOutputNames = runnerStepOutputNames(built.steps);
|
|
662
|
-
const duplicateAppendedOutputs = duplicateNames(appendedOutputNames);
|
|
663
|
-
if (duplicateAppendedOutputs.length > 0) {
|
|
664
|
-
return {
|
|
665
|
-
content: [{ type: "text", text: `Cannot append step to run '${resolved.id}': duplicate output name in appended step: ${duplicateAppendedOutputs.join(", ")}.` }],
|
|
666
|
-
isError: true,
|
|
667
|
-
details: { mode: "management", results: [] },
|
|
668
|
-
};
|
|
669
|
-
}
|
|
670
|
-
const pendingOutputNames = new Set(pendingAppendRequests.flatMap((request) => runnerStepOutputNames(request.steps)));
|
|
671
|
-
const pendingDuplicateOutputs = appendedOutputNames.filter((name) => pendingOutputNames.has(name));
|
|
672
|
-
if (pendingDuplicateOutputs.length > 0) {
|
|
673
|
-
return {
|
|
674
|
-
content: [{ type: "text", text: `Cannot append step to run '${resolved.id}': output name already belongs to a pending append: ${pendingDuplicateOutputs.join(", ")}.` }],
|
|
675
|
-
isError: true,
|
|
676
|
-
details: { mode: "management", results: [] },
|
|
677
|
-
};
|
|
678
|
-
}
|
|
679
|
-
try {
|
|
680
|
-
const result = enqueueChainAppendRequest({
|
|
681
|
-
asyncDir: resolved.location.asyncDir,
|
|
682
|
-
runId: resolved.id,
|
|
683
|
-
steps: built.steps,
|
|
684
|
-
});
|
|
685
|
-
const stepText = built.steps.length === 1 ? "step" : "steps";
|
|
686
|
-
return {
|
|
687
|
-
content: [{
|
|
688
|
-
type: "text",
|
|
689
|
-
text: `Append queued for chain run ${resolved.id}: ${built.steps.length} ${stepText}. It becomes eligible after the chain's already-queued steps finish. Pending appends: ${result.pendingCount}.`,
|
|
690
|
-
}],
|
|
691
|
-
details: { mode: "management", results: [], asyncId: resolved.id, asyncDir: resolved.location.asyncDir },
|
|
692
|
-
};
|
|
693
|
-
}
|
|
694
|
-
catch (error) {
|
|
695
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
696
|
-
return {
|
|
697
|
-
content: [{ type: "text", text: `Failed to append step to chain run ${resolved.id}: ${message}` }],
|
|
698
|
-
isError: true,
|
|
699
|
-
details: { mode: "management", results: [] },
|
|
700
|
-
};
|
|
701
|
-
}
|
|
702
|
-
}
|
|
703
|
-
function nestedRunSessionFile(run) {
|
|
704
|
-
return run.sessionFile ?? (run.steps?.length === 1 ? run.steps[0]?.sessionFile : undefined);
|
|
705
|
-
}
|
|
706
|
-
function nestedRunAgent(run) {
|
|
707
|
-
return run.agent ?? run.agents?.[0] ?? (run.steps?.length === 1 ? run.steps[0]?.agent : undefined);
|
|
708
|
-
}
|
|
709
|
-
function pathWithin(base, candidate) {
|
|
710
|
-
const resolvedBase = path.resolve(base);
|
|
711
|
-
const resolvedCandidate = path.resolve(candidate);
|
|
712
|
-
return resolvedCandidate === resolvedBase || resolvedCandidate.startsWith(`${resolvedBase}${path.sep}`);
|
|
713
|
-
}
|
|
714
|
-
function validateNestedSessionFile(run, trustedSessionRoots) {
|
|
715
|
-
const sessionFile = nestedRunSessionFile(run);
|
|
716
|
-
if (!sessionFile)
|
|
717
|
-
throw new Error(`Nested run '${run.id}' does not have a persisted session file to resume from.`);
|
|
718
|
-
if (path.extname(sessionFile) !== ".jsonl")
|
|
719
|
-
throw new Error(`Nested run '${run.id}' session file must be a .jsonl file: ${sessionFile}`);
|
|
720
|
-
const resolved = path.resolve(sessionFile);
|
|
721
|
-
if (!path.isAbsolute(sessionFile))
|
|
722
|
-
throw new Error(`Nested run '${run.id}' session file must be absolute: ${sessionFile}`);
|
|
723
|
-
if (!fs.existsSync(resolved))
|
|
724
|
-
throw new Error(`Nested run '${run.id}' session file does not exist: ${sessionFile}`);
|
|
725
|
-
const stat = fs.lstatSync(resolved);
|
|
726
|
-
if (!stat.isFile() || stat.isSymbolicLink())
|
|
727
|
-
throw new Error(`Nested run '${run.id}' session file is not a regular file: ${sessionFile}`);
|
|
728
|
-
const realSessionFile = fs.realpathSync(resolved);
|
|
729
|
-
const trustedRoots = trustedSessionRoots
|
|
730
|
-
.filter((root) => fs.existsSync(root))
|
|
731
|
-
.map((root) => fs.realpathSync(root));
|
|
732
|
-
if (!trustedRoots.some((root) => pathWithin(root, realSessionFile))) {
|
|
733
|
-
throw new Error(`Nested run '${run.id}' session file is outside trusted nested session roots: ${sessionFile}`);
|
|
734
|
-
}
|
|
735
|
-
if (!realSessionFile.split(path.sep).includes(run.id)) {
|
|
736
|
-
throw new Error(`Nested run '${run.id}' session file is not under that nested run's session directory: ${sessionFile}`);
|
|
737
|
-
}
|
|
738
|
-
return realSessionFile;
|
|
739
|
-
}
|
|
740
|
-
function resolveNestedResumeTarget(match, trustedSessionRoots) {
|
|
741
|
-
const run = match.match.run;
|
|
742
|
-
if (run.state === "running" || run.state === "queued")
|
|
743
|
-
throw new Error(`Nested run '${run.id}' is live; route the follow-up to the owner process instead.`);
|
|
744
|
-
const agent = nestedRunAgent(run);
|
|
745
|
-
if (!agent)
|
|
746
|
-
throw new Error(`Could not determine child agent for nested run '${run.id}'.`);
|
|
747
|
-
const state = run.state === "complete" || run.state === "failed" || run.state === "paused" || run.state === "stopped" ? run.state : "failed";
|
|
748
|
-
const asyncDir = resolveNestedAsyncDir(match.match.rootRunId, run);
|
|
749
|
-
return {
|
|
750
|
-
kind: "revive",
|
|
751
|
-
source: "nested",
|
|
752
|
-
runId: run.id,
|
|
753
|
-
state,
|
|
754
|
-
agent,
|
|
755
|
-
index: 0,
|
|
756
|
-
intercomTarget: resolveSubagentIntercomTarget(run.id, agent, 0),
|
|
757
|
-
cwd: asyncDir ? path.dirname(asyncDir) : undefined,
|
|
758
|
-
sessionFile: validateNestedSessionFile(run, trustedSessionRoots),
|
|
759
|
-
};
|
|
760
|
-
}
|
|
761
|
-
async function waitForNestedControlResult(target, requestId, timeoutMs = 1_000) {
|
|
762
|
-
const deadline = Date.now() + timeoutMs;
|
|
763
|
-
while (Date.now() < deadline) {
|
|
764
|
-
const result = readNestedControlResults(target.match.route).find((candidate) => candidate.requestId === requestId && candidate.targetRunId === target.match.run.id);
|
|
765
|
-
if (result)
|
|
766
|
-
return result;
|
|
767
|
-
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
768
|
-
}
|
|
769
|
-
return undefined;
|
|
770
|
-
}
|
|
771
|
-
async function sendNestedControlRequest(target, action, message) {
|
|
772
|
-
const requestId = randomUUID();
|
|
773
|
-
writeNestedControlRequest(target.match.route, {
|
|
774
|
-
ts: Date.now(),
|
|
775
|
-
requestId,
|
|
776
|
-
targetRunId: target.match.run.id,
|
|
777
|
-
action,
|
|
778
|
-
...(message ? { message } : {}),
|
|
779
|
-
});
|
|
780
|
-
return waitForNestedControlResult(target, requestId);
|
|
781
|
-
}
|
|
782
|
-
function directNestedAsyncInterrupt(target) {
|
|
783
|
-
const run = target.match.run;
|
|
784
|
-
const asyncDir = resolveNestedAsyncDir(target.match.rootRunId, run);
|
|
785
|
-
if (!asyncDir)
|
|
786
|
-
return undefined;
|
|
787
|
-
const status = reconcileAsyncRun(asyncDir, { resultsDir: path.join(RESULTS_DIR, "nested", target.match.rootRunId) }).status;
|
|
788
|
-
const pid = typeof status?.pid === "number" && status.pid > 0 ? status.pid : run.pid;
|
|
789
|
-
if (!status || status.state !== "running" || typeof pid !== "number" || pid <= 0)
|
|
790
|
-
return undefined;
|
|
791
|
-
try {
|
|
792
|
-
deliverInterruptRequest({ asyncDir, pid, source: "nested-interrupt" });
|
|
793
|
-
return { content: [{ type: "text", text: `Interrupt requested for nested async run ${run.id}.` }], details: { mode: "management", results: [] } };
|
|
794
|
-
}
|
|
795
|
-
catch (error) {
|
|
796
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
797
|
-
return { content: [{ type: "text", text: `Failed to interrupt nested async run ${run.id}: ${message}` }], isError: true, details: { mode: "management", results: [] } };
|
|
798
|
-
}
|
|
799
|
-
}
|
|
800
|
-
async function directNestedAsyncSteer(input) {
|
|
801
|
-
const run = input.target.match.run;
|
|
802
|
-
const asyncDir = resolveNestedAsyncDir(input.target.match.rootRunId, run);
|
|
803
|
-
if (!asyncDir)
|
|
804
|
-
return undefined;
|
|
805
|
-
const status = reconcileAsyncRun(asyncDir, { resultsDir: path.join(RESULTS_DIR, "nested", input.target.match.rootRunId) }).status;
|
|
806
|
-
if (!status || (status.state !== "running" && status.state !== "queued"))
|
|
807
|
-
return undefined;
|
|
808
|
-
const steps = status.steps ?? [];
|
|
809
|
-
if (input.index !== undefined) {
|
|
810
|
-
if (input.index < 0 || input.index >= steps.length)
|
|
811
|
-
return { content: [{ type: "text", text: `Nested async run ${run.id} has ${steps.length} children. Index ${input.index} is out of range.` }], isError: true, details: { mode: "management", results: [] } };
|
|
812
|
-
const step = steps[input.index];
|
|
813
|
-
if (step && step.status !== "running" && step.status !== "pending")
|
|
814
|
-
return { content: [{ type: "text", text: `Nested async run ${run.id} child ${input.index} is ${step.status} and cannot be steered.` }], isError: true, details: { mode: "management", results: [] } };
|
|
815
|
-
}
|
|
816
|
-
const runningIndexes = steps
|
|
817
|
-
.map((step, index) => step.status === "running" ? index : undefined)
|
|
818
|
-
.filter((index) => index !== undefined);
|
|
819
|
-
const effectiveTargetIndex = input.index ?? (status.mode === "single" && runningIndexes.length === 0 && steps[0]?.status === "pending" ? 0 : undefined);
|
|
820
|
-
const targetIndexes = effectiveTargetIndex !== undefined ? [effectiveTargetIndex] : runningIndexes;
|
|
821
|
-
if (targetIndexes.length === 0)
|
|
822
|
-
return { content: [{ type: "text", text: `Nested async run ${run.id} has no running child to steer.` }], isError: true, details: { mode: "management", results: [] } };
|
|
823
|
-
const requestId = randomUUID();
|
|
824
|
-
try {
|
|
825
|
-
requestAsyncSteer(asyncDir, {
|
|
826
|
-
message: input.message,
|
|
827
|
-
...(effectiveTargetIndex !== undefined ? { targetIndex: effectiveTargetIndex } : { targetIndexes }),
|
|
828
|
-
source: "nested-steer",
|
|
829
|
-
id: requestId,
|
|
830
|
-
});
|
|
831
|
-
}
|
|
832
|
-
catch (error) {
|
|
833
|
-
return { content: [{ type: "text", text: `Failed to queue steering for nested async run ${run.id}: ${error instanceof Error ? error.message : String(error)}` }], isError: true, details: { mode: "management", results: [] } };
|
|
834
|
-
}
|
|
835
|
-
const targets = targetIndexes.map((index) => ({ index, state: steps[index]?.status === "pending" ? "scheduled" : "pending" }));
|
|
836
|
-
if (targets.every((target) => target.state === "scheduled")) {
|
|
837
|
-
const scheduled = { requestId, state: "scheduled", sourceRunId: run.id, targets };
|
|
838
|
-
return { content: [{ type: "text", text: `Steering scheduled for nested async run ${run.id} (request ${requestId}).` }], details: { mode: "management", results: [], steering: scheduled } };
|
|
839
|
-
}
|
|
840
|
-
const waited = await waitForSteeringAction({ asyncDir, sourceRunId: run.id, requestId, timeoutMs: 3_000, signal: input.signal });
|
|
841
|
-
const result = waited ?? { requestId, state: "pending", sourceRunId: run.id, targets };
|
|
842
|
-
const stateText = result.state === "delivered" ? "delivered" : result.state === "failed" ? "failed" : result.state === "partial" ? "partial" : "pending";
|
|
843
|
-
return { content: [{ type: "text", text: `Steering ${stateText} for nested async run ${run.id} (request ${requestId}).` }], ...(result.state === "failed" || result.state === "partial" ? { isError: true } : {}), details: { mode: "management", results: [], steering: result } };
|
|
844
|
-
}
|
|
845
|
-
async function interruptNestedRun(target) {
|
|
846
|
-
const run = target.match.run;
|
|
847
|
-
if (run.state === "complete")
|
|
848
|
-
return { content: [{ type: "text", text: `Nested run ${run.id} is already complete and cannot be interrupted.` }], isError: true, details: { mode: "management", results: [] } };
|
|
849
|
-
if (run.state === "failed")
|
|
850
|
-
return { content: [{ type: "text", text: `Nested run ${run.id} has failed and cannot be interrupted.` }], isError: true, details: { mode: "management", results: [] } };
|
|
851
|
-
if (run.state === "paused")
|
|
852
|
-
return { content: [{ type: "text", text: `Nested run ${run.id} is already paused.` }], isError: true, details: { mode: "management", results: [] } };
|
|
853
|
-
const result = await sendNestedControlRequest(target, "interrupt");
|
|
854
|
-
if (result)
|
|
855
|
-
return { content: [{ type: "text", text: result.message }], isError: result.ok ? undefined : true, details: { mode: "management", results: [] } };
|
|
856
|
-
const direct = directNestedAsyncInterrupt(target);
|
|
857
|
-
if (direct)
|
|
858
|
-
return direct;
|
|
859
|
-
return { content: [{ type: "text", text: `Nested run ${run.id} owner is not reachable and no safe direct async interrupt fallback is available.` }], isError: true, details: { mode: "management", results: [] } };
|
|
860
|
-
}
|
|
861
|
-
async function resumeLiveNestedRun(input) {
|
|
862
|
-
const run = input.target.match.run;
|
|
863
|
-
const result = await sendNestedControlRequest(input.target, "resume", input.message);
|
|
864
|
-
if (result)
|
|
865
|
-
return { content: [{ type: "text", text: result.message }], isError: result.ok ? undefined : true, details: { mode: "management", results: [] } };
|
|
866
|
-
return { content: [{ type: "text", text: `Nested run ${run.id} appears live but its owner route is not reachable. Wait for completion, then retry action='resume'.` }], isError: true, details: { mode: "management", results: [] } };
|
|
867
|
-
}
|
|
868
|
-
async function steerNestedRun(input) {
|
|
869
|
-
const run = input.target.match.run;
|
|
870
|
-
if (run.state !== "running" && run.state !== "queued")
|
|
871
|
-
return { content: [{ type: "text", text: `Nested run ${run.id} is ${run.state} and cannot be steered.` }], isError: true, details: { mode: "management", results: [] } };
|
|
872
|
-
const direct = await directNestedAsyncSteer(input);
|
|
873
|
-
if (direct)
|
|
874
|
-
return direct;
|
|
875
|
-
return { content: [{ type: "text", text: `Nested run ${run.id} is not a live async Pi child session with a steering inbox. action='steer' cannot target foreground nested runs.` }], isError: true, details: { mode: "management", results: [] } };
|
|
876
|
-
}
|
|
877
191
|
async function resumeAsyncRun(input) {
|
|
878
192
|
const followUp = (input.params.message ?? input.params.task ?? "").trim();
|
|
879
193
|
const attachChain = (input.params.chain?.length ?? 0) > 0 ? input.params.chain : undefined;
|
|
@@ -1187,17 +501,6 @@ async function resumeAsyncRun(input) {
|
|
|
1187
501
|
].filter((line) => Boolean(line));
|
|
1188
502
|
return { content: [{ type: "text", text: formatAsyncStartedMessage(lines.join("\n")) }], details: result.details };
|
|
1189
503
|
}
|
|
1190
|
-
function resultSummaryForIntercom(result) {
|
|
1191
|
-
const output = getSingleResultOutput(result);
|
|
1192
|
-
if (result.exitCode !== 0 && result.error) {
|
|
1193
|
-
return output ? `${result.error}\n\nOutput:\n${output}` : result.error;
|
|
1194
|
-
}
|
|
1195
|
-
const summary = output || result.error || "(no output)";
|
|
1196
|
-
// Inline mode sends the reply as the summary, so name the saved output file too: a relative
|
|
1197
|
-
// `output` lands in the run's directory, not where the model would guess.
|
|
1198
|
-
const reference = result.outputReference?.message;
|
|
1199
|
-
return reference && !summary.includes(reference) ? `${summary}\n\n${reference}` : summary;
|
|
1200
|
-
}
|
|
1201
504
|
function formatFailedSingleRunOutput(result, displayOutput) {
|
|
1202
505
|
const error = result.error || "Failed";
|
|
1203
506
|
const output = displayOutput.trim();
|
|
@@ -1210,468 +513,15 @@ function formatFailedSingleRunOutput(result, displayOutput) {
|
|
|
1210
513
|
}
|
|
1211
514
|
return lines.join("\n");
|
|
1212
515
|
}
|
|
1213
|
-
function
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
if (!input.intercomBridge.active || !input.intercomBridge.orchestratorTarget)
|
|
1223
|
-
return null;
|
|
1224
|
-
const children = input.results.flatMap((result, index) => result.detached ? [] : [{
|
|
1225
|
-
agent: result.agent,
|
|
1226
|
-
status: resolveSubagentResultStatus({
|
|
1227
|
-
exitCode: result.exitCode,
|
|
1228
|
-
interrupted: result.interrupted,
|
|
1229
|
-
detached: result.detached,
|
|
1230
|
-
}),
|
|
1231
|
-
summary: resultSummaryForIntercom(result),
|
|
1232
|
-
index,
|
|
1233
|
-
artifactPath: result.artifactPaths?.outputPath,
|
|
1234
|
-
sessionPath: result.sessionFile,
|
|
1235
|
-
intercomTarget: resolveSubagentIntercomTarget(input.runId, result.agent, index),
|
|
1236
|
-
}]);
|
|
1237
|
-
if (children.length === 0)
|
|
1238
|
-
return null;
|
|
1239
|
-
const payload = buildSubagentResultIntercomPayload({
|
|
1240
|
-
to: input.intercomBridge.orchestratorTarget,
|
|
1241
|
-
runId: input.runId,
|
|
1242
|
-
mode: input.mode,
|
|
1243
|
-
source: "foreground",
|
|
1244
|
-
children: attachNestedChildrenToResultChildren(input.runId, children, input.nestedChildren),
|
|
1245
|
-
...(typeof input.chainSteps === "number" ? { chainSteps: input.chainSteps } : {}),
|
|
1246
|
-
});
|
|
1247
|
-
const delivered = await deliverSubagentResultIntercomEvent(input.pi.events, payload);
|
|
1248
|
-
if (!delivered)
|
|
1249
|
-
return null;
|
|
1250
|
-
return payload;
|
|
1251
|
-
}
|
|
1252
|
-
async function maybeBuildForegroundIntercomReceipt(input) {
|
|
1253
|
-
const payload = await emitForegroundResultIntercom({
|
|
1254
|
-
pi: input.pi,
|
|
1255
|
-
intercomBridge: input.intercomBridge,
|
|
1256
|
-
runId: input.runId,
|
|
1257
|
-
mode: input.mode,
|
|
1258
|
-
results: input.details.results,
|
|
1259
|
-
...(typeof input.details.totalSteps === "number" ? { chainSteps: input.details.totalSteps } : {}),
|
|
1260
|
-
...(input.nestedChildren?.length ? { nestedChildren: input.nestedChildren } : {}),
|
|
1261
|
-
});
|
|
1262
|
-
if (!payload)
|
|
1263
|
-
return null;
|
|
1264
|
-
// The receipt replaces the result text, so output files that failed to save must be named here.
|
|
1265
|
-
const warnings = input.details.results.flatMap((result) => result.outputSaveError ? [`Output warning (${result.agent}): ${result.outputSaveError}`] : []);
|
|
1266
|
-
return {
|
|
1267
|
-
text: [formatSubagentResultReceipt({ mode: input.mode, runId: input.runId, payload }), ...warnings].join("\n"),
|
|
1268
|
-
details: stripDetailsOutputsForIntercomReceipt(input.details),
|
|
1269
|
-
};
|
|
1270
|
-
}
|
|
1271
|
-
function validateExecutionInput(params, hasChain, hasTasks, hasSingle, allowClarifyTaskPrompt) {
|
|
1272
|
-
if (Number(hasChain) + Number(hasTasks) + Number(hasSingle) !== 1) {
|
|
1273
|
-
return {
|
|
1274
|
-
content: [
|
|
1275
|
-
{
|
|
1276
|
-
type: "text",
|
|
1277
|
-
text: "Provide exactly one mode: { task, description, permissions? }, { tasks: [...] }, or { chain: [...] }.",
|
|
1278
|
-
},
|
|
1279
|
-
],
|
|
1280
|
-
isError: true,
|
|
1281
|
-
details: { mode: "single", results: [] },
|
|
1282
|
-
};
|
|
1283
|
-
}
|
|
1284
|
-
const acceptanceErrors = validateExecutionAcceptance(params);
|
|
1285
|
-
if (acceptanceErrors.length > 0) {
|
|
1286
|
-
return {
|
|
1287
|
-
content: [{ type: "text", text: acceptanceErrors.join(" ") }],
|
|
1288
|
-
isError: true,
|
|
1289
|
-
details: { mode: getRequestedModeLabel(params), results: [] },
|
|
1290
|
-
};
|
|
1291
|
-
}
|
|
1292
|
-
if (hasSingle && !params.description) {
|
|
1293
|
-
return {
|
|
1294
|
-
content: [{ type: "text", text: "description is required and must be a concise single-line label (max 80 characters)." }],
|
|
1295
|
-
isError: true,
|
|
1296
|
-
details: { mode: "single", results: [] },
|
|
1297
|
-
};
|
|
1298
|
-
}
|
|
1299
|
-
if (hasTasks && params.tasks) {
|
|
1300
|
-
for (let i = 0; i < params.tasks.length; i++) {
|
|
1301
|
-
const task = params.tasks[i];
|
|
1302
|
-
if (!task.description) {
|
|
1303
|
-
return {
|
|
1304
|
-
content: [{ type: "text", text: `description is required (task ${i + 1})` }],
|
|
1305
|
-
isError: true,
|
|
1306
|
-
details: { mode: "parallel", results: [] },
|
|
1307
|
-
};
|
|
1308
|
-
}
|
|
1309
|
-
}
|
|
1310
|
-
}
|
|
1311
|
-
if (hasChain && params.chain) {
|
|
1312
|
-
if (params.chain.length === 0) {
|
|
1313
|
-
return {
|
|
1314
|
-
content: [{ type: "text", text: "Chain must have at least one step" }],
|
|
1315
|
-
isError: true,
|
|
1316
|
-
details: { mode: "chain", results: [] },
|
|
1317
|
-
};
|
|
1318
|
-
}
|
|
1319
|
-
const firstStep = params.chain[0];
|
|
1320
|
-
if (isParallelStep(firstStep)) {
|
|
1321
|
-
const missingTaskIndex = firstStep.parallel.findIndex((t) => !t.task);
|
|
1322
|
-
if (missingTaskIndex !== -1) {
|
|
1323
|
-
return {
|
|
1324
|
-
content: [{ type: "text", text: `First parallel step: task ${missingTaskIndex + 1} must have a task (no previous output to reference)` }],
|
|
1325
|
-
isError: true,
|
|
1326
|
-
details: { mode: "chain", results: [] },
|
|
1327
|
-
};
|
|
1328
|
-
}
|
|
1329
|
-
}
|
|
1330
|
-
else if (isDynamicParallelStep(firstStep)) {
|
|
1331
|
-
return {
|
|
1332
|
-
content: [{ type: "text", text: "First step in chain cannot be dynamic fanout; expand.from requires a prior structured named output" }],
|
|
1333
|
-
isError: true,
|
|
1334
|
-
details: { mode: "chain", results: [] },
|
|
1335
|
-
};
|
|
1336
|
-
}
|
|
1337
|
-
else if (!firstStep.task && !params.task && !allowClarifyTaskPrompt) {
|
|
1338
|
-
return {
|
|
1339
|
-
content: [{ type: "text", text: "First step in chain must have a task" }],
|
|
1340
|
-
isError: true,
|
|
1341
|
-
details: { mode: "chain", results: [] },
|
|
1342
|
-
};
|
|
1343
|
-
}
|
|
1344
|
-
for (let i = 0; i < params.chain.length; i++) {
|
|
1345
|
-
const step = params.chain[i];
|
|
1346
|
-
if (!isParallelStep(step) && !isDynamicParallelStep(step) && !step.description) {
|
|
1347
|
-
return {
|
|
1348
|
-
content: [{ type: "text", text: `description is required (step ${i + 1})` }],
|
|
1349
|
-
isError: true,
|
|
1350
|
-
details: { mode: "chain", results: [] },
|
|
1351
|
-
};
|
|
1352
|
-
}
|
|
1353
|
-
if (isParallelStep(step)) {
|
|
1354
|
-
const missing = step.parallel.findIndex((t) => !t.description);
|
|
1355
|
-
if (missing !== -1) {
|
|
1356
|
-
return {
|
|
1357
|
-
content: [{ type: "text", text: `description is required (step ${i + 1}, parallel task ${missing + 1})` }],
|
|
1358
|
-
isError: true,
|
|
1359
|
-
details: { mode: "chain", results: [] },
|
|
1360
|
-
};
|
|
1361
|
-
}
|
|
1362
|
-
}
|
|
1363
|
-
if (isParallelStep(step) && step.parallel.length === 0) {
|
|
1364
|
-
return {
|
|
1365
|
-
content: [{ type: "text", text: `Parallel step ${i + 1} must have at least one task` }],
|
|
1366
|
-
isError: true,
|
|
1367
|
-
details: { mode: "chain", results: [] },
|
|
1368
|
-
};
|
|
1369
|
-
}
|
|
1370
|
-
}
|
|
1371
|
-
}
|
|
1372
|
-
return null;
|
|
1373
|
-
}
|
|
1374
|
-
function validateExecutionChainBindings(params, dynamicFanoutMaxItems) {
|
|
1375
|
-
if ((params.chain?.length ?? 0) === 0)
|
|
1376
|
-
return null;
|
|
1377
|
-
try {
|
|
1378
|
-
validateChainOutputBindingsWithContext(params.chain, { maxItems: dynamicFanoutMaxItems });
|
|
1379
|
-
}
|
|
1380
|
-
catch (error) {
|
|
1381
|
-
if (error instanceof ChainOutputValidationError) {
|
|
1382
|
-
return {
|
|
1383
|
-
content: [{ type: "text", text: error.message }],
|
|
1384
|
-
isError: true,
|
|
1385
|
-
details: { mode: "chain", results: [] },
|
|
1386
|
-
};
|
|
1387
|
-
}
|
|
1388
|
-
throw error;
|
|
1389
|
-
}
|
|
1390
|
-
return null;
|
|
1391
|
-
}
|
|
1392
|
-
function getRequestedModeLabel(params) {
|
|
1393
|
-
if ((params.chain?.length ?? 0) > 0)
|
|
1394
|
-
return "chain";
|
|
1395
|
-
if ((params.tasks?.length ?? 0) > 0)
|
|
1396
|
-
return "parallel";
|
|
1397
|
-
if (params.task)
|
|
1398
|
-
return "single";
|
|
1399
|
-
return "single";
|
|
1400
|
-
}
|
|
1401
|
-
function resolveAgentDefaultContextPolicy(params) {
|
|
1402
|
-
// lunr: hide fork from the model; force every child to fresh. Fork internals stay.
|
|
1403
|
-
return lunrContextPolicy(params);
|
|
1404
|
-
}
|
|
1405
|
-
function resolveExplicitContextPolicy(params) {
|
|
1406
|
-
// lunr: `context: "fork"` from the model is coerced to fresh.
|
|
1407
|
-
return lunrContextPolicy(params);
|
|
1408
|
-
}
|
|
1409
|
-
function shouldForkAgent(contextPolicy, agentName) {
|
|
1410
|
-
return contextPolicy.contextForAgent(agentName) === "fork";
|
|
1411
|
-
}
|
|
1412
|
-
function buildRequestedModeError(params, message) {
|
|
1413
|
-
return withForkContext({
|
|
1414
|
-
content: [{ type: "text", text: message }],
|
|
1415
|
-
isError: true,
|
|
1416
|
-
details: { mode: getRequestedModeLabel(params), results: [] },
|
|
1417
|
-
}, params.context);
|
|
1418
|
-
}
|
|
1419
|
-
function runtimeConfigFromChildSpec(spec) {
|
|
1420
|
-
return {
|
|
1421
|
-
name: spec.childId,
|
|
1422
|
-
description: spec.description,
|
|
1423
|
-
model: spec.model,
|
|
1424
|
-
thinking: undefined,
|
|
1425
|
-
systemPromptMode: "append",
|
|
1426
|
-
inheritProjectContext: true,
|
|
1427
|
-
inheritSkills: false,
|
|
1428
|
-
acceptanceRole: spec.effectivePermissions === "read-only" ? "read-only" : "writer",
|
|
1429
|
-
systemPrompt: "",
|
|
1430
|
-
skills: spec.skill === false ? [] : normalizeSkillInput(spec.skill) || undefined,
|
|
1431
|
-
output: typeof spec.output === "string" ? spec.output : undefined,
|
|
1432
|
-
toolBudget: spec.toolBudget,
|
|
1433
|
-
};
|
|
1434
|
-
}
|
|
1435
|
-
// The 3 casts to MaterializedParams below: a call sets only one of tasks, chain or task.
|
|
1436
|
-
// The lists this function leaves alone are empty, or validateExecutionInput (execute) or the
|
|
1437
|
-
// append-step guard rejects the call before anything runs.
|
|
1438
|
-
function internalizePromptDrivenChildren(params, options) {
|
|
1439
|
-
const agents = [];
|
|
1440
|
-
let flatIndex = 0;
|
|
1441
|
-
const normalize = (input, defaultTask) => {
|
|
1442
|
-
const spec = normalizeChildSpec(input, {
|
|
1443
|
-
parentMode: options.parentMode,
|
|
1444
|
-
runId: options.runId,
|
|
1445
|
-
index: flatIndex,
|
|
1446
|
-
defaultTask,
|
|
1447
|
-
});
|
|
1448
|
-
agents.push(runtimeConfigFromChildSpec(spec));
|
|
1449
|
-
return { input: { ...input, agent: spec.childId }, spec };
|
|
1450
|
-
};
|
|
1451
|
-
if ((params.tasks?.length ?? 0) > 0) {
|
|
1452
|
-
const tasks = params.tasks.map((task) => {
|
|
1453
|
-
const normalized = normalize(task);
|
|
1454
|
-
flatIndex++;
|
|
1455
|
-
return normalized.input;
|
|
1456
|
-
});
|
|
1457
|
-
return { params: { ...params, tasks }, agents };
|
|
1458
|
-
}
|
|
1459
|
-
if ((params.chain?.length ?? 0) > 0) {
|
|
1460
|
-
const chain = params.chain.map((step) => {
|
|
1461
|
-
if (isParallelStep(step)) {
|
|
1462
|
-
const parallel = step.parallel.map((task) => {
|
|
1463
|
-
const normalized = normalize(task, flatIndex === 0 ? params.task : "{previous}");
|
|
1464
|
-
flatIndex++;
|
|
1465
|
-
return normalized.input;
|
|
1466
|
-
});
|
|
1467
|
-
return { ...step, parallel };
|
|
1468
|
-
}
|
|
1469
|
-
if (isDynamicParallelStep(step)) {
|
|
1470
|
-
const normalized = normalize(step.parallel, "{previous}");
|
|
1471
|
-
const reserved = step.expand.maxItems ?? options.dynamicFanoutMaxItems ?? 1;
|
|
1472
|
-
flatIndex += Math.max(1, reserved);
|
|
1473
|
-
return { ...step, parallel: normalized.input };
|
|
1474
|
-
}
|
|
1475
|
-
const normalized = normalize(step, flatIndex === 0 ? params.task : "{previous}");
|
|
1476
|
-
flatIndex++;
|
|
1477
|
-
return normalized.input;
|
|
1478
|
-
});
|
|
1479
|
-
return { params: { ...params, chain }, agents };
|
|
1480
|
-
}
|
|
1481
|
-
const normalized = normalize({
|
|
1482
|
-
agent: params.agent,
|
|
1483
|
-
task: params.task ?? "",
|
|
1484
|
-
description: params.description,
|
|
1485
|
-
permissions: params.permissions,
|
|
1486
|
-
cwd: params.cwd,
|
|
1487
|
-
model: params.model,
|
|
1488
|
-
tier: params.tier,
|
|
1489
|
-
thinking: params.thinking,
|
|
1490
|
-
skill: params.skill,
|
|
1491
|
-
output: params.output,
|
|
1492
|
-
outputMode: params.outputMode,
|
|
1493
|
-
acceptance: params.acceptance,
|
|
1494
|
-
toolBudget: params.toolBudget,
|
|
1495
|
-
});
|
|
1496
|
-
return {
|
|
1497
|
-
params: { ...params, agent: normalized.spec.childId },
|
|
1498
|
-
agents,
|
|
1499
|
-
};
|
|
1500
|
-
}
|
|
1501
|
-
function resolveForegroundTimeout(params) {
|
|
1502
|
-
const rawTimeout = params.timeoutMs;
|
|
1503
|
-
const rawMaxRuntime = params.maxRuntimeMs;
|
|
1504
|
-
if (rawTimeout === undefined && rawMaxRuntime === undefined)
|
|
1505
|
-
return {};
|
|
1506
|
-
for (const [name, value] of [["timeoutMs", rawTimeout], ["maxRuntimeMs", rawMaxRuntime]]) {
|
|
1507
|
-
if (value === undefined)
|
|
1508
|
-
continue;
|
|
1509
|
-
if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
|
|
1510
|
-
return { error: `${name} must be a positive integer.` };
|
|
1511
|
-
}
|
|
1512
|
-
}
|
|
1513
|
-
if (rawTimeout !== undefined && rawMaxRuntime !== undefined && rawTimeout !== rawMaxRuntime) {
|
|
1514
|
-
return { error: "timeoutMs and maxRuntimeMs are aliases; provide only one value or use the same value for both." };
|
|
1515
|
-
}
|
|
1516
|
-
return { timeoutMs: rawTimeout ?? rawMaxRuntime };
|
|
1517
|
-
}
|
|
1518
|
-
function resolveToolBudget(raw, label = "toolBudget") {
|
|
1519
|
-
const resolved = validateToolBudgetConfig(raw, label);
|
|
1520
|
-
return { toolBudget: resolved.budget, error: resolved.error };
|
|
1521
|
-
}
|
|
1522
|
-
function resolveEffectiveToolBudget(input) {
|
|
1523
|
-
if (input.stepBudget !== undefined)
|
|
1524
|
-
return resolveToolBudget(input.stepBudget, "toolBudget");
|
|
1525
|
-
if (input.runBudget !== undefined)
|
|
1526
|
-
return { toolBudget: input.runBudget };
|
|
1527
|
-
if (input.agentBudget !== undefined)
|
|
1528
|
-
return resolveToolBudget(input.agentBudget, "agent.toolBudget");
|
|
1529
|
-
return resolveToolBudget(input.configBudget, "config.toolBudget");
|
|
1530
|
-
}
|
|
1531
|
-
function expandTopLevelTaskCounts(tasks) {
|
|
1532
|
-
const expanded = [];
|
|
1533
|
-
for (let taskIndex = 0; taskIndex < tasks.length; taskIndex++) {
|
|
1534
|
-
const task = tasks[taskIndex];
|
|
1535
|
-
const rawCount = task.count;
|
|
1536
|
-
if (rawCount !== undefined && (typeof rawCount !== "number" || !Number.isInteger(rawCount) || rawCount < 1)) {
|
|
1537
|
-
return { error: `tasks[${taskIndex}].count must be an integer >= 1` };
|
|
1538
|
-
}
|
|
1539
|
-
const { count, ...concreteTask } = task;
|
|
1540
|
-
for (let repeat = 0; repeat < (rawCount ?? 1); repeat++) {
|
|
1541
|
-
expanded.push({ ...concreteTask });
|
|
1542
|
-
}
|
|
1543
|
-
}
|
|
1544
|
-
return { tasks: expanded };
|
|
1545
|
-
}
|
|
1546
|
-
function expandChainParallelCounts(chain) {
|
|
1547
|
-
const expandedChain = [];
|
|
1548
|
-
for (let stepIndex = 0; stepIndex < chain.length; stepIndex++) {
|
|
1549
|
-
const step = chain[stepIndex];
|
|
1550
|
-
if (!isParallelStep(step)) {
|
|
1551
|
-
expandedChain.push(step);
|
|
1552
|
-
continue;
|
|
1553
|
-
}
|
|
1554
|
-
const expandedParallel = [];
|
|
1555
|
-
for (let taskIndex = 0; taskIndex < step.parallel.length; taskIndex++) {
|
|
1556
|
-
const task = step.parallel[taskIndex];
|
|
1557
|
-
const rawCount = task.count;
|
|
1558
|
-
if (rawCount !== undefined && (typeof rawCount !== "number" || !Number.isInteger(rawCount) || rawCount < 1)) {
|
|
1559
|
-
return { error: `chain[${stepIndex}].parallel[${taskIndex}].count must be an integer >= 1` };
|
|
1560
|
-
}
|
|
1561
|
-
const { count, ...concreteTask } = task;
|
|
1562
|
-
for (let repeat = 0; repeat < (rawCount ?? 1); repeat++) {
|
|
1563
|
-
expandedParallel.push({ ...concreteTask });
|
|
1564
|
-
}
|
|
1565
|
-
}
|
|
1566
|
-
expandedChain.push({ ...step, parallel: expandedParallel });
|
|
1567
|
-
}
|
|
1568
|
-
return { chain: expandedChain };
|
|
1569
|
-
}
|
|
1570
|
-
function normalizeRepeatedParallelCounts(params) {
|
|
1571
|
-
if (params.tasks) {
|
|
1572
|
-
const expandedTasks = expandTopLevelTaskCounts(params.tasks);
|
|
1573
|
-
if (expandedTasks.error) {
|
|
1574
|
-
return { error: buildRequestedModeError(params, expandedTasks.error) };
|
|
1575
|
-
}
|
|
1576
|
-
return { params: { ...params, tasks: expandedTasks.tasks } };
|
|
1577
|
-
}
|
|
1578
|
-
if (params.chain) {
|
|
1579
|
-
const expandedChain = expandChainParallelCounts(params.chain);
|
|
1580
|
-
if (expandedChain.error) {
|
|
1581
|
-
return { error: buildRequestedModeError(params, expandedChain.error) };
|
|
1582
|
-
}
|
|
1583
|
-
return { params: { ...params, chain: expandedChain.chain } };
|
|
1584
|
-
}
|
|
1585
|
-
return { params };
|
|
1586
|
-
}
|
|
1587
|
-
function withForkContext(result, context) {
|
|
1588
|
-
if (context !== "fork" || !result.details)
|
|
1589
|
-
return result;
|
|
1590
|
-
return {
|
|
1591
|
-
...result,
|
|
1592
|
-
details: {
|
|
1593
|
-
...result.details,
|
|
1594
|
-
context: "fork",
|
|
1595
|
-
},
|
|
1596
|
-
};
|
|
1597
|
-
}
|
|
1598
|
-
function withForkThinkingNotes(result, downgrades) {
|
|
1599
|
-
if (downgrades.size === 0)
|
|
1600
|
-
return result;
|
|
1601
|
-
const children = [...downgrades.entries()]
|
|
1602
|
-
.sort(([a], [b]) => a - b)
|
|
1603
|
-
.map(([index, agent]) => `${agent} (child ${index})`)
|
|
1604
|
-
.join(", ");
|
|
1605
|
-
const note = `Note: fork context forced thinking off for ${children}. The forked transcript contained signed Anthropic thinking blocks that were sanitized, and Anthropic children cannot resume such a transcript with thinking enabled. Use context: "fresh" when an Anthropic child needs thinking.`;
|
|
1606
|
-
return { ...result, content: [...result.content, { type: "text", text: note }] };
|
|
1607
|
-
}
|
|
1608
|
-
function toExecutionErrorResult(params, error) {
|
|
1609
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
1610
|
-
return withForkContext({
|
|
1611
|
-
content: [{ type: "text", text: message }],
|
|
1612
|
-
isError: true,
|
|
1613
|
-
details: { mode: getRequestedModeLabel(params), results: [] },
|
|
1614
|
-
}, params.context);
|
|
1615
|
-
}
|
|
1616
|
-
function collectChainSessionFiles(chain, sessionFileForTask, dynamicFanoutMaxItems) {
|
|
1617
|
-
const sessionFiles = [];
|
|
1618
|
-
let flatIndex = 0;
|
|
1619
|
-
for (const step of chain) {
|
|
1620
|
-
if (isParallelStep(step)) {
|
|
1621
|
-
for (const task of step.parallel) {
|
|
1622
|
-
sessionFiles.push(sessionFileForTask(task.agent, flatIndex, task.model));
|
|
1623
|
-
flatIndex++;
|
|
1624
|
-
}
|
|
1625
|
-
continue;
|
|
1626
|
-
}
|
|
1627
|
-
if (isDynamicParallelStep(step)) {
|
|
1628
|
-
const maxItems = step.expand.maxItems ?? dynamicFanoutMaxItems ?? 0;
|
|
1629
|
-
for (let itemIndex = 0; itemIndex < maxItems; itemIndex++) {
|
|
1630
|
-
sessionFiles.push(sessionFileForTask(step.parallel.agent, flatIndex, step.parallel.model));
|
|
1631
|
-
flatIndex++;
|
|
1632
|
-
}
|
|
1633
|
-
continue;
|
|
1634
|
-
}
|
|
1635
|
-
const sequential = step;
|
|
1636
|
-
sessionFiles.push(sessionFileForTask(sequential.agent, flatIndex, sequential.model));
|
|
1637
|
-
flatIndex++;
|
|
1638
|
-
}
|
|
1639
|
-
return sessionFiles;
|
|
1640
|
-
}
|
|
1641
|
-
function collectChainThinkingOverrides(chain, thinkingOverrideForTask, dynamicFanoutMaxItems) {
|
|
1642
|
-
const thinkingOverrides = [];
|
|
1643
|
-
let flatIndex = 0;
|
|
1644
|
-
for (const step of chain) {
|
|
1645
|
-
if (isParallelStep(step)) {
|
|
1646
|
-
for (const task of step.parallel) {
|
|
1647
|
-
thinkingOverrides.push(thinkingOverrideForTask(task.agent, flatIndex, task.model));
|
|
1648
|
-
flatIndex++;
|
|
1649
|
-
}
|
|
1650
|
-
continue;
|
|
1651
|
-
}
|
|
1652
|
-
if (isDynamicParallelStep(step)) {
|
|
1653
|
-
const maxItems = step.expand.maxItems ?? dynamicFanoutMaxItems ?? 0;
|
|
1654
|
-
for (let itemIndex = 0; itemIndex < maxItems; itemIndex++) {
|
|
1655
|
-
thinkingOverrides.push(thinkingOverrideForTask(step.parallel.agent, flatIndex, step.parallel.model));
|
|
1656
|
-
flatIndex++;
|
|
1657
|
-
}
|
|
1658
|
-
continue;
|
|
1659
|
-
}
|
|
1660
|
-
const sequential = step;
|
|
1661
|
-
thinkingOverrides.push(thinkingOverrideForTask(sequential.agent, flatIndex, sequential.model));
|
|
1662
|
-
flatIndex++;
|
|
1663
|
-
}
|
|
1664
|
-
return thinkingOverrides;
|
|
1665
|
-
}
|
|
1666
|
-
function firstChainAgent(chain) {
|
|
1667
|
-
const first = chain[0];
|
|
1668
|
-
if (!first)
|
|
1669
|
-
return undefined;
|
|
1670
|
-
if (isParallelStep(first))
|
|
1671
|
-
return first.parallel[0]?.agent;
|
|
1672
|
-
if (isDynamicParallelStep(first))
|
|
1673
|
-
return first.parallel.agent;
|
|
1674
|
-
return first.agent;
|
|
516
|
+
function firstChainAgent(chain) {
|
|
517
|
+
const first = chain[0];
|
|
518
|
+
if (!first)
|
|
519
|
+
return undefined;
|
|
520
|
+
if (isParallelStep(first))
|
|
521
|
+
return first.parallel[0]?.agent;
|
|
522
|
+
if (isDynamicParallelStep(first))
|
|
523
|
+
return first.parallel.agent;
|
|
524
|
+
return first.agent;
|
|
1675
525
|
}
|
|
1676
526
|
function firstRawChainTask(chain) {
|
|
1677
527
|
const first = chain[0];
|
|
@@ -1692,81 +542,6 @@ function resolveAsyncEventGoal(workflowTask, rawChain, unwrapForkFallback = fals
|
|
|
1692
542
|
const forkPrefix = `${DEFAULT_FORK_PREAMBLE}\n\nTask:\n`;
|
|
1693
543
|
return fallback.startsWith(forkPrefix) ? fallback.slice(forkPrefix.length) : fallback;
|
|
1694
544
|
}
|
|
1695
|
-
function wrapChainTasksForFork(chain, contextPolicy) {
|
|
1696
|
-
return chain.map((step, stepIndex) => {
|
|
1697
|
-
if (isParallelStep(step)) {
|
|
1698
|
-
return {
|
|
1699
|
-
...step,
|
|
1700
|
-
parallel: step.parallel.map((task) => ({
|
|
1701
|
-
...task,
|
|
1702
|
-
task: shouldForkAgent(contextPolicy, task.agent)
|
|
1703
|
-
? wrapForkTask(task.task ?? "{previous}")
|
|
1704
|
-
: task.task,
|
|
1705
|
-
})),
|
|
1706
|
-
};
|
|
1707
|
-
}
|
|
1708
|
-
if (isDynamicParallelStep(step)) {
|
|
1709
|
-
return {
|
|
1710
|
-
...step,
|
|
1711
|
-
parallel: {
|
|
1712
|
-
...step.parallel,
|
|
1713
|
-
task: shouldForkAgent(contextPolicy, step.parallel.agent)
|
|
1714
|
-
? wrapForkTask(step.parallel.task ?? "{previous}")
|
|
1715
|
-
: step.parallel.task,
|
|
1716
|
-
},
|
|
1717
|
-
};
|
|
1718
|
-
}
|
|
1719
|
-
const sequential = step;
|
|
1720
|
-
return {
|
|
1721
|
-
...sequential,
|
|
1722
|
-
task: shouldForkAgent(contextPolicy, sequential.agent)
|
|
1723
|
-
? wrapForkTask(sequential.task ?? (stepIndex === 0 ? "{task}" : "{previous}"))
|
|
1724
|
-
: sequential.task,
|
|
1725
|
-
};
|
|
1726
|
-
});
|
|
1727
|
-
}
|
|
1728
|
-
function preflightForkSessionsForStaticTasks(params, contextPolicy, sessionFileForTask, dynamicFanoutMaxItems) {
|
|
1729
|
-
if (!contextPolicy.usesFork)
|
|
1730
|
-
return;
|
|
1731
|
-
if (params.agent) {
|
|
1732
|
-
if (shouldForkAgent(contextPolicy, params.agent))
|
|
1733
|
-
sessionFileForTask(params.agent, 0, params.model);
|
|
1734
|
-
return;
|
|
1735
|
-
}
|
|
1736
|
-
if (params.tasks) {
|
|
1737
|
-
params.tasks.forEach((task, index) => {
|
|
1738
|
-
if (shouldForkAgent(contextPolicy, task.agent))
|
|
1739
|
-
sessionFileForTask(task.agent, index, task.model);
|
|
1740
|
-
});
|
|
1741
|
-
return;
|
|
1742
|
-
}
|
|
1743
|
-
if (!params.chain?.length)
|
|
1744
|
-
return;
|
|
1745
|
-
let flatIndex = 0;
|
|
1746
|
-
for (const step of params.chain) {
|
|
1747
|
-
if (isParallelStep(step)) {
|
|
1748
|
-
for (const task of step.parallel) {
|
|
1749
|
-
if (shouldForkAgent(contextPolicy, task.agent))
|
|
1750
|
-
sessionFileForTask(task.agent, flatIndex, task.model);
|
|
1751
|
-
flatIndex++;
|
|
1752
|
-
}
|
|
1753
|
-
continue;
|
|
1754
|
-
}
|
|
1755
|
-
if (isDynamicParallelStep(step)) {
|
|
1756
|
-
const maxItems = step.expand.maxItems ?? dynamicFanoutMaxItems ?? 0;
|
|
1757
|
-
if (shouldForkAgent(contextPolicy, step.parallel.agent)) {
|
|
1758
|
-
for (let itemIndex = 0; itemIndex < maxItems; itemIndex++)
|
|
1759
|
-
sessionFileForTask(step.parallel.agent, flatIndex + itemIndex, step.parallel.model);
|
|
1760
|
-
}
|
|
1761
|
-
flatIndex += maxItems;
|
|
1762
|
-
continue;
|
|
1763
|
-
}
|
|
1764
|
-
const sequential = step;
|
|
1765
|
-
if (shouldForkAgent(contextPolicy, sequential.agent))
|
|
1766
|
-
sessionFileForTask(sequential.agent, flatIndex, sequential.model);
|
|
1767
|
-
flatIndex++;
|
|
1768
|
-
}
|
|
1769
|
-
}
|
|
1770
545
|
function runAsyncPath(data, deps) {
|
|
1771
546
|
const { params, effectiveCwd, agents, ctx, sessionRoot, sessionFileForIndex, sessionFileForTask, thinkingOverrideForTask, artifactConfig, artifactsDir, effectiveAsync, controlConfig, intercomBridge, nestedRoute, contextPolicy, } = data;
|
|
1772
547
|
const hasChain = (params.chain?.length ?? 0) > 0;
|
|
@@ -2128,38 +903,6 @@ async function runChainPath(data, deps) {
|
|
|
2128
903
|
}
|
|
2129
904
|
return chainDetails ? { ...chainResult, details: chainDetails } : chainResult;
|
|
2130
905
|
}
|
|
2131
|
-
function buildParallelModeError(message) {
|
|
2132
|
-
return {
|
|
2133
|
-
content: [{ type: "text", text: message }],
|
|
2134
|
-
isError: true,
|
|
2135
|
-
details: { mode: "parallel", results: [] },
|
|
2136
|
-
};
|
|
2137
|
-
}
|
|
2138
|
-
function createParallelWorktreeSetup(enabled, cwd, runId, tasks, setupHook, setupHookTimeoutMs, baseDir) {
|
|
2139
|
-
if (!enabled)
|
|
2140
|
-
return {};
|
|
2141
|
-
try {
|
|
2142
|
-
return {
|
|
2143
|
-
setup: createWorktrees(cwd, runId, tasks.length, {
|
|
2144
|
-
agents: tasks.map((task) => task.agent),
|
|
2145
|
-
setupHook: setupHook
|
|
2146
|
-
? { hookPath: setupHook, timeoutMs: setupHookTimeoutMs }
|
|
2147
|
-
: undefined,
|
|
2148
|
-
baseDir,
|
|
2149
|
-
}),
|
|
2150
|
-
};
|
|
2151
|
-
}
|
|
2152
|
-
catch (error) {
|
|
2153
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
2154
|
-
return { errorResult: buildParallelModeError(message) };
|
|
2155
|
-
}
|
|
2156
|
-
}
|
|
2157
|
-
function buildParallelWorktreeTaskCwdError(tasks, sharedCwd) {
|
|
2158
|
-
const conflict = findWorktreeTaskCwdConflict(tasks, sharedCwd);
|
|
2159
|
-
if (!conflict)
|
|
2160
|
-
return undefined;
|
|
2161
|
-
return formatWorktreeTaskCwdConflict(conflict, sharedCwd);
|
|
2162
|
-
}
|
|
2163
906
|
/** A sync chain without `chainDir` works in `chain-runs/` of the private artifacts dir, like the run's other files. */
|
|
2164
907
|
function defaultChainRunsDir(artifactsDir) {
|
|
2165
908
|
ensureArtifactsDir(artifactsDir);
|
|
@@ -2184,486 +927,6 @@ function buildChainWorktreeTaskCwdError(chain, sharedCwd) {
|
|
|
2184
927
|
}
|
|
2185
928
|
return undefined;
|
|
2186
929
|
}
|
|
2187
|
-
function resolveParallelTaskCwd(task, paramsCwd, worktreeSetup, index) {
|
|
2188
|
-
if (worktreeSetup)
|
|
2189
|
-
return worktreeSetup.worktrees[index].agentCwd;
|
|
2190
|
-
return resolveChildCwd(paramsCwd, task.cwd);
|
|
2191
|
-
}
|
|
2192
|
-
function buildParallelWorktreeSuffix(worktreeSetup, artifactsDir, tasks) {
|
|
2193
|
-
if (!worktreeSetup)
|
|
2194
|
-
return "";
|
|
2195
|
-
const diffsDir = path.join(artifactsDir, "worktree-diffs");
|
|
2196
|
-
const diffs = diffWorktrees(worktreeSetup, tasks.map((task) => task.agent), diffsDir);
|
|
2197
|
-
return formatWorktreeDiffSummary(diffs);
|
|
2198
|
-
}
|
|
2199
|
-
function findDuplicateParallelOutputPath(input) {
|
|
2200
|
-
const seen = new Map();
|
|
2201
|
-
for (let index = 0; index < input.tasks.length; index++) {
|
|
2202
|
-
const behavior = input.behaviors[index];
|
|
2203
|
-
if (!behavior?.output)
|
|
2204
|
-
continue;
|
|
2205
|
-
const task = input.tasks[index];
|
|
2206
|
-
const taskCwd = resolveParallelTaskCwd(task, input.paramsCwd, input.worktreeSetup, index);
|
|
2207
|
-
const outputPath = resolveSingleOutputPath(behavior.output, input.ctxCwd, taskCwd, input.outputBaseDir);
|
|
2208
|
-
if (!outputPath)
|
|
2209
|
-
continue;
|
|
2210
|
-
const previous = seen.get(outputPath);
|
|
2211
|
-
if (previous) {
|
|
2212
|
-
return `Parallel tasks ${previous.index + 1} (${previous.agent}) and ${index + 1} (${task.agent}) resolve output to the same path: ${outputPath}. Use distinct output paths.`;
|
|
2213
|
-
}
|
|
2214
|
-
seen.set(outputPath, { index, agent: task.agent });
|
|
2215
|
-
}
|
|
2216
|
-
return undefined;
|
|
2217
|
-
}
|
|
2218
|
-
async function runForegroundParallelTasks(input) {
|
|
2219
|
-
// Pre-warm fork session files sequentially before concurrent dispatch to avoid
|
|
2220
|
-
// races where multiple workers simultaneously try to branch the same parent session.
|
|
2221
|
-
for (let i = 0; i < input.tasks.length; i++) {
|
|
2222
|
-
input.sessionFileForTask(input.tasks[i].agent, i, input.modelOverrides[i]);
|
|
2223
|
-
}
|
|
2224
|
-
return mapConcurrent(input.tasks, input.concurrencyLimit, async (task, index) => {
|
|
2225
|
-
const behavior = input.behaviors[index];
|
|
2226
|
-
const effectiveSkills = behavior?.skills;
|
|
2227
|
-
const taskCwd = resolveParallelTaskCwd(task, input.paramsCwd, input.worktreeSetup, index);
|
|
2228
|
-
const readInstructions = behavior
|
|
2229
|
-
? buildChainInstructions({ ...behavior, output: false, progress: false }, taskCwd, false)
|
|
2230
|
-
: { prefix: "", suffix: "" };
|
|
2231
|
-
const progressInstructions = behavior
|
|
2232
|
-
? buildChainInstructions({ ...behavior, output: false, reads: false }, input.progressDir, index === input.firstProgressIndex)
|
|
2233
|
-
: { prefix: "", suffix: "" };
|
|
2234
|
-
const outputPath = resolveSingleOutputPath(behavior?.output, input.ctx.cwd, taskCwd, input.outputBaseDir);
|
|
2235
|
-
const agentConfig = input.agents.find((agent) => agent.name === task.agent);
|
|
2236
|
-
const taskText = injectSingleOutputInstruction(`${readInstructions.prefix}${input.taskTexts[index]}${progressInstructions.suffix}`, outputPath, agentConfig);
|
|
2237
|
-
const interruptController = new AbortController();
|
|
2238
|
-
if (input.foregroundControl) {
|
|
2239
|
-
input.foregroundControl.currentAgent = task.description || task.agent;
|
|
2240
|
-
input.foregroundControl.currentChildId = task.agent;
|
|
2241
|
-
input.foregroundControl.currentIndex = index;
|
|
2242
|
-
input.foregroundControl.currentActivityState = undefined;
|
|
2243
|
-
input.foregroundControl.updatedAt = Date.now();
|
|
2244
|
-
input.foregroundControl.interrupt = () => {
|
|
2245
|
-
if (interruptController.signal.aborted)
|
|
2246
|
-
return false;
|
|
2247
|
-
interruptController.abort();
|
|
2248
|
-
input.foregroundControl.currentActivityState = undefined;
|
|
2249
|
-
input.foregroundControl.updatedAt = Date.now();
|
|
2250
|
-
return true;
|
|
2251
|
-
};
|
|
2252
|
-
}
|
|
2253
|
-
const modelSelection = input.modelSelections[index] ?? captureModelSelection({ model: task.model, tier: task.tier });
|
|
2254
|
-
return runSync(input.ctx.cwd, normalizeChildSpec({
|
|
2255
|
-
task: taskText,
|
|
2256
|
-
description: task.description,
|
|
2257
|
-
permissions: task.permissions,
|
|
2258
|
-
model: task.model,
|
|
2259
|
-
tier: task.tier,
|
|
2260
|
-
thinking: task.thinking,
|
|
2261
|
-
modelSelection,
|
|
2262
|
-
skill: task.skill,
|
|
2263
|
-
cwd: taskCwd,
|
|
2264
|
-
output: task.output,
|
|
2265
|
-
outputMode: task.outputMode,
|
|
2266
|
-
acceptance: task.acceptance,
|
|
2267
|
-
toolBudget: task.toolBudget,
|
|
2268
|
-
}, { parentMode: snapshotParentPermissionMode(input.ctx.sessionManager.getSessionId() ?? undefined), runId: input.runId, index }), {
|
|
2269
|
-
parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
|
|
2270
|
-
cwd: taskCwd,
|
|
2271
|
-
signal: input.signal,
|
|
2272
|
-
interruptSignal: interruptController.signal,
|
|
2273
|
-
allowIntercomDetach: agentConfig?.systemPrompt?.includes(INTERCOM_BRIDGE_MARKER) === true,
|
|
2274
|
-
intercomEvents: input.intercomEvents,
|
|
2275
|
-
runId: input.runId,
|
|
2276
|
-
index,
|
|
2277
|
-
sessionDir: input.sessionDirForIndex(index),
|
|
2278
|
-
sessionFile: input.sessionFileForTask(task.agent, index, input.modelOverrides[index]),
|
|
2279
|
-
artifactsDir: input.artifactConfig.enabled ? input.artifactsDir : undefined,
|
|
2280
|
-
artifactConfig: input.artifactConfig,
|
|
2281
|
-
maxOutput: input.maxOutput,
|
|
2282
|
-
outputPath,
|
|
2283
|
-
outputMode: behavior?.outputMode,
|
|
2284
|
-
maxSubagentDepth: input.maxSubagentDepths[index],
|
|
2285
|
-
waitToolEnabled: input.waitToolEnabled,
|
|
2286
|
-
controlConfig: input.controlConfig,
|
|
2287
|
-
onControlEvent: input.onControlEvent,
|
|
2288
|
-
onDetachedExit: (result) => updateRememberedForegroundChild(input.state, { runId: input.runId, mode: "parallel", cwd: taskCwd, sessionId: input.parentSessionId, index, result, events: input.intercomEvents }),
|
|
2289
|
-
intercomSessionName: input.childIntercomTarget?.(task.agent, index),
|
|
2290
|
-
orchestratorIntercomTarget: input.orchestratorIntercomTarget,
|
|
2291
|
-
communicationEnabled: input.communicationEnabled,
|
|
2292
|
-
nestedRoute: input.foregroundControl?.nestedRoute,
|
|
2293
|
-
modelOverride: input.modelOverrides[index],
|
|
2294
|
-
thinkingOverride: input.thinkingOverrideForTask(task.agent, index, input.modelOverrides[index]),
|
|
2295
|
-
availableModels: input.availableModels,
|
|
2296
|
-
preferredModelProvider: input.ctx.model?.provider,
|
|
2297
|
-
modelScope: input.modelScope,
|
|
2298
|
-
skills: effectiveSkills === false ? [] : effectiveSkills,
|
|
2299
|
-
acceptance: task.acceptance,
|
|
2300
|
-
acceptanceContext: { mode: "parallel" },
|
|
2301
|
-
timeoutMs: input.timeoutMs,
|
|
2302
|
-
deadlineAt: input.deadlineAt,
|
|
2303
|
-
turnBudget: input.turnBudget,
|
|
2304
|
-
toolBudget: input.toolBudgets[index],
|
|
2305
|
-
onUpdate: input.onUpdate
|
|
2306
|
-
? (progressUpdate) => {
|
|
2307
|
-
const stepResults = progressUpdate.details?.results || [];
|
|
2308
|
-
const stepProgress = progressUpdate.details?.progress || [];
|
|
2309
|
-
if (input.foregroundControl && stepProgress.length > 0) {
|
|
2310
|
-
const current = stepProgress[0];
|
|
2311
|
-
input.foregroundControl.currentAgent = task.description || task.agent;
|
|
2312
|
-
input.foregroundControl.currentChildId = task.agent;
|
|
2313
|
-
input.foregroundControl.currentIndex = index;
|
|
2314
|
-
input.foregroundControl.currentActivityState = current?.activityState;
|
|
2315
|
-
input.foregroundControl.lastActivityAt = current?.lastActivityAt;
|
|
2316
|
-
input.foregroundControl.currentTool = current?.currentTool;
|
|
2317
|
-
input.foregroundControl.currentToolStartedAt = current?.currentToolStartedAt;
|
|
2318
|
-
input.foregroundControl.currentPath = current?.currentPath;
|
|
2319
|
-
input.foregroundControl.turnCount = current?.turnCount;
|
|
2320
|
-
input.foregroundControl.tokens = current?.tokens;
|
|
2321
|
-
input.foregroundControl.toolCount = current?.toolCount;
|
|
2322
|
-
input.foregroundControl.updatedAt = Date.now();
|
|
2323
|
-
}
|
|
2324
|
-
if (stepResults.length > 0)
|
|
2325
|
-
input.liveResults[index] = stepResults[0];
|
|
2326
|
-
if (stepProgress.length > 0)
|
|
2327
|
-
input.liveProgress[index] = stepProgress[0];
|
|
2328
|
-
const mergedResults = input.liveResults.filter((result) => result !== undefined);
|
|
2329
|
-
const mergedProgress = input.liveProgress.filter((progress) => progress !== undefined);
|
|
2330
|
-
input.onUpdate?.({
|
|
2331
|
-
content: progressUpdate.content,
|
|
2332
|
-
details: {
|
|
2333
|
-
mode: "parallel",
|
|
2334
|
-
results: mergedResults,
|
|
2335
|
-
progress: mergedProgress,
|
|
2336
|
-
controlEvents: progressUpdate.details?.controlEvents,
|
|
2337
|
-
totalSteps: input.tasks.length,
|
|
2338
|
-
},
|
|
2339
|
-
});
|
|
2340
|
-
}
|
|
2341
|
-
: undefined,
|
|
2342
|
-
}).finally(() => {
|
|
2343
|
-
if (input.foregroundControl?.currentIndex === index) {
|
|
2344
|
-
input.foregroundControl.interrupt = undefined;
|
|
2345
|
-
input.foregroundControl.updatedAt = Date.now();
|
|
2346
|
-
}
|
|
2347
|
-
});
|
|
2348
|
-
}, input.globalSemaphore, {
|
|
2349
|
-
signal: input.signal,
|
|
2350
|
-
onAbort: (task) => ({
|
|
2351
|
-
agent: task.agent, task: task.task ?? "", exitCode: 1, messages: [],
|
|
2352
|
-
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 },
|
|
2353
|
-
error: "Subagent launch cancelled.",
|
|
2354
|
-
}),
|
|
2355
|
-
});
|
|
2356
|
-
}
|
|
2357
|
-
async function runParallelPath(data, deps) {
|
|
2358
|
-
const { params, effectiveCwd, agents, ctx, signal, runId, sessionDirForIndex, sessionFileForIndex, sessionFileForTask, thinkingOverrideForTask, artifactConfig, artifactsDir, backgroundRequestedWhileClarifying, onUpdate, sessionRoot, controlConfig, contextPolicy, } = data;
|
|
2359
|
-
const onControlEvent = createForegroundControlNotifier(data, deps);
|
|
2360
|
-
const childIntercomTarget = data.intercomBridge.active ? resolveSubagentIntercomTarget : undefined;
|
|
2361
|
-
const allProgress = [];
|
|
2362
|
-
const allArtifactPaths = [];
|
|
2363
|
-
const tasks = params.tasks;
|
|
2364
|
-
const maxParallelTasks = resolveTopLevelParallelMaxTasks(deps.config.parallel?.maxTasks);
|
|
2365
|
-
const parallelConcurrency = resolveTopLevelParallelConcurrency(params.concurrency, deps.config.parallel?.concurrency);
|
|
2366
|
-
if (tasks.length > maxParallelTasks)
|
|
2367
|
-
return {
|
|
2368
|
-
content: [{ type: "text", text: `Max ${maxParallelTasks} tasks` }],
|
|
2369
|
-
isError: true,
|
|
2370
|
-
details: { mode: "parallel", results: [] },
|
|
2371
|
-
};
|
|
2372
|
-
const agentConfigs = [];
|
|
2373
|
-
for (const t of tasks) {
|
|
2374
|
-
const config = agents.find((a) => a.name === t.agent);
|
|
2375
|
-
if (!config) {
|
|
2376
|
-
return {
|
|
2377
|
-
content: [{ type: "text", text: `Unknown agent: ${t.agent}` }],
|
|
2378
|
-
isError: true,
|
|
2379
|
-
details: { mode: "parallel", results: [] },
|
|
2380
|
-
};
|
|
2381
|
-
}
|
|
2382
|
-
agentConfigs.push(config);
|
|
2383
|
-
}
|
|
2384
|
-
const currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth);
|
|
2385
|
-
const maxSubagentDepths = agentConfigs.map((config) => resolveChildMaxSubagentDepth(currentMaxSubagentDepth, config.maxSubagentDepth));
|
|
2386
|
-
const toolBudgets = [];
|
|
2387
|
-
for (let index = 0; index < tasks.length; index++) {
|
|
2388
|
-
const resolved = resolveEffectiveToolBudget({ stepBudget: tasks[index]?.toolBudget, runBudget: data.toolBudget, agentBudget: agentConfigs[index]?.toolBudget, configBudget: data.configToolBudget });
|
|
2389
|
-
if (resolved.error)
|
|
2390
|
-
return buildParallelModeError(resolved.error);
|
|
2391
|
-
toolBudgets.push(resolved.toolBudget);
|
|
2392
|
-
}
|
|
2393
|
-
if (params.worktree) {
|
|
2394
|
-
const worktreeTaskCwdError = buildParallelWorktreeTaskCwdError(tasks, effectiveCwd);
|
|
2395
|
-
if (worktreeTaskCwdError)
|
|
2396
|
-
return buildParallelModeError(worktreeTaskCwdError);
|
|
2397
|
-
}
|
|
2398
|
-
const currentProvider = ctx.model?.provider;
|
|
2399
|
-
const availableModels = ctx.modelRegistry.getAvailable().map(toModelInfo);
|
|
2400
|
-
let taskTexts = tasks.map((t) => t.task);
|
|
2401
|
-
const skillOverrides = tasks.map((t) => normalizeSkillInput(t.skill));
|
|
2402
|
-
const behaviorOverrides = tasks.map((task, index) => ({
|
|
2403
|
-
...(task.output !== undefined && task.output !== true ? { output: task.output } : {}),
|
|
2404
|
-
...(task.outputMode !== undefined ? { outputMode: task.outputMode } : {}),
|
|
2405
|
-
...(task.reads !== undefined && task.reads !== true ? { reads: task.reads } : {}),
|
|
2406
|
-
...(task.progress !== undefined ? { progress: task.progress } : {}),
|
|
2407
|
-
...(skillOverrides[index] !== undefined ? { skills: skillOverrides[index] } : {}),
|
|
2408
|
-
}));
|
|
2409
|
-
const modelSelections = tasks.map((task) => captureModelSelection({ model: task.model, tier: task.tier }));
|
|
2410
|
-
const modelOverrides = tasks.map((task, index) => resolveExecutableChildModel({
|
|
2411
|
-
modelSelection: modelSelections[index],
|
|
2412
|
-
model: task.model,
|
|
2413
|
-
tier: task.tier,
|
|
2414
|
-
thinking: task.thinking,
|
|
2415
|
-
availableModels,
|
|
2416
|
-
preferredProvider: currentProvider,
|
|
2417
|
-
}));
|
|
2418
|
-
if (params.clarify === true && ctx.hasUI) {
|
|
2419
|
-
const behaviors = agentConfigs.map((_c, i) => resolveStepBehavior(behaviorOverrides[i]));
|
|
2420
|
-
const availableSkills = discoverAvailableSkills(effectiveCwd);
|
|
2421
|
-
const result = await ctx.ui.custom((tui, theme, _kb, done) => new ChainClarifyComponent(tui, theme, agentConfigs, taskTexts, "", undefined, behaviors, availableModels, currentProvider, availableSkills, done, "parallel"), { overlay: true, overlayOptions: { anchor: "center", width: 84, maxHeight: "80%" } });
|
|
2422
|
-
if (!result || !result.confirmed) {
|
|
2423
|
-
return { content: [{ type: "text", text: "Cancelled" }], details: { mode: "parallel", results: [] } };
|
|
2424
|
-
}
|
|
2425
|
-
taskTexts = result.templates;
|
|
2426
|
-
for (let i = 0; i < result.behaviorOverrides.length; i++) {
|
|
2427
|
-
const override = result.behaviorOverrides[i];
|
|
2428
|
-
if (override?.output !== undefined)
|
|
2429
|
-
behaviorOverrides[i].output = override.output;
|
|
2430
|
-
if (override?.reads !== undefined)
|
|
2431
|
-
behaviorOverrides[i].reads = override.reads;
|
|
2432
|
-
if (override?.progress !== undefined)
|
|
2433
|
-
behaviorOverrides[i].progress = override.progress;
|
|
2434
|
-
if (override?.skills !== undefined) {
|
|
2435
|
-
skillOverrides[i] = override.skills;
|
|
2436
|
-
behaviorOverrides[i].skills = override.skills;
|
|
2437
|
-
}
|
|
2438
|
-
}
|
|
2439
|
-
if (result.runInBackground) {
|
|
2440
|
-
if (!isAsyncAvailable()) {
|
|
2441
|
-
return {
|
|
2442
|
-
content: [{ type: "text", text: "Background mode requires upstream jiti for TypeScript execution but it could not be found. Ensure the pi-subagents package dependencies are installed." }],
|
|
2443
|
-
isError: true,
|
|
2444
|
-
details: { mode: "parallel", results: [] },
|
|
2445
|
-
};
|
|
2446
|
-
}
|
|
2447
|
-
const id = randomUUID();
|
|
2448
|
-
const asyncCtx = {
|
|
2449
|
-
pi: deps.pi,
|
|
2450
|
-
cwd: ctx.cwd,
|
|
2451
|
-
currentSessionId: deps.state.currentSessionId,
|
|
2452
|
-
parentSessionId: ctx.sessionManager.getSessionId() ?? undefined,
|
|
2453
|
-
currentModelProvider: ctx.model?.provider,
|
|
2454
|
-
currentModel: ctx.model,
|
|
2455
|
-
modelScope: data.modelScope,
|
|
2456
|
-
};
|
|
2457
|
-
const parallelTasks = tasks.map((t, i) => {
|
|
2458
|
-
const taskText = shouldForkAgent(contextPolicy, t.agent) ? wrapForkTask(taskTexts[i]) : taskTexts[i];
|
|
2459
|
-
const progress = taskDisallowsFileUpdates(taskText) ? false : behaviorOverrides[i]?.progress;
|
|
2460
|
-
return {
|
|
2461
|
-
agent: t.agent,
|
|
2462
|
-
task: taskText,
|
|
2463
|
-
description: t.description,
|
|
2464
|
-
permissions: t.permissions,
|
|
2465
|
-
cwd: t.cwd,
|
|
2466
|
-
model: t.model,
|
|
2467
|
-
tier: t.tier,
|
|
2468
|
-
thinking: t.thinking,
|
|
2469
|
-
...(skillOverrides[i] !== undefined ? { skill: skillOverrides[i] } : {}),
|
|
2470
|
-
...(behaviorOverrides[i]?.output !== undefined ? { output: behaviorOverrides[i].output } : {}),
|
|
2471
|
-
...(behaviorOverrides[i]?.outputMode !== undefined ? { outputMode: behaviorOverrides[i].outputMode } : {}),
|
|
2472
|
-
...(behaviorOverrides[i]?.reads !== undefined ? { reads: behaviorOverrides[i].reads } : {}),
|
|
2473
|
-
...(progress !== undefined ? { progress } : {}),
|
|
2474
|
-
...(t.toolBudget !== undefined ? { toolBudget: t.toolBudget } : {}),
|
|
2475
|
-
...(t.acceptance !== undefined ? { acceptance: t.acceptance } : {}),
|
|
2476
|
-
};
|
|
2477
|
-
});
|
|
2478
|
-
return executeAsyncChain(id, {
|
|
2479
|
-
chain: [{ parallel: parallelTasks, concurrency: parallelConcurrency, worktree: params.worktree }],
|
|
2480
|
-
resultMode: "parallel",
|
|
2481
|
-
goal: taskTexts[0] ?? "",
|
|
2482
|
-
communicationEnabled: data.intercomBridge.communicationEnabled,
|
|
2483
|
-
ctx: asyncCtx,
|
|
2484
|
-
availableModels,
|
|
2485
|
-
cwd: effectiveCwd,
|
|
2486
|
-
maxOutput: params.maxOutput,
|
|
2487
|
-
artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
|
|
2488
|
-
artifactConfig,
|
|
2489
|
-
sessionRoot,
|
|
2490
|
-
chainSkills: [],
|
|
2491
|
-
sessionFilesByFlatIndex: tasks.map((task, index) => sessionFileForTask(task.agent, index, modelOverrides[index])),
|
|
2492
|
-
thinkingOverridesByFlatIndex: tasks.map((task, index) => thinkingOverrideForTask(task.agent, index, modelOverrides[index])),
|
|
2493
|
-
maxSubagentDepth: currentMaxSubagentDepth,
|
|
2494
|
-
waitToolEnabled: deps.waitToolEnabled,
|
|
2495
|
-
worktreeSetupHook: deps.config.worktreeSetupHook,
|
|
2496
|
-
worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
|
|
2497
|
-
worktreeBaseDir: deps.config.worktreeBaseDir,
|
|
2498
|
-
controlConfig,
|
|
2499
|
-
controlIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,
|
|
2500
|
-
childIntercomTarget: data.intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(id, agent, index) : undefined,
|
|
2501
|
-
timeoutMs: data.timeoutMs,
|
|
2502
|
-
turnBudget: data.turnBudget,
|
|
2503
|
-
globalConcurrencyLimit: deps.config.globalConcurrencyLimit,
|
|
2504
|
-
});
|
|
2505
|
-
}
|
|
2506
|
-
}
|
|
2507
|
-
const behaviors = agentConfigs.map((_config, index) => suppressProgressForReadOnlyTask(resolveStepBehavior(behaviorOverrides[index]), taskTexts[index]));
|
|
2508
|
-
const firstProgressIndex = behaviors.findIndex((behavior) => behavior.progress);
|
|
2509
|
-
const liveResults = new Array(tasks.length).fill(undefined);
|
|
2510
|
-
const liveProgress = new Array(tasks.length).fill(undefined);
|
|
2511
|
-
const foregroundControl = deps.state.foregroundControls.get(runId);
|
|
2512
|
-
const { setup: worktreeSetup, errorResult } = createParallelWorktreeSetup(params.worktree, effectiveCwd, runId, tasks, deps.config.worktreeSetupHook, deps.config.worktreeSetupHookTimeoutMs, deps.config.worktreeBaseDir);
|
|
2513
|
-
if (errorResult)
|
|
2514
|
-
return errorResult;
|
|
2515
|
-
try {
|
|
2516
|
-
const outputBaseDir = path.join(artifactsDir, "outputs", runId);
|
|
2517
|
-
const duplicateOutputError = findDuplicateParallelOutputPath({
|
|
2518
|
-
tasks,
|
|
2519
|
-
behaviors,
|
|
2520
|
-
paramsCwd: effectiveCwd,
|
|
2521
|
-
ctxCwd: ctx.cwd,
|
|
2522
|
-
outputBaseDir,
|
|
2523
|
-
worktreeSetup,
|
|
2524
|
-
});
|
|
2525
|
-
if (duplicateOutputError)
|
|
2526
|
-
return buildParallelModeError(duplicateOutputError);
|
|
2527
|
-
for (let index = 0; index < tasks.length; index++) {
|
|
2528
|
-
const taskCwd = resolveParallelTaskCwd(tasks[index], effectiveCwd, worktreeSetup, index);
|
|
2529
|
-
const outputPath = resolveSingleOutputPath(behaviors[index]?.output, ctx.cwd, taskCwd, outputBaseDir);
|
|
2530
|
-
const validationError = validateFileOnlyOutputMode(behaviors[index]?.outputMode, outputPath, `Parallel task ${index + 1} (${tasks[index].agent})`) ?? outputTargetError(outputPath, ctx.cwd) ?? readOnlyOutputError(outputPath, outputBaseDir, ctx.sessionManager.getSessionId() ?? undefined);
|
|
2531
|
-
if (validationError)
|
|
2532
|
-
return buildParallelModeError(validationError);
|
|
2533
|
-
}
|
|
2534
|
-
const parallelProgressPrecreated = firstProgressIndex !== -1;
|
|
2535
|
-
const parallelProgressDir = path.join(artifactsDir, "progress", runId);
|
|
2536
|
-
if (parallelProgressPrecreated)
|
|
2537
|
-
writeInitialProgressFile(parallelProgressDir);
|
|
2538
|
-
for (let i = 0; i < taskTexts.length; i++) {
|
|
2539
|
-
if (shouldForkAgent(contextPolicy, tasks[i].agent))
|
|
2540
|
-
taskTexts[i] = wrapForkTask(taskTexts[i]);
|
|
2541
|
-
}
|
|
2542
|
-
const deadlineAt = data.deadlineAt ?? (data.timeoutMs !== undefined ? Date.now() + data.timeoutMs : undefined);
|
|
2543
|
-
const results = await runForegroundParallelTasks({
|
|
2544
|
-
tasks,
|
|
2545
|
-
taskTexts,
|
|
2546
|
-
agents,
|
|
2547
|
-
ctx,
|
|
2548
|
-
state: deps.state,
|
|
2549
|
-
intercomEvents: deps.pi.events,
|
|
2550
|
-
parentSessionId: ctx.sessionManager.getSessionId() ?? undefined,
|
|
2551
|
-
signal,
|
|
2552
|
-
runId,
|
|
2553
|
-
sessionDirForIndex,
|
|
2554
|
-
sessionFileForIndex,
|
|
2555
|
-
sessionFileForTask,
|
|
2556
|
-
thinkingOverrideForTask,
|
|
2557
|
-
artifactConfig,
|
|
2558
|
-
artifactsDir,
|
|
2559
|
-
outputBaseDir,
|
|
2560
|
-
maxOutput: params.maxOutput,
|
|
2561
|
-
paramsCwd: effectiveCwd,
|
|
2562
|
-
progressDir: parallelProgressDir,
|
|
2563
|
-
availableModels,
|
|
2564
|
-
modelScope: data.modelScope,
|
|
2565
|
-
modelOverrides,
|
|
2566
|
-
modelSelections,
|
|
2567
|
-
behaviors,
|
|
2568
|
-
firstProgressIndex: parallelProgressPrecreated ? -1 : firstProgressIndex,
|
|
2569
|
-
controlConfig,
|
|
2570
|
-
onControlEvent,
|
|
2571
|
-
childIntercomTarget: childIntercomTarget ? (agent, index) => childIntercomTarget(runId, agent, index) : undefined,
|
|
2572
|
-
orchestratorIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,
|
|
2573
|
-
communicationEnabled: data.intercomBridge.communicationEnabled,
|
|
2574
|
-
foregroundControl,
|
|
2575
|
-
concurrencyLimit: parallelConcurrency,
|
|
2576
|
-
globalSemaphore: new Semaphore(deps.config.globalConcurrencyLimit ?? DEFAULT_GLOBAL_CONCURRENCY_LIMIT),
|
|
2577
|
-
maxSubagentDepths,
|
|
2578
|
-
waitToolEnabled: deps.waitToolEnabled,
|
|
2579
|
-
liveResults,
|
|
2580
|
-
liveProgress,
|
|
2581
|
-
onUpdate,
|
|
2582
|
-
worktreeSetup,
|
|
2583
|
-
timeoutMs: data.timeoutMs,
|
|
2584
|
-
deadlineAt,
|
|
2585
|
-
turnBudget: data.turnBudget,
|
|
2586
|
-
toolBudgets,
|
|
2587
|
-
});
|
|
2588
|
-
for (let i = 0; i < results.length; i++) {
|
|
2589
|
-
const run = results[i];
|
|
2590
|
-
recordRun(run.agent, taskTexts[i], run.exitCode, run.progressSummary?.durationMs ?? 0);
|
|
2591
|
-
}
|
|
2592
|
-
for (const result of results) {
|
|
2593
|
-
if (result.progress)
|
|
2594
|
-
allProgress.push(result.progress);
|
|
2595
|
-
if (result.artifactPaths)
|
|
2596
|
-
allArtifactPaths.push(result.artifactPaths);
|
|
2597
|
-
}
|
|
2598
|
-
if (foregroundControl) {
|
|
2599
|
-
updateForegroundNestedProjection(foregroundControl);
|
|
2600
|
-
attachRootChildrenToSteps(runId, results, foregroundControl.nestedChildren);
|
|
2601
|
-
}
|
|
2602
|
-
const interrupted = results.find((result) => result.interrupted);
|
|
2603
|
-
const details = compactForegroundDetails({
|
|
2604
|
-
mode: "parallel",
|
|
2605
|
-
runId,
|
|
2606
|
-
results,
|
|
2607
|
-
progress: params.includeProgress ? allProgress : undefined,
|
|
2608
|
-
artifacts: allArtifactPaths.length ? { dir: artifactsDir, files: allArtifactPaths } : undefined,
|
|
2609
|
-
totalChildUsage: sumResultsUsage(results),
|
|
2610
|
-
totalCost: sumResultsCost(results),
|
|
2611
|
-
});
|
|
2612
|
-
rememberForegroundRun(deps.state, { runId, mode: "parallel", cwd: effectiveCwd, sessionId: data.parentSessionId, results: details.results });
|
|
2613
|
-
if (interrupted) {
|
|
2614
|
-
return {
|
|
2615
|
-
content: [{ type: "text", text: `Parallel run paused after interrupt (${interrupted.agent}). Waiting for explicit next action.` }],
|
|
2616
|
-
details,
|
|
2617
|
-
};
|
|
2618
|
-
}
|
|
2619
|
-
const detachedIndex = results.findIndex((result) => result.detached);
|
|
2620
|
-
const detached = detachedIndex >= 0 ? results[detachedIndex] : undefined;
|
|
2621
|
-
if (detached) {
|
|
2622
|
-
return {
|
|
2623
|
-
content: [{ type: "text", text: `Parallel run detached for intercom coordination (${detached.agent}). Reply to the supervisor request first, then wait with subagent_wait({ id: "${runId}" }). Use subagent({ action: "status", id: "${runId}" }) to recover the result; do not resume or launch a replacement while it remains detached.` }],
|
|
2624
|
-
details,
|
|
2625
|
-
};
|
|
2626
|
-
}
|
|
2627
|
-
if (foregroundControl)
|
|
2628
|
-
updateForegroundNestedProjection(foregroundControl);
|
|
2629
|
-
const intercomReceipt = await maybeBuildForegroundIntercomReceipt({
|
|
2630
|
-
pi: deps.pi,
|
|
2631
|
-
intercomBridge: data.intercomBridge,
|
|
2632
|
-
runId,
|
|
2633
|
-
mode: "parallel",
|
|
2634
|
-
details,
|
|
2635
|
-
...(foregroundControl?.nestedChildren?.length ? { nestedChildren: foregroundControl.nestedChildren } : {}),
|
|
2636
|
-
});
|
|
2637
|
-
if (intercomReceipt) {
|
|
2638
|
-
return {
|
|
2639
|
-
content: [{ type: "text", text: intercomReceipt.text }],
|
|
2640
|
-
details: intercomReceipt.details,
|
|
2641
|
-
};
|
|
2642
|
-
}
|
|
2643
|
-
const worktreeSuffix = buildParallelWorktreeSuffix(worktreeSetup, artifactsDir, tasks);
|
|
2644
|
-
const ok = results.filter((result) => result.exitCode === 0).length;
|
|
2645
|
-
const downgradeNote = backgroundRequestedWhileClarifying ? " (background requested, but clarify kept this run foreground)" : "";
|
|
2646
|
-
const aggregatedOutput = aggregateParallelOutputs(results.map((result) => ({
|
|
2647
|
-
agent: result.agent,
|
|
2648
|
-
output: result.truncation?.text || getSingleResultOutput(result),
|
|
2649
|
-
exitCode: result.exitCode,
|
|
2650
|
-
error: result.error,
|
|
2651
|
-
timedOut: result.timedOut,
|
|
2652
|
-
})), (i, agent) => `=== Task ${i + 1}: ${agent} ===`);
|
|
2653
|
-
const summary = `${ok}/${results.length} succeeded${downgradeNote}`;
|
|
2654
|
-
const fullContent = worktreeSuffix
|
|
2655
|
-
? `${summary}\n\n${aggregatedOutput}\n\n${worktreeSuffix}`
|
|
2656
|
-
: `${summary}\n\n${aggregatedOutput}`;
|
|
2657
|
-
return {
|
|
2658
|
-
content: [{ type: "text", text: fullContent }],
|
|
2659
|
-
details,
|
|
2660
|
-
};
|
|
2661
|
-
}
|
|
2662
|
-
finally {
|
|
2663
|
-
if (worktreeSetup)
|
|
2664
|
-
cleanupWorktrees(worktreeSetup);
|
|
2665
|
-
}
|
|
2666
|
-
}
|
|
2667
930
|
async function runSinglePath(data, deps) {
|
|
2668
931
|
const { params, effectiveCwd, agents, ctx, signal, runId, sessionDirForIndex, sessionFileForTask, thinkingOverrideForTask, artifactConfig, artifactsDir, onUpdate, sessionRoot, controlConfig, contextPolicy, } = data;
|
|
2669
932
|
const onControlEvent = createForegroundControlNotifier(data, deps);
|