pi-cohort 2.0.0

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 (92) hide show
  1. package/CHANGELOG.md +1151 -0
  2. package/LICENSE +22 -0
  3. package/README.md +1220 -0
  4. package/agents/context-builder.md +45 -0
  5. package/agents/delegate.md +12 -0
  6. package/agents/oracle.md +73 -0
  7. package/agents/planner.md +55 -0
  8. package/agents/reviewer.md +91 -0
  9. package/agents/scout.md +50 -0
  10. package/agents/worker.md +67 -0
  11. package/package.json +87 -0
  12. package/prompts/gather-context-and-clarify.md +13 -0
  13. package/prompts/parallel-cleanup.md +59 -0
  14. package/prompts/parallel-context-build.md +55 -0
  15. package/prompts/parallel-handoff-plan.md +61 -0
  16. package/prompts/parallel-review.md +54 -0
  17. package/prompts/review-loop.md +41 -0
  18. package/skills/pi-cohort/SKILL.md +818 -0
  19. package/src/agents/agent-management.ts +685 -0
  20. package/src/agents/agent-scope.ts +6 -0
  21. package/src/agents/agent-selection.ts +23 -0
  22. package/src/agents/agent-serializer.ts +83 -0
  23. package/src/agents/agents.ts +1141 -0
  24. package/src/agents/chain-serializer.ts +251 -0
  25. package/src/agents/frontmatter.ts +29 -0
  26. package/src/agents/identity.ts +30 -0
  27. package/src/agents/skills.ts +632 -0
  28. package/src/extension/config.ts +16 -0
  29. package/src/extension/control-notices.ts +92 -0
  30. package/src/extension/doctor.ts +236 -0
  31. package/src/extension/fanout-child.ts +170 -0
  32. package/src/extension/grand-total.ts +109 -0
  33. package/src/extension/index.ts +630 -0
  34. package/src/extension/schemas.ts +306 -0
  35. package/src/intercom/intercom-bridge.ts +379 -0
  36. package/src/intercom/result-intercom.ts +377 -0
  37. package/src/runs/background/async-execution.ts +796 -0
  38. package/src/runs/background/async-job-tracker.ts +320 -0
  39. package/src/runs/background/async-resume.ts +345 -0
  40. package/src/runs/background/async-status.ts +335 -0
  41. package/src/runs/background/completion-dedupe.ts +63 -0
  42. package/src/runs/background/notify.ts +108 -0
  43. package/src/runs/background/parallel-groups.ts +45 -0
  44. package/src/runs/background/result-watcher.ts +307 -0
  45. package/src/runs/background/run-id-resolver.ts +83 -0
  46. package/src/runs/background/run-status.ts +272 -0
  47. package/src/runs/background/stale-run-reconciler.ts +336 -0
  48. package/src/runs/background/subagent-runner.ts +2326 -0
  49. package/src/runs/background/top-level-async.ts +13 -0
  50. package/src/runs/foreground/chain-clarify.ts +1333 -0
  51. package/src/runs/foreground/chain-execution.ts +1187 -0
  52. package/src/runs/foreground/execution.ts +1028 -0
  53. package/src/runs/foreground/subagent-executor.ts +2580 -0
  54. package/src/runs/shared/acceptance.ts +605 -0
  55. package/src/runs/shared/chain-outputs.ts +101 -0
  56. package/src/runs/shared/completion-guard.ts +143 -0
  57. package/src/runs/shared/dynamic-fanout.ts +293 -0
  58. package/src/runs/shared/long-running-guard.ts +175 -0
  59. package/src/runs/shared/model-fallback.ts +103 -0
  60. package/src/runs/shared/nested-events.ts +822 -0
  61. package/src/runs/shared/nested-path.ts +52 -0
  62. package/src/runs/shared/nested-render.ts +115 -0
  63. package/src/runs/shared/parallel-utils.ts +136 -0
  64. package/src/runs/shared/pi-args.ts +221 -0
  65. package/src/runs/shared/pi-spawn.ts +115 -0
  66. package/src/runs/shared/run-history.ts +60 -0
  67. package/src/runs/shared/single-output.ts +164 -0
  68. package/src/runs/shared/structured-output.ts +77 -0
  69. package/src/runs/shared/subagent-control.ts +287 -0
  70. package/src/runs/shared/subagent-prompt-runtime.ts +220 -0
  71. package/src/runs/shared/workflow-graph.ts +206 -0
  72. package/src/runs/shared/worktree.ts +577 -0
  73. package/src/shared/artifacts.ts +98 -0
  74. package/src/shared/atomic-json.ts +16 -0
  75. package/src/shared/file-coalescer.ts +40 -0
  76. package/src/shared/fork-context.ts +76 -0
  77. package/src/shared/formatters.ts +133 -0
  78. package/src/shared/jsonl-writer.ts +81 -0
  79. package/src/shared/model-info.ts +78 -0
  80. package/src/shared/post-exit-stdio-guard.ts +85 -0
  81. package/src/shared/session-identity.ts +10 -0
  82. package/src/shared/session-tokens.ts +46 -0
  83. package/src/shared/settings.ts +447 -0
  84. package/src/shared/status-format.ts +59 -0
  85. package/src/shared/types.ts +1072 -0
  86. package/src/shared/utils.ts +451 -0
  87. package/src/slash/prompt-template-bridge.ts +397 -0
  88. package/src/slash/slash-bridge.ts +174 -0
  89. package/src/slash/slash-commands.ts +567 -0
  90. package/src/slash/slash-live-state.ts +292 -0
  91. package/src/tui/render-helpers.ts +80 -0
  92. package/src/tui/render.ts +1476 -0
@@ -0,0 +1,220 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
+ import { SUBAGENT_FANOUT_CHILD_ENV } from "./pi-args.ts";
5
+ import { STRUCTURED_OUTPUT_CAPTURE_ENV, STRUCTURED_OUTPUT_SCHEMA_ENV, validateStructuredOutputValue } from "./structured-output.ts";
6
+ import type { JsonSchemaObject } from "../../shared/types.ts";
7
+
8
+ const SUBAGENT_INHERIT_PROJECT_CONTEXT_ENV = "PI_SUBAGENT_INHERIT_PROJECT_CONTEXT";
9
+ const SUBAGENT_INHERIT_SKILLS_ENV = "PI_SUBAGENT_INHERIT_SKILLS";
10
+ export const SUBAGENT_INTERCOM_SESSION_NAME_ENV = "PI_SUBAGENT_INTERCOM_SESSION_NAME";
11
+
12
+ const STRUCTURED_OUTPUT_INSTRUCTIONS = [
13
+ "This subagent step has a strict structured output contract.",
14
+ "Your final action must be to call the `structured_output` tool with JSON matching the provided schema.",
15
+ "Do not rely on prose-only completion; if you do not call `structured_output`, the parent will fail this step.",
16
+ ].join("\n");
17
+
18
+ export const CHILD_SUBAGENT_BOUNDARY_INSTRUCTIONS = [
19
+ "You are a child subagent, not the parent orchestrator.",
20
+ "The parent session owns delegation, orchestration, review fanout, and follow-up worker launches.",
21
+ "Ignore prior parent-only orchestration instructions in inherited conversation history.",
22
+ "Do not propose or run subagents. Complete only your assigned role-specific task with the tools available to you.",
23
+ "If you need to edit files, call the actual edit/write tools. Do not print tool-call syntax, patches, or pseudo-tool calls as text.",
24
+ ].join("\n");
25
+
26
+ export const CHILD_FANOUT_BOUNDARY_INSTRUCTIONS = [
27
+ "You are a child subagent with explicit fanout responsibility for this assigned task.",
28
+ "The parent session owns final orchestration, acceptance, and follow-up implementation launches.",
29
+ "You may use the `subagent` tool only for the fanout work explicitly requested in this task.",
30
+ "Do not broaden yourself into general parent orchestration. Do not launch follow-up workers unless the task explicitly asks for that.",
31
+ "The maxSubagentDepth cap still applies and may block further fanout.",
32
+ "If you need to edit files, call the actual edit/write tools. Do not print tool-call syntax, patches, or pseudo-tool calls as text.",
33
+ ].join("\n");
34
+
35
+ const PARENT_ONLY_CUSTOM_MESSAGE_TYPES = new Set([
36
+ "subagent-orchestration-instructions",
37
+ "subagent-slash-result",
38
+ "subagent-notify",
39
+ "subagent_control_notice",
40
+ "subagent-control",
41
+ "subagent-control-notice",
42
+ ]);
43
+ const SUBAGENT_ORCHESTRATION_SKILL_NAME_PATTERN = /<name>\s*pi-cohort\s*<\/name>/;
44
+ const PROJECT_CONTEXT_HEADER = "\n\n# Project Context\n\nProject-specific instructions and guidelines:\n\n";
45
+ const SKILLS_HEADER = "\n\nThe following skills provide specialized instructions for specific tasks.";
46
+ const DATE_HEADER = "\nCurrent date:";
47
+
48
+ function readBooleanEnv(name: string): boolean | undefined {
49
+ const value = process.env[name];
50
+ if (value === undefined) return undefined;
51
+ return value !== "0";
52
+ }
53
+
54
+ function findSectionEnd(prompt: string, startIndex: number, nextHeaders: string[]): number {
55
+ let endIndex = prompt.length;
56
+ for (const header of nextHeaders) {
57
+ const index = prompt.indexOf(header, startIndex);
58
+ if (index !== -1 && index < endIndex) {
59
+ endIndex = index;
60
+ }
61
+ }
62
+ return endIndex;
63
+ }
64
+
65
+ export function stripProjectContext(prompt: string): string {
66
+ const startIndex = prompt.indexOf(PROJECT_CONTEXT_HEADER);
67
+ if (startIndex === -1) return prompt;
68
+ const endIndex = findSectionEnd(prompt, startIndex + PROJECT_CONTEXT_HEADER.length, [SKILLS_HEADER, DATE_HEADER]);
69
+ return `${prompt.slice(0, startIndex)}${prompt.slice(endIndex)}`;
70
+ }
71
+
72
+ export function stripInheritedSkills(prompt: string): string {
73
+ const startIndex = prompt.indexOf(SKILLS_HEADER);
74
+ if (startIndex === -1) return prompt;
75
+ const endIndex = findSectionEnd(prompt, startIndex + SKILLS_HEADER.length, [DATE_HEADER]);
76
+ return `${prompt.slice(0, startIndex)}${prompt.slice(endIndex)}`;
77
+ }
78
+
79
+ export function stripSubagentOrchestrationSkill(prompt: string): string {
80
+ return prompt
81
+ .replace(/\n{0,2}<skill\s+name=["']pi-cohort["'][^>]*>[\s\S]*?<\/skill>\n{0,2}/g, "\n\n")
82
+ .replace(/[ \t]*<skill>\s*[\s\S]*?<\/skill>\s*/g, (block) => SUBAGENT_ORCHESTRATION_SKILL_NAME_PATTERN.test(block) ? "" : block);
83
+ }
84
+
85
+ function stripChildBoundaryInstructions(prompt: string): string {
86
+ let rewritten = prompt;
87
+ for (const boundary of [CHILD_SUBAGENT_BOUNDARY_INSTRUCTIONS, CHILD_FANOUT_BOUNDARY_INSTRUCTIONS]) {
88
+ rewritten = rewritten.split(boundary).join("");
89
+ }
90
+ return rewritten.replace(/^(?:[ \t]*\r?\n)+/, "");
91
+ }
92
+
93
+ export function rewriteSubagentPrompt(
94
+ prompt: string,
95
+ options: { inheritProjectContext: boolean; inheritSkills: boolean; fanoutChild?: boolean },
96
+ ): string {
97
+ let rewritten = prompt;
98
+ if (!options.inheritProjectContext) {
99
+ rewritten = stripProjectContext(rewritten);
100
+ }
101
+ if (!options.inheritSkills) {
102
+ rewritten = stripInheritedSkills(rewritten);
103
+ }
104
+ rewritten = stripSubagentOrchestrationSkill(rewritten);
105
+ rewritten = stripChildBoundaryInstructions(rewritten);
106
+ const boundary = options.fanoutChild ? CHILD_FANOUT_BOUNDARY_INSTRUCTIONS : CHILD_SUBAGENT_BOUNDARY_INSTRUCTIONS;
107
+ const structured = process.env[STRUCTURED_OUTPUT_CAPTURE_ENV] ? `\n\n${STRUCTURED_OUTPUT_INSTRUCTIONS}` : "";
108
+ return `${boundary}${structured}\n\n${rewritten}`;
109
+ }
110
+
111
+ function isParentOnlySubagentMessage(message: unknown): boolean {
112
+ const m = message as { role?: string; customType?: string };
113
+ return m?.role === "custom"
114
+ && typeof m.customType === "string"
115
+ && PARENT_ONLY_CUSTOM_MESSAGE_TYPES.has(m.customType);
116
+ }
117
+
118
+ function isSubagentToolResultMessage(message: unknown): boolean {
119
+ const m = message as { role?: string; toolName?: string };
120
+ return m?.role === "toolResult" && m.toolName === "subagent";
121
+ }
122
+
123
+ function isSubagentToolCallBlock(block: unknown): boolean {
124
+ const b = block as { type?: string; name?: string };
125
+ return b?.type === "toolCall" && b.name === "subagent";
126
+ }
127
+
128
+ function stripAssistantSubagentToolCallBlocks(message: unknown): unknown | undefined {
129
+ const m = message as { role?: string; content?: unknown };
130
+ if (m?.role !== "assistant" || !Array.isArray(m.content)) return message;
131
+ const filteredContent = m.content.filter((block) => !isSubagentToolCallBlock(block));
132
+ if (filteredContent.length === m.content.length) return message;
133
+ if (filteredContent.length === 0) return undefined;
134
+ return { ...m, content: filteredContent };
135
+ }
136
+
137
+ export function stripParentOnlySubagentMessages(messages: unknown[]): unknown[] {
138
+ let changed = false;
139
+ const filtered: unknown[] = [];
140
+ for (const message of messages) {
141
+ if (isParentOnlySubagentMessage(message) || isSubagentToolResultMessage(message)) {
142
+ changed = true;
143
+ continue;
144
+ }
145
+ const stripped = stripAssistantSubagentToolCallBlocks(message);
146
+ if (stripped === undefined) {
147
+ changed = true;
148
+ continue;
149
+ }
150
+ if (stripped !== message) changed = true;
151
+ filtered.push(stripped);
152
+ }
153
+ return changed ? filtered : messages;
154
+ }
155
+
156
+ export default function registerSubagentPromptRuntime(pi: ExtensionAPI): void {
157
+ const structuredOutputPath = process.env[STRUCTURED_OUTPUT_CAPTURE_ENV];
158
+ const structuredSchemaPath = process.env[STRUCTURED_OUTPUT_SCHEMA_ENV];
159
+ if (structuredOutputPath && structuredSchemaPath) {
160
+ const schema = JSON.parse(fs.readFileSync(structuredSchemaPath, "utf-8")) as JsonSchemaObject;
161
+ const parameters = {
162
+ type: "object",
163
+ properties: { value: schema },
164
+ required: ["value"],
165
+ additionalProperties: false,
166
+ };
167
+ const registerTool = pi.registerTool as unknown as (tool: {
168
+ name: string;
169
+ label: string;
170
+ description: string;
171
+ parameters: unknown;
172
+ execute: (_id: string, params: { value: unknown }) => Promise<unknown>;
173
+ }) => void;
174
+ registerTool({
175
+ name: "structured_output",
176
+ label: "Structured Output",
177
+ description: "Submit the required final structured output for this subagent step. This terminates the step.",
178
+ parameters: parameters as never,
179
+ async execute(_id: string, params: { value: unknown }) {
180
+ const validation = validateStructuredOutputValue(schema, params.value);
181
+ if (validation.status === "invalid") {
182
+ throw new Error(`Structured output validation failed: ${validation.message}`);
183
+ }
184
+ fs.mkdirSync(path.dirname(structuredOutputPath), { recursive: true });
185
+ fs.writeFileSync(structuredOutputPath, JSON.stringify(params.value), { mode: 0o600 });
186
+ return {
187
+ content: [{ type: "text", text: "Structured output captured." }],
188
+ details: { path: structuredOutputPath },
189
+ terminate: true,
190
+ };
191
+ },
192
+ });
193
+ }
194
+
195
+ const onRuntimeEvent = pi.on as unknown as (event: string, handler: (event: unknown) => unknown) => void;
196
+ onRuntimeEvent("context", (event: { messages: unknown[] }) => {
197
+ const messages = stripParentOnlySubagentMessages(event.messages);
198
+ if (messages === event.messages) return undefined;
199
+ return { messages };
200
+ });
201
+
202
+ onRuntimeEvent("before_agent_start", async (event: { systemPrompt: string }) => {
203
+ const intercomSessionName = process.env[SUBAGENT_INTERCOM_SESSION_NAME_ENV]?.trim();
204
+ if (intercomSessionName && typeof pi.setSessionName === "function") {
205
+ pi.setSessionName(intercomSessionName);
206
+ }
207
+
208
+ const inheritProjectContext = readBooleanEnv(SUBAGENT_INHERIT_PROJECT_CONTEXT_ENV);
209
+ const inheritSkills = readBooleanEnv(SUBAGENT_INHERIT_SKILLS_ENV);
210
+ const fanoutChild = readBooleanEnv(SUBAGENT_FANOUT_CHILD_ENV);
211
+ if (inheritProjectContext === undefined && inheritSkills === undefined && fanoutChild === undefined) return;
212
+ const rewritten = rewriteSubagentPrompt(event.systemPrompt, {
213
+ inheritProjectContext: inheritProjectContext ?? true,
214
+ inheritSkills: inheritSkills ?? true,
215
+ fanoutChild: fanoutChild === true,
216
+ });
217
+ if (rewritten === event.systemPrompt) return;
218
+ return { systemPrompt: rewritten };
219
+ });
220
+ }
@@ -0,0 +1,206 @@
1
+ import { isDynamicParallelStep, isParallelStep, type ChainStep, type SequentialStep } from "../../shared/settings.ts";
2
+ import type { SingleResult, SubagentRunMode, WorkflowGraphNode, WorkflowGraphSnapshot, WorkflowNodeStatus } from "../../shared/types.ts";
3
+
4
+ export interface WorkflowGraphBuildInput {
5
+ runId: string;
6
+ mode?: SubagentRunMode;
7
+ steps: ChainStep[];
8
+ results?: Array<Pick<SingleResult, "exitCode" | "detached" | "interrupted" | "error" | "acceptance">>;
9
+ currentFlatIndex?: number;
10
+ currentStepIndex?: number;
11
+ stepStatuses?: Array<{ status?: string; error?: string }>;
12
+ dynamicChildren?: Record<number, Array<{ agent: string; label?: string; flatIndex: number; itemKey: string; outputName?: string; structured?: boolean; error?: string }>>;
13
+ dynamicGroupStatuses?: Record<number, { status: WorkflowNodeStatus; error?: string; acceptance?: SingleResult["acceptance"] }>;
14
+ }
15
+
16
+ function normalizeStatus(status: string | undefined): WorkflowNodeStatus | undefined {
17
+ switch (status) {
18
+ case "complete":
19
+ case "completed":
20
+ return "completed";
21
+ case "running":
22
+ return "running";
23
+ case "failed":
24
+ return "failed";
25
+ case "paused":
26
+ return "paused";
27
+ case "detached":
28
+ return "detached";
29
+ case "pending":
30
+ return "pending";
31
+ default:
32
+ return undefined;
33
+ }
34
+ }
35
+
36
+ function resultStatus(result: Pick<SingleResult, "exitCode" | "detached" | "interrupted"> | undefined): WorkflowNodeStatus | undefined {
37
+ if (!result) return undefined;
38
+ if (result.detached) return "detached";
39
+ if (result.interrupted) return "paused";
40
+ return result.exitCode === 0 ? "completed" : "failed";
41
+ }
42
+
43
+ function nodeStatus(input: WorkflowGraphBuildInput, flatIndex: number): WorkflowNodeStatus {
44
+ return normalizeStatus(input.stepStatuses?.[flatIndex]?.status)
45
+ ?? resultStatus(input.results?.[flatIndex])
46
+ ?? (input.currentFlatIndex === flatIndex ? "running" : "pending");
47
+ }
48
+
49
+ function pushPhase(phases: WorkflowGraphSnapshot["phases"], phase: string | undefined, nodeId: string): void {
50
+ if (!phase) return;
51
+ let group = phases.find((candidate) => candidate.title === phase);
52
+ if (!group) {
53
+ group = { title: phase, nodeIds: [] };
54
+ phases.push(group);
55
+ }
56
+ group.nodeIds.push(nodeId);
57
+ }
58
+
59
+ function seqLabel(step: SequentialStep, stepIndex: number): string {
60
+ return step.label?.trim() || step.agent || `Step ${stepIndex + 1}`;
61
+ }
62
+
63
+ function summarizeParallelStatuses(statuses: WorkflowNodeStatus[]): WorkflowNodeStatus {
64
+ if (statuses.some((status) => status === "running")) return "running";
65
+ if (statuses.some((status) => status === "failed")) return "failed";
66
+ if (statuses.some((status) => status === "paused")) return "paused";
67
+ if (statuses.some((status) => status === "detached")) return "detached";
68
+ if (statuses.length > 0 && statuses.every((status) => status === "completed")) return "completed";
69
+ if (statuses.some((status) => status === "completed")) return "running";
70
+ return "pending";
71
+ }
72
+
73
+ export function buildWorkflowGraphSnapshot(input: WorkflowGraphBuildInput): WorkflowGraphSnapshot {
74
+ const nodes: WorkflowGraphNode[] = [];
75
+ const phases: WorkflowGraphSnapshot["phases"] = [];
76
+ let flatIndex = 0;
77
+ let currentNodeId: string | undefined;
78
+
79
+ for (let stepIndex = 0; stepIndex < input.steps.length; stepIndex++) {
80
+ const step = input.steps[stepIndex]!;
81
+ if (isParallelStep(step)) {
82
+ const groupId = `step-${stepIndex}`;
83
+ const children: WorkflowGraphNode[] = [];
84
+ const childStatuses: WorkflowNodeStatus[] = [];
85
+ for (let taskIndex = 0; taskIndex < step.parallel.length; taskIndex++) {
86
+ const task = step.parallel[taskIndex]!;
87
+ const status = nodeStatus(input, flatIndex);
88
+ childStatuses.push(status);
89
+ const childId = `step-${stepIndex}-agent-${taskIndex}`;
90
+ const child: WorkflowGraphNode = {
91
+ id: childId,
92
+ kind: "agent",
93
+ agent: task.agent,
94
+ phase: task.phase,
95
+ label: task.label?.trim() || task.agent || `Agent ${taskIndex + 1}`,
96
+ status,
97
+ flatIndex,
98
+ stepIndex,
99
+ outputName: task.as,
100
+ structured: Boolean(task.outputSchema),
101
+ acceptanceStatus: input.results?.[flatIndex]?.acceptance?.status,
102
+ error: input.stepStatuses?.[flatIndex]?.error ?? input.results?.[flatIndex]?.error,
103
+ };
104
+ children.push(child);
105
+ pushPhase(phases, task.phase, childId);
106
+ if (status === "running" || input.currentFlatIndex === flatIndex) currentNodeId = childId;
107
+ flatIndex++;
108
+ }
109
+ const groupStatus = summarizeParallelStatuses(childStatuses);
110
+ if (input.currentStepIndex === stepIndex && !currentNodeId) currentNodeId = groupId;
111
+ nodes.push({
112
+ id: groupId,
113
+ kind: "parallel-group",
114
+ label: step.parallel.length === 1 ? "Parallel task" : `Parallel group (${step.parallel.length})`,
115
+ status: groupStatus,
116
+ stepIndex,
117
+ children,
118
+ });
119
+ continue;
120
+ }
121
+
122
+ if (isDynamicParallelStep(step)) {
123
+ const groupId = `step-${stepIndex}`;
124
+ const materialized = input.dynamicChildren?.[stepIndex] ?? [];
125
+ const groupOverride = input.dynamicGroupStatuses?.[stepIndex];
126
+ const children: WorkflowGraphNode[] = [];
127
+ const childStatuses: WorkflowNodeStatus[] = [];
128
+ for (let taskIndex = 0; taskIndex < materialized.length; taskIndex++) {
129
+ const task = materialized[taskIndex]!;
130
+ const status = nodeStatus(input, task.flatIndex);
131
+ childStatuses.push(status);
132
+ const childId = `step-${stepIndex}-item-${task.itemKey.replace(/[^a-zA-Z0-9_-]/g, "-")}`;
133
+ const child: WorkflowGraphNode = {
134
+ id: childId,
135
+ kind: "agent",
136
+ agent: task.agent,
137
+ phase: step.parallel.phase ?? step.phase,
138
+ label: task.label?.trim() || step.parallel.label?.trim() || `${task.agent} ${task.itemKey}`,
139
+ status,
140
+ flatIndex: task.flatIndex,
141
+ stepIndex,
142
+ itemKey: task.itemKey,
143
+ outputName: task.outputName,
144
+ structured: task.structured,
145
+ acceptanceStatus: input.results?.[task.flatIndex]?.acceptance?.status,
146
+ error: input.stepStatuses?.[task.flatIndex]?.error ?? input.results?.[task.flatIndex]?.error ?? task.error,
147
+ };
148
+ children.push(child);
149
+ pushPhase(phases, child.phase, childId);
150
+ if (status === "running" || input.currentFlatIndex === task.flatIndex) currentNodeId = childId;
151
+ }
152
+ const groupStatus = groupOverride?.status ?? (children.length > 0 ? summarizeParallelStatuses(childStatuses) : (input.currentStepIndex === stepIndex ? "running" : "pending"));
153
+ if (input.currentStepIndex === stepIndex && !currentNodeId) currentNodeId = groupId;
154
+ nodes.push({
155
+ id: groupId,
156
+ kind: "dynamic-parallel-group",
157
+ label: step.label?.trim() || step.parallel.label?.trim() || `Dynamic fanout (${step.collect.as})`,
158
+ status: groupStatus,
159
+ stepIndex,
160
+ outputName: step.collect.as,
161
+ structured: Boolean(step.collect.outputSchema),
162
+ acceptanceStatus: groupOverride?.acceptance?.status,
163
+ error: groupOverride?.error,
164
+ dynamic: {
165
+ sourceOutput: step.expand.from.output,
166
+ sourcePath: step.expand.from.path,
167
+ itemName: step.expand.item ?? "item",
168
+ maxItems: step.expand.maxItems,
169
+ collectAs: step.collect.as,
170
+ },
171
+ children,
172
+ });
173
+ if (materialized.length > 0) flatIndex = Math.max(flatIndex, ...materialized.map((child) => child.flatIndex + 1));
174
+ continue;
175
+ }
176
+
177
+ const seq = step as SequentialStep;
178
+ const status = nodeStatus(input, flatIndex);
179
+ const id = `step-${stepIndex}`;
180
+ nodes.push({
181
+ id,
182
+ kind: "step",
183
+ agent: seq.agent,
184
+ phase: seq.phase,
185
+ label: seqLabel(seq, stepIndex),
186
+ status,
187
+ flatIndex,
188
+ stepIndex,
189
+ outputName: seq.as,
190
+ structured: Boolean(seq.outputSchema),
191
+ acceptanceStatus: input.results?.[flatIndex]?.acceptance?.status,
192
+ error: input.stepStatuses?.[flatIndex]?.error ?? input.results?.[flatIndex]?.error,
193
+ });
194
+ pushPhase(phases, seq.phase, id);
195
+ if (status === "running" || input.currentFlatIndex === flatIndex || input.currentStepIndex === stepIndex) currentNodeId = id;
196
+ flatIndex++;
197
+ }
198
+
199
+ return {
200
+ runId: input.runId,
201
+ mode: input.mode ?? "chain",
202
+ phases,
203
+ nodes,
204
+ currentNodeId,
205
+ };
206
+ }