@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
|
@@ -0,0 +1,537 @@
|
|
|
1
|
+
// The foreground parallel run path: worktree setup, per-task cwd and output checks, and the concurrent task runs.
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import { snapshotParentPermissionMode } from "../../../../../core/subagent-permission-inherit.js";
|
|
5
|
+
import { resolveChildCwd, mapConcurrent, compactForegroundDetails, sumResultsUsage, sumResultsCost, getSingleResultOutput } from "../../shared/utils.js";
|
|
6
|
+
import { normalizeChildSpec } from "../../shared/child-spec.js";
|
|
7
|
+
import { ChainClarifyComponent } from "./chain-clarify.js";
|
|
8
|
+
import { toModelInfo } from "../../shared/model-info.js";
|
|
9
|
+
import { runSync } from "./execution.js";
|
|
10
|
+
import { captureModelSelection, resolveExecutableChildModel } from "../shared/model-fallback.js";
|
|
11
|
+
import { Semaphore, DEFAULT_GLOBAL_CONCURRENCY_LIMIT, aggregateParallelOutputs } from "../shared/parallel-utils.js";
|
|
12
|
+
import { recordRun } from "../shared/run-history.js";
|
|
13
|
+
import { resolveStepBehavior, buildChainInstructions, taskDisallowsFileUpdates, suppressProgressForReadOnlyTask, writeInitialProgressFile } from "../../shared/settings.js";
|
|
14
|
+
import { normalizeSkillInput, discoverAvailableSkills } from "../../agents/skills.js";
|
|
15
|
+
import { isAsyncAvailable, executeAsyncChain } from "../background/async-execution.js";
|
|
16
|
+
import { INTERCOM_BRIDGE_MARKER, resolveSubagentIntercomTarget } from "../../intercom/intercom-bridge.js";
|
|
17
|
+
import { resolveSingleOutputPath, injectSingleOutputInstruction, validateFileOnlyOutputMode, outputTargetError, readOnlyOutputError } from "../shared/single-output.js";
|
|
18
|
+
import { updateForegroundNestedProjection, attachRootChildrenToSteps } from "../shared/nested-events.js";
|
|
19
|
+
import { createWorktrees, findWorktreeTaskCwdConflict, formatWorktreeTaskCwdConflict, diffWorktrees, formatWorktreeDiffSummary, cleanupWorktrees } from "../shared/worktree.js";
|
|
20
|
+
import { resolveTopLevelParallelMaxTasks, resolveTopLevelParallelConcurrency, resolveCurrentMaxSubagentDepth, resolveChildMaxSubagentDepth, wrapForkTask } from "../../shared/types.js";
|
|
21
|
+
import { resolveEffectiveToolBudget } from "./execution-input.js";
|
|
22
|
+
import { createForegroundControlNotifier, maybeBuildForegroundIntercomReceipt } from "./foreground-notifications.js";
|
|
23
|
+
import { updateRememberedForegroundChild, rememberForegroundRun } from "./foreground-run-registry.js";
|
|
24
|
+
import { shouldForkAgent } from "./fork-policy.js";
|
|
25
|
+
export function buildParallelModeError(message) {
|
|
26
|
+
return {
|
|
27
|
+
content: [{ type: "text", text: message }],
|
|
28
|
+
isError: true,
|
|
29
|
+
details: { mode: "parallel", results: [] },
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
function createParallelWorktreeSetup(enabled, cwd, runId, tasks, setupHook, setupHookTimeoutMs, baseDir) {
|
|
33
|
+
if (!enabled)
|
|
34
|
+
return {};
|
|
35
|
+
try {
|
|
36
|
+
return {
|
|
37
|
+
setup: createWorktrees(cwd, runId, tasks.length, {
|
|
38
|
+
agents: tasks.map((task) => task.agent),
|
|
39
|
+
setupHook: setupHook
|
|
40
|
+
? { hookPath: setupHook, timeoutMs: setupHookTimeoutMs }
|
|
41
|
+
: undefined,
|
|
42
|
+
baseDir,
|
|
43
|
+
}),
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
48
|
+
return { errorResult: buildParallelModeError(message) };
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
export function buildParallelWorktreeTaskCwdError(tasks, sharedCwd) {
|
|
52
|
+
const conflict = findWorktreeTaskCwdConflict(tasks, sharedCwd);
|
|
53
|
+
if (!conflict)
|
|
54
|
+
return undefined;
|
|
55
|
+
return formatWorktreeTaskCwdConflict(conflict, sharedCwd);
|
|
56
|
+
}
|
|
57
|
+
function resolveParallelTaskCwd(task, paramsCwd, worktreeSetup, index) {
|
|
58
|
+
if (worktreeSetup)
|
|
59
|
+
return worktreeSetup.worktrees[index].agentCwd;
|
|
60
|
+
return resolveChildCwd(paramsCwd, task.cwd);
|
|
61
|
+
}
|
|
62
|
+
function buildParallelWorktreeSuffix(worktreeSetup, artifactsDir, tasks) {
|
|
63
|
+
if (!worktreeSetup)
|
|
64
|
+
return "";
|
|
65
|
+
const diffsDir = path.join(artifactsDir, "worktree-diffs");
|
|
66
|
+
const diffs = diffWorktrees(worktreeSetup, tasks.map((task) => task.agent), diffsDir);
|
|
67
|
+
return formatWorktreeDiffSummary(diffs);
|
|
68
|
+
}
|
|
69
|
+
function findDuplicateParallelOutputPath(input) {
|
|
70
|
+
const seen = new Map();
|
|
71
|
+
for (let index = 0; index < input.tasks.length; index++) {
|
|
72
|
+
const behavior = input.behaviors[index];
|
|
73
|
+
if (!behavior?.output)
|
|
74
|
+
continue;
|
|
75
|
+
const task = input.tasks[index];
|
|
76
|
+
const taskCwd = resolveParallelTaskCwd(task, input.paramsCwd, input.worktreeSetup, index);
|
|
77
|
+
const outputPath = resolveSingleOutputPath(behavior.output, input.ctxCwd, taskCwd, input.outputBaseDir);
|
|
78
|
+
if (!outputPath)
|
|
79
|
+
continue;
|
|
80
|
+
const previous = seen.get(outputPath);
|
|
81
|
+
if (previous) {
|
|
82
|
+
return `Parallel tasks ${previous.index + 1} (${previous.agent}) and ${index + 1} (${task.agent}) resolve output to the same path: ${outputPath}. Use distinct output paths.`;
|
|
83
|
+
}
|
|
84
|
+
seen.set(outputPath, { index, agent: task.agent });
|
|
85
|
+
}
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
async function runForegroundParallelTasks(input) {
|
|
89
|
+
// Pre-warm fork session files sequentially before concurrent dispatch to avoid
|
|
90
|
+
// races where multiple workers simultaneously try to branch the same parent session.
|
|
91
|
+
for (let i = 0; i < input.tasks.length; i++) {
|
|
92
|
+
input.sessionFileForTask(input.tasks[i].agent, i, input.modelOverrides[i]);
|
|
93
|
+
}
|
|
94
|
+
return mapConcurrent(input.tasks, input.concurrencyLimit, async (task, index) => {
|
|
95
|
+
const behavior = input.behaviors[index];
|
|
96
|
+
const effectiveSkills = behavior?.skills;
|
|
97
|
+
const taskCwd = resolveParallelTaskCwd(task, input.paramsCwd, input.worktreeSetup, index);
|
|
98
|
+
const readInstructions = behavior
|
|
99
|
+
? buildChainInstructions({ ...behavior, output: false, progress: false }, taskCwd, false)
|
|
100
|
+
: { prefix: "", suffix: "" };
|
|
101
|
+
const progressInstructions = behavior
|
|
102
|
+
? buildChainInstructions({ ...behavior, output: false, reads: false }, input.progressDir, index === input.firstProgressIndex)
|
|
103
|
+
: { prefix: "", suffix: "" };
|
|
104
|
+
const outputPath = resolveSingleOutputPath(behavior?.output, input.ctx.cwd, taskCwd, input.outputBaseDir);
|
|
105
|
+
const agentConfig = input.agents.find((agent) => agent.name === task.agent);
|
|
106
|
+
const taskText = injectSingleOutputInstruction(`${readInstructions.prefix}${input.taskTexts[index]}${progressInstructions.suffix}`, outputPath, agentConfig);
|
|
107
|
+
const interruptController = new AbortController();
|
|
108
|
+
if (input.foregroundControl) {
|
|
109
|
+
input.foregroundControl.currentAgent = task.description || task.agent;
|
|
110
|
+
input.foregroundControl.currentChildId = task.agent;
|
|
111
|
+
input.foregroundControl.currentIndex = index;
|
|
112
|
+
input.foregroundControl.currentActivityState = undefined;
|
|
113
|
+
input.foregroundControl.updatedAt = Date.now();
|
|
114
|
+
input.foregroundControl.interrupt = () => {
|
|
115
|
+
if (interruptController.signal.aborted)
|
|
116
|
+
return false;
|
|
117
|
+
interruptController.abort();
|
|
118
|
+
input.foregroundControl.currentActivityState = undefined;
|
|
119
|
+
input.foregroundControl.updatedAt = Date.now();
|
|
120
|
+
return true;
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
const modelSelection = input.modelSelections[index] ?? captureModelSelection({ model: task.model, tier: task.tier });
|
|
124
|
+
return runSync(input.ctx.cwd, normalizeChildSpec({
|
|
125
|
+
task: taskText,
|
|
126
|
+
description: task.description,
|
|
127
|
+
permissions: task.permissions,
|
|
128
|
+
model: task.model,
|
|
129
|
+
tier: task.tier,
|
|
130
|
+
thinking: task.thinking,
|
|
131
|
+
modelSelection,
|
|
132
|
+
skill: task.skill,
|
|
133
|
+
cwd: taskCwd,
|
|
134
|
+
output: task.output,
|
|
135
|
+
outputMode: task.outputMode,
|
|
136
|
+
acceptance: task.acceptance,
|
|
137
|
+
toolBudget: task.toolBudget,
|
|
138
|
+
}, { parentMode: snapshotParentPermissionMode(input.ctx.sessionManager.getSessionId() ?? undefined), runId: input.runId, index }), {
|
|
139
|
+
parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
|
|
140
|
+
cwd: taskCwd,
|
|
141
|
+
signal: input.signal,
|
|
142
|
+
interruptSignal: interruptController.signal,
|
|
143
|
+
allowIntercomDetach: agentConfig?.systemPrompt?.includes(INTERCOM_BRIDGE_MARKER) === true,
|
|
144
|
+
intercomEvents: input.intercomEvents,
|
|
145
|
+
runId: input.runId,
|
|
146
|
+
index,
|
|
147
|
+
sessionDir: input.sessionDirForIndex(index),
|
|
148
|
+
sessionFile: input.sessionFileForTask(task.agent, index, input.modelOverrides[index]),
|
|
149
|
+
artifactsDir: input.artifactConfig.enabled ? input.artifactsDir : undefined,
|
|
150
|
+
artifactConfig: input.artifactConfig,
|
|
151
|
+
maxOutput: input.maxOutput,
|
|
152
|
+
outputPath,
|
|
153
|
+
outputMode: behavior?.outputMode,
|
|
154
|
+
maxSubagentDepth: input.maxSubagentDepths[index],
|
|
155
|
+
waitToolEnabled: input.waitToolEnabled,
|
|
156
|
+
controlConfig: input.controlConfig,
|
|
157
|
+
onControlEvent: input.onControlEvent,
|
|
158
|
+
onDetachedExit: (result) => updateRememberedForegroundChild(input.state, { runId: input.runId, mode: "parallel", cwd: taskCwd, sessionId: input.parentSessionId, index, result, events: input.intercomEvents }),
|
|
159
|
+
intercomSessionName: input.childIntercomTarget?.(task.agent, index),
|
|
160
|
+
orchestratorIntercomTarget: input.orchestratorIntercomTarget,
|
|
161
|
+
communicationEnabled: input.communicationEnabled,
|
|
162
|
+
nestedRoute: input.foregroundControl?.nestedRoute,
|
|
163
|
+
modelOverride: input.modelOverrides[index],
|
|
164
|
+
thinkingOverride: input.thinkingOverrideForTask(task.agent, index, input.modelOverrides[index]),
|
|
165
|
+
availableModels: input.availableModels,
|
|
166
|
+
preferredModelProvider: input.ctx.model?.provider,
|
|
167
|
+
modelScope: input.modelScope,
|
|
168
|
+
skills: effectiveSkills === false ? [] : effectiveSkills,
|
|
169
|
+
acceptance: task.acceptance,
|
|
170
|
+
acceptanceContext: { mode: "parallel" },
|
|
171
|
+
timeoutMs: input.timeoutMs,
|
|
172
|
+
deadlineAt: input.deadlineAt,
|
|
173
|
+
turnBudget: input.turnBudget,
|
|
174
|
+
toolBudget: input.toolBudgets[index],
|
|
175
|
+
onUpdate: input.onUpdate
|
|
176
|
+
? (progressUpdate) => {
|
|
177
|
+
const stepResults = progressUpdate.details?.results || [];
|
|
178
|
+
const stepProgress = progressUpdate.details?.progress || [];
|
|
179
|
+
if (input.foregroundControl && stepProgress.length > 0) {
|
|
180
|
+
const current = stepProgress[0];
|
|
181
|
+
input.foregroundControl.currentAgent = task.description || task.agent;
|
|
182
|
+
input.foregroundControl.currentChildId = task.agent;
|
|
183
|
+
input.foregroundControl.currentIndex = index;
|
|
184
|
+
input.foregroundControl.currentActivityState = current?.activityState;
|
|
185
|
+
input.foregroundControl.lastActivityAt = current?.lastActivityAt;
|
|
186
|
+
input.foregroundControl.currentTool = current?.currentTool;
|
|
187
|
+
input.foregroundControl.currentToolStartedAt = current?.currentToolStartedAt;
|
|
188
|
+
input.foregroundControl.currentPath = current?.currentPath;
|
|
189
|
+
input.foregroundControl.turnCount = current?.turnCount;
|
|
190
|
+
input.foregroundControl.tokens = current?.tokens;
|
|
191
|
+
input.foregroundControl.toolCount = current?.toolCount;
|
|
192
|
+
input.foregroundControl.updatedAt = Date.now();
|
|
193
|
+
}
|
|
194
|
+
if (stepResults.length > 0)
|
|
195
|
+
input.liveResults[index] = stepResults[0];
|
|
196
|
+
if (stepProgress.length > 0)
|
|
197
|
+
input.liveProgress[index] = stepProgress[0];
|
|
198
|
+
const mergedResults = input.liveResults.filter((result) => result !== undefined);
|
|
199
|
+
const mergedProgress = input.liveProgress.filter((progress) => progress !== undefined);
|
|
200
|
+
input.onUpdate?.({
|
|
201
|
+
content: progressUpdate.content,
|
|
202
|
+
details: {
|
|
203
|
+
mode: "parallel",
|
|
204
|
+
results: mergedResults,
|
|
205
|
+
progress: mergedProgress,
|
|
206
|
+
controlEvents: progressUpdate.details?.controlEvents,
|
|
207
|
+
totalSteps: input.tasks.length,
|
|
208
|
+
},
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
: undefined,
|
|
212
|
+
}).finally(() => {
|
|
213
|
+
if (input.foregroundControl?.currentIndex === index) {
|
|
214
|
+
input.foregroundControl.interrupt = undefined;
|
|
215
|
+
input.foregroundControl.updatedAt = Date.now();
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
}, input.globalSemaphore, {
|
|
219
|
+
signal: input.signal,
|
|
220
|
+
onAbort: (task) => ({
|
|
221
|
+
agent: task.agent, task: task.task ?? "", exitCode: 1, messages: [],
|
|
222
|
+
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 },
|
|
223
|
+
error: "Subagent launch cancelled.",
|
|
224
|
+
}),
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
export async function runParallelPath(data, deps) {
|
|
228
|
+
const { params, effectiveCwd, agents, ctx, signal, runId, sessionDirForIndex, sessionFileForIndex, sessionFileForTask, thinkingOverrideForTask, artifactConfig, artifactsDir, backgroundRequestedWhileClarifying, onUpdate, sessionRoot, controlConfig, contextPolicy, } = data;
|
|
229
|
+
const onControlEvent = createForegroundControlNotifier(data, deps);
|
|
230
|
+
const childIntercomTarget = data.intercomBridge.active ? resolveSubagentIntercomTarget : undefined;
|
|
231
|
+
const allProgress = [];
|
|
232
|
+
const allArtifactPaths = [];
|
|
233
|
+
const tasks = params.tasks;
|
|
234
|
+
const maxParallelTasks = resolveTopLevelParallelMaxTasks(deps.config.parallel?.maxTasks);
|
|
235
|
+
const parallelConcurrency = resolveTopLevelParallelConcurrency(params.concurrency, deps.config.parallel?.concurrency);
|
|
236
|
+
if (tasks.length > maxParallelTasks)
|
|
237
|
+
return {
|
|
238
|
+
content: [{ type: "text", text: `Max ${maxParallelTasks} tasks` }],
|
|
239
|
+
isError: true,
|
|
240
|
+
details: { mode: "parallel", results: [] },
|
|
241
|
+
};
|
|
242
|
+
const agentConfigs = [];
|
|
243
|
+
for (const t of tasks) {
|
|
244
|
+
const config = agents.find((a) => a.name === t.agent);
|
|
245
|
+
if (!config) {
|
|
246
|
+
return {
|
|
247
|
+
content: [{ type: "text", text: `Unknown agent: ${t.agent}` }],
|
|
248
|
+
isError: true,
|
|
249
|
+
details: { mode: "parallel", results: [] },
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
agentConfigs.push(config);
|
|
253
|
+
}
|
|
254
|
+
const currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth);
|
|
255
|
+
const maxSubagentDepths = agentConfigs.map((config) => resolveChildMaxSubagentDepth(currentMaxSubagentDepth, config.maxSubagentDepth));
|
|
256
|
+
const toolBudgets = [];
|
|
257
|
+
for (let index = 0; index < tasks.length; index++) {
|
|
258
|
+
const resolved = resolveEffectiveToolBudget({ stepBudget: tasks[index]?.toolBudget, runBudget: data.toolBudget, agentBudget: agentConfigs[index]?.toolBudget, configBudget: data.configToolBudget });
|
|
259
|
+
if (resolved.error)
|
|
260
|
+
return buildParallelModeError(resolved.error);
|
|
261
|
+
toolBudgets.push(resolved.toolBudget);
|
|
262
|
+
}
|
|
263
|
+
if (params.worktree) {
|
|
264
|
+
const worktreeTaskCwdError = buildParallelWorktreeTaskCwdError(tasks, effectiveCwd);
|
|
265
|
+
if (worktreeTaskCwdError)
|
|
266
|
+
return buildParallelModeError(worktreeTaskCwdError);
|
|
267
|
+
}
|
|
268
|
+
const currentProvider = ctx.model?.provider;
|
|
269
|
+
const availableModels = ctx.modelRegistry.getAvailable().map(toModelInfo);
|
|
270
|
+
let taskTexts = tasks.map((t) => t.task);
|
|
271
|
+
const skillOverrides = tasks.map((t) => normalizeSkillInput(t.skill));
|
|
272
|
+
const behaviorOverrides = tasks.map((task, index) => ({
|
|
273
|
+
...(task.output !== undefined && task.output !== true ? { output: task.output } : {}),
|
|
274
|
+
...(task.outputMode !== undefined ? { outputMode: task.outputMode } : {}),
|
|
275
|
+
...(task.reads !== undefined && task.reads !== true ? { reads: task.reads } : {}),
|
|
276
|
+
...(task.progress !== undefined ? { progress: task.progress } : {}),
|
|
277
|
+
...(skillOverrides[index] !== undefined ? { skills: skillOverrides[index] } : {}),
|
|
278
|
+
}));
|
|
279
|
+
const modelSelections = tasks.map((task) => captureModelSelection({ model: task.model, tier: task.tier }));
|
|
280
|
+
const modelOverrides = tasks.map((task, index) => resolveExecutableChildModel({
|
|
281
|
+
modelSelection: modelSelections[index],
|
|
282
|
+
model: task.model,
|
|
283
|
+
tier: task.tier,
|
|
284
|
+
thinking: task.thinking,
|
|
285
|
+
availableModels,
|
|
286
|
+
preferredProvider: currentProvider,
|
|
287
|
+
}));
|
|
288
|
+
if (params.clarify === true && ctx.hasUI) {
|
|
289
|
+
const behaviors = agentConfigs.map((_c, i) => resolveStepBehavior(behaviorOverrides[i]));
|
|
290
|
+
const availableSkills = discoverAvailableSkills(effectiveCwd);
|
|
291
|
+
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%" } });
|
|
292
|
+
if (!result || !result.confirmed) {
|
|
293
|
+
return { content: [{ type: "text", text: "Cancelled" }], details: { mode: "parallel", results: [] } };
|
|
294
|
+
}
|
|
295
|
+
taskTexts = result.templates;
|
|
296
|
+
for (let i = 0; i < result.behaviorOverrides.length; i++) {
|
|
297
|
+
const override = result.behaviorOverrides[i];
|
|
298
|
+
if (override?.output !== undefined)
|
|
299
|
+
behaviorOverrides[i].output = override.output;
|
|
300
|
+
if (override?.reads !== undefined)
|
|
301
|
+
behaviorOverrides[i].reads = override.reads;
|
|
302
|
+
if (override?.progress !== undefined)
|
|
303
|
+
behaviorOverrides[i].progress = override.progress;
|
|
304
|
+
if (override?.skills !== undefined) {
|
|
305
|
+
skillOverrides[i] = override.skills;
|
|
306
|
+
behaviorOverrides[i].skills = override.skills;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
if (result.runInBackground) {
|
|
310
|
+
if (!isAsyncAvailable()) {
|
|
311
|
+
return {
|
|
312
|
+
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." }],
|
|
313
|
+
isError: true,
|
|
314
|
+
details: { mode: "parallel", results: [] },
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
const id = randomUUID();
|
|
318
|
+
const asyncCtx = {
|
|
319
|
+
pi: deps.pi,
|
|
320
|
+
cwd: ctx.cwd,
|
|
321
|
+
currentSessionId: deps.state.currentSessionId,
|
|
322
|
+
parentSessionId: ctx.sessionManager.getSessionId() ?? undefined,
|
|
323
|
+
currentModelProvider: ctx.model?.provider,
|
|
324
|
+
currentModel: ctx.model,
|
|
325
|
+
modelScope: data.modelScope,
|
|
326
|
+
};
|
|
327
|
+
const parallelTasks = tasks.map((t, i) => {
|
|
328
|
+
const taskText = shouldForkAgent(contextPolicy, t.agent) ? wrapForkTask(taskTexts[i]) : taskTexts[i];
|
|
329
|
+
const progress = taskDisallowsFileUpdates(taskText) ? false : behaviorOverrides[i]?.progress;
|
|
330
|
+
return {
|
|
331
|
+
agent: t.agent,
|
|
332
|
+
task: taskText,
|
|
333
|
+
description: t.description,
|
|
334
|
+
permissions: t.permissions,
|
|
335
|
+
cwd: t.cwd,
|
|
336
|
+
model: t.model,
|
|
337
|
+
tier: t.tier,
|
|
338
|
+
thinking: t.thinking,
|
|
339
|
+
...(skillOverrides[i] !== undefined ? { skill: skillOverrides[i] } : {}),
|
|
340
|
+
...(behaviorOverrides[i]?.output !== undefined ? { output: behaviorOverrides[i].output } : {}),
|
|
341
|
+
...(behaviorOverrides[i]?.outputMode !== undefined ? { outputMode: behaviorOverrides[i].outputMode } : {}),
|
|
342
|
+
...(behaviorOverrides[i]?.reads !== undefined ? { reads: behaviorOverrides[i].reads } : {}),
|
|
343
|
+
...(progress !== undefined ? { progress } : {}),
|
|
344
|
+
...(t.toolBudget !== undefined ? { toolBudget: t.toolBudget } : {}),
|
|
345
|
+
...(t.acceptance !== undefined ? { acceptance: t.acceptance } : {}),
|
|
346
|
+
};
|
|
347
|
+
});
|
|
348
|
+
return executeAsyncChain(id, {
|
|
349
|
+
chain: [{ parallel: parallelTasks, concurrency: parallelConcurrency, worktree: params.worktree }],
|
|
350
|
+
resultMode: "parallel",
|
|
351
|
+
goal: taskTexts[0] ?? "",
|
|
352
|
+
communicationEnabled: data.intercomBridge.communicationEnabled,
|
|
353
|
+
ctx: asyncCtx,
|
|
354
|
+
availableModels,
|
|
355
|
+
cwd: effectiveCwd,
|
|
356
|
+
maxOutput: params.maxOutput,
|
|
357
|
+
artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
|
|
358
|
+
artifactConfig,
|
|
359
|
+
sessionRoot,
|
|
360
|
+
chainSkills: [],
|
|
361
|
+
sessionFilesByFlatIndex: tasks.map((task, index) => sessionFileForTask(task.agent, index, modelOverrides[index])),
|
|
362
|
+
thinkingOverridesByFlatIndex: tasks.map((task, index) => thinkingOverrideForTask(task.agent, index, modelOverrides[index])),
|
|
363
|
+
maxSubagentDepth: currentMaxSubagentDepth,
|
|
364
|
+
waitToolEnabled: deps.waitToolEnabled,
|
|
365
|
+
worktreeSetupHook: deps.config.worktreeSetupHook,
|
|
366
|
+
worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
|
|
367
|
+
worktreeBaseDir: deps.config.worktreeBaseDir,
|
|
368
|
+
controlConfig,
|
|
369
|
+
controlIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,
|
|
370
|
+
childIntercomTarget: data.intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(id, agent, index) : undefined,
|
|
371
|
+
timeoutMs: data.timeoutMs,
|
|
372
|
+
turnBudget: data.turnBudget,
|
|
373
|
+
globalConcurrencyLimit: deps.config.globalConcurrencyLimit,
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
const behaviors = agentConfigs.map((_config, index) => suppressProgressForReadOnlyTask(resolveStepBehavior(behaviorOverrides[index]), taskTexts[index]));
|
|
378
|
+
const firstProgressIndex = behaviors.findIndex((behavior) => behavior.progress);
|
|
379
|
+
const liveResults = new Array(tasks.length).fill(undefined);
|
|
380
|
+
const liveProgress = new Array(tasks.length).fill(undefined);
|
|
381
|
+
const foregroundControl = deps.state.foregroundControls.get(runId);
|
|
382
|
+
const { setup: worktreeSetup, errorResult } = createParallelWorktreeSetup(params.worktree, effectiveCwd, runId, tasks, deps.config.worktreeSetupHook, deps.config.worktreeSetupHookTimeoutMs, deps.config.worktreeBaseDir);
|
|
383
|
+
if (errorResult)
|
|
384
|
+
return errorResult;
|
|
385
|
+
try {
|
|
386
|
+
const outputBaseDir = path.join(artifactsDir, "outputs", runId);
|
|
387
|
+
const duplicateOutputError = findDuplicateParallelOutputPath({
|
|
388
|
+
tasks,
|
|
389
|
+
behaviors,
|
|
390
|
+
paramsCwd: effectiveCwd,
|
|
391
|
+
ctxCwd: ctx.cwd,
|
|
392
|
+
outputBaseDir,
|
|
393
|
+
worktreeSetup,
|
|
394
|
+
});
|
|
395
|
+
if (duplicateOutputError)
|
|
396
|
+
return buildParallelModeError(duplicateOutputError);
|
|
397
|
+
for (let index = 0; index < tasks.length; index++) {
|
|
398
|
+
const taskCwd = resolveParallelTaskCwd(tasks[index], effectiveCwd, worktreeSetup, index);
|
|
399
|
+
const outputPath = resolveSingleOutputPath(behaviors[index]?.output, ctx.cwd, taskCwd, outputBaseDir);
|
|
400
|
+
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);
|
|
401
|
+
if (validationError)
|
|
402
|
+
return buildParallelModeError(validationError);
|
|
403
|
+
}
|
|
404
|
+
const parallelProgressPrecreated = firstProgressIndex !== -1;
|
|
405
|
+
const parallelProgressDir = path.join(artifactsDir, "progress", runId);
|
|
406
|
+
if (parallelProgressPrecreated)
|
|
407
|
+
writeInitialProgressFile(parallelProgressDir);
|
|
408
|
+
for (let i = 0; i < taskTexts.length; i++) {
|
|
409
|
+
if (shouldForkAgent(contextPolicy, tasks[i].agent))
|
|
410
|
+
taskTexts[i] = wrapForkTask(taskTexts[i]);
|
|
411
|
+
}
|
|
412
|
+
const deadlineAt = data.deadlineAt ?? (data.timeoutMs !== undefined ? Date.now() + data.timeoutMs : undefined);
|
|
413
|
+
const results = await runForegroundParallelTasks({
|
|
414
|
+
tasks,
|
|
415
|
+
taskTexts,
|
|
416
|
+
agents,
|
|
417
|
+
ctx,
|
|
418
|
+
state: deps.state,
|
|
419
|
+
intercomEvents: deps.pi.events,
|
|
420
|
+
parentSessionId: ctx.sessionManager.getSessionId() ?? undefined,
|
|
421
|
+
signal,
|
|
422
|
+
runId,
|
|
423
|
+
sessionDirForIndex,
|
|
424
|
+
sessionFileForIndex,
|
|
425
|
+
sessionFileForTask,
|
|
426
|
+
thinkingOverrideForTask,
|
|
427
|
+
artifactConfig,
|
|
428
|
+
artifactsDir,
|
|
429
|
+
outputBaseDir,
|
|
430
|
+
maxOutput: params.maxOutput,
|
|
431
|
+
paramsCwd: effectiveCwd,
|
|
432
|
+
progressDir: parallelProgressDir,
|
|
433
|
+
availableModels,
|
|
434
|
+
modelScope: data.modelScope,
|
|
435
|
+
modelOverrides,
|
|
436
|
+
modelSelections,
|
|
437
|
+
behaviors,
|
|
438
|
+
firstProgressIndex: parallelProgressPrecreated ? -1 : firstProgressIndex,
|
|
439
|
+
controlConfig,
|
|
440
|
+
onControlEvent,
|
|
441
|
+
childIntercomTarget: childIntercomTarget ? (agent, index) => childIntercomTarget(runId, agent, index) : undefined,
|
|
442
|
+
orchestratorIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,
|
|
443
|
+
communicationEnabled: data.intercomBridge.communicationEnabled,
|
|
444
|
+
foregroundControl,
|
|
445
|
+
concurrencyLimit: parallelConcurrency,
|
|
446
|
+
globalSemaphore: new Semaphore(deps.config.globalConcurrencyLimit ?? DEFAULT_GLOBAL_CONCURRENCY_LIMIT),
|
|
447
|
+
maxSubagentDepths,
|
|
448
|
+
waitToolEnabled: deps.waitToolEnabled,
|
|
449
|
+
liveResults,
|
|
450
|
+
liveProgress,
|
|
451
|
+
onUpdate,
|
|
452
|
+
worktreeSetup,
|
|
453
|
+
timeoutMs: data.timeoutMs,
|
|
454
|
+
deadlineAt,
|
|
455
|
+
turnBudget: data.turnBudget,
|
|
456
|
+
toolBudgets,
|
|
457
|
+
});
|
|
458
|
+
for (let i = 0; i < results.length; i++) {
|
|
459
|
+
const run = results[i];
|
|
460
|
+
recordRun(run.agent, taskTexts[i], run.exitCode, run.progressSummary?.durationMs ?? 0);
|
|
461
|
+
}
|
|
462
|
+
for (const result of results) {
|
|
463
|
+
if (result.progress)
|
|
464
|
+
allProgress.push(result.progress);
|
|
465
|
+
if (result.artifactPaths)
|
|
466
|
+
allArtifactPaths.push(result.artifactPaths);
|
|
467
|
+
}
|
|
468
|
+
if (foregroundControl) {
|
|
469
|
+
updateForegroundNestedProjection(foregroundControl);
|
|
470
|
+
attachRootChildrenToSteps(runId, results, foregroundControl.nestedChildren);
|
|
471
|
+
}
|
|
472
|
+
const interrupted = results.find((result) => result.interrupted);
|
|
473
|
+
const details = compactForegroundDetails({
|
|
474
|
+
mode: "parallel",
|
|
475
|
+
runId,
|
|
476
|
+
results,
|
|
477
|
+
progress: params.includeProgress ? allProgress : undefined,
|
|
478
|
+
artifacts: allArtifactPaths.length ? { dir: artifactsDir, files: allArtifactPaths } : undefined,
|
|
479
|
+
totalChildUsage: sumResultsUsage(results),
|
|
480
|
+
totalCost: sumResultsCost(results),
|
|
481
|
+
});
|
|
482
|
+
rememberForegroundRun(deps.state, { runId, mode: "parallel", cwd: effectiveCwd, sessionId: data.parentSessionId, results: details.results });
|
|
483
|
+
if (interrupted) {
|
|
484
|
+
return {
|
|
485
|
+
content: [{ type: "text", text: `Parallel run paused after interrupt (${interrupted.agent}). Waiting for explicit next action.` }],
|
|
486
|
+
details,
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
const detachedIndex = results.findIndex((result) => result.detached);
|
|
490
|
+
const detached = detachedIndex >= 0 ? results[detachedIndex] : undefined;
|
|
491
|
+
if (detached) {
|
|
492
|
+
return {
|
|
493
|
+
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.` }],
|
|
494
|
+
details,
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
if (foregroundControl)
|
|
498
|
+
updateForegroundNestedProjection(foregroundControl);
|
|
499
|
+
const intercomReceipt = await maybeBuildForegroundIntercomReceipt({
|
|
500
|
+
pi: deps.pi,
|
|
501
|
+
intercomBridge: data.intercomBridge,
|
|
502
|
+
runId,
|
|
503
|
+
mode: "parallel",
|
|
504
|
+
details,
|
|
505
|
+
...(foregroundControl?.nestedChildren?.length ? { nestedChildren: foregroundControl.nestedChildren } : {}),
|
|
506
|
+
});
|
|
507
|
+
if (intercomReceipt) {
|
|
508
|
+
return {
|
|
509
|
+
content: [{ type: "text", text: intercomReceipt.text }],
|
|
510
|
+
details: intercomReceipt.details,
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
const worktreeSuffix = buildParallelWorktreeSuffix(worktreeSetup, artifactsDir, tasks);
|
|
514
|
+
const ok = results.filter((result) => result.exitCode === 0).length;
|
|
515
|
+
const downgradeNote = backgroundRequestedWhileClarifying ? " (background requested, but clarify kept this run foreground)" : "";
|
|
516
|
+
const aggregatedOutput = aggregateParallelOutputs(results.map((result) => ({
|
|
517
|
+
agent: result.agent,
|
|
518
|
+
output: result.truncation?.text || getSingleResultOutput(result),
|
|
519
|
+
exitCode: result.exitCode,
|
|
520
|
+
error: result.error,
|
|
521
|
+
timedOut: result.timedOut,
|
|
522
|
+
})), (i, agent) => `=== Task ${i + 1}: ${agent} ===`);
|
|
523
|
+
const summary = `${ok}/${results.length} succeeded${downgradeNote}`;
|
|
524
|
+
const fullContent = worktreeSuffix
|
|
525
|
+
? `${summary}\n\n${aggregatedOutput}\n\n${worktreeSuffix}`
|
|
526
|
+
: `${summary}\n\n${aggregatedOutput}`;
|
|
527
|
+
return {
|
|
528
|
+
content: [{ type: "text", text: fullContent }],
|
|
529
|
+
details,
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
finally {
|
|
533
|
+
if (worktreeSetup)
|
|
534
|
+
cleanupWorktrees(worktreeSetup);
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
//# sourceMappingURL=parallel-run.js.map
|
|
@@ -1,85 +1,9 @@
|
|
|
1
|
-
import type { AgentToolResult
|
|
2
|
-
import type {
|
|
3
|
-
import type
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
interface TaskParam {
|
|
7
|
-
agent?: string;
|
|
8
|
-
task: string;
|
|
9
|
-
thinking?: ThinkingLevel;
|
|
10
|
-
description?: string;
|
|
11
|
-
permissions?: "full" | "read-only";
|
|
12
|
-
cwd?: string;
|
|
13
|
-
count?: number;
|
|
14
|
-
output?: string | boolean;
|
|
15
|
-
outputMode?: "inline" | "file-only";
|
|
16
|
-
reads?: string[] | boolean;
|
|
17
|
-
progress?: boolean;
|
|
18
|
-
model?: string;
|
|
19
|
-
tier?: "light" | "standard" | "heavy";
|
|
20
|
-
skill?: string | string[] | boolean;
|
|
21
|
-
acceptance?: AcceptanceInput;
|
|
22
|
-
toolBudget?: ToolBudgetConfig;
|
|
23
|
-
}
|
|
24
|
-
export interface SubagentParamsLike {
|
|
25
|
-
action?: string;
|
|
26
|
-
id?: string;
|
|
27
|
-
runId?: string;
|
|
28
|
-
dir?: string;
|
|
29
|
-
index?: number;
|
|
30
|
-
view?: "fleet" | "transcript";
|
|
31
|
-
lines?: number;
|
|
32
|
-
agent?: string;
|
|
33
|
-
task?: string;
|
|
34
|
-
description?: string;
|
|
35
|
-
permissions?: "full" | "read-only";
|
|
36
|
-
message?: string;
|
|
37
|
-
chain?: ChainStep[];
|
|
38
|
-
tasks?: TaskParam[];
|
|
39
|
-
concurrency?: number;
|
|
40
|
-
worktree?: boolean;
|
|
41
|
-
context?: "fresh" | "fork";
|
|
42
|
-
async?: boolean;
|
|
43
|
-
foregroundOnly?: boolean;
|
|
44
|
-
timeoutMs?: number;
|
|
45
|
-
maxRuntimeMs?: number;
|
|
46
|
-
turnBudget?: TurnBudgetConfig;
|
|
47
|
-
toolBudget?: ToolBudgetConfig;
|
|
48
|
-
clarify?: boolean;
|
|
49
|
-
control?: ControlConfig;
|
|
50
|
-
sessionDir?: string;
|
|
51
|
-
cwd?: string;
|
|
52
|
-
maxOutput?: MaxOutputConfig;
|
|
53
|
-
artifacts?: boolean;
|
|
54
|
-
includeProgress?: boolean;
|
|
55
|
-
model?: string;
|
|
56
|
-
tier?: "light" | "standard" | "heavy";
|
|
57
|
-
thinking?: string | false;
|
|
58
|
-
scope?: string;
|
|
59
|
-
target?: string;
|
|
60
|
-
skill?: string | string[] | boolean;
|
|
61
|
-
output?: string | boolean;
|
|
62
|
-
outputMode?: "inline" | "file-only";
|
|
63
|
-
chainDir?: string;
|
|
64
|
-
acceptance?: AcceptanceInput;
|
|
65
|
-
schedule?: string;
|
|
66
|
-
scheduleName?: string;
|
|
67
|
-
}
|
|
68
|
-
interface ExecutorDeps {
|
|
69
|
-
pi: ExtensionAPI;
|
|
70
|
-
state: SubagentState;
|
|
71
|
-
config: ExtensionConfig;
|
|
72
|
-
waitToolEnabled?: boolean;
|
|
73
|
-
handleScheduledRunAction?: (params: SubagentParamsLike, ctx: ExtensionContext) => Promise<AgentToolResult<Details>>;
|
|
74
|
-
watchdog?: MainWatchdogRuntime;
|
|
75
|
-
tempArtifactsDir: string;
|
|
76
|
-
getSubagentSessionRoot: (parentSessionFile: string | null) => string;
|
|
77
|
-
expandTilde: (p: string) => string;
|
|
78
|
-
allowMutatingManagementActions?: boolean;
|
|
79
|
-
kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean;
|
|
80
|
-
}
|
|
1
|
+
import type { AgentToolResult } from "@ashx-j/lunr-agent";
|
|
2
|
+
import type { ExtensionContext } from "@ashx-j/lunr-dev";
|
|
3
|
+
import { type Details } from "../../shared/types.ts";
|
|
4
|
+
import type { ExecutorDeps, SubagentParamsLike } from "./executor-types.ts";
|
|
5
|
+
export type { SubagentParamsLike } from "./executor-types.ts";
|
|
81
6
|
export declare function createSubagentExecutor(deps: ExecutorDeps): {
|
|
82
7
|
execute: (id: string, params: SubagentParamsLike, signal: AbortSignal | undefined, onUpdate: ((r: AgentToolResult<Details>) => void) | undefined, ctx: ExtensionContext) => Promise<AgentToolResult<Details>>;
|
|
83
8
|
};
|
|
84
|
-
export {};
|
|
85
9
|
//# sourceMappingURL=subagent-executor.d.ts.map
|