@ferris1225/pi-subagents 6.0.0 → 6.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +63 -0
- package/README.md +110 -42
- package/package.json +4 -4
- package/src/configuration/models.ts +10 -5
- package/src/configuration/setup.ts +54 -35
- package/src/configuration/ui.ts +109 -221
- package/src/delegation/agents.ts +15 -22
- package/src/delegation/dispatch.ts +17 -122
- package/src/delegation/prompt.ts +10 -10
- package/src/execution/cli-run.ts +112 -39
- package/src/execution/process-tree.ts +12 -8
- package/src/execution/run-control.ts +11 -3
- package/src/execution/spawn.ts +9 -2
- package/src/isolation/cleanup.ts +22 -7
- package/src/isolation/managed-paths.ts +6 -4
- package/src/isolation/manifest-mutation.ts +17 -1
- package/src/isolation/recovery.ts +11 -15
- package/src/isolation/temp-hygiene.ts +1 -1
- package/src/lifecycle/await-results.ts +114 -0
- package/src/lifecycle/dispatch-core.ts +7 -1
- package/src/lifecycle/durable.ts +25 -17
- package/src/lifecycle/runtime.ts +3 -1
- package/src/lifecycle/thread-lifecycle.ts +6 -4
- package/src/lifecycle/thread-restore.ts +12 -21
- package/src/lifecycle/tools.ts +90 -33
- package/src/presentation/announcements.ts +8 -2
- package/src/workflow/durable.ts +3 -3
- package/src/workflow/engine.ts +44 -22
- package/src/workflow/tool.ts +47 -10
package/src/lifecycle/tools.ts
CHANGED
|
@@ -1,17 +1,19 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/** Run inspection, steering, completed-run follow-ups, and destructive cancellation. */
|
|
2
2
|
|
|
3
3
|
import { randomUUID } from "node:crypto";
|
|
4
|
-
import { copyFile, mkdir, mkdtemp,
|
|
5
|
-
import { join } from "node:path";
|
|
4
|
+
import { copyFile, mkdir, mkdtemp, rm } from "node:fs/promises";
|
|
5
|
+
import { basename, join } from "node:path";
|
|
6
6
|
import type { Message } from "@earendil-works/pi-ai";
|
|
7
7
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
8
8
|
import { Text } from "@earendil-works/pi-tui";
|
|
9
9
|
import { Type } from "typebox";
|
|
10
10
|
import { DEFAULT_MAX_RESULT_LINES, loadConfig } from "../configuration/config.ts";
|
|
11
11
|
import { loadBuiltinAgents } from "../delegation/agents.ts";
|
|
12
|
-
import { getProjectRoot, getResultOutput, sessionExists } from "../execution/spawn.ts";
|
|
12
|
+
import { findSessionFile, getProjectRoot, getResultOutput, isFailedResult, sessionExists } from "../execution/spawn.ts";
|
|
13
13
|
import { writeTempOwnerMarker } from "../isolation/temp-hygiene.ts";
|
|
14
14
|
import type { DispatchCore } from "./dispatch-core.ts";
|
|
15
|
+
import { awaitRunResults, WaitSchema } from "./await-results.ts";
|
|
16
|
+
import { cancelActiveWork } from "./cancellation.ts";
|
|
15
17
|
import { stopThreads } from "./stop.ts";
|
|
16
18
|
import { formatCompletionBlock, matchRunIds } from "../presentation/format.ts";
|
|
17
19
|
import { emptyUsage } from "../execution/run-control.ts";
|
|
@@ -124,6 +126,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
124
126
|
waitReason: state === "queued" ? live?.waitReason : undefined,
|
|
125
127
|
activity: live?.activity,
|
|
126
128
|
recentActivity: live?.recentActivity ?? [],
|
|
129
|
+
lastSteering: thread.lastSteering,
|
|
127
130
|
elapsedMs: monitor.getElapsedMs(thread.id) ?? thread.elapsedMs,
|
|
128
131
|
model: live?.model ?? result?.model,
|
|
129
132
|
thinking: live?.thinking ?? result?.thinking ?? thread.thinkingLevel,
|
|
@@ -133,6 +136,9 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
133
136
|
errorMessage: result ? getResultError(result) : state === "failed" ? "No failure reason was recorded." : undefined,
|
|
134
137
|
resultFile: result?.resultFile,
|
|
135
138
|
sessionDir: thread.retired ? undefined : thread.sessionDir ?? result?.sessionDir,
|
|
139
|
+
followUpContext: state === "completed"
|
|
140
|
+
? thread.sessionDir && thread.sessionId && sessionExists(thread.sessionDir, thread.sessionId) ? "session" : "summary"
|
|
141
|
+
: undefined,
|
|
136
142
|
isolation: thread.isolation,
|
|
137
143
|
isolationNote: result?.isolationNote,
|
|
138
144
|
integrationStatus: live?.integrationStatus ?? result?.integrationStatus ?? thread.worktree?.state,
|
|
@@ -149,6 +155,8 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
149
155
|
if (run.phaseId) lines.push(` phase: ${run.phaseId}`);
|
|
150
156
|
if (run.scope) lines.push(` scope: ${JSON.stringify(run.scope)}`);
|
|
151
157
|
if (run.isolationNote) lines.push(` isolation: ${run.isolationNote}`);
|
|
158
|
+
if (run.lastSteering) lines.push(` last steering: ${run.lastSteering.disposition} · acknowledged ${formatDuration(Math.max(0, Date.now() - run.lastSteering.acknowledgedAt))} ago${run.lastSteering.requestId ? ` · request ${run.lastSteering.requestId}` : ""} · ${run.lastSteering.message}`);
|
|
159
|
+
if (run.followUpContext) lines.push(` follow-up: ${run.followUpContext}${run.followUpContext === "summary" ? " (retained session unavailable)" : " available"}`);
|
|
152
160
|
// The trail is the progress answer: what the run has been doing,
|
|
153
161
|
// newest last. It replaces pointing the parent at child session
|
|
154
162
|
// files, which it cannot usefully read mid-run.
|
|
@@ -216,65 +224,114 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
216
224
|
pi.registerTool({
|
|
217
225
|
name: "subagent_message",
|
|
218
226
|
label: "Subagent Message",
|
|
219
|
-
description: "Send a steering message to a running subagent, or continue a completed run.
|
|
227
|
+
description: "Send a steering message to a running subagent, or continue a successfully completed run. Omit context or use \"auto\" to reuse its retained session when available and otherwise start from a bounded summary, reporting the fallback. Use \"session\" only when full history is required; missing history is an error. Use \"summary\" for a new next step with only the earlier objective, result, and touched files. Session copies preserve history and the provider cache key; summary runs have neither. Use wait:true to receive a completed-run follow-up in this call; one-shot print/JSON sessions wait by default. Steering waits for the child RPC acknowledgement and reports queued, handled by an input hook, or accepted with queue state unknown. Receipt is not proof of model execution; status retains the latest acknowledgement.",
|
|
220
228
|
exposure: "model-only",
|
|
221
|
-
executionMode: "
|
|
229
|
+
executionMode: "parallel",
|
|
222
230
|
parameters: Type.Object({
|
|
223
231
|
id: Type.Integer({ minimum: 1, description: "Exact run id in this parent session." }),
|
|
224
232
|
message: Type.String({ minLength: 1, pattern: "\\S", description: "Additional instruction or follow-up question." }),
|
|
225
|
-
context: Type.Optional(Type.String({ enum: ["session", "summary"], description: "
|
|
233
|
+
context: Type.Optional(Type.String({ enum: ["auto", "session", "summary"], description: "auto (default) uses the retained session when available, otherwise a bounded summary and reports the fallback. session requires the full retained history and fails if unavailable. summary always starts fresh with the earlier objective, result, and touched files; no history or cache reuse." })),
|
|
234
|
+
wait: WaitSchema,
|
|
226
235
|
}),
|
|
227
|
-
async execute(_toolCallId, params, _signal,
|
|
236
|
+
async execute(_toolCallId, params, _signal, onUpdate, ctx) {
|
|
228
237
|
await runtime.durableRestore;
|
|
229
238
|
const thread = runtime.threads.get(params.id);
|
|
230
239
|
const fail = (message: string) => ({ content: [{ type: "text" as const, text: message }], details: {}, isError: true });
|
|
240
|
+
if (_signal?.aborted) return fail("Subagent message cancelled before delivery.");
|
|
231
241
|
if (!thread || thread.retired) return fail(`No available run matches #${params.id} in this session.`);
|
|
232
242
|
if (thread.state === "running" && !thread.lifecycleOperation) {
|
|
233
243
|
try {
|
|
234
|
-
await thread.control.steer(params.message);
|
|
235
|
-
|
|
236
|
-
|
|
244
|
+
const receipt = await thread.control.steer(params.message);
|
|
245
|
+
thread.lastSteering = { ...receipt, message: formatTaskSummary(params.message, 160, false) };
|
|
246
|
+
const status = receipt.disposition === "queued"
|
|
247
|
+
? `Received by #${thread.id} · queued for the next steering boundary. Model execution is not yet confirmed.`
|
|
248
|
+
: receipt.disposition === "handled"
|
|
249
|
+
? `Received by #${thread.id} · handled by an input hook. Delivery to the model is not confirmed.`
|
|
250
|
+
: `Accepted by #${thread.id} · queue state unconfirmed. Model execution is not yet confirmed.`;
|
|
251
|
+
monitor.setActivity(thread.id, `steering ${receipt.disposition}`);
|
|
252
|
+
return {
|
|
253
|
+
content: [{ type: "text" as const, text: `${status}${receipt.requestId ? `\nChild RPC acknowledgement: ${receipt.requestId}` : ""}` }],
|
|
254
|
+
details: { id: thread.id, steering: thread.lastSteering },
|
|
255
|
+
};
|
|
256
|
+
} catch (error) { return fail(`Steering to #${thread.id} was not confirmed: ${error instanceof Error ? error.message : String(error)}`); }
|
|
237
257
|
}
|
|
238
258
|
if (thread.state !== "completed" || thread.lifecycleOperation) {
|
|
239
|
-
|
|
259
|
+
const state = thread.state === "parked" ? "interrupted" : thread.state;
|
|
260
|
+
const terminal = !thread.lifecycleOperation && ["parked", "failed", "stopped"].includes(thread.state);
|
|
261
|
+
return fail(`Run #${thread.id} is ${state}; ${terminal
|
|
262
|
+
? "inspect retained results with subagent_status and handle unfinished work in main. This run cannot be continued with subagent_message."
|
|
263
|
+
: "messages require a running or successfully completed run. Results arrive automatically."}`);
|
|
240
264
|
}
|
|
241
265
|
if (!dispatchCore) return fail("Follow-up dispatch is unavailable in this process.");
|
|
242
|
-
const
|
|
243
|
-
|
|
244
|
-
|
|
266
|
+
const context = params.context ?? "auto";
|
|
267
|
+
const sourceFile = context !== "summary" && thread.sessionDir && thread.sessionId
|
|
268
|
+
? findSessionFile(thread.sessionDir, thread.sessionId) : undefined;
|
|
269
|
+
if (context === "session" && !sourceFile) {
|
|
270
|
+
return fail(`Run #${thread.id} has no available session to continue; use context: "auto" or "summary" for a bounded summary without the earlier history.`);
|
|
245
271
|
}
|
|
272
|
+
let fallbackReason = context === "auto" && !sourceFile ? "Retained session is unavailable." : undefined;
|
|
246
273
|
let copyDir: string | undefined;
|
|
247
274
|
try {
|
|
248
275
|
dispatchCore.setEnvironment({ ctx, config: await loadConfig(runtime.configPath), agents: loadBuiltinAgents() });
|
|
249
|
-
if (
|
|
250
|
-
const
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
276
|
+
if (sourceFile) {
|
|
277
|
+
const root = join(getProjectRoot(runtime.configPath, thread.cwd), "sessions");
|
|
278
|
+
await mkdir(root, { recursive: true });
|
|
279
|
+
copyDir = await mkdtemp(join(root, "pi-subagent-session-"));
|
|
280
|
+
writeTempOwnerMarker(copyDir);
|
|
281
|
+
try {
|
|
282
|
+
await copyFile(sourceFile, join(copyDir, basename(sourceFile)));
|
|
283
|
+
} catch (error) {
|
|
284
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
285
|
+
if (context !== "auto" || (code !== "ENOENT" && code !== "ENOTDIR")) throw error;
|
|
286
|
+
await rm(copyDir, { recursive: true, force: true });
|
|
287
|
+
copyDir = undefined;
|
|
288
|
+
fallbackReason = "Retained session became unavailable before it could be copied.";
|
|
289
|
+
}
|
|
256
290
|
}
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
if (thread.retired || thread.lifecycleOperation || thread.state !== "completed") throw new Error("The source run changed while its session was copied.");
|
|
265
|
-
const task = `Follow-up to run #${thread.id} (${randomUUID()}):\n${params.message}`;
|
|
291
|
+
if (_signal?.aborted) throw new Error("Follow-up cancelled before dispatch.");
|
|
292
|
+
if (thread.retired || thread.lifecycleOperation || thread.state !== "completed") throw new Error("The source run changed while the follow-up was prepared.");
|
|
293
|
+
const selectedContext = copyDir ? "session" : "summary";
|
|
294
|
+
const task = copyDir
|
|
295
|
+
? `Follow-up to run #${thread.id} (${randomUUID()}):\n${params.message}`
|
|
296
|
+
: buildSummaryFollowUp(thread, params.message);
|
|
297
|
+
const wait = params.wait ?? (ctx.hasUI === false);
|
|
266
298
|
const result = await dispatchCore.startBackground(thread.agentName, task, thread.cwd, thread.isolation, {
|
|
267
299
|
phaseId: `followup:${thread.id}:${randomUUID()}`, scope: thread.scope,
|
|
268
|
-
|
|
300
|
+
deliveryRoute: wait ? "await" : "background",
|
|
301
|
+
...(copyDir ? { resumeSession: { sessionId: thread.sessionId!, sessionDir: copyDir } } : {}),
|
|
269
302
|
});
|
|
270
303
|
if (result.runId === undefined) throw new Error(result.errorMessage || "Follow-up dispatch failed.");
|
|
271
304
|
copyDir = undefined;
|
|
272
|
-
|
|
305
|
+
const contextNote = selectedContext === "session" ? "its retained session" : "a summary only";
|
|
306
|
+
const receipt = `Follow-up #${result.runId} from #${thread.id} with ${contextNote}${fallbackReason ? ` (${fallbackReason})` : ""}`;
|
|
307
|
+
const details = { id: result.runId, sourceId: thread.id, context: selectedContext, ...(fallbackReason ? { fallbackReason } : {}) };
|
|
308
|
+
if (wait) {
|
|
309
|
+
const blocks = await awaitRunResults(runtime, [result.runId], _signal, DEFAULT_MAX_RESULT_LINES, thread.cwd, (text) => {
|
|
310
|
+
onUpdate?.({ content: [{ type: "text", text }], details });
|
|
311
|
+
});
|
|
312
|
+
if (_signal?.aborted) await cancelActiveWork(runtime, "Parent run was cancelled.");
|
|
313
|
+
else runtime.completeAwaitDelivery([result.runId]);
|
|
314
|
+
const settled = runtime.settledRuns.get(result.runId);
|
|
315
|
+
return {
|
|
316
|
+
content: [{ type: "text" as const, text: `${receipt}\n\n${blocks}` }], details,
|
|
317
|
+
...(_signal?.aborted || !settled || isFailedResult(settled) ? { isError: true } : {}),
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
return {
|
|
321
|
+
content: [{ type: "text" as const, text: `${receipt} started; results arrive automatically. Continue independent work, then use the result to finish the task.` }], details,
|
|
322
|
+
};
|
|
273
323
|
} catch (error) {
|
|
274
324
|
if (copyDir) await rm(copyDir, { recursive: true, force: true }).catch(() => undefined);
|
|
275
325
|
return fail(`Could not continue #${thread.id}: ${error instanceof Error ? error.message : String(error)}`);
|
|
276
326
|
}
|
|
277
327
|
},
|
|
328
|
+
renderCall(args, theme) {
|
|
329
|
+
return new Text(`${theme.fg("toolTitle", theme.bold("subagent_message "))}${theme.fg("accent", `#${args.id ?? "?"}`)} ${theme.fg("dim", formatTaskSummary(args.message ?? "", 80, false))}`, 0, 0);
|
|
330
|
+
},
|
|
331
|
+
renderResult(result, options, theme) {
|
|
332
|
+
if (options.expanded) return new Text(result.content.map((part) => part.type === "text" ? part.text : "").join("\n"), 0, 0);
|
|
333
|
+
return renderFirstLine(result, "subagent_message ", theme);
|
|
334
|
+
},
|
|
278
335
|
});
|
|
279
336
|
|
|
280
337
|
// Cancel one or more active runs: aborts the queue controller, which
|
|
@@ -35,8 +35,14 @@ async function removeUnavailableAgentModels(
|
|
|
35
35
|
export function registerAnnouncements(pi: ExtensionAPI, runtime: SubagentRuntime): void {
|
|
36
36
|
pi.on("session_start", async (_event, ctx) => {
|
|
37
37
|
await ensureDefaultConfig(ctx, runtime.configPath);
|
|
38
|
-
|
|
39
|
-
|
|
38
|
+
try {
|
|
39
|
+
await relocateRecoveryManifest(runtime.configPath);
|
|
40
|
+
await announceRecoveryRecords(runtime.configPath, ctx);
|
|
41
|
+
} catch (error) {
|
|
42
|
+
// Recovery readers must fail closed for cleanup, but a failed notice
|
|
43
|
+
// must not prevent the rest of the session UI from being installed.
|
|
44
|
+
ctx.ui.notify(`pi-subagents: recovery inspection failed; continuing startup: ${error instanceof Error ? error.message : String(error)}`, "warning");
|
|
45
|
+
}
|
|
40
46
|
await removeUnavailableAgentModels(ctx, runtime);
|
|
41
47
|
// Bootstrap also runs on session_start; wait so this notice sees restored
|
|
42
48
|
// threads instead of racing an empty list.
|
package/src/workflow/durable.ts
CHANGED
|
@@ -15,9 +15,9 @@
|
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
17
|
import { createHash } from "node:crypto";
|
|
18
|
-
import { withManifestMutation } from "../isolation/manifest-mutation.ts";
|
|
18
|
+
import { replaceManifestFile, withManifestMutation } from "../isolation/manifest-mutation.ts";
|
|
19
19
|
import { readdirSync } from "node:fs";
|
|
20
|
-
import { mkdir, readFile,
|
|
20
|
+
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
21
21
|
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
22
22
|
import { getProjectRoot, getSubagentsRoot } from "../execution/spawn.ts";
|
|
23
23
|
import { PARKED_RECORD_MAX_AGE_MS } from "../lifecycle/durable.ts";
|
|
@@ -154,7 +154,7 @@ async function writeManifest(path: string, records: readonly WorkflowRecord[]):
|
|
|
154
154
|
try {
|
|
155
155
|
const manifest: WorkflowsManifest = { version: WORKFLOWS_MANIFEST_VERSION, records: [...records] };
|
|
156
156
|
await writeFile(temporaryPath, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
|
|
157
|
-
await
|
|
157
|
+
await replaceManifestFile(temporaryPath, path);
|
|
158
158
|
} finally {
|
|
159
159
|
await rm(temporaryPath, { force: true }).catch(() => undefined);
|
|
160
160
|
}
|
package/src/workflow/engine.ts
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* through the same dispatcher a `subagent` call uses — same lifecycle ownership, same
|
|
7
7
|
* admission, same isolation, same durable checkpoint — and is `quiet`, meaning
|
|
8
8
|
* it reports into this graph instead of sending its own completion message.
|
|
9
|
-
* The parent
|
|
9
|
+
* The parent receives the graph's summary once, through its chosen delivery route.
|
|
10
10
|
*
|
|
11
11
|
* Failure is contained by the graph, not the session: a failed node blocks only
|
|
12
12
|
* its dependents, independent branches keep running, and the summary states
|
|
@@ -46,6 +46,8 @@ export interface WorkflowRunDeps {
|
|
|
46
46
|
startBackground: StartBackgroundInternal;
|
|
47
47
|
/** Isolation the graph wants for a node, resolved against the live catalog. */
|
|
48
48
|
resolveIsolation: (agentName: string) => "shared" | "worktree";
|
|
49
|
+
/** Awaited graphs return their summary in the tool result instead of waking the parent. */
|
|
50
|
+
deliveryRoute?: "background" | "await";
|
|
49
51
|
/** Project-scoped results directory for the full workflow report. */
|
|
50
52
|
resultsRoot: string;
|
|
51
53
|
notify: (message: string, kind: "info" | "warning" | "error") => void;
|
|
@@ -53,7 +55,7 @@ export interface WorkflowRunDeps {
|
|
|
53
55
|
|
|
54
56
|
export interface WorkflowHandle {
|
|
55
57
|
run: WorkflowRun;
|
|
56
|
-
/** Resolves after the graph settles and
|
|
58
|
+
/** Resolves after the graph settles and background delivery, when requested. */
|
|
57
59
|
done: Promise<WorkflowRun>;
|
|
58
60
|
}
|
|
59
61
|
|
|
@@ -295,7 +297,6 @@ async function drive(ctx: RunContext): Promise<void> {
|
|
|
295
297
|
await ctx.waitForWake();
|
|
296
298
|
}
|
|
297
299
|
await Promise.all(inFlight);
|
|
298
|
-
await settle(ctx);
|
|
299
300
|
}
|
|
300
301
|
|
|
301
302
|
function stateLabel(state: WorkflowRunState): string {
|
|
@@ -470,14 +471,6 @@ async function settle(ctx: RunContext): Promise<void> {
|
|
|
470
471
|
run.endedAt ??= Date.now();
|
|
471
472
|
if (runtime.sessionActive) monitor.updateWorkflow(run);
|
|
472
473
|
if (!interrupted && run.durableId) await removeWorkflowRecord(runtime.configPath, run.durableId, run.cwd).catch(() => undefined);
|
|
473
|
-
if (!runtime.sessionActive) return;
|
|
474
|
-
const item: CompletionMessageItem = {
|
|
475
|
-
agent: `workflow:${run.name}`,
|
|
476
|
-
block: formatWorkflowSummary(run, ctx.resultsRoot),
|
|
477
|
-
};
|
|
478
|
-
// No usage on the item: the summary carries its own per-model tally, and a
|
|
479
|
-
// group total would merge different models' spend into one number.
|
|
480
|
-
runtime.sendCompletionGroup([item]);
|
|
481
474
|
}
|
|
482
475
|
|
|
483
476
|
/** A phase a live or retained thread already owns. */
|
|
@@ -587,17 +580,46 @@ export function startWorkflow(deps: WorkflowRunDeps, workflow: CompiledWorkflow)
|
|
|
587
580
|
// Declared writer overlap inside the graph was rejected at compile time; the
|
|
588
581
|
// dispatcher still runs its own admission per node, so a node that conflicts
|
|
589
582
|
// with unrelated live work fails alone instead of poisoning the graph.
|
|
590
|
-
const
|
|
591
|
-
|
|
592
|
-
(
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
583
|
+
const recordFailure = (error: unknown): void => {
|
|
584
|
+
run.state = "failed";
|
|
585
|
+
run.endedAt = Date.now();
|
|
586
|
+
run.stopReason = error instanceof Error ? error.message : String(error);
|
|
587
|
+
};
|
|
588
|
+
const done = (async () => {
|
|
589
|
+
let crashed = false;
|
|
590
|
+
try {
|
|
591
|
+
await drive(ctx);
|
|
592
|
+
await settle(ctx);
|
|
593
|
+
} catch (error) {
|
|
594
|
+
crashed = true;
|
|
595
|
+
recordFailure(error);
|
|
596
|
+
await removeWorkflowRecord(runtime.configPath, durableId, run.cwd).catch(() => undefined);
|
|
597
|
+
}
|
|
598
|
+
// Both normal and unexpected failure paths use this sole delivery point.
|
|
599
|
+
// Never retry delivery when the sender itself throws: it may have sent.
|
|
600
|
+
try {
|
|
601
|
+
if (runtime.sessionActive && deps.deliveryRoute !== "await") {
|
|
602
|
+
const item: CompletionMessageItem = {
|
|
603
|
+
agent: `workflow:${run.name}`,
|
|
604
|
+
block: formatWorkflowSummary(run, ctx.resultsRoot),
|
|
605
|
+
};
|
|
606
|
+
// The summary carries its own per-model tally; a group total would
|
|
607
|
+
// merge different models' spend into one number.
|
|
608
|
+
runtime.sendCompletionGroup([item]);
|
|
609
|
+
}
|
|
610
|
+
} catch (error) {
|
|
611
|
+
crashed = true;
|
|
612
|
+
recordFailure(error);
|
|
613
|
+
}
|
|
614
|
+
if (crashed) {
|
|
615
|
+
try {
|
|
616
|
+
deps.notify(`✗ workflow ${run.name} crashed: ${run.stopReason}`, "error");
|
|
617
|
+
} catch {
|
|
618
|
+
/* Notification failure must not strand callers waiting on done. */
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
return run;
|
|
622
|
+
})();
|
|
601
623
|
run.done = done;
|
|
602
624
|
return { run, done };
|
|
603
625
|
}
|
package/src/workflow/tool.ts
CHANGED
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
* Scheduling, isolation, and independent acceptance are owned by the runtime.
|
|
4
4
|
*
|
|
5
5
|
* The graph is validated before anything starts (see plan.ts), so an invalid
|
|
6
|
-
* plan costs zero child processes.
|
|
7
|
-
*
|
|
6
|
+
* plan costs zero child processes. Headless calls await the complete graph by
|
|
7
|
+
* default; UI calls return a launch receipt and receive one completion message.
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
import { StringEnum } from "@earendil-works/pi-ai";
|
|
@@ -17,11 +17,14 @@ import { findRuntimeWriterConflict } from "../delegation/ownership.ts";
|
|
|
17
17
|
import { loadConfig } from "../configuration/config.ts";
|
|
18
18
|
import type { SubagentRuntime } from "../lifecycle/runtime.ts";
|
|
19
19
|
import type { DispatchCore } from "../lifecycle/dispatch-core.ts";
|
|
20
|
+
import { cancelActiveWork } from "../lifecycle/cancellation.ts";
|
|
20
21
|
import { projectResultsRoot } from "../lifecycle/thread-shared.ts";
|
|
21
22
|
import { formatTaskSummary, monitor } from "../presentation/monitor.ts";
|
|
22
23
|
import { pruneWorkflowRecords } from "./durable.ts";
|
|
23
24
|
import {
|
|
24
25
|
findOwnedPhases,
|
|
26
|
+
formatWorkflowSummary,
|
|
27
|
+
formatWorkflowStatus,
|
|
25
28
|
persistInterruptedWorkflows,
|
|
26
29
|
readRetainedWorkflows,
|
|
27
30
|
startWorkflow,
|
|
@@ -34,6 +37,9 @@ const WorkflowParams = Type.Object({
|
|
|
34
37
|
workflow: StringEnum(["code-review", "research", "migration"] as const, {
|
|
35
38
|
description: "Built-in plan: code-review inspects a target; research answers a question; migration applies two planned slices. Every plan ends with independent acceptance.",
|
|
36
39
|
}),
|
|
40
|
+
wait: Type.Optional(Type.Boolean({
|
|
41
|
+
description: "Wait for all nodes, integration, and independent acceptance, then return the final summary. Defaults to true in one-shot print/JSON sessions and false in TUI/RPC. Explicit false returns a launch receipt and delivers one background summary.",
|
|
42
|
+
})),
|
|
37
43
|
inputs: Type.Record(Type.String(), Type.String({ minLength: 1, pattern: "\\S" }), {
|
|
38
44
|
description: "Named inputs. code-review: TARGET. research: QUESTION. migration: TARGET, CONTRACT, CORE_CHANGE, ADAPTER_CHANGE, CORE_SCOPE, CORE_TEST_SCOPE, ADAPTER_SCOPE, ADAPTER_TEST_SCOPE. Scope values are exact paths relative to cwd. Include existing evidence and done conditions in task inputs.",
|
|
39
45
|
}),
|
|
@@ -60,7 +66,7 @@ function launchReceipt(status: WorkflowStatusView): string {
|
|
|
60
66
|
return parts.join(" · ");
|
|
61
67
|
}),
|
|
62
68
|
"",
|
|
63
|
-
"Every node is owned by this graph, including nodes waiting on dependencies. Do not perform or redispatch their work in main or another agent. Required independent acceptance runs after all authored work settles and integrates, including failed branches; the graph succeeds only when all work and acceptance pass. The graph sends one summary; continue
|
|
69
|
+
"Every node is owned by this graph, including nodes waiting on dependencies. Do not perform or redispatch their work in main or another agent. Required independent acceptance runs after all authored work settles and integrates, including failed branches; the graph succeeds only when all work and acceptance pass. The graph sends one summary; continue disjoint work or pause this turn until it arrives, then finish the requested outcome. A launch receipt is not task completion. Do not poll.",
|
|
64
70
|
];
|
|
65
71
|
return lines.join("\n");
|
|
66
72
|
}
|
|
@@ -100,7 +106,7 @@ export function registerWorkflowTool(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
100
106
|
name: "subagent_workflow",
|
|
101
107
|
label: "Subagent Workflow",
|
|
102
108
|
description:
|
|
103
|
-
"Run a built-in workflow with named inputs: code-review, research, or migration. Custom graphs and workflow files are unsupported. The runtime schedules dependencies, integrates work, and requires an independent sentinel acceptance PASS. Pending nodes own their work; main must not duplicate it. Duplicate deliverables and writer conflicts reject the plan before dispatch. One
|
|
109
|
+
"Run a built-in workflow with named inputs: code-review, research, or migration. Custom graphs and workflow files are unsupported. The runtime schedules dependencies, integrates work, and requires an independent sentinel acceptance PASS. Pending nodes own their work; main must not duplicate it. Duplicate deliverables and writer conflicts reject the plan before dispatch. One-shot print/JSON calls wait by default; TUI/RPC calls run in the background. Set wait to override. Awaited calls return the summary once, after integration and acceptance. Use subagent for a single phase or independent tasks.",
|
|
104
110
|
exposure: "model-only",
|
|
105
111
|
executionMode: "parallel",
|
|
106
112
|
annotations: {
|
|
@@ -111,7 +117,7 @@ export function registerWorkflowTool(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
111
117
|
},
|
|
112
118
|
parameters: WorkflowParams,
|
|
113
119
|
|
|
114
|
-
async execute(_toolCallId, params,
|
|
120
|
+
async execute(_toolCallId, params, signal, onUpdate, ctx) {
|
|
115
121
|
await runtime.durableRestore;
|
|
116
122
|
monitor.beginTurn();
|
|
117
123
|
const config = await loadConfig(runtime.configPath);
|
|
@@ -124,12 +130,12 @@ export function registerWorkflowTool(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
124
130
|
// Ignore empty legacy placeholders, which previously triggered ambiguous
|
|
125
131
|
// source errors. A supplied custom definition is always rejected.
|
|
126
132
|
const unsupported = Object.entries(params as Record<string, unknown>).filter(([key, value]) =>
|
|
127
|
-
key !== "workflow" && key !== "inputs" && value !== undefined && value !== null && value !== ""
|
|
133
|
+
key !== "workflow" && key !== "inputs" && key !== "wait" && value !== undefined && value !== null && value !== ""
|
|
128
134
|
&& !(Array.isArray(value) && value.length === 0),
|
|
129
135
|
).map(([key]) => key);
|
|
130
|
-
if (unsupported.length) throw new Error(`Custom workflow fields are unsupported: ${unsupported.join(", ")}. Use only workflow and
|
|
136
|
+
if (unsupported.length) throw new Error(`Custom workflow fields are unsupported: ${unsupported.join(", ")}. Use only workflow, inputs, and wait. No nodes were started.`);
|
|
131
137
|
const workflow = compileBuiltinWorkflow(params.workflow, params.inputs, ctx.cwd, agents.map((agent) => agent.name));
|
|
132
|
-
if (
|
|
138
|
+
if (signal?.aborted) throw new Error("Workflow cancelled before any node started.");
|
|
133
139
|
|
|
134
140
|
// Re-using a phase another owner holds fails the first node and blocks the
|
|
135
141
|
// rest; reject the whole graph instead, with the owners named.
|
|
@@ -143,7 +149,7 @@ export function registerWorkflowTool(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
143
149
|
"Workflow \"" + workflow.name + "\" was not started: " + owned.length + " of " + workflow.nodes.length +
|
|
144
150
|
" node" + (owned.length === 1 ? " reuses" : "s reuse") + " a phase this session already owns.\n" +
|
|
145
151
|
lines.join("\n") +
|
|
146
|
-
"\nInspect the owning run or workflow with subagent_status and reuse its evidence. Main handles follow-up work. Retire an interrupted run with subagent_stop({ id: <run id
|
|
152
|
+
"\nInspect the owning run or workflow with subagent_status and reuse its evidence. Main handles follow-up work. Retire an interrupted run with subagent_stop({ id: \"<run id>\" }) only when discarding its retained session is intended. Different deliverables need different task inputs. No nodes were started.",
|
|
147
153
|
);
|
|
148
154
|
}
|
|
149
155
|
|
|
@@ -154,6 +160,8 @@ export function registerWorkflowTool(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
154
160
|
if (conflict) throw new Error(`Workflow node "${node.id}" scope ${conflict.overlap.left} overlaps ${conflict.owner} scope ${conflict.overlap.right}. No nodes were started.`);
|
|
155
161
|
}
|
|
156
162
|
|
|
163
|
+
const wait = params.wait ?? (ctx.hasUI === false);
|
|
164
|
+
const resultsRoot = projectResultsRoot(runtime.configPath, ctx.cwd);
|
|
157
165
|
const handle = startWorkflow(
|
|
158
166
|
{
|
|
159
167
|
runtime,
|
|
@@ -166,11 +174,40 @@ export function registerWorkflowTool(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
166
174
|
agent ? isWriteCapableAgent(agent, toolInfos) : undefined,
|
|
167
175
|
);
|
|
168
176
|
},
|
|
169
|
-
|
|
177
|
+
deliveryRoute: wait ? "await" : "background",
|
|
178
|
+
resultsRoot,
|
|
170
179
|
notify: (message, kind) => ctx.ui.notify(message, kind),
|
|
171
180
|
},
|
|
172
181
|
workflow,
|
|
173
182
|
);
|
|
183
|
+
if (wait) {
|
|
184
|
+
let cancellation: Promise<void> | undefined;
|
|
185
|
+
const onAbort = (): void => {
|
|
186
|
+
cancellation ??= cancelActiveWork(runtime, "Parent run was cancelled.");
|
|
187
|
+
};
|
|
188
|
+
const emitProgress = (): void => {
|
|
189
|
+
onUpdate?.({
|
|
190
|
+
content: [{ type: "text", text: formatWorkflowStatus(handle.run).join("\n") }],
|
|
191
|
+
details: { workflow: workflowStatus(handle.run) } satisfies WorkflowToolDetails,
|
|
192
|
+
});
|
|
193
|
+
};
|
|
194
|
+
const unsubscribe = onUpdate ? monitor.subscribe(emitProgress) : undefined;
|
|
195
|
+
try {
|
|
196
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
197
|
+
if (signal?.aborted) onAbort();
|
|
198
|
+
emitProgress();
|
|
199
|
+
const run = await handle.done;
|
|
200
|
+
await cancellation;
|
|
201
|
+
return {
|
|
202
|
+
content: [{ type: "text", text: formatWorkflowSummary(run, resultsRoot) }],
|
|
203
|
+
details: { workflow: workflowStatus(run) } satisfies WorkflowToolDetails,
|
|
204
|
+
isError: run.state !== "completed",
|
|
205
|
+
};
|
|
206
|
+
} finally {
|
|
207
|
+
signal?.removeEventListener("abort", onAbort);
|
|
208
|
+
unsubscribe?.();
|
|
209
|
+
}
|
|
210
|
+
}
|
|
174
211
|
const status = workflowStatus(handle.run);
|
|
175
212
|
return {
|
|
176
213
|
content: [{ type: "text", text: launchReceipt(status) }],
|