@ferris1225/pi-subagents 4.3.32 → 4.3.34
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 +36 -0
- package/README.md +94 -2
- package/index.ts +10 -1
- package/package.json +6 -1
- package/skills/workflow/SKILL.md +230 -0
- package/src/delegation/agents.ts +1 -0
- package/src/delegation/dispatch.ts +11 -115
- package/src/delegation/prompt.ts +1 -0
- package/src/lifecycle/dispatch-core.ts +142 -0
- package/src/lifecycle/runtime.ts +28 -0
- package/src/lifecycle/thread-lifecycle.ts +36 -19
- package/src/lifecycle/thread-shared.ts +7 -0
- package/src/lifecycle/tools.ts +82 -6
- package/src/presentation/monitor.ts +17 -1
- package/src/workflow/durable.ts +195 -0
- package/src/workflow/engine.ts +660 -0
- package/src/workflow/files.ts +217 -0
- package/src/workflow/plan.ts +340 -0
- package/src/workflow/state.ts +48 -0
- package/src/workflow/tool.ts +286 -0
- package/workflows/code-review.md +57 -0
- package/workflows/migration.md +52 -0
- package/workflows/research.md +47 -0
package/src/delegation/prompt.ts
CHANGED
|
@@ -162,6 +162,7 @@ function delegationBody(agents: AgentConfig[]): string {
|
|
|
162
162
|
...(preferred ? [preferred] : []),
|
|
163
163
|
"Children inherit this session's live tool surface: a role without an allowlist gets everything you have, including `codemode`, and a read-only role keeps only the tools the host proves read-only. Do not plan a phase that needs a tool its role cannot reach.",
|
|
164
164
|
"Give each phase one owner, a stable `phaseId`, and exact writer `scope`. Parallelize independent phases in one call; never overlap writers or duplicate an owned phase. Dependent phases wait for prerequisites. Scope is conflict metadata, not permissions or a sandbox.",
|
|
165
|
+
"When the request is one deliverable spanning ordered phases (survey, then independent changes, then a single gate), declare the graph once with `subagent_workflow` instead of dispatching wave after wave: the runtime starts each node the moment its prerequisites settle and sends one summary when the graph does. Saved graphs under `.pi/workflows/` run by name.",
|
|
165
166
|
"Children have no parent conversation; send a self-contained brief and reuse established evidence.",
|
|
166
167
|
"One-shot runs return once. Main takes over failed or incomplete work from partial edits and artifacts; a different deliverable needs a new phase.",
|
|
167
168
|
"Use `wait: true` for an immediate dependency or one-shot session; otherwise continue disjoint work and end your turn when none remains — completions arrive automatically and wake you; do not poll or sleep to wait. Conclude the overall task only after every run settles or is stopped.",
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared background-dispatch machinery used by both delegation tools.
|
|
3
|
+
*
|
|
4
|
+
* The `subagent` tool and the workflow runner start children through the same
|
|
5
|
+
* dispatcher, live-activity projection, terminal-notification path, and tool-card
|
|
6
|
+
* details builder. Keeping them here means a workflow node is an ordinary
|
|
7
|
+
* managed run: same queue pacing, isolation, admission, durable checkpointing,
|
|
8
|
+
* and completion accounting.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { createBackgroundDispatcher } from "./thread-lifecycle.ts";
|
|
12
|
+
import { getResultError, type SingleResult, type SubagentDetails, type SubagentLiveEvent } from "../execution/spawn.ts";
|
|
13
|
+
import { formatTaskSummary, formatToolActivity, monitor } from "../presentation/monitor.ts";
|
|
14
|
+
import type { StartBackgroundInternal, DispatchEnvironment } from "./thread-shared.ts";
|
|
15
|
+
import { persistThreadCheckpoint } from "./thread-shared.ts";
|
|
16
|
+
import type { SubagentRuntime } from "./runtime.ts";
|
|
17
|
+
|
|
18
|
+
export interface DispatchCore {
|
|
19
|
+
/** Publish the context/config/catalog a dispatch needs; every fresh call refreshes it. */
|
|
20
|
+
setEnvironment(environment: DispatchEnvironment): void;
|
|
21
|
+
startBackground: StartBackgroundInternal;
|
|
22
|
+
/** Stamp a terminal monitor state and toast the result once. */
|
|
23
|
+
finishRun: (runId: number, status: "done" | "failed", opts?: { silent?: boolean }) => void;
|
|
24
|
+
makeLiveHandler: (runId: number, generation?: number) => (event: SubagentLiveEvent) => void;
|
|
25
|
+
makeDetails: (mode: "single" | "parallel", background?: boolean) => (results: SingleResult[]) => SubagentDetails;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function createDispatchCore(runtime: SubagentRuntime): DispatchCore {
|
|
29
|
+
const environmentRef: { current: DispatchEnvironment | undefined } = { current: undefined };
|
|
30
|
+
|
|
31
|
+
// Terminal rows stay in the monitor until the next beginTurn so the footer
|
|
32
|
+
// can count them beside siblings that are still live. The widget ignores
|
|
33
|
+
// them. Repeated publication of the same settlement is a no-op.
|
|
34
|
+
const publishedEndedAt = new Map<number, number>();
|
|
35
|
+
const finishRun = (
|
|
36
|
+
runId: number,
|
|
37
|
+
status: "done" | "failed",
|
|
38
|
+
opts?: { silent?: boolean },
|
|
39
|
+
): void => {
|
|
40
|
+
const run = monitor.findRun(runId);
|
|
41
|
+
if (!run) return;
|
|
42
|
+
monitor.setStatus(runId, status); // stamps endedAt for the elapsed time
|
|
43
|
+
const endedAt = monitor.findRun(runId)?.endedAt;
|
|
44
|
+
if (endedAt !== undefined && publishedEndedAt.get(runId) === endedAt) return;
|
|
45
|
+
if (endedAt !== undefined) publishedEndedAt.set(runId, endedAt);
|
|
46
|
+
if (opts?.silent || !runtime.sessionActive) return;
|
|
47
|
+
const icon = status === "done" ? "✓" : "✗";
|
|
48
|
+
const result = runtime.threads.get(runId)?.lastResult;
|
|
49
|
+
const error = status === "failed" ? result ? getResultError(result) : "No failure reason was recorded." : undefined;
|
|
50
|
+
environmentRef.current?.ctx.ui.notify(
|
|
51
|
+
`${icon} #${run.id} ${monitor.summarize(run)}${error ? ` · ${formatTaskSummary(error, 300, false)}` : ""}`,
|
|
52
|
+
status === "done" ? "info" : "error",
|
|
53
|
+
);
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
// Live sub-agent activity → concise one-line status ("thinking",
|
|
57
|
+
// "read src/index.ts", ...), never a raw args blob. The live handler
|
|
58
|
+
// only updates monitor state; the queue task owns terminal removal,
|
|
59
|
+
// notification, and lifecycle decisions.
|
|
60
|
+
const makeLiveHandler = (runId: number, generation?: number) => {
|
|
61
|
+
// Every child turn reports "running"; the manifest is rewritten only when
|
|
62
|
+
// what it records for recovery (session path, child pids) actually changed.
|
|
63
|
+
let checkpointKey: string | undefined;
|
|
64
|
+
return (e: SubagentLiveEvent): void => {
|
|
65
|
+
if (generation !== undefined && runtime.threads.get(runId)?.generation !== generation) return;
|
|
66
|
+
switch (e.kind) {
|
|
67
|
+
case "status":
|
|
68
|
+
monitor.setStatus(runId, e.status);
|
|
69
|
+
// A fresh running segment refreshes the durable checkpoint (session
|
|
70
|
+
// path plus child pids) so a crash mid-generation still restores.
|
|
71
|
+
if (e.status === "running") {
|
|
72
|
+
const thread = runtime.threads.get(runId);
|
|
73
|
+
if (thread?.sessionId && thread.sessionDir) {
|
|
74
|
+
const key = `${thread.sessionDir}\0${thread.control.getChildPids().join(",")}`;
|
|
75
|
+
if (key !== checkpointKey) {
|
|
76
|
+
checkpointKey = key;
|
|
77
|
+
persistThreadCheckpoint(runtime, thread, "parked");
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
break;
|
|
82
|
+
case "model":
|
|
83
|
+
monitor.setModel(runId, e.model, e.fallbackFrom);
|
|
84
|
+
monitor.setThinking(runId, e.thinking);
|
|
85
|
+
break;
|
|
86
|
+
case "usage":
|
|
87
|
+
monitor.setUsage(runId, e.usage, e.model);
|
|
88
|
+
break;
|
|
89
|
+
case "session": {
|
|
90
|
+
runtime.retainSession({ sessionDir: e.sessionDir });
|
|
91
|
+
const thread = runtime.threads.get(runId);
|
|
92
|
+
if (thread && (generation === undefined || runtime.threads.get(runId)?.generation === generation)) {
|
|
93
|
+
thread.sessionId = e.sessionId;
|
|
94
|
+
thread.sessionDir = e.sessionDir;
|
|
95
|
+
persistThreadCheckpoint(runtime, thread, "parked");
|
|
96
|
+
}
|
|
97
|
+
break;
|
|
98
|
+
}
|
|
99
|
+
case "tool_start":
|
|
100
|
+
monitor.recordToolStart(runId, e.toolName, formatToolActivity(e.toolName, e.args));
|
|
101
|
+
break;
|
|
102
|
+
case "tool_end":
|
|
103
|
+
monitor.recordToolEnd(runId, e.toolName, e.isError);
|
|
104
|
+
break;
|
|
105
|
+
case "thinking":
|
|
106
|
+
monitor.setActivity(runId, "thinking");
|
|
107
|
+
break;
|
|
108
|
+
case "text":
|
|
109
|
+
// A text delta is model output, not a filesystem write.
|
|
110
|
+
monitor.setActivity(runId, "responding");
|
|
111
|
+
break;
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
const makeDetails =
|
|
117
|
+
(mode: "single" | "parallel", background = false) =>
|
|
118
|
+
(results: SingleResult[]): SubagentDetails => ({ mode, results, background });
|
|
119
|
+
|
|
120
|
+
const startBackground = createBackgroundDispatcher({
|
|
121
|
+
runtime,
|
|
122
|
+
getEnvironment: () => {
|
|
123
|
+
if (!environmentRef.current) {
|
|
124
|
+
throw new Error("pi-subagents dispatch environment is not ready yet.");
|
|
125
|
+
}
|
|
126
|
+
return environmentRef.current;
|
|
127
|
+
},
|
|
128
|
+
finishRun,
|
|
129
|
+
makeLiveHandler,
|
|
130
|
+
makeDetails,
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
return {
|
|
134
|
+
setEnvironment: (environment) => {
|
|
135
|
+
environmentRef.current = environment;
|
|
136
|
+
},
|
|
137
|
+
startBackground,
|
|
138
|
+
finishRun,
|
|
139
|
+
makeLiveHandler,
|
|
140
|
+
makeDetails,
|
|
141
|
+
};
|
|
142
|
+
}
|
package/src/lifecycle/runtime.ts
CHANGED
|
@@ -25,6 +25,7 @@ import { isRunActiveStatus, monitor } from "../presentation/monitor.ts";
|
|
|
25
25
|
import type { RpcRunControl } from "../execution/rpc-control.ts";
|
|
26
26
|
import { isFailedResult, type SingleResult } from "../execution/spawn.ts";
|
|
27
27
|
import type { IsolationMode, WorktreeFinalization, WorktreeIsolation } from "../isolation/worktree.ts";
|
|
28
|
+
import type { WorkflowRun } from "../workflow/state.ts";
|
|
28
29
|
|
|
29
30
|
export type ThreadState = "queued" | "running" | "interrupting" | "parked" | "completed" | "failed" | "stopped";
|
|
30
31
|
|
|
@@ -115,6 +116,15 @@ export interface SubagentRuntime {
|
|
|
115
116
|
registerRunResult: (runId: number, result: SingleResult) => void;
|
|
116
117
|
/** Logical threads outlive process attempts and completed generations. */
|
|
117
118
|
threads: Map<number, SubagentThread>;
|
|
119
|
+
/** Workflow graphs started in this parent session, live and settled. */
|
|
120
|
+
workflows: Map<number, WorkflowRun>;
|
|
121
|
+
/** Allocate a graph id that no retained or live workflow record owns. */
|
|
122
|
+
reserveWorkflowId: () => number;
|
|
123
|
+
/** Raise the graph-id allocator above an id restored from a durable record. */
|
|
124
|
+
ensureWorkflowIdAbove: (id: number) => void;
|
|
125
|
+
/** Session-teardown tasks that must run before runtime state is released
|
|
126
|
+
* (persisting a graph's shape, for example). */
|
|
127
|
+
shutdownHooks: Array<() => Promise<void> | void>;
|
|
118
128
|
/** Every session directory retained for this parent session. */
|
|
119
129
|
sessionDirs: Set<string>;
|
|
120
130
|
retainSession: (result: Pick<SingleResult, "sessionDir">) => void;
|
|
@@ -125,6 +135,7 @@ export interface SubagentRuntime {
|
|
|
125
135
|
|
|
126
136
|
export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRuntime {
|
|
127
137
|
const backgroundQueue = new BackgroundTaskQueue(resolveSubagentConcurrency());
|
|
138
|
+
let nextWorkflowId = 1;
|
|
128
139
|
// Compaction reads the whole history, summarizes it, and replaces it. A
|
|
129
140
|
// completion injected into that window can be swallowed by the summary,
|
|
130
141
|
// silently losing a result a child spent minutes producing — so delivery is
|
|
@@ -215,6 +226,12 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
|
|
|
215
226
|
settledRuns: new Map<number, SingleResult>(),
|
|
216
227
|
settledListeners: new Map<number, Set<(result: SingleResult) => void>>(),
|
|
217
228
|
threads: new Map<number, SubagentThread>(),
|
|
229
|
+
workflows: new Map<number, WorkflowRun>(),
|
|
230
|
+
reserveWorkflowId: () => nextWorkflowId++,
|
|
231
|
+
ensureWorkflowIdAbove: (id) => {
|
|
232
|
+
if (id >= nextWorkflowId) nextWorkflowId = id + 1;
|
|
233
|
+
},
|
|
234
|
+
shutdownHooks: [],
|
|
218
235
|
sessionDirs: new Set<string>(),
|
|
219
236
|
retainSession: (result) => {
|
|
220
237
|
if (result.sessionDir) runtime.sessionDirs.add(result.sessionDir);
|
|
@@ -334,6 +351,15 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
|
|
|
334
351
|
/* best-effort; the state-root sweep catches leftovers later */
|
|
335
352
|
}
|
|
336
353
|
}
|
|
354
|
+
// Let owners persist their own last state (a workflow's shape) while the
|
|
355
|
+
// threads it refers to still exist.
|
|
356
|
+
for (const hook of runtime.shutdownHooks) {
|
|
357
|
+
try {
|
|
358
|
+
await hook();
|
|
359
|
+
} catch {
|
|
360
|
+
/* a teardown hook must never block shutdown */
|
|
361
|
+
}
|
|
362
|
+
}
|
|
337
363
|
runtime.settledRuns.clear();
|
|
338
364
|
runtime.settledListeners.clear();
|
|
339
365
|
runtime.runControllers.clear();
|
|
@@ -342,6 +368,8 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
|
|
|
342
368
|
// manifest; the next process re-registers them at restore.
|
|
343
369
|
runtime.sessionDirs.clear();
|
|
344
370
|
runtime.threads.clear();
|
|
371
|
+
runtime.workflows.clear();
|
|
372
|
+
runtime.shutdownHooks = [];
|
|
345
373
|
monitor.clear();
|
|
346
374
|
},
|
|
347
375
|
};
|
|
@@ -113,6 +113,10 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
113
113
|
return failedStartResult(agentName, task, error instanceof Error ? error.message : String(error));
|
|
114
114
|
}
|
|
115
115
|
const writeCapable = Boolean(startOptions.writeCapable) || isWriteCapableAgent(agent, toolInfos);
|
|
116
|
+
// A workflow node is an ordinary managed run whose reporting belongs to
|
|
117
|
+
// the graph: it settles into the graph's single summary instead of
|
|
118
|
+
// waking the parent once per node.
|
|
119
|
+
const quiet = startOptions.quiet === true;
|
|
116
120
|
if (isolation === "worktree" && !isWorktreeCapableAgent(agent, toolInfos)) {
|
|
117
121
|
return {
|
|
118
122
|
...failedStartResult(agentName, task, `Agent "${agentName}" is read-only; worktree isolation is available only to write-capable agents such as artisan.`),
|
|
@@ -121,8 +125,17 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
121
125
|
}
|
|
122
126
|
const duplicate = findDuplicateDispatch(runtime.threads.values(), task, originalCwd, phaseId);
|
|
123
127
|
if (duplicate) {
|
|
128
|
+
// A phase stays owned across reloads: an interrupted run keeps its claim
|
|
129
|
+
// until it is retired, so "let it finish" is wrong advice for a parked
|
|
130
|
+
// owner and leaves the caller with no way forward.
|
|
131
|
+
const owner = duplicate.source;
|
|
132
|
+
const remedy = owner.state === "parked" || owner.retired
|
|
133
|
+
? `That run was interrupted (possibly in an earlier session) and keeps the phase claimed; retire it with subagent_stop({ id: ${owner.id} }) to reuse the phase, or give this work a different phaseId. Main handles follow-up work.`
|
|
134
|
+
: owner.state === "completed" || owner.state === "failed"
|
|
135
|
+
? "Inspect it with subagent_status; a different deliverable needs a different phaseId. Main handles follow-up work."
|
|
136
|
+
: "Do not redispatch it; inspect its result or let it finish. Main handles follow-up work.";
|
|
124
137
|
return failedStartResult(agentName, task,
|
|
125
|
-
`Run #${
|
|
138
|
+
`Run #${owner.id} (${owner.agentName}) already owns this logical phase (${owner.state}). ${remedy}`);
|
|
126
139
|
}
|
|
127
140
|
if (writeCapable && scope) {
|
|
128
141
|
const conflict = findWriterLeaseScopeOverlap(scope, runtime.threads.values());
|
|
@@ -143,7 +156,10 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
143
156
|
? { ...resolvedRoute, agent: withWorktreeSystemPrompt(resolvedRoute.agent) }
|
|
144
157
|
: resolvedRoute;
|
|
145
158
|
const thinkingLevel = route.thinkingLevel;
|
|
146
|
-
const runId = monitor.addRun(agent.name, task, route.agent.model, thinkingLevel, {
|
|
159
|
+
const runId = monitor.addRun(agent.name, task, route.agent.model, thinkingLevel, {
|
|
160
|
+
isolation,
|
|
161
|
+
...(startOptions.workflow ? { workflow: startOptions.workflow } : {}),
|
|
162
|
+
});
|
|
147
163
|
runtime.claimRunDelivery(runId, startOptions.deliveryRoute ?? "background");
|
|
148
164
|
const generation = 1;
|
|
149
165
|
const pending: SingleResult = {
|
|
@@ -342,26 +358,26 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
342
358
|
finishRun(
|
|
343
359
|
runId,
|
|
344
360
|
failed ? "failed" : "done",
|
|
345
|
-
modelLevel || dispatchFailed ? { silent: true } : undefined,
|
|
361
|
+
quiet || modelLevel || dispatchFailed ? { silent: true } : undefined,
|
|
346
362
|
);
|
|
347
363
|
runtime.registerRunResult(runId, result);
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
364
|
+
if (!quiet) {
|
|
365
|
+
const block = formatCompletionBlock(result, DEFAULT_MAX_RESULT_LINES, {
|
|
366
|
+
resultRoot: projectResultsRoot(runtime.configPath, result.projectCwd ?? originalCwd),
|
|
367
|
+
});
|
|
368
|
+
const completion: CompletionMessageItem = {
|
|
369
|
+
agent: result.agent,
|
|
370
|
+
block: modelLevel ? `${block}\n\n${modelLevelTakeoverNote(result)}` : block,
|
|
371
|
+
usage: result.usage,
|
|
372
|
+
model: result.model,
|
|
373
|
+
};
|
|
374
|
+
if (modelLevel) {
|
|
375
|
+
const detail = notifyDetail(result.errorMessage, "model unavailable or broken");
|
|
376
|
+
runCtx.ui.notify(`✗ ${result.agent} dispatch failed: ${detail} — task handed to the main window`, "error");
|
|
377
|
+
} else if (dispatchFailed) {
|
|
378
|
+
runCtx.ui.notify(`✗ ${result.agent} dispatch failed: ${notifyDetail(result.errorMessage, "dispatch crashed")}`, "error");
|
|
379
|
+
}
|
|
363
380
|
}
|
|
364
|
-
runtime.publishRunCompletion(runId, completion, failed);
|
|
365
381
|
} finally {
|
|
366
382
|
if (ownsSettlement()) thread.lifecycleOperation = undefined;
|
|
367
383
|
}
|
|
@@ -451,6 +467,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
451
467
|
runtime.runControllers.delete(runId);
|
|
452
468
|
thread.queueController = undefined;
|
|
453
469
|
if (!runtime.sessionActive || !ownsSettlement()) return;
|
|
470
|
+
if (quiet) return;
|
|
454
471
|
try {
|
|
455
472
|
runCtx.ui.notify(`✗ ${crashed.agent} dispatch failed: ${notifyDetail(crashed.errorMessage, "dispatch crashed")}`, "error");
|
|
456
473
|
runtime.publishRunCompletion(runId, {
|
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
resolveAgentModelRoute,
|
|
16
16
|
resolveThinkingLevel,
|
|
17
17
|
} from "../configuration/models.ts";
|
|
18
|
+
import type { RunWorkflowTag } from "../presentation/monitor.ts";
|
|
18
19
|
import type { SubagentRuntime, SubagentThread } from "./runtime.ts";
|
|
19
20
|
import { getProjectRoot, type SingleResult } from "../execution/spawn.ts";
|
|
20
21
|
import { resolveRepositoryRoot, type IsolationMode } from "../isolation/worktree.ts";
|
|
@@ -156,6 +157,12 @@ export interface StartBackgroundOptions {
|
|
|
156
157
|
writeCapable?: boolean;
|
|
157
158
|
/** Chosen by the tool call before the queue can start a fast child. */
|
|
158
159
|
deliveryRoute?: "background" | "await";
|
|
160
|
+
/** A workflow node reports through its graph's single summary: no per-run
|
|
161
|
+
* completion message and no per-run toast, so a wide graph cannot flood the
|
|
162
|
+
* parent with one wake-up per node. */
|
|
163
|
+
quiet?: boolean;
|
|
164
|
+
/** Graph membership rendered by the widget and node status rows. */
|
|
165
|
+
workflow?: RunWorkflowTag;
|
|
159
166
|
}
|
|
160
167
|
|
|
161
168
|
export type StartBackgroundInternal = (
|
package/src/lifecycle/tools.ts
CHANGED
|
@@ -13,6 +13,13 @@ import { persistRecoveryRecords, recoveryRecordFromFinalization } from "../isola
|
|
|
13
13
|
import type { SubagentRuntime, SubagentThread } from "./runtime.ts";
|
|
14
14
|
import { CONTROL_QUIESCE_TIMEOUT_MS, projectResultsRoot, quiesced } from "./thread-shared.ts";
|
|
15
15
|
import { getResultError, type SingleResult } from "../execution/spawn.ts";
|
|
16
|
+
import {
|
|
17
|
+
formatRetainedWorkflow,
|
|
18
|
+
formatWorkflowStatus,
|
|
19
|
+
readRetainedWorkflows,
|
|
20
|
+
stopWorkflow,
|
|
21
|
+
workflowStatus,
|
|
22
|
+
} from "../workflow/engine.ts";
|
|
16
23
|
import type { WorktreeFinalization } from "../isolation/worktree.ts";
|
|
17
24
|
|
|
18
25
|
function renderFirstLine(result: { content?: unknown }, label: string, theme: any): Text {
|
|
@@ -40,8 +47,9 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
|
|
|
40
47
|
},
|
|
41
48
|
parameters: Type.Object({
|
|
42
49
|
id: Type.Optional(Type.Integer({ minimum: 1, description: "Exact run id; omit to list all runs in this parent session." })),
|
|
50
|
+
workflow: Type.Optional(Type.Integer({ minimum: 1, description: "Workflow graph id; omit to list every graph in this parent session." })),
|
|
43
51
|
}),
|
|
44
|
-
async execute(_toolCallId, params) {
|
|
52
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
45
53
|
await runtime.durableRestore;
|
|
46
54
|
const threads = [...runtime.threads.values()]
|
|
47
55
|
.filter((thread) => params.id === undefined || thread.id === params.id)
|
|
@@ -103,10 +111,34 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
|
|
|
103
111
|
if (paths.length > 0) lines.push(` ${paths.join("\n ")}`);
|
|
104
112
|
return lines.join("\n");
|
|
105
113
|
}).join("\n");
|
|
114
|
+
// Workflow graphs are reported beside individual runs: which nodes have
|
|
115
|
+
// started, which one is waiting on a dependency, and what a graph that
|
|
116
|
+
// outlived its session left behind.
|
|
117
|
+
const workflowRuns = [...runtime.workflows.values()]
|
|
118
|
+
.filter((run) => params.workflow === undefined || run.id === params.workflow)
|
|
119
|
+
.sort((left, right) => left.id - right.id);
|
|
120
|
+
const retainedWorkflows = (await readRetainedWorkflows(runtime, ctx?.cwd ?? process.cwd()).catch(() => []))
|
|
121
|
+
.filter((record) => params.workflow === undefined || record.id === params.workflow)
|
|
122
|
+
.filter((record) => !workflowRuns.some((run) => run.id === record.id));
|
|
123
|
+
const workflowSections = [
|
|
124
|
+
...workflowRuns.map((run) => formatWorkflowStatus(run).join("\n")),
|
|
125
|
+
...retainedWorkflows.map((record) => formatRetainedWorkflow(record).join("\n")),
|
|
126
|
+
];
|
|
127
|
+
const sections = [text, ...workflowSections].filter((section) => section.trim().length > 0);
|
|
128
|
+
const unknownWorkflow = params.workflow !== undefined && workflowRuns.length === 0 && retainedWorkflows.length === 0;
|
|
106
129
|
return {
|
|
107
|
-
content: [{
|
|
108
|
-
|
|
109
|
-
|
|
130
|
+
content: [{
|
|
131
|
+
type: "text",
|
|
132
|
+
text: unknownWorkflow
|
|
133
|
+
? `No workflow graph matches #${params.workflow} in this parent session.`
|
|
134
|
+
: sections.join("\n\n"),
|
|
135
|
+
}],
|
|
136
|
+
details: {
|
|
137
|
+
runs,
|
|
138
|
+
workflows: workflowRuns.map(workflowStatus),
|
|
139
|
+
retainedWorkflows,
|
|
140
|
+
},
|
|
141
|
+
...((params.id !== undefined && runs.length === 0) || unknownWorkflow ? { isError: true } : {}),
|
|
110
142
|
};
|
|
111
143
|
},
|
|
112
144
|
renderCall(args, theme) {
|
|
@@ -127,7 +159,11 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
|
|
|
127
159
|
description: "Run id or prefix to stop (see subagent dispatch output).",
|
|
128
160
|
}),
|
|
129
161
|
),
|
|
130
|
-
all: Type.Optional(Type.Boolean({ description: "Stop every active run (default false)." })),
|
|
162
|
+
all: Type.Optional(Type.Boolean({ description: "Stop every active run and every running workflow (default false)." })),
|
|
163
|
+
workflow: Type.Optional(Type.Integer({
|
|
164
|
+
minimum: 1,
|
|
165
|
+
description: "Stop this workflow graph: no dependent node starts and running nodes are cancelled.",
|
|
166
|
+
})),
|
|
131
167
|
});
|
|
132
168
|
|
|
133
169
|
pi.registerTool({
|
|
@@ -146,6 +182,40 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
|
|
|
146
182
|
|
|
147
183
|
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
148
184
|
await runtime.durableRestore;
|
|
185
|
+
// A graph stop owns its own lifecycle: dependents must not start, and the
|
|
186
|
+
// graph's own summary reports what had already completed. Stopping the
|
|
187
|
+
// nodes one by one first would let the runner dispatch the next layer.
|
|
188
|
+
if (params.workflow !== undefined) {
|
|
189
|
+
const graph = runtime.workflows.get(params.workflow);
|
|
190
|
+
if (!graph) {
|
|
191
|
+
const known = [...runtime.workflows.keys()].map((id) => `#${id}`).join(", ");
|
|
192
|
+
return {
|
|
193
|
+
content: [{
|
|
194
|
+
type: "text",
|
|
195
|
+
text: `No workflow graph matches #${params.workflow}.${known ? ` Known graphs: ${known}.` : ""}`,
|
|
196
|
+
}],
|
|
197
|
+
details: {},
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
const cancelled = await stopWorkflow(runtime, graph, "Stopped by subagent_stop.");
|
|
201
|
+
return {
|
|
202
|
+
content: [{
|
|
203
|
+
type: "text",
|
|
204
|
+
text: `Stopped workflow #${graph.id} ${graph.name}${cancelled.length > 0 ? `; cancelled ${cancelled.map((id) => `#${id}`).join(", ")}` : "; no node had started"}. Its summary reports the completed work, and each node keeps its own run evidence.`,
|
|
205
|
+
}],
|
|
206
|
+
details: {},
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
const graphStops: string[] = [];
|
|
210
|
+
if (params.all === true) {
|
|
211
|
+
for (const graph of [...runtime.workflows.values()]) {
|
|
212
|
+
if (graph.state !== "running") continue;
|
|
213
|
+
const cancelled = await stopWorkflow(runtime, graph, "Stopped by subagent_stop.");
|
|
214
|
+
graphStops.push(
|
|
215
|
+
`workflow #${graph.id} ${graph.name}${cancelled.length > 0 ? ` (${cancelled.length} node${cancelled.length === 1 ? "" : "s"} cancelled)` : ""}`,
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
149
219
|
const completionResults: SingleResult[] = [];
|
|
150
220
|
const candidateIds = params.all === true
|
|
151
221
|
? [...new Set([
|
|
@@ -161,6 +231,12 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
|
|
|
161
231
|
|
|
162
232
|
if (targets.length === 0) {
|
|
163
233
|
const available = [...runtime.threads.keys()].map((id) => `#${id}`).join(", ");
|
|
234
|
+
if (graphStops.length > 0) {
|
|
235
|
+
return {
|
|
236
|
+
content: [{ type: "text", text: `Stopped ${graphStops.length} workflow${graphStops.length === 1 ? "" : "s"}: ${graphStops.join(", ")}.` }],
|
|
237
|
+
details: {},
|
|
238
|
+
};
|
|
239
|
+
}
|
|
164
240
|
return {
|
|
165
241
|
content: [{ type: "text", text: params.all === true
|
|
166
242
|
? "No active subagent runs to stop."
|
|
@@ -340,7 +416,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
|
|
|
340
416
|
return {
|
|
341
417
|
content: [{
|
|
342
418
|
type: "text",
|
|
343
|
-
text: `Stopped ${stopped.length} thread${stopped.length === 1 ? "" : "s"}: ${stopped.join(", ")}. Retained sessions were retired; worktree changes are integrated on settlement.${retainedIntegration.length > 0 ? ` Integration failed for ${retainedIntegration.join(", ")}; inspect its result for retained recovery paths.` : ""}${pendingIntegration.length > 0 ? ` Integration is still settling in the background for ${pendingIntegration.join(", ")}; a recovery record was persisted in case it fails.` : ""}`,
|
|
419
|
+
text: `${graphStops.length > 0 ? `Stopped ${graphStops.length} workflow${graphStops.length === 1 ? "" : "s"}: ${graphStops.join(", ")}. ` : ""}Stopped ${stopped.length} thread${stopped.length === 1 ? "" : "s"}: ${stopped.join(", ")}. Retained sessions were retired; worktree changes are integrated on settlement.${retainedIntegration.length > 0 ? ` Integration failed for ${retainedIntegration.join(", ")}; inspect its result for retained recovery paths.` : ""}${pendingIntegration.length > 0 ? ` Integration is still settling in the background for ${pendingIntegration.join(", ")}; a recovery record was persisted in case it fails.` : ""}`,
|
|
344
420
|
}],
|
|
345
421
|
details: {},
|
|
346
422
|
};
|
|
@@ -40,6 +40,14 @@ export function isRunActiveStatus(status: RunStatus): boolean {
|
|
|
40
40
|
* terminal WorktreeFinalizationStatus. */
|
|
41
41
|
export type RunIntegrationStatus = "pending" | "finalizing" | WorktreeFinalizationStatus;
|
|
42
42
|
|
|
43
|
+
/** Workflow membership of a run: which graph, and which node of it. Rendered so
|
|
44
|
+
* a workflow's nodes read as one group in the widget and the status view. */
|
|
45
|
+
export interface RunWorkflowTag {
|
|
46
|
+
workflowId: number;
|
|
47
|
+
name: string;
|
|
48
|
+
nodeId: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
43
51
|
export interface RunView {
|
|
44
52
|
id: number;
|
|
45
53
|
agent: string;
|
|
@@ -73,11 +81,15 @@ export interface RunView {
|
|
|
73
81
|
elapsedMs: number;
|
|
74
82
|
/** Epoch ms when the latest active segment stopped. */
|
|
75
83
|
endedAt?: number;
|
|
84
|
+
/** Workflow membership, when this run is a node of a `subagent_workflow` graph. */
|
|
85
|
+
workflow?: RunWorkflowTag;
|
|
76
86
|
}
|
|
77
87
|
|
|
78
88
|
export interface RunChainMeta {
|
|
79
89
|
isolation?: IsolationMode;
|
|
80
90
|
worktreeId?: string;
|
|
91
|
+
/** Set for nodes the workflow runner dispatches. */
|
|
92
|
+
workflow?: RunWorkflowTag;
|
|
81
93
|
/** Initial wait reason; defaults to "process-slot" (a fresh dispatch enters
|
|
82
94
|
* the process queue). Children spawned outside the queue pass "starting"
|
|
83
95
|
* because they never wait for a slot. */
|
|
@@ -494,7 +506,10 @@ export class MonitorStore {
|
|
|
494
506
|
id,
|
|
495
507
|
agent,
|
|
496
508
|
task,
|
|
497
|
-
|
|
509
|
+
// A graph node is identified by its graph and node id: the task text it
|
|
510
|
+
// actually runs is interpolated with upstream answers, which makes a
|
|
511
|
+
// fragment-extracted label read like noise.
|
|
512
|
+
label: meta?.workflow ? `${meta.workflow.name}/${meta.workflow.nodeId}` : runLabel(task),
|
|
498
513
|
model,
|
|
499
514
|
thinking,
|
|
500
515
|
status: "queued",
|
|
@@ -502,6 +517,7 @@ export class MonitorStore {
|
|
|
502
517
|
usage: emptyUsage(),
|
|
503
518
|
elapsedMs: 0,
|
|
504
519
|
...(meta?.isolation ? { isolation: meta.isolation, integrationStatus: meta.isolation === "worktree" ? "pending" : undefined, ...(meta.worktreeId ? { worktreeId: meta.worktreeId } : {}) } : {}),
|
|
520
|
+
...(meta?.workflow ? { workflow: meta.workflow } : {}),
|
|
505
521
|
});
|
|
506
522
|
this.notify();
|
|
507
523
|
return id;
|