@ferris1225/pi-subagents 4.3.32 → 4.3.33

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.
@@ -0,0 +1,625 @@
1
+ /**
2
+ * Workflow runner: a dependency-ordered graph of ordinary managed sub-agent runs.
3
+ *
4
+ * The rule this module exists for is "dispatch the next node the moment its
5
+ * prerequisites settle, without waking the parent model". Each node is started
6
+ * through the same dispatcher a `subagent` call uses — same queue pacing, same
7
+ * admission, same isolation, same durable checkpoint — and is `quiet`, meaning
8
+ * it reports into this graph instead of sending its own completion message.
9
+ * The parent is woken exactly once, with the graph's summary.
10
+ *
11
+ * Failure is contained by the graph, not the session: a failed node blocks only
12
+ * its dependents, independent branches keep running, and the summary states
13
+ * what completed, what failed, and what never ran. Nodes do not retry and do not
14
+ * resume — main finishes incomplete work from their retained evidence, exactly
15
+ * as for a failed one-shot run.
16
+ */
17
+
18
+ import { isFailedResult, getResultError, getResultOutput, truncateResultOutput, writeResultArtifact, type SingleResult } from "../execution/spawn.ts";
19
+ import { formatDuration, formatTaskSummary, monitor } from "../presentation/monitor.ts";
20
+ import { perModelTotals, type CompletionMessageItem } from "../lifecycle/completion.ts";
21
+ import type { SubagentRuntime } from "../lifecycle/runtime.ts";
22
+ import type { StartBackgroundInternal } from "../lifecycle/thread-shared.ts";
23
+ import { defaultPhaseId, renderNodeTask, type CompiledWorkflow, type UpstreamOutput } from "./plan.ts";
24
+ import {
25
+ readWorkflowRecords,
26
+ removeWorkflowRecord,
27
+ upsertWorkflowRecord,
28
+ type RecordedNodeState,
29
+ type WorkflowRecord,
30
+ } from "./durable.ts";
31
+ import type { WorkflowNodeRun, WorkflowRun, WorkflowRunState } from "./state.ts";
32
+
33
+ /** Lines of one node's answer inlined into the graph summary. The complete text
34
+ * of every node is always written to a single workflow artifact, so nothing is
35
+ * lost and nothing is delivered twice. */
36
+ export const NODE_SUMMARY_LINES = 12;
37
+
38
+ export interface WorkflowRunDeps {
39
+ runtime: SubagentRuntime;
40
+ startBackground: StartBackgroundInternal;
41
+ /** Isolation the graph wants for a node, resolved against the live catalog. */
42
+ resolveIsolation: (agentName: string) => "shared" | "worktree";
43
+ /** Project-scoped results directory for the full workflow report. */
44
+ resultsRoot: string;
45
+ notify: (message: string, kind: "info" | "warning" | "error") => void;
46
+ }
47
+
48
+ export interface WorkflowHandle {
49
+ run: WorkflowRun;
50
+ /** Resolves after the graph settles and its summary is delivered. */
51
+ done: Promise<WorkflowRun>;
52
+ }
53
+
54
+ interface RunContext extends WorkflowRunDeps {
55
+ run: WorkflowRun;
56
+ wake: () => void;
57
+ waitForWake: () => Promise<void>;
58
+ }
59
+
60
+ function nodeById(run: WorkflowRun, id: string): WorkflowNodeRun | undefined {
61
+ return run.nodes.find((node) => node.id === id);
62
+ }
63
+
64
+ function terminalFailure(state: WorkflowNodeStateUnion): boolean {
65
+ return state === "failed" || state === "blocked" || state === "stopped";
66
+ }
67
+
68
+ type WorkflowNodeStateUnion = WorkflowNodeRun["state"];
69
+
70
+ function describeError(result: SingleResult): string | undefined {
71
+ return getResultError(result)?.trim() || undefined;
72
+ }
73
+
74
+ /** Upstream fact view passed to a dependent node's brief. */
75
+ function upstreamView(node: WorkflowNodeRun): UpstreamOutput {
76
+ const result = node.result;
77
+ const output = result ? getResultOutput(result) : "";
78
+ return {
79
+ status: node.state === "completed" ? "completed" : node.state === "failed" ? "failed" : node.state === "blocked" ? "blocked" : "stopped",
80
+ output,
81
+ ...(node.runId !== undefined ? { runId: node.runId } : {}),
82
+ ...(node.error ? { error: node.error } : {}),
83
+ };
84
+ }
85
+
86
+ /** Resolve once the run reports a terminal result, or once it stops existing. */
87
+ function waitForNodeSettlement(
88
+ runtime: SubagentRuntime,
89
+ runId: number,
90
+ signal: AbortSignal,
91
+ ): Promise<SingleResult | undefined> {
92
+ const already = runtime.settledRuns.get(runId);
93
+ if (already) return Promise.resolve(already);
94
+ return new Promise((resolve) => {
95
+ let done = false;
96
+ let unsubscribe: (() => void) | undefined;
97
+ const cleanup = (): void => {
98
+ unsubscribe?.();
99
+ signal.removeEventListener("abort", onAbort);
100
+ runtime.settledListeners.get(runId)?.delete(onSettled);
101
+ };
102
+ const finish = (result: SingleResult | undefined): void => {
103
+ if (done) return;
104
+ done = true;
105
+ cleanup();
106
+ resolve(result);
107
+ };
108
+ const onSettled = (result: SingleResult): void => finish(result);
109
+ const onAbort = (): void => finish(undefined);
110
+ const listeners = runtime.settledListeners.get(runId) ?? new Set<(result: SingleResult) => void>();
111
+ runtime.settledListeners.set(runId, listeners);
112
+ listeners.add(onSettled);
113
+ unsubscribe = monitor.subscribe(() => {
114
+ const settled = runtime.settledRuns.get(runId);
115
+ if (settled) {
116
+ finish(settled);
117
+ return;
118
+ }
119
+ if (monitor.findRun(runId)) return;
120
+ // Removal is followed synchronously by registerRunResult on the normal
121
+ // path; a cancelled run never registers one, so fall back to whatever
122
+ // the thread recorded before giving up on this node.
123
+ setTimeout(() => {
124
+ finish(runtime.settledRuns.get(runId) ?? runtime.threads.get(runId)?.lastResult);
125
+ }, 0);
126
+ });
127
+ if (signal.aborted) finish(undefined);
128
+ else signal.addEventListener("abort", onAbort, { once: true });
129
+ });
130
+ }
131
+
132
+ async function dispatchNode(ctx: RunContext, node: WorkflowNodeRun): Promise<void> {
133
+ const { run } = ctx;
134
+ const upstream = new Map<string, UpstreamOutput>();
135
+ for (const dependency of node.dependsOn) {
136
+ const upstreamNode = nodeById(run, dependency);
137
+ if (upstreamNode) upstream.set(dependency, upstreamView(upstreamNode));
138
+ }
139
+ const task = renderNodeTask(node.task, upstream);
140
+ node.dispatchedTask = task;
141
+ node.state = "running";
142
+ node.startedAt = Date.now();
143
+ let started: SingleResult;
144
+ try {
145
+ started = await ctx.startBackground(node.agent, task, node.cwd, ctx.resolveIsolation(node.agent), {
146
+ phaseId: node.phaseId,
147
+ scope: node.scope,
148
+ deliveryRoute: "background",
149
+ quiet: true,
150
+ workflow: { workflowId: run.id, name: run.name, nodeId: node.id },
151
+ });
152
+ } catch (error) {
153
+ node.state = "failed";
154
+ node.error = `dispatch crashed: ${error instanceof Error ? error.message : String(error)}`;
155
+ node.endedAt = Date.now();
156
+ return;
157
+ }
158
+ if (started.runId === undefined || started.exitCode !== -1) {
159
+ // A rejected start (unknown agent, duplicate phase, overlapping scope,
160
+ // worktree admission) never allocated a run; its text is the reason.
161
+ node.state = "failed";
162
+ node.error = getResultOutput(started).trim() || getResultError(started) || "the node could not start";
163
+ node.result = started;
164
+ node.endedAt = Date.now();
165
+ return;
166
+ }
167
+ node.runId = started.runId;
168
+ const result = await waitForNodeSettlement(ctx.runtime, started.runId, run.controller.signal);
169
+ node.endedAt = Date.now();
170
+ node.result = result;
171
+ if (run.state !== "running") {
172
+ node.state = "stopped";
173
+ node.error ??= run.stopReason ?? "workflow stopped";
174
+ return;
175
+ }
176
+ if (!result) {
177
+ node.state = "stopped";
178
+ node.error = "the run ended without reporting a result";
179
+ return;
180
+ }
181
+ if (isFailedResult(result)) {
182
+ node.state = "failed";
183
+ node.error = describeError(result) ?? "the run failed";
184
+ ctx.notify(
185
+ `✗ workflow ${run.name} · node ${node.id} (${node.agent}) failed: ${formatTaskSummary(node.error, 200, false)}`,
186
+ "error",
187
+ );
188
+ return;
189
+ }
190
+ node.state = "completed";
191
+ }
192
+
193
+ /** Blocked nodes are reported, not silently skipped: a graph that never ran a
194
+ * node must say why. */
195
+ function blockDependents(run: WorkflowRun): boolean {
196
+ let changed = false;
197
+ for (const node of run.nodes) {
198
+ if (node.state !== "pending") continue;
199
+ const broken = node.dependsOn.find((dependency) => {
200
+ const state = nodeById(run, dependency)?.state;
201
+ return state !== undefined && terminalFailure(state);
202
+ });
203
+ if (!broken) continue;
204
+ node.state = "blocked";
205
+ node.error = `dependency "${broken}" did not complete; this node never ran`;
206
+ changed = true;
207
+ }
208
+ return changed;
209
+ }
210
+
211
+ async function drive(ctx: RunContext): Promise<void> {
212
+ const { run } = ctx;
213
+ while (run.state === "running") {
214
+ blockDependents(run);
215
+ const ready = run.nodes.filter(
216
+ (node) =>
217
+ node.state === "pending" &&
218
+ node.dependsOn.every((dependency) => nodeById(run, dependency)?.state === "completed"),
219
+ );
220
+ for (const node of ready) {
221
+ // dispatchNode marks the node running synchronously, so the next pass
222
+ // cannot start it twice.
223
+ void dispatchNode(ctx, node).finally(ctx.wake);
224
+ }
225
+ if (run.state !== "running") break;
226
+ const running = run.nodes.some((node) => node.state === "running");
227
+ if (!running && run.nodes.every((node) => node.state !== "pending")) break;
228
+ // Nothing can start until a running node settles (or a node that was just
229
+ // marked blocked frees the pass); wait for one wake-up instead of polling.
230
+ await ctx.waitForWake();
231
+ }
232
+ await settle(ctx);
233
+ }
234
+
235
+ function stateLabel(state: WorkflowRunState): string {
236
+ switch (state) {
237
+ case "completed":
238
+ return "completed";
239
+ case "failed":
240
+ return "finished with failures";
241
+ case "stopped":
242
+ return "stopped";
243
+ case "interrupted":
244
+ return "interrupted";
245
+ default:
246
+ return "running";
247
+ }
248
+ }
249
+
250
+ function nodeStateWord(node: WorkflowNodeRun): string {
251
+ return node.state === "blocked" ? "never ran (blocked)" : node.state;
252
+ }
253
+
254
+ /** One line per node: what ran, what it cost in wall-clock, and why it failed. */
255
+ export function formatNodeLine(node: WorkflowNodeRun): string {
256
+ const parts = [`${node.id} (${node.agent}) ${nodeStateWord(node)}`];
257
+ if (node.runId !== undefined) parts.push(`run #${node.runId}`);
258
+ if (node.startedAt !== undefined) {
259
+ parts.push(formatDuration((node.endedAt ?? Date.now()) - node.startedAt));
260
+ }
261
+ if (node.error && node.state !== "completed") {
262
+ parts.push(`error: ${formatTaskSummary(node.error, 220, false)}`);
263
+ }
264
+ if (node.state === "pending" && node.dependsOn.length > 0) {
265
+ parts.push(`waiting for ${node.dependsOn.join(", ")}`);
266
+ }
267
+ return `- ${parts.join(" · ")}`;
268
+ }
269
+
270
+ function completedCount(run: WorkflowRun): number {
271
+ return run.nodes.filter((node) => node.state === "completed").length;
272
+ }
273
+
274
+ /** Full markdown report: every node's line and every node's complete answer. */
275
+ export function formatWorkflowReport(run: WorkflowRun): string {
276
+ const lines = [
277
+ `# Workflow ${run.name} — ${stateLabel(run.state)}`,
278
+ "",
279
+ ...(run.description ? [run.description, ""] : []),
280
+ `Nodes: ${completedCount(run)} of ${run.nodes.length} completed`,
281
+ ...(run.stopReason ? [`Stop reason: ${run.stopReason}`] : []),
282
+ "",
283
+ ...run.nodes.map(formatNodeLine),
284
+ ];
285
+ for (const node of run.nodes) {
286
+ const output = node.result ? getResultOutput(node.result).trim() : "";
287
+ lines.push("", `## ${node.id} (${node.agent}) — ${nodeStateWord(node)}`, "");
288
+ lines.push(output || "(no answer recorded)");
289
+ }
290
+ return lines.join("\n");
291
+ }
292
+
293
+ /** Lines of one node's answer inlined into the completion message. */
294
+ function inlineNodeAnswer(node: WorkflowNodeRun): { text: string; truncated: boolean } {
295
+ const output = node.result ? getResultOutput(node.result) : "";
296
+ if (!output.trim()) return { text: "", truncated: false };
297
+ const clipped = truncateResultOutput(output, NODE_SUMMARY_LINES);
298
+ return { text: clipped.text.trim(), truncated: clipped.truncated };
299
+ }
300
+
301
+ /** The parent's one handoff for the whole graph. */
302
+ export function formatWorkflowSummary(run: WorkflowRun, resultsRoot?: string): string {
303
+ const completed = completedCount(run);
304
+ const failed = run.nodes.filter((node) => node.state === "failed").length;
305
+ const blocked = run.nodes.filter((node) => node.state === "blocked").length;
306
+ const stopped = run.nodes.filter((node) => node.state === "stopped").length;
307
+ const counts = [
308
+ `${completed}/${run.nodes.length} completed`,
309
+ ...(failed > 0 ? [`${failed} failed`] : []),
310
+ ...(blocked > 0 ? [`${blocked} never ran`] : []),
311
+ ...(stopped > 0 ? [`${stopped} stopped`] : []),
312
+ ].join(", ");
313
+ const lines = [
314
+ `### workflow ${run.name} ${stateLabel(run.state)} (${counts})`,
315
+ ...(run.description ? [run.description] : []),
316
+ ...(run.stopReason ? [`Stop reason: ${run.stopReason}`] : []),
317
+ "",
318
+ ...run.nodes.map(formatNodeLine),
319
+ ];
320
+
321
+ const answers: string[] = [];
322
+ let anyTruncated = false;
323
+ for (const node of run.nodes) {
324
+ const inline = inlineNodeAnswer(node);
325
+ if (!inline.text) continue;
326
+ if (inline.truncated) anyTruncated = true;
327
+ answers.push(`#### ${node.id} (${node.agent})`, inline.text, "");
328
+ }
329
+ if (answers.length > 0) {
330
+ lines.push("", "Node answers:", "", ...answers);
331
+ }
332
+ if (anyTruncated && resultsRoot) {
333
+ try {
334
+ const reportPath = writeResultArtifact(formatWorkflowReport(run), `workflow-${run.slug}`, resultsRoot);
335
+ lines.push(`⚠ Some node answers are clipped here. Read the complete report, including every node's full answer: ${reportPath}`);
336
+ } catch {
337
+ /* the summary is still useful without the artifact pointer */
338
+ }
339
+ }
340
+ const totals = perModelTotals(
341
+ run.nodes
342
+ .filter((node): node is WorkflowNodeRun & { result: SingleResult } => node.result !== undefined)
343
+ .map((node) => ({ agent: node.agent, block: "", usage: node.result.usage, model: node.result.model })),
344
+ );
345
+ if (totals) lines.push("", `Totals: ${run.nodes.length} nodes · ${totals}`);
346
+ if (failed > 0 || blocked > 0 || stopped > 0) {
347
+ lines.push(
348
+ "",
349
+ "Main owns the rest: inspect what failed or never ran, reuse the partial edits and artifacts those runs retained, then finish the work and run the project's own gate. Do not re-dispatch a phase this graph already owns.",
350
+ );
351
+ }
352
+ return lines.join("\n");
353
+ }
354
+
355
+ function workflowRecord(run: WorkflowRun, state: WorkflowRecord["state"]): WorkflowRecord {
356
+ return {
357
+ workflowId: run.id,
358
+ name: run.name,
359
+ ...(run.description ? { description: run.description } : {}),
360
+ cwd: run.cwd,
361
+ state,
362
+ startedAt: run.startedAt,
363
+ updatedAt: Date.now(),
364
+ ...(run.stopReason ? { stopReason: run.stopReason } : {}),
365
+ nodes: run.nodes.map((node) => ({
366
+ id: node.id,
367
+ agent: node.agent,
368
+ task: node.task,
369
+ dependsOn: [...node.dependsOn],
370
+ state: node.state as RecordedNodeState,
371
+ ...(node.runId !== undefined ? { runId: node.runId } : {}),
372
+ ...(node.error ? { error: node.error } : {}),
373
+ })),
374
+ };
375
+ }
376
+
377
+ async function settle(ctx: RunContext): Promise<void> {
378
+ const { run, runtime } = ctx;
379
+ // A graph interrupted by session teardown keeps the record the teardown wrote:
380
+ // it is the evidence the next session explains, not a settled run.
381
+ const interrupted = run.state === "interrupted";
382
+ if (run.state === "running") {
383
+ run.state = run.nodes.some((node) => node.state === "failed" || node.state === "blocked") ? "failed" : "completed";
384
+ }
385
+ run.endedAt ??= Date.now();
386
+ if (!interrupted) await removeWorkflowRecord(runtime.configPath, run.id, run.cwd).catch(() => undefined);
387
+ if (!runtime.sessionActive) return;
388
+ const item: CompletionMessageItem = {
389
+ agent: `workflow:${run.name}`,
390
+ block: formatWorkflowSummary(run, ctx.resultsRoot),
391
+ };
392
+ // No usage on the item: the summary carries its own per-model tally, and a
393
+ // group total would merge different models' spend into one number.
394
+ runtime.sendCompletionGroup([item]);
395
+ }
396
+
397
+ /** Start a compiled graph. Nodes dispatch as their prerequisites settle. */
398
+ export function startWorkflow(deps: WorkflowRunDeps, workflow: CompiledWorkflow): WorkflowHandle {
399
+ const runtime = deps.runtime;
400
+ const run: WorkflowRun = {
401
+ id: runtime.reserveWorkflowId(),
402
+ name: workflow.name,
403
+ slug: workflow.slug,
404
+ ...(workflow.description ? { description: workflow.description } : {}),
405
+ cwd: workflow.cwd,
406
+ state: "running",
407
+ startedAt: Date.now(),
408
+ controller: new AbortController(),
409
+ nodes: workflow.nodes.map((node) => ({
410
+ id: node.id,
411
+ index: node.index,
412
+ agent: node.agent,
413
+ task: node.task,
414
+ dependsOn: [...node.dependsOn],
415
+ phaseId: node.phaseId ?? defaultPhaseId(workflow, node),
416
+ ...(node.scope ? { scope: node.scope } : {}),
417
+ cwd: node.cwd,
418
+ state: "pending",
419
+ })),
420
+ };
421
+ runtime.workflows.set(run.id, run);
422
+
423
+ let wakeRequested = false;
424
+ let wakeResolver: (() => void) | undefined;
425
+ const ctx: RunContext = {
426
+ ...deps,
427
+ run,
428
+ wake: () => {
429
+ if (wakeResolver) {
430
+ const resolve = wakeResolver;
431
+ wakeResolver = undefined;
432
+ resolve();
433
+ } else {
434
+ wakeRequested = true;
435
+ }
436
+ },
437
+ waitForWake: async () => {
438
+ if (wakeRequested) {
439
+ wakeRequested = false;
440
+ return;
441
+ }
442
+ await new Promise<void>((resolve) => {
443
+ wakeResolver = resolve;
444
+ });
445
+ },
446
+ };
447
+
448
+ // Declared writer overlap inside the graph was rejected at compile time; the
449
+ // dispatcher still runs its own admission per node, so a node that conflicts
450
+ // with unrelated live work fails alone instead of poisoning the graph.
451
+ const done = drive(ctx).then(
452
+ () => run,
453
+ (error: unknown) => {
454
+ run.state = "failed";
455
+ run.endedAt = Date.now();
456
+ run.stopReason = error instanceof Error ? error.message : String(error);
457
+ deps.notify(`✗ workflow ${run.name} crashed: ${run.stopReason}`, "error");
458
+ void removeWorkflowRecord(runtime.configPath, run.id, run.cwd).catch(() => undefined);
459
+ return run;
460
+ },
461
+ );
462
+ return { run, done };
463
+ }
464
+
465
+ /** Stop a graph: no new node starts, running nodes are cancelled, and the
466
+ * summary still reports what had already completed. */
467
+ export async function stopWorkflow(
468
+ runtime: SubagentRuntime,
469
+ run: WorkflowRun,
470
+ reason = "Stopped by subagent_stop.",
471
+ ): Promise<number[]> {
472
+ if (run.state !== "running" && run.state !== "interrupted") return [];
473
+ run.state = "stopped";
474
+ run.stopReason = reason;
475
+ run.controller.abort();
476
+ const cancelled: number[] = [];
477
+ const stopping: Array<Promise<void>> = [];
478
+ for (const node of run.nodes) {
479
+ if (node.state === "pending") {
480
+ node.state = "stopped";
481
+ node.error = "stopped before it started";
482
+ continue;
483
+ }
484
+ if (node.state !== "running") continue;
485
+ if (node.runId === undefined) {
486
+ node.state = "stopped";
487
+ continue;
488
+ }
489
+ const thread = runtime.threads.get(node.runId);
490
+ stopping.push(thread ? thread.control.stop(reason).catch(() => undefined) : Promise.resolve());
491
+ runtime.backgroundQueue.cancel(thread?.queueController ?? runtime.runControllers.get(node.runId));
492
+ cancelled.push(node.runId);
493
+ }
494
+ await Promise.all(stopping);
495
+ return cancelled;
496
+ }
497
+
498
+ /** Persist the shape of every graph still running when the session ends, so the
499
+ * next session explains what was in flight instead of showing loose threads. */
500
+ export async function persistInterruptedWorkflows(runtime: SubagentRuntime): Promise<void> {
501
+ const live = [...runtime.workflows.values()].filter((run) => run.state === "running");
502
+ await Promise.all(
503
+ live.map(async (run) => {
504
+ run.state = "interrupted";
505
+ run.endedAt = Date.now();
506
+ run.stopReason ??= "the parent session ended before this workflow settled";
507
+ await upsertWorkflowRecord(runtime.configPath, workflowRecord(run, "interrupted")).catch(() => undefined);
508
+ // Wake the runner's waiters so the graph unwinds instead of holding a
509
+ // promise past shutdown; settle() keeps the record and skips delivery.
510
+ run.controller.abort();
511
+ }),
512
+ );
513
+ }
514
+
515
+ export interface RetainedWorkflow {
516
+ id: number;
517
+ name: string;
518
+ state: WorkflowRecord["state"];
519
+ stopReason?: string;
520
+ updatedAt: number;
521
+ nodes: WorkflowRecord["nodes"];
522
+ }
523
+
524
+ /** Retained records for this checkout, offered to the status view and to the
525
+ * session-start notice. Also raises the id allocator above restored graphs. */
526
+ export async function readRetainedWorkflows(runtime: SubagentRuntime, cwd: string): Promise<RetainedWorkflow[]> {
527
+ const records = await readWorkflowRecords(runtime.configPath, cwd);
528
+ for (const record of records) runtime.ensureWorkflowIdAbove(record.workflowId);
529
+ return records.map((record) => ({
530
+ id: record.workflowId,
531
+ name: record.name,
532
+ state: record.state,
533
+ ...(record.stopReason ? { stopReason: record.stopReason } : {}),
534
+ updatedAt: record.updatedAt,
535
+ nodes: record.nodes,
536
+ }));
537
+ }
538
+
539
+ /** Status-facing projection of a live or settled graph. */
540
+ export interface WorkflowStatusView {
541
+ id: number;
542
+ name: string;
543
+ state: WorkflowRunState;
544
+ description?: string;
545
+ stopReason?: string;
546
+ cwd: string;
547
+ startedAt: number;
548
+ endedAt?: number;
549
+ nodes: Array<{
550
+ id: string;
551
+ agent: string;
552
+ state: WorkflowNodeRun["state"];
553
+ runId?: number;
554
+ waitingFor?: string[];
555
+ error?: string;
556
+ activity?: string;
557
+ elapsedMs?: number;
558
+ }>;
559
+ }
560
+
561
+ export function workflowStatus(run: WorkflowRun): WorkflowStatusView {
562
+ return {
563
+ id: run.id,
564
+ name: run.name,
565
+ state: run.state,
566
+ ...(run.description ? { description: run.description } : {}),
567
+ ...(run.stopReason ? { stopReason: run.stopReason } : {}),
568
+ cwd: run.cwd,
569
+ startedAt: run.startedAt,
570
+ ...(run.endedAt !== undefined ? { endedAt: run.endedAt } : {}),
571
+ nodes: run.nodes.map((node) => {
572
+ const live = node.runId === undefined ? undefined : monitor.findRun(node.runId);
573
+ return {
574
+ id: node.id,
575
+ agent: node.agent,
576
+ state: node.state,
577
+ ...(node.runId !== undefined ? { runId: node.runId } : {}),
578
+ ...(node.state === "pending" && node.dependsOn.length > 0 ? { waitingFor: [...node.dependsOn] } : {}),
579
+ ...(node.error ? { error: node.error } : {}),
580
+ ...(live?.activity ? { activity: live.activity } : {}),
581
+ ...(node.startedAt !== undefined ? { elapsedMs: (node.endedAt ?? Date.now()) - node.startedAt } : {}),
582
+ };
583
+ }),
584
+ };
585
+ }
586
+
587
+ /** Multi-line text view used by `subagent_status`. */
588
+ export function formatWorkflowStatus(run: WorkflowRun): string[] {
589
+ const view = workflowStatus(run);
590
+ const lines = [
591
+ `workflow #${view.id} ${view.name} · ${stateLabel(view.state)} · ${completedCount(run)}/${run.nodes.length} completed · ${formatDuration((view.endedAt ?? Date.now()) - view.startedAt)}`,
592
+ ];
593
+ if (view.description) lines.push(` ${view.description}`);
594
+ if (view.stopReason) lines.push(` stop reason: ${formatTaskSummary(view.stopReason, 200, false)}`);
595
+ for (const node of view.nodes) {
596
+ const parts = [`${node.id} (${node.agent}) ${node.state}`];
597
+ if (node.runId !== undefined) parts.push(`run #${node.runId}`);
598
+ if (node.waitingFor) parts.push(`waiting for ${node.waitingFor.join(", ")}`);
599
+ if (node.elapsedMs !== undefined) parts.push(formatDuration(node.elapsedMs));
600
+ if (node.activity) parts.push(node.activity);
601
+ if (node.error) parts.push(`error: ${formatTaskSummary(node.error, 200, false)}`);
602
+ lines.push(` - ${parts.join(" · ")}`);
603
+ }
604
+ return lines;
605
+ }
606
+
607
+ /** Multi-line view of a graph retained from a previous session. */
608
+ export function formatRetainedWorkflow(record: RetainedWorkflow): string[] {
609
+ const done = record.nodes.filter((node) => node.state === "completed").length;
610
+ const age = formatDuration(Date.now() - record.updatedAt);
611
+ const lines = [
612
+ "workflow #" + record.id + " " + record.name + " · " + record.state + " (retained) · " +
613
+ done + "/" + record.nodes.length + " completed · updated " + age + " ago",
614
+ ];
615
+ if (record.stopReason) lines.push(" stop reason: " + formatTaskSummary(record.stopReason, 200, false));
616
+ for (const node of record.nodes) {
617
+ const parts = [node.id + " (" + node.agent + ") " + node.state];
618
+ if (node.runId !== undefined) parts.push("run #" + node.runId);
619
+ if (node.dependsOn.length > 0) parts.push("after " + node.dependsOn.join(", "));
620
+ if (node.error) parts.push("error: " + formatTaskSummary(node.error, 160, false));
621
+ lines.push(" - " + parts.join(" · "));
622
+ }
623
+ lines.push(" A retained graph is not resumed automatically: main finishes the unfinished nodes from their run evidence.");
624
+ return lines;
625
+ }