@ferris1225/pi-subagents 5.0.6 → 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.
Files changed (43) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/README.md +187 -97
  3. package/index.ts +1 -1
  4. package/package.json +4 -9
  5. package/src/configuration/role-migration.ts +2 -2
  6. package/src/configuration/setup.ts +4 -2
  7. package/src/configuration/ui.ts +144 -132
  8. package/src/delegation/agents.ts +15 -22
  9. package/src/delegation/dispatch.ts +17 -122
  10. package/src/delegation/prompt.ts +13 -12
  11. package/src/execution/cli-run.ts +112 -39
  12. package/src/execution/process-tree.ts +12 -8
  13. package/src/execution/run-control.ts +11 -3
  14. package/src/execution/spawn.ts +24 -7
  15. package/src/isolation/cleanup.ts +31 -12
  16. package/src/isolation/managed-paths.ts +6 -4
  17. package/src/isolation/manifest-mutation.ts +89 -0
  18. package/src/isolation/recovery.ts +33 -29
  19. package/src/isolation/temp-hygiene.ts +1 -1
  20. package/src/lifecycle/await-results.ts +114 -0
  21. package/src/lifecycle/dispatch-core.ts +7 -1
  22. package/src/lifecycle/durable.ts +83 -39
  23. package/src/lifecycle/runtime.ts +12 -4
  24. package/src/lifecycle/stop.ts +2 -2
  25. package/src/lifecycle/thread-lifecycle.ts +10 -5
  26. package/src/lifecycle/thread-restore.ts +26 -25
  27. package/src/lifecycle/thread-shared.ts +15 -3
  28. package/src/lifecycle/tools.ts +90 -33
  29. package/src/presentation/announcements.ts +8 -2
  30. package/src/presentation/monitor.ts +5 -3
  31. package/src/presentation/widget.ts +157 -113
  32. package/src/workflow/acceptance.ts +67 -0
  33. package/src/workflow/durable.ts +34 -14
  34. package/src/workflow/engine.ts +161 -51
  35. package/src/workflow/plan.ts +25 -4
  36. package/src/workflow/state.ts +6 -0
  37. package/src/workflow/templates.ts +156 -0
  38. package/src/workflow/tool.ts +65 -109
  39. package/skills/workflow/SKILL.md +0 -268
  40. package/src/workflow/files.ts +0 -236
  41. package/workflows/code-review.md +0 -38
  42. package/workflows/migration.md +0 -42
  43. package/workflows/research.md +0 -48
@@ -20,9 +20,10 @@ import {
20
20
  type PhaseScopeInput,
21
21
  } from "../delegation/phase-scope.ts";
22
22
  import type { IsolationMode } from "../isolation/worktree.ts";
23
+ import { acceptanceTask, WORKFLOW_ACCEPTANCE_AGENT, WORKFLOW_ACCEPTANCE_ID } from "./acceptance.ts";
23
24
 
24
- /** Nodes per graph. A workflow pays for one model session per node, so this is
25
- * a guard against a graph nobody will read, not a concurrency limit. */
25
+ /** Authored nodes per graph, plus one mandatory internal acceptance session.
26
+ * This bounds graph size rather than concurrency. */
26
27
  export const WORKFLOW_NODE_LIMIT = 24;
27
28
 
28
29
  export const WORKFLOW_NODE_ID_MAX_LENGTH = 40;
@@ -56,6 +57,8 @@ export interface WorkflowPlanInput {
56
57
 
57
58
  export interface CompiledWorkflowNode {
58
59
  id: string;
60
+ /** Compiler-owned required review; authored work omits kind. */
61
+ kind?: "acceptance";
59
62
  agent: string;
60
63
  task: string;
61
64
  /** Direct prerequisites, in author order. */
@@ -82,7 +85,7 @@ export interface CompiledWorkflow {
82
85
  }
83
86
 
84
87
  /** Placeholder syntax accepted in a node's task. */
85
- const PLACEHOLDER = /\{\{\s*([^{}]+?)\s*\}\}/gu;
88
+ const PLACEHOLDER = /(?<!\\)\{\{\s*([^{}]+?)\s*\}\}/gu;
86
89
  const FACT_SUFFIXES = [".status", ".runId", ".error"] as const;
87
90
  type PlaceholderFact = "output" | "status" | "runId" | "error";
88
91
 
@@ -207,6 +210,7 @@ export function compileWorkflow(
207
210
  throw new Error(error instanceof Error ? error.message : String(error));
208
211
  }
209
212
 
213
+ if (!knownAgents.includes(WORKFLOW_ACCEPTANCE_AGENT)) problems.push(`Required acceptance agent "${WORKFLOW_ACCEPTANCE_AGENT}" is not an enabled agent.`);
210
214
  const ids: string[] = [];
211
215
  const seenIds = new Set<string>();
212
216
  for (const [index, node] of rawNodes.entries()) {
@@ -218,6 +222,7 @@ export function compileWorkflow(
218
222
  );
219
223
  continue;
220
224
  }
225
+ if (id === WORKFLOW_ACCEPTANCE_ID) problems.push(`${label}.id "${id}" is reserved for required workflow acceptance.`);
221
226
  if (seenIds.has(id)) {
222
227
  problems.push(`${label}.id "${id}" is declared twice; node ids identify results and dependencies.`);
223
228
  continue;
@@ -303,6 +308,19 @@ export function compileWorkflow(
303
308
  });
304
309
  }
305
310
 
311
+ // Append before ownership checks so authored phase ids cannot collide with
312
+ // the mandatory reviewer. The authored node limit remains unchanged.
313
+ nodes.push({
314
+ id: WORKFLOW_ACCEPTANCE_ID,
315
+ kind: "acceptance",
316
+ agent: WORKFLOW_ACCEPTANCE_AGENT,
317
+ task: acceptanceTask(name),
318
+ dependsOn: [...ids],
319
+ ancestors: [...ids],
320
+ cwd: resolve(callerCwd),
321
+ isolation: "shared",
322
+ });
323
+
306
324
  for (const [index, node] of nodes.entries()) {
307
325
  const phaseId = node.phaseId ?? defaultPhaseId({ slug: slugify(name) }, node);
308
326
  const duplicate = nodes.slice(0, index).find((other) => {
@@ -362,7 +380,10 @@ function boundOutput(view: UpstreamOutput): string {
362
380
 
363
381
  /** Render a node's brief, substituting facts from the nodes it waited for. */
364
382
  export function renderNodeTask(task: string, upstream: ReadonlyMap<string, UpstreamOutput>): string {
365
- const rendered = task.replace(PLACEHOLDER, (whole, rawToken: string) => {
383
+ const rendered = task.replace(/\\\{\{|\{\{\s*([^{}]+?)\s*\}\}/gu, (whole, rawToken: string | undefined) => {
384
+ // Literal task inputs are unescaped in this pass, never interpreted as
385
+ // dependencies or reprocessed after an upstream answer is inserted.
386
+ if (rawToken === undefined) return "{{";
366
387
  const { id, fact } = splitPlaceholder(rawToken.trim(), (id) => upstream.has(id));
367
388
  const view = upstream.get(id);
368
389
  if (!view) return whole;
@@ -12,6 +12,9 @@ export type WorkflowNodeState = RecordedNodeState;
12
12
 
13
13
  export interface WorkflowNodeRun {
14
14
  id: string;
15
+ kind?: "acceptance";
16
+ /** Complete pre-review graph evidence retained for independent acceptance. */
17
+ evidenceFile?: string;
15
18
  agent: string;
16
19
  /** Authored brief, still carrying its result placeholders. */
17
20
  task: string;
@@ -23,6 +26,7 @@ export interface WorkflowNodeRun {
23
26
  cwd: string;
24
27
  state: WorkflowNodeState;
25
28
  runId?: number;
29
+ durableRunId?: string;
26
30
  startedAt?: number;
27
31
  endedAt?: number;
28
32
  result?: SingleResult;
@@ -32,6 +36,8 @@ export interface WorkflowNodeRun {
32
36
  export type WorkflowRunState = "running" | "completed" | "failed" | "stopped" | "interrupted";
33
37
 
34
38
  export interface WorkflowRun {
39
+ /** Stable persisted identity; id is local to this Pi window. */
40
+ durableId?: string;
35
41
  id: number;
36
42
  name: string;
37
43
  slug: string;
@@ -0,0 +1,156 @@
1
+ /** Built-in workflow plans and their explicit input slots. Runtime policy lives
2
+ * in the compiler/runner; templates contain only task-specific briefs. */
3
+
4
+ import { createHash } from "node:crypto";
5
+ import { compileWorkflow, type CompiledWorkflow, type WorkflowPlanInput } from "./plan.ts";
6
+
7
+ export const WORKFLOW_INPUT_KEYS = [
8
+ "QUESTION", "TARGET", "CONTRACT", "CORE_CHANGE", "ADAPTER_CHANGE",
9
+ "CORE_SCOPE", "CORE_TEST_SCOPE", "ADAPTER_SCOPE", "ADAPTER_TEST_SCOPE",
10
+ ] as const;
11
+
12
+ const INPUT_PATTERN = new RegExp(`<(${WORKFLOW_INPUT_KEYS.join("|")})>`, "gu");
13
+
14
+ /** Each lookup returns a fresh plan so customizing one dispatch cannot mutate
15
+ * the catalog used by the next dispatch. */
16
+ export function builtinWorkflowPlans(): WorkflowPlanInput[] {
17
+ return [
18
+ {
19
+ name: "code-review",
20
+ description: "Inspect a target change; the required acceptance review checks the findings and evidence.",
21
+ nodes: [{
22
+ id: "review",
23
+ agent: "sentinel",
24
+ task: "Review <TARGET> against the stated requirements and relevant callers. Establish the diff once, then inspect correctness, regressions, compatibility, and concrete failure paths within that target. Reuse existing research and valid checks; run a focused reproduction only to resolve a suspected defect. Stay read-only and do not change Git state. Return confirmed actionable findings with path:line, trigger, consequence, evidence, and smallest fix; include checks and material gaps. State clearly if no confirmed findings were found. The final acceptance officer will verify the report and its evidence; do not add another general review.",
25
+ }],
26
+ },
27
+ {
28
+ name: "research",
29
+ description: "Research a question from independent angles, synthesize an answer, and submit its evidence for acceptance.",
30
+ nodes: [
31
+ {
32
+ id: "primary",
33
+ agent: "scout",
34
+ task: "Research <QUESTION> from first-party sources only: official documentation, specifications, release notes, and the project's own repository. Record versions and dates. Cite every fact you state. Mark anything you could only find second-hand.",
35
+ },
36
+ {
37
+ id: "practice",
38
+ agent: "scout",
39
+ task: "Research <QUESTION> from practice: issue threads, migration notes, benchmarks, and post-mortems that describe what actually happened when people used it. Separate reported experience from vendor claims and cite each source.",
40
+ },
41
+ {
42
+ id: "codebase",
43
+ agent: "scout",
44
+ task: "Establish what this repository already does about <QUESTION>: the relevant modules, configuration, and tests, with path:line citations. State where the code disagrees with the documentation if you find such a place.",
45
+ },
46
+ {
47
+ id: "synthesis",
48
+ agent: "scout",
49
+ dependsOn: ["primary", "practice", "codebase"],
50
+ task: "Answer <QUESTION> from these three research passes. Reconcile disagreements explicitly; check dates, versions, and conditions when official claims conflict with observed practice. Prefer evidence applicable to this question.\n\nFirst-party:\n{{primary}}\n\nPractice:\n{{practice}}\n\nThis repository:\n{{codebase}}\n\nReturn the answer, decisive citations, open questions, and what would change the answer. The final acceptance officer checks the answer and its evidence.",
51
+ },
52
+ ],
53
+ },
54
+ {
55
+ name: "migration",
56
+ description: "Apply two planned migration slices, run their integrated gate, and submit the result for acceptance.",
57
+ nodes: [
58
+ {
59
+ id: "apply-core",
60
+ agent: "artisan",
61
+ task: "Migrate the core slice to <TARGET>. <CORE_CHANGE>. Interface contract: <CONTRACT>. Follow the declared write scope. Implement the change and its regression tests together; run the relevant checks. Report changed paths, command results, and blockers. If the plan conflicts with the code or requires another slice's files, stop and report evidence instead of inventing a new scope.",
62
+ scope: { paths: ["<CORE_SCOPE>", "<CORE_TEST_SCOPE>"] },
63
+ },
64
+ {
65
+ id: "apply-adapters",
66
+ agent: "artisan",
67
+ task: "Migrate the adapter slice to <TARGET>. <ADAPTER_CHANGE>. Interface contract: <CONTRACT>. Follow the declared write scope. Implement the change and its regression tests together; run the relevant checks. Report changed paths, command results, and blockers. If the plan conflicts with the code or requires another slice's files, stop and report evidence instead of inventing a new scope.",
68
+ scope: { paths: ["<ADAPTER_SCOPE>", "<ADAPTER_TEST_SCOPE>"] },
69
+ },
70
+ {
71
+ id: "gate",
72
+ agent: "artisan",
73
+ dependsOn: ["apply-core", "apply-adapters"],
74
+ task: "Run the project's documented required checks on the integrated migration to <TARGET>. Interface contract: <CONTRACT>. Verify both slices meet their done conditions; report missing prerequisites instead of guessing. Reuse valid checks on unchanged code and inspect cross-slice callers for mismatches. Fix failures caused by the migration within its declared scope. Report commands, results, and unverified risks. The final acceptance officer independently checks the result.\n\nCore:\n{{apply-core}}\n\nAdapters:\n{{apply-adapters}}",
75
+ scope: { paths: ["<CORE_SCOPE>", "<CORE_TEST_SCOPE>", "<ADAPTER_SCOPE>", "<ADAPTER_TEST_SCOPE>"] },
76
+ },
77
+ ],
78
+ },
79
+ ];
80
+ }
81
+
82
+ /** Resolve only a shipped plan. There is no filesystem discovery and callers
83
+ * cannot replace the graph, its roles, or the acceptance policy. */
84
+ export function resolveBuiltinWorkflow(
85
+ name: string,
86
+ inputs: Record<string, string> = {},
87
+ ): WorkflowPlanInput {
88
+ const plans = builtinWorkflowPlans();
89
+ const plan = typeof name === "string" ? plans.find((entry) => entry.name === name.trim().toLowerCase()) : undefined;
90
+ if (!plan) {
91
+ throw new Error(`Unknown built-in workflow "${String(name ?? "")}". Choose ${plans.map((entry) => entry.name).join(", ")}. No nodes were started.`);
92
+ }
93
+ return fillWorkflowTemplate(plan, inputs);
94
+ }
95
+
96
+ /** Different built-in inputs own different phases; the same deliverable keeps
97
+ * its identity across repeated calls. Display names remain short and stable. */
98
+ export function compileBuiltinWorkflow(
99
+ name: string,
100
+ inputs: Record<string, string> | undefined,
101
+ cwd: string,
102
+ knownAgents: readonly string[],
103
+ ): CompiledWorkflow {
104
+ const plan = resolveBuiltinWorkflow(name, inputs);
105
+ const identity = createHash("sha256").update(JSON.stringify(plan)).digest("hex").slice(0, 12);
106
+ const workflow = compileWorkflow(plan, cwd, knownAgents);
107
+ workflow.slug = `${workflow.slug}-${identity}`;
108
+ for (const node of workflow.nodes) {
109
+ // Pending phases also match exact task text. Acceptance must distinguish
110
+ // two questions even before their evidence briefs have been built.
111
+ if (node.kind === "acceptance") node.task += `\n\nDeliverable identity: ${workflow.slug}`;
112
+ }
113
+ return workflow;
114
+ }
115
+
116
+ /** Fill only explicit template slots, in one pass. Ordinary code such as <T>
117
+ * and graph result placeholders {{id}} keep their original meaning. Unknown or
118
+ * unused inputs are errors so a misspelled scope cannot silently change a plan. */
119
+ function fillWorkflowTemplate(
120
+ plan: WorkflowPlanInput,
121
+ inputs: Record<string, string> = {},
122
+ ): WorkflowPlanInput {
123
+ if (!inputs || typeof inputs !== "object" || Array.isArray(inputs)) {
124
+ throw new Error("Workflow inputs must be an object of named strings. No nodes were started.");
125
+ }
126
+ for (const [key, value] of Object.entries(inputs)) {
127
+ if (!(WORKFLOW_INPUT_KEYS as readonly string[]).includes(key)) {
128
+ throw new Error(`Unknown workflow input "${key}". Available inputs: ${WORKFLOW_INPUT_KEYS.join(", ")}. No nodes were started.`);
129
+ }
130
+ if (typeof value !== "string" || !value.trim()) {
131
+ throw new Error(`Workflow input "${key}" must be a non-blank string. No nodes were started.`);
132
+ }
133
+ }
134
+ const used = new Set<string>();
135
+ const missing = new Set<string>();
136
+ const fill = (value: string, literalTask = false): string => value.replace(INPUT_PATTERN, (slot, key: string) => {
137
+ used.add(key);
138
+ if (!Object.hasOwn(inputs, key)) { missing.add(key); return slot; }
139
+ return literalTask ? inputs[key]!.replace(/\{\{/gu, "\\{{") : inputs[key]!;
140
+ });
141
+ const next: WorkflowPlanInput = {
142
+ ...plan,
143
+ nodes: plan.nodes.map((node) => ({
144
+ ...node,
145
+ task: fill(node.task, true),
146
+ ...(node.scope ? { scope: {
147
+ ...node.scope,
148
+ paths: node.scope.paths?.map((path) => fill(path)),
149
+ } } : {}),
150
+ })),
151
+ };
152
+ if (missing.size) throw new Error(`Workflow "${plan.name}" requires inputs: ${[...missing].join(", ")}. No nodes were started.`);
153
+ const unused = Object.keys(inputs).filter((key) => !used.has(key));
154
+ if (unused.length) throw new Error(`Unused workflow inputs: ${unused.join(", ")}. No nodes were started.`);
155
+ return next;
156
+ }
@@ -1,77 +1,48 @@
1
1
  /**
2
- * The subagent_workflow tool: declare a dependency graph of sub-agent phases
3
- * once and let the runtime dispatch dependents as prerequisites settle.
2
+ * The subagent_workflow tool runs a built-in plan with named task inputs.
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
+ import { StringEnum } from "@earendil-works/pi-ai";
10
11
  import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
11
12
  import { Text } from "@earendil-works/pi-tui";
12
13
  import { Type } from "typebox";
13
14
  import { isWriteCapableAgent, loadBuiltinAgents } from "../delegation/agents.ts";
14
- import { defaultIsolationMode, IsolationSchema, PhaseIdSchema, ScopeSchema } from "../delegation/dispatch.ts";
15
+ import { defaultIsolationMode } from "../delegation/dispatch.ts";
15
16
  import { findRuntimeWriterConflict } from "../delegation/ownership.ts";
16
17
  import { loadConfig } from "../configuration/config.ts";
17
18
  import type { SubagentRuntime } from "../lifecycle/runtime.ts";
18
19
  import type { DispatchCore } from "../lifecycle/dispatch-core.ts";
20
+ import { cancelActiveWork } from "../lifecycle/cancellation.ts";
19
21
  import { projectResultsRoot } from "../lifecycle/thread-shared.ts";
20
22
  import { formatTaskSummary, monitor } from "../presentation/monitor.ts";
21
23
  import { pruneWorkflowRecords } from "./durable.ts";
22
24
  import {
23
25
  findOwnedPhases,
26
+ formatWorkflowSummary,
27
+ formatWorkflowStatus,
24
28
  persistInterruptedWorkflows,
25
29
  readRetainedWorkflows,
26
30
  startWorkflow,
27
31
  workflowStatus,
28
32
  type WorkflowStatusView,
29
33
  } from "./engine.ts";
30
- import { migrateWorkflowDefinition, resolveWorkflowDefinition } from "./files.ts";
31
- import { compileWorkflow, WORKFLOW_NODE_ID_MAX_LENGTH, type WorkflowPlanInput } from "./plan.ts";
34
+ import { compileBuiltinWorkflow } from "./templates.ts";
32
35
 
33
- const WorkflowNodeSchema = Type.Object({
34
- id: Type.String({
35
- minLength: 1,
36
- maxLength: WORKFLOW_NODE_ID_MAX_LENGTH,
37
- pattern: "^[A-Za-z][A-Za-z0-9._-]*$",
38
- description: "Stable node id. Dependents name it in dependsOn and in result placeholders.",
36
+ const WorkflowParams = Type.Object({
37
+ workflow: StringEnum(["code-review", "research", "migration"] as const, {
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.",
39
39
  }),
40
- agent: Type.String({ minLength: 1, description: "Name of an enabled agent." }),
41
- task: Type.String({
42
- minLength: 1,
43
- pattern: "\\S",
44
- description:
45
- "Self-contained brief. {{<dependency-id>}} interpolates an upstream node's answer; {{<id>.status}}, {{<id>.runId}} and {{<id>.error}} interpolate facts. Only declared dependencies may be referenced.",
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
+ })),
43
+ inputs: Type.Record(Type.String(), Type.String({ minLength: 1, pattern: "\\S" }), {
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.",
46
45
  }),
47
- dependsOn: Type.Optional(
48
- Type.Array(Type.String({ minLength: 1 }), {
49
- description: "Node ids that must complete before this one starts. Omit for a node that starts immediately.",
50
- }),
51
- ),
52
- phaseId: PhaseIdSchema,
53
- scope: ScopeSchema,
54
- cwd: Type.Optional(Type.String({ description: "Working directory for this node; defaults to the caller cwd." })),
55
- isolation: IsolationSchema,
56
- });
57
-
58
- const WorkflowParams = Type.Object({
59
- name: Type.Optional(
60
- Type.String({
61
- maxLength: 60,
62
- description: "Workflow name: shown in the widget and status, and the namespace for derived phase ids.",
63
- }),
64
- ),
65
- description: Type.Optional(Type.String({ description: "One line stating what the graph delivers." })),
66
- nodes: Type.Optional(
67
- Type.Array(WorkflowNodeSchema, { description: "Inline graph. Mutually exclusive with workflow/file." }),
68
- ),
69
- workflow: Type.Optional(
70
- Type.String({ description: "Name of a saved workflow under .pi/workflows/ or ~/.pi/agent/workflows/." }),
71
- ),
72
- file: Type.Optional(
73
- Type.String({ description: "Workflow definition file (JSON, or Markdown with a json fenced block)." }),
74
- ),
75
46
  });
76
47
 
77
48
  export interface WorkflowToolDetails {
@@ -88,14 +59,14 @@ function launchReceipt(status: WorkflowStatusView): string {
88
59
  "",
89
60
  "Nodes:",
90
61
  ...status.nodes.map((node) => {
91
- const parts = ["- " + node.id + " (" + node.agent + ")"];
62
+ const parts = ["- " + node.id + " (" + node.agent + ")" + (node.kind === "acceptance" ? " · required independent acceptance" : "")];
92
63
  if (node.runId !== undefined) parts.push("run #" + node.runId);
93
64
  else if (node.waitingFor) parts.push("waits for " + node.waitingFor.join(", "));
94
65
  else parts.push(node.state);
95
66
  return parts.join(" · ");
96
67
  }),
97
68
  "",
98
- "Every node is owned by this graph, including nodes waiting on dependencies. Do not perform or redispatch their work in main or another agent. The graph dispatches dependents automatically and 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.",
99
70
  ];
100
71
  return lines.join("\n");
101
72
  }
@@ -135,7 +106,7 @@ export function registerWorkflowTool(pi: ExtensionAPI, runtime: SubagentRuntime,
135
106
  name: "subagent_workflow",
136
107
  label: "Subagent Workflow",
137
108
  description:
138
- "Run a fixed dependency graph for substantial phases with known scopes. dependsOn starts a node after prerequisites finish and integrate. Pending nodes already own their work; main must not execute or redispatch it. Duplicate phases and external writer conflicts reject the graph before any child starts. Independent work without dependency edges uses subagent tasks. If a result must decide the next phase, dispatch it alone and decide in main. Omit isolation for automatic selection. One summary arrives after settlement; main checks outcomes, integrates, and releases.",
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.",
139
110
  exposure: "model-only",
140
111
  executionMode: "parallel",
141
112
  annotations: {
@@ -146,7 +117,7 @@ export function registerWorkflowTool(pi: ExtensionAPI, runtime: SubagentRuntime,
146
117
  },
147
118
  parameters: WorkflowParams,
148
119
 
149
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
120
+ async execute(_toolCallId, params, signal, onUpdate, ctx) {
150
121
  await runtime.durableRestore;
151
122
  monitor.beginTurn();
152
123
  const config = await loadConfig(runtime.configPath);
@@ -156,58 +127,15 @@ export function registerWorkflowTool(pi: ExtensionAPI, runtime: SubagentRuntime,
156
127
  const toolInfos = runtime.getToolInfos();
157
128
  core.setEnvironment({ ctx, config, agents });
158
129
 
159
- const hasInline = params.nodes !== undefined;
160
- const hasReference = Boolean(params.workflow?.trim() || params.file?.trim());
161
- if (Number(hasInline) + Number(Boolean(params.workflow?.trim())) + Number(Boolean(params.file?.trim())) !== 1) {
162
- throw new Error(
163
- "Provide exactly one graph source: inline nodes, or a saved workflow/file. No nodes were started.",
164
- );
165
- }
166
-
167
- let plan: WorkflowPlanInput = {
168
- ...(params.name ? { name: params.name } : {}),
169
- ...(params.description ? { description: params.description } : {}),
170
- nodes: params.nodes ?? [],
171
- };
172
- let fallbackName = params.name ?? "workflow";
173
- if (hasReference) {
174
- const resolved = resolveWorkflowDefinition(
175
- ctx.cwd,
176
- { ...(params.workflow ? { name: params.workflow } : {}), ...(params.file ? { path: params.file } : {}) },
177
- { projectTrusted: ctx.isProjectTrusted?.() === true },
178
- );
179
- if (resolved.error || !resolved.definition) {
180
- throw new Error((resolved.error ?? "workflow definition could not be read") + ". No nodes were started.");
181
- }
182
- const definition = await migrateWorkflowDefinition(resolved.definition);
183
- plan = {
184
- name: params.name ?? definition.plan.name ?? definition.name,
185
- ...(params.description ?? definition.description
186
- ? { description: params.description ?? definition.description }
187
- : {}),
188
- nodes: definition.plan.nodes,
189
- };
190
- fallbackName = definition.name;
191
- }
192
-
193
- let workflow;
194
- try {
195
- workflow = compileWorkflow(plan, ctx.cwd, agents.map((agent) => agent.name), { fallbackName });
196
- } catch (error) {
197
- throw new Error(
198
- "Workflow rejected before any node started:\n" + (error instanceof Error ? error.message : String(error)),
199
- );
200
- }
201
-
202
- if (_signal?.aborted) throw new Error("Workflow cancelled before any node started.");
203
- if (hasReference) {
204
- const unfilled = [...new Set(workflow.nodes.flatMap((node) => node.task.match(/<(?:QUESTION|TARGET|CORE_CHANGE|ADAPTER_CHANGE)>/gu) ?? []))];
205
- if (unfilled.length) throw new Error(`Customize ${unfilled.join(", ")} in the saved template before running it. No nodes were started.`);
206
- }
207
- for (const node of workflow.nodes) {
208
- const agent = agents.find((candidate) => candidate.name === node.agent)!;
209
- if (node.isolation === "worktree" && !isWriteCapableAgent(agent, toolInfos)) throw new Error(`Node "${node.id}" is read-only and cannot use worktree isolation. No nodes were started.`);
210
- }
130
+ // Ignore empty legacy placeholders, which previously triggered ambiguous
131
+ // source errors. A supplied custom definition is always rejected.
132
+ const unsupported = Object.entries(params as Record<string, unknown>).filter(([key, value]) =>
133
+ key !== "workflow" && key !== "inputs" && key !== "wait" && value !== undefined && value !== null && value !== ""
134
+ && !(Array.isArray(value) && value.length === 0),
135
+ ).map(([key]) => key);
136
+ if (unsupported.length) throw new Error(`Custom workflow fields are unsupported: ${unsupported.join(", ")}. Use only workflow, inputs, and wait. No nodes were started.`);
137
+ const workflow = compileBuiltinWorkflow(params.workflow, params.inputs, ctx.cwd, agents.map((agent) => agent.name));
138
+ if (signal?.aborted) throw new Error("Workflow cancelled before any node started.");
211
139
 
212
140
  // Re-using a phase another owner holds fails the first node and blocks the
213
141
  // rest; reject the whole graph instead, with the owners named.
@@ -221,7 +149,7 @@ export function registerWorkflowTool(pi: ExtensionAPI, runtime: SubagentRuntime,
221
149
  "Workflow \"" + workflow.name + "\" was not started: " + owned.length + " of " + workflow.nodes.length +
222
150
  " node" + (owned.length === 1 ? " reuses" : "s reuse") + " a phase this session already owns.\n" +
223
151
  lines.join("\n") +
224
- "\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. A genuinely different deliverable needs a distinct brief and phaseId. 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.",
225
153
  );
226
154
  }
227
155
 
@@ -232,6 +160,8 @@ export function registerWorkflowTool(pi: ExtensionAPI, runtime: SubagentRuntime,
232
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.`);
233
161
  }
234
162
 
163
+ const wait = params.wait ?? (ctx.hasUI === false);
164
+ const resultsRoot = projectResultsRoot(runtime.configPath, ctx.cwd);
235
165
  const handle = startWorkflow(
236
166
  {
237
167
  runtime,
@@ -244,11 +174,40 @@ export function registerWorkflowTool(pi: ExtensionAPI, runtime: SubagentRuntime,
244
174
  agent ? isWriteCapableAgent(agent, toolInfos) : undefined,
245
175
  );
246
176
  },
247
- resultsRoot: projectResultsRoot(runtime.configPath, ctx.cwd),
177
+ deliveryRoute: wait ? "await" : "background",
178
+ resultsRoot,
248
179
  notify: (message, kind) => ctx.ui.notify(message, kind),
249
180
  },
250
181
  workflow,
251
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
+ }
252
211
  const status = workflowStatus(handle.run);
253
212
  return {
254
213
  content: [{ type: "text", text: launchReceipt(status) }],
@@ -257,11 +216,8 @@ export function registerWorkflowTool(pi: ExtensionAPI, runtime: SubagentRuntime,
257
216
  },
258
217
 
259
218
  renderCall(args, theme) {
260
- const count = args.nodes?.length ?? 0;
261
- const label = args.name ?? args.workflow ?? args.file ?? "inline";
262
- const graph = count > 0 ? " " + count + " nodes" : "";
263
219
  return new Text(
264
- theme.fg("toolTitle", theme.bold("subagent_workflow ")) + theme.fg("accent", label) + theme.fg("dim", graph),
220
+ theme.fg("toolTitle", theme.bold("subagent_workflow ")) + theme.fg("accent", args.workflow ?? "?"),
265
221
  0,
266
222
  0,
267
223
  );