@ferris1225/pi-subagents 6.0.0 → 6.0.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.
@@ -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 is woken exactly once, with the graph's summary.
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 its summary is delivered. */
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 done = drive(ctx).then(
591
- () => run,
592
- (error: unknown) => {
593
- run.state = "failed";
594
- run.endedAt = Date.now();
595
- run.stopReason = error instanceof Error ? error.message : String(error);
596
- deps.notify(`✗ workflow ${run.name} crashed: ${run.stopReason}`, "error");
597
- void removeWorkflowRecord(runtime.configPath, durableId, run.cwd).catch(() => undefined);
598
- return run;
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
  }
@@ -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. A valid plan returns a launch receipt
7
- * immediately; one completion message summarises the whole graph.
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 only disjoint work or end your turn, and do not poll.",
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 final summary arrives automatically. Use subagent for a single phase or independent tasks.",
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, _signal, _onUpdate, ctx) {
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 inputs. No nodes were started.`);
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 (_signal?.aborted) throw new Error("Workflow cancelled before any node started.");
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> }) only when discarding its retained session is intended. Different deliverables need different task inputs. No nodes were started.",
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
- resultsRoot: projectResultsRoot(runtime.configPath, ctx.cwd),
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) }],