@ferris1225/pi-subagents 4.3.31 → 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.
- package/CHANGELOG.md +80 -0
- package/LICENSE +1 -1
- package/README.md +215 -273
- package/index.ts +15 -14
- package/package.json +10 -10
- package/skills/workflow/SKILL.md +226 -0
- package/src/configuration/config.ts +17 -121
- package/src/configuration/models.ts +1 -1
- package/src/configuration/setup.ts +80 -176
- package/src/configuration/ui.ts +28 -66
- package/src/delegation/agents.ts +79 -209
- package/src/delegation/builtin-agents.ts +60 -0
- package/src/delegation/dispatch.ts +32 -149
- package/src/delegation/prompt.ts +7 -5
- package/src/execution/rpc-control.ts +6 -2
- package/src/execution/rpc-run.ts +60 -20
- package/src/execution/spawn.ts +17 -28
- package/src/isolation/git-command.ts +1 -2
- package/src/isolation/recovery.ts +1 -1
- package/src/isolation/temp-hygiene.ts +2 -2
- package/src/isolation/worktree.ts +31 -17
- package/src/lifecycle/completion.ts +1 -1
- package/src/lifecycle/dispatch-core.ts +142 -0
- package/src/lifecycle/durable.ts +3 -3
- package/src/lifecycle/runtime.ts +34 -1
- package/src/lifecycle/thread-lifecycle.ts +36 -25
- package/src/lifecycle/thread-shared.ts +11 -4
- package/src/lifecycle/tools.ts +84 -11
- package/src/presentation/monitor.ts +39 -17
- package/src/presentation/widget.ts +2 -2
- package/src/workflow/durable.ts +195 -0
- package/src/workflow/engine.ts +625 -0
- package/src/workflow/files.ts +217 -0
- package/src/workflow/plan.ts +340 -0
- package/src/workflow/state.ts +48 -0
- package/src/workflow/tool.ts +269 -0
- package/workflows/code-review.md +57 -0
- package/workflows/migration.md +52 -0
- package/workflows/research.md +47 -0
- package/agents/artisan.md +0 -18
- package/agents/scout.md +0 -19
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Workflow definition discovery.
|
|
3
|
+
*
|
|
4
|
+
* A graph can be declared inline in the tool call or saved as a file so it can
|
|
5
|
+
* be reviewed, versioned, and re-run. Files are read from three scopes with the
|
|
6
|
+
* same override rule as agents — builtin < user < project, where the same name
|
|
7
|
+
* wins at the higher scope:
|
|
8
|
+
*
|
|
9
|
+
* builtin : <package>/workflows (shipped templates)
|
|
10
|
+
* user : <agentDir>/workflows (~/.pi/agent/workflows)
|
|
11
|
+
* project : <cwd...>/.pi/workflows (nearest, walking up)
|
|
12
|
+
*
|
|
13
|
+
* Two file shapes are accepted: a JSON document, and Markdown with a `json`
|
|
14
|
+
* fenced block holding the plan (so a template can explain itself in prose and
|
|
15
|
+
* keep the graph machine-readable).
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { type Dirent, existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
19
|
+
import { basename, dirname, join } from "node:path";
|
|
20
|
+
import { fileURLToPath } from "node:url";
|
|
21
|
+
import { CONFIG_DIR_NAME, getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent";
|
|
22
|
+
import type { WorkflowNodeInput, WorkflowPlanInput } from "./plan.ts";
|
|
23
|
+
|
|
24
|
+
/** Which workflow directories discovery reads. Same precedence as the templates
|
|
25
|
+
* they ship with: project > user > built-in for the same name. */
|
|
26
|
+
export type WorkflowScope = "user" | "project" | "both";
|
|
27
|
+
|
|
28
|
+
export type WorkflowSource = "builtin" | "user" | "project";
|
|
29
|
+
|
|
30
|
+
export interface WorkflowDefinition {
|
|
31
|
+
name: string;
|
|
32
|
+
description?: string;
|
|
33
|
+
plan: WorkflowPlanInput;
|
|
34
|
+
filePath: string;
|
|
35
|
+
source: WorkflowSource;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
39
|
+
/** <package>/workflows — templates shipped with this extension. */
|
|
40
|
+
export const BUILTIN_WORKFLOWS_DIR = join(here, "..", "..", "workflows");
|
|
41
|
+
|
|
42
|
+
function isDirectory(path: string): boolean {
|
|
43
|
+
try {
|
|
44
|
+
return statSync(path).isDirectory();
|
|
45
|
+
} catch {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function findNearestProjectWorkflowsDir(cwd: string): string | null {
|
|
51
|
+
let current = cwd;
|
|
52
|
+
while (true) {
|
|
53
|
+
const candidate = join(current, CONFIG_DIR_NAME, "workflows");
|
|
54
|
+
if (isDirectory(candidate)) return candidate;
|
|
55
|
+
const parent = dirname(current);
|
|
56
|
+
if (parent === current) return null;
|
|
57
|
+
current = parent;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const NODE_ID_PATTERN = /^[A-Za-z][A-Za-z0-9._-]*$/u;
|
|
62
|
+
|
|
63
|
+
function asNode(value: unknown): WorkflowNodeInput | undefined {
|
|
64
|
+
if (!value || typeof value !== "object") return undefined;
|
|
65
|
+
const raw = value as Record<string, unknown>;
|
|
66
|
+
if (typeof raw.id !== "string" || !NODE_ID_PATTERN.test(raw.id.trim())) return undefined;
|
|
67
|
+
if (typeof raw.agent !== "string" || raw.agent.trim().length === 0) return undefined;
|
|
68
|
+
if (typeof raw.task !== "string" || raw.task.trim().length === 0) return undefined;
|
|
69
|
+
const dependsOn = Array.isArray(raw.dependsOn)
|
|
70
|
+
? raw.dependsOn.filter((dep): dep is string => typeof dep === "string")
|
|
71
|
+
: undefined;
|
|
72
|
+
return {
|
|
73
|
+
id: raw.id.trim(),
|
|
74
|
+
agent: raw.agent.trim(),
|
|
75
|
+
task: raw.task,
|
|
76
|
+
...(dependsOn && dependsOn.length > 0 ? { dependsOn } : {}),
|
|
77
|
+
...(typeof raw.phaseId === "string" ? { phaseId: raw.phaseId } : {}),
|
|
78
|
+
...(raw.scope && typeof raw.scope === "object" ? { scope: raw.scope as WorkflowNodeInput["scope"] } : {}),
|
|
79
|
+
...(typeof raw.cwd === "string" ? { cwd: raw.cwd } : {}),
|
|
80
|
+
...(raw.isolation === "shared" || raw.isolation === "worktree" ? { isolation: raw.isolation } : {}),
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Accept either the full plan object or a bare node array. */
|
|
85
|
+
function asPlan(value: unknown, fallbackName: string): WorkflowPlanInput | undefined {
|
|
86
|
+
const raw = Array.isArray(value) ? { nodes: value } : value;
|
|
87
|
+
if (!raw || typeof raw !== "object") return undefined;
|
|
88
|
+
const record = raw as Record<string, unknown>;
|
|
89
|
+
if (!Array.isArray(record.nodes)) return undefined;
|
|
90
|
+
const nodes = record.nodes.map(asNode);
|
|
91
|
+
if (nodes.some((node) => node === undefined)) return undefined;
|
|
92
|
+
return {
|
|
93
|
+
name: typeof record.name === "string" && record.name.trim() ? record.name.trim() : fallbackName,
|
|
94
|
+
...(typeof record.description === "string" && record.description.trim()
|
|
95
|
+
? { description: record.description.trim() }
|
|
96
|
+
: {}),
|
|
97
|
+
nodes: nodes as WorkflowNodeInput[],
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function fencedJson(body: string): string | undefined {
|
|
102
|
+
const match = /^[ \t]*```json[ \t]*\r?\n([\s\S]*?)^[ \t]*```/mu.exec(body);
|
|
103
|
+
return match?.[1];
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Read one definition file. Returns an error string instead of throwing so a
|
|
107
|
+
* broken file in a shared directory cannot hide the rest of the catalog. */
|
|
108
|
+
export function readWorkflowFile(
|
|
109
|
+
filePath: string,
|
|
110
|
+
source: WorkflowSource,
|
|
111
|
+
): { definition?: WorkflowDefinition; error?: string } {
|
|
112
|
+
const fallbackName = basename(filePath).replace(/\.(json|md)$/iu, "");
|
|
113
|
+
let content: string;
|
|
114
|
+
try {
|
|
115
|
+
content = readFileSync(filePath, "utf8");
|
|
116
|
+
} catch (error) {
|
|
117
|
+
return { error: `${filePath}: ${error instanceof Error ? error.message : String(error)}` };
|
|
118
|
+
}
|
|
119
|
+
if (filePath.endsWith(".json")) {
|
|
120
|
+
let parsed: unknown;
|
|
121
|
+
try {
|
|
122
|
+
parsed = JSON.parse(content);
|
|
123
|
+
} catch (error) {
|
|
124
|
+
return { error: `${filePath}: invalid JSON (${error instanceof Error ? error.message : String(error)})` };
|
|
125
|
+
}
|
|
126
|
+
const plan = asPlan(parsed, fallbackName);
|
|
127
|
+
if (!plan) return { error: `${filePath}: expected { name?, description?, nodes: [{ id, agent, task, dependsOn? }] }.` };
|
|
128
|
+
return { definition: { name: plan.name ?? fallbackName, ...(plan.description ? { description: plan.description } : {}), plan, filePath, source } };
|
|
129
|
+
}
|
|
130
|
+
const { frontmatter, body } = parseFrontmatter<Record<string, string>>(content);
|
|
131
|
+
const json = fencedJson(body);
|
|
132
|
+
if (json === undefined) return { error: `${filePath}: a Markdown workflow needs a \`\`\`json fenced block holding the plan.` };
|
|
133
|
+
let parsed: unknown;
|
|
134
|
+
try {
|
|
135
|
+
parsed = JSON.parse(json);
|
|
136
|
+
} catch (error) {
|
|
137
|
+
return { error: `${filePath}: invalid JSON in the fenced block (${error instanceof Error ? error.message : String(error)})` };
|
|
138
|
+
}
|
|
139
|
+
const name = typeof frontmatter.name === "string" && frontmatter.name.trim() ? frontmatter.name.trim() : fallbackName;
|
|
140
|
+
const plan = asPlan(parsed, name);
|
|
141
|
+
if (!plan) return { error: `${filePath}: expected a plan object or a node array in the fenced block.` };
|
|
142
|
+
const description = typeof frontmatter.description === "string" && frontmatter.description.trim()
|
|
143
|
+
? frontmatter.description.trim()
|
|
144
|
+
: plan.description;
|
|
145
|
+
return {
|
|
146
|
+
definition: { name: plan.name ?? name, ...(description ? { description } : {}), plan, filePath, source },
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function loadDefinitionsFromDir(dir: string, source: WorkflowSource): WorkflowDefinition[] {
|
|
151
|
+
if (!existsSync(dir)) return [];
|
|
152
|
+
let entries: Dirent[];
|
|
153
|
+
try {
|
|
154
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
155
|
+
} catch {
|
|
156
|
+
return [];
|
|
157
|
+
}
|
|
158
|
+
const definitions: WorkflowDefinition[] = [];
|
|
159
|
+
for (const entry of entries) {
|
|
160
|
+
if (!entry.name.endsWith(".json") && !entry.name.endsWith(".md")) continue;
|
|
161
|
+
if (!entry.isFile() && !entry.isSymbolicLink()) continue;
|
|
162
|
+
const { definition } = readWorkflowFile(join(dir, entry.name), source);
|
|
163
|
+
if (definition) definitions.push(definition);
|
|
164
|
+
}
|
|
165
|
+
return definitions;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export interface DiscoverWorkflowsOptions {
|
|
169
|
+
scope?: WorkflowScope;
|
|
170
|
+
projectTrusted?: boolean;
|
|
171
|
+
builtinDir?: string;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Every workflow definition visible from `cwd`, merged with project > user >
|
|
176
|
+
* builtin precedence for the same name and sorted by name.
|
|
177
|
+
*/
|
|
178
|
+
export function discoverWorkflows(cwd: string, options: DiscoverWorkflowsOptions = {}): WorkflowDefinition[] {
|
|
179
|
+
const scope = options.scope ?? "user";
|
|
180
|
+
const projectDir = findNearestProjectWorkflowsDir(cwd);
|
|
181
|
+
const builtin = loadDefinitionsFromDir(options.builtinDir ?? BUILTIN_WORKFLOWS_DIR, "builtin");
|
|
182
|
+
const user = scope === "project" ? [] : loadDefinitionsFromDir(join(getAgentDir(), "workflows"), "user");
|
|
183
|
+
const project =
|
|
184
|
+
scope === "user" || !projectDir || options.projectTrusted !== true
|
|
185
|
+
? []
|
|
186
|
+
: loadDefinitionsFromDir(projectDir, "project");
|
|
187
|
+
|
|
188
|
+
const byName = new Map<string, WorkflowDefinition>();
|
|
189
|
+
for (const definition of builtin) byName.set(definition.name, definition);
|
|
190
|
+
for (const definition of user) byName.set(definition.name, definition);
|
|
191
|
+
for (const definition of project) byName.set(definition.name, definition);
|
|
192
|
+
return [...byName.values()].sort((left, right) => left.name.localeCompare(right.name));
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Resolve a name or file path to a definition; error text names what is available. */
|
|
196
|
+
export function resolveWorkflowDefinition(
|
|
197
|
+
cwd: string,
|
|
198
|
+
request: { name?: string; path?: string },
|
|
199
|
+
options: DiscoverWorkflowsOptions = {},
|
|
200
|
+
): { definition?: WorkflowDefinition; error?: string } {
|
|
201
|
+
if (request.path) {
|
|
202
|
+
const filePath = join(cwd, request.path);
|
|
203
|
+
if (!existsSync(filePath)) return { error: `workflow file not found: ${filePath}` };
|
|
204
|
+
const read = readWorkflowFile(filePath, "project");
|
|
205
|
+
if (read.error) return { error: read.error };
|
|
206
|
+
return read;
|
|
207
|
+
}
|
|
208
|
+
const name = request.name?.trim();
|
|
209
|
+
if (!name) return { error: "provide either inline nodes, a workflow name, or a workflow file path." };
|
|
210
|
+
const available = discoverWorkflows(cwd, options);
|
|
211
|
+
const match = available.find((definition) => definition.name.toLowerCase() === name.toLowerCase());
|
|
212
|
+
if (!match) {
|
|
213
|
+
const names = available.map((definition) => definition.name).join(", ");
|
|
214
|
+
return { error: `no workflow named "${name}". Available: ${names || "none"}. Save one under .pi/workflows/ or ~/.pi/agent/workflows/.` };
|
|
215
|
+
}
|
|
216
|
+
return { definition: match };
|
|
217
|
+
}
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Workflow graph contract: authoring input, compile-time validation, and the
|
|
3
|
+
* dependency-ordered task template a node's brief is rendered from.
|
|
4
|
+
*
|
|
5
|
+
* A workflow is a DAG of ordinary sub-agent phases. Compilation is deliberately
|
|
6
|
+
* strict and happens before anything starts: unique node ids, existing
|
|
7
|
+
* dependencies, no cycles, resolvable result placeholders, and no declared
|
|
8
|
+
* writer overlap between nodes that could run at the same time. An invalid
|
|
9
|
+
* graph therefore costs zero child processes.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { resolve } from "node:path";
|
|
13
|
+
import {
|
|
14
|
+
findPhaseScopeOverlap,
|
|
15
|
+
normalizePhaseId,
|
|
16
|
+
normalizePhaseScope,
|
|
17
|
+
PHASE_ID_MAX_LENGTH,
|
|
18
|
+
PHASE_ID_PATTERN_SOURCE,
|
|
19
|
+
type PhaseScope,
|
|
20
|
+
type PhaseScopeInput,
|
|
21
|
+
} from "../delegation/phase-scope.ts";
|
|
22
|
+
import type { IsolationMode } from "../isolation/worktree.ts";
|
|
23
|
+
|
|
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. */
|
|
26
|
+
export const WORKFLOW_NODE_LIMIT = 24;
|
|
27
|
+
|
|
28
|
+
export const WORKFLOW_NODE_ID_MAX_LENGTH = 40;
|
|
29
|
+
const WORKFLOW_NODE_ID_PATTERN = /^[A-Za-z][A-Za-z0-9._-]*$/u;
|
|
30
|
+
const WORKFLOW_NAME_MAX_LENGTH = 60;
|
|
31
|
+
|
|
32
|
+
/** How much of an upstream node's answer is interpolated into a downstream
|
|
33
|
+
* brief: enough to act on, bounded so a wide graph cannot push its whole
|
|
34
|
+
* transcript through prompts. The rest stays in that node's result artifact. */
|
|
35
|
+
export const UPSTREAM_OUTPUT_MAX_CHARS = 6_000;
|
|
36
|
+
|
|
37
|
+
export interface WorkflowNodeInput {
|
|
38
|
+
/** Stable node id, referenced by `dependsOn` and by result placeholders. */
|
|
39
|
+
id: string;
|
|
40
|
+
agent: string;
|
|
41
|
+
/** Brief for this node. `{{id}}` interpolates an upstream node's answer;
|
|
42
|
+
* `{{id.status}}`, `{{id.runId}}`, and `{{id.error}}` interpolate facts. */
|
|
43
|
+
task: string;
|
|
44
|
+
dependsOn?: string[];
|
|
45
|
+
phaseId?: string;
|
|
46
|
+
scope?: PhaseScopeInput;
|
|
47
|
+
cwd?: string;
|
|
48
|
+
isolation?: IsolationMode;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface WorkflowPlanInput {
|
|
52
|
+
name?: string;
|
|
53
|
+
description?: string;
|
|
54
|
+
nodes: WorkflowNodeInput[];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface CompiledWorkflowNode {
|
|
58
|
+
id: string;
|
|
59
|
+
index: number;
|
|
60
|
+
agent: string;
|
|
61
|
+
task: string;
|
|
62
|
+
/** Direct prerequisites, in author order. */
|
|
63
|
+
dependsOn: string[];
|
|
64
|
+
/** Every transitive prerequisite; used for placeholder and scope checks. */
|
|
65
|
+
ancestors: string[];
|
|
66
|
+
/** Declared phase id, or the workflow-derived default assigned at dispatch. */
|
|
67
|
+
phaseId?: string;
|
|
68
|
+
scope?: PhaseScope;
|
|
69
|
+
/** Absolute working directory resolved from the compile-time caller cwd. */
|
|
70
|
+
cwd: string;
|
|
71
|
+
isolation?: IsolationMode;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export interface CompiledWorkflow {
|
|
75
|
+
/** Display name: the workflow definition's name or a derived label. */
|
|
76
|
+
name: string;
|
|
77
|
+
/** Identifier-safe form used for derived phase ids. */
|
|
78
|
+
slug: string;
|
|
79
|
+
description?: string;
|
|
80
|
+
/** Caller-facing directory the graph was compiled against. */
|
|
81
|
+
cwd: string;
|
|
82
|
+
nodes: CompiledWorkflowNode[];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Placeholder syntax accepted in a node's task. */
|
|
86
|
+
const PLACEHOLDER = /\{\{\s*([^{}]+?)\s*\}\}/gu;
|
|
87
|
+
const FACT_SUFFIXES = [".status", ".runId", ".error"] as const;
|
|
88
|
+
type PlaceholderFact = "output" | "status" | "runId" | "error";
|
|
89
|
+
|
|
90
|
+
function singleLine(value: string): string {
|
|
91
|
+
return value.replace(/\s+/gu, " ").trim();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Identifier-safe slug for derived phase ids. */
|
|
95
|
+
function slugify(name: string): string {
|
|
96
|
+
const slug = singleLine(name)
|
|
97
|
+
.toLowerCase()
|
|
98
|
+
.replace(/[^a-z0-9]+/gu, "-")
|
|
99
|
+
.replace(/^-+|-+$/gu, "")
|
|
100
|
+
.slice(0, 32)
|
|
101
|
+
.replace(/-+$/gu, "");
|
|
102
|
+
return slug || "workflow";
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function normalizeWorkflowName(raw: string | undefined, fallback: string): string {
|
|
106
|
+
const name = raw === undefined ? "" : singleLine(raw);
|
|
107
|
+
const chosen = name || singleLine(fallback);
|
|
108
|
+
if (chosen.length === 0) throw new Error("workflow name must be non-blank.");
|
|
109
|
+
if (chosen.length > WORKFLOW_NAME_MAX_LENGTH) {
|
|
110
|
+
throw new Error(`workflow name must be at most ${WORKFLOW_NAME_MAX_LENGTH} characters.`);
|
|
111
|
+
}
|
|
112
|
+
return chosen;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function splitPlaceholder(token: string): { id: string; fact: PlaceholderFact } {
|
|
116
|
+
for (const suffix of FACT_SUFFIXES) {
|
|
117
|
+
if (token.endsWith(suffix) && token.length > suffix.length) {
|
|
118
|
+
return { id: token.slice(0, -suffix.length), fact: suffix.slice(1) as PlaceholderFact };
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return { id: token, fact: "output" };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Resolve `dependsOn` transitively. Returns the ancestors of every node. */
|
|
125
|
+
function resolveAncestors(ids: readonly string[], direct: Map<string, string[]>): Map<string, string[]> {
|
|
126
|
+
const memo = new Map<string, string[]>();
|
|
127
|
+
const visiting = new Set<string>();
|
|
128
|
+
const walk = (id: string): string[] => {
|
|
129
|
+
const cached = memo.get(id);
|
|
130
|
+
if (cached) return cached;
|
|
131
|
+
if (visiting.has(id)) throw new Error(`dependency cycle through node "${id}".`);
|
|
132
|
+
visiting.add(id);
|
|
133
|
+
const collected = new Set<string>();
|
|
134
|
+
for (const dependency of direct.get(id) ?? []) {
|
|
135
|
+
collected.add(dependency);
|
|
136
|
+
for (const ancestor of walk(dependency)) collected.add(ancestor);
|
|
137
|
+
}
|
|
138
|
+
visiting.delete(id);
|
|
139
|
+
const list = [...collected];
|
|
140
|
+
memo.set(id, list);
|
|
141
|
+
return list;
|
|
142
|
+
};
|
|
143
|
+
for (const id of ids) walk(id);
|
|
144
|
+
return memo;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function validatePhaseId(node: WorkflowNodeInput, label: string): string | undefined {
|
|
148
|
+
try {
|
|
149
|
+
return normalizePhaseId(node.phaseId);
|
|
150
|
+
} catch (error) {
|
|
151
|
+
throw new Error(`${label}.phaseId: ${error instanceof Error ? error.message : String(error)}`);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Compile an authored plan into a runnable graph. Every problem is reported at
|
|
157
|
+
* once, so fixing a graph does not take one round-trip per mistake.
|
|
158
|
+
*/
|
|
159
|
+
export function compileWorkflow(
|
|
160
|
+
input: WorkflowPlanInput,
|
|
161
|
+
callerCwd: string,
|
|
162
|
+
knownAgents: readonly string[],
|
|
163
|
+
options: { fallbackName?: string } = {},
|
|
164
|
+
): CompiledWorkflow {
|
|
165
|
+
const problems: string[] = [];
|
|
166
|
+
const rawNodes = Array.isArray(input.nodes) ? input.nodes : [];
|
|
167
|
+
if (rawNodes.length === 0) throw new Error("a workflow needs at least one node.");
|
|
168
|
+
if (rawNodes.length > WORKFLOW_NODE_LIMIT) {
|
|
169
|
+
throw new Error(`a workflow may declare at most ${WORKFLOW_NODE_LIMIT} nodes (got ${rawNodes.length}); split it into sequential workflows instead.`);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
let name: string;
|
|
173
|
+
try {
|
|
174
|
+
name = normalizeWorkflowName(input.name, options.fallbackName ?? "workflow");
|
|
175
|
+
} catch (error) {
|
|
176
|
+
throw new Error(error instanceof Error ? error.message : String(error));
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const ids: string[] = [];
|
|
180
|
+
const seenIds = new Set<string>();
|
|
181
|
+
for (const [index, node] of rawNodes.entries()) {
|
|
182
|
+
const label = `nodes[${index}]`;
|
|
183
|
+
const id = typeof node?.id === "string" ? node.id.trim() : "";
|
|
184
|
+
if (!WORKFLOW_NODE_ID_PATTERN.test(id) || id.length > WORKFLOW_NODE_ID_MAX_LENGTH) {
|
|
185
|
+
problems.push(
|
|
186
|
+
`${label}.id must be 1-${WORKFLOW_NODE_ID_MAX_LENGTH} characters of ASCII letters, numbers, or ._- starting with a letter ("${id}").`,
|
|
187
|
+
);
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
if (seenIds.has(id)) {
|
|
191
|
+
problems.push(`${label}.id "${id}" is declared twice; node ids identify results and dependencies.`);
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
seenIds.add(id);
|
|
195
|
+
ids.push(id);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const direct = new Map<string, string[]>();
|
|
199
|
+
for (const [index, node] of rawNodes.entries()) {
|
|
200
|
+
const label = `nodes[${index}]`;
|
|
201
|
+
if (typeof node?.agent !== "string" || !knownAgents.includes(node.agent.trim())) {
|
|
202
|
+
problems.push(`${label}.agent "${String(node?.agent)}" is not an enabled agent (available: ${knownAgents.join(", ") || "none"}).`);
|
|
203
|
+
}
|
|
204
|
+
if (typeof node?.task !== "string" || node.task.trim().length === 0) {
|
|
205
|
+
problems.push(`${label}.task must be a non-blank brief.`);
|
|
206
|
+
}
|
|
207
|
+
const dependsOn = node?.dependsOn ?? [];
|
|
208
|
+
if (!Array.isArray(dependsOn)) {
|
|
209
|
+
problems.push(`${label}.dependsOn must be an array of node ids.`);
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
const unique: string[] = [];
|
|
213
|
+
for (const dependency of dependsOn) {
|
|
214
|
+
const dep = typeof dependency === "string" ? dependency.trim() : "";
|
|
215
|
+
if (!seenIds.has(dep)) {
|
|
216
|
+
problems.push(`${label}.dependsOn references unknown node "${dep}".`);
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
if (dep === node.id) {
|
|
220
|
+
problems.push(`${label} depends on itself.`);
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
if (!unique.includes(dep)) unique.push(dep);
|
|
224
|
+
}
|
|
225
|
+
direct.set(node.id, unique);
|
|
226
|
+
}
|
|
227
|
+
if (problems.length > 0) throw new Error(problems.join("\n"));
|
|
228
|
+
|
|
229
|
+
let ancestors: Map<string, string[]>;
|
|
230
|
+
try {
|
|
231
|
+
ancestors = resolveAncestors(ids, direct);
|
|
232
|
+
} catch (error) {
|
|
233
|
+
throw new Error(error instanceof Error ? error.message : String(error));
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const nodes: CompiledWorkflowNode[] = [];
|
|
237
|
+
for (const [index, node] of rawNodes.entries()) {
|
|
238
|
+
const label = `nodes[${index}] ("${node.id}")`;
|
|
239
|
+
const nodeAncestors = ancestors.get(node.id) ?? [];
|
|
240
|
+
const ancestorSet = new Set(nodeAncestors);
|
|
241
|
+
for (const match of node.task.matchAll(PLACEHOLDER)) {
|
|
242
|
+
const { id, fact } = splitPlaceholder(match[1]?.trim() ?? "");
|
|
243
|
+
if (!ancestorSet.has(id)) {
|
|
244
|
+
problems.push(
|
|
245
|
+
`${label}.task references {{${match[1]?.trim()}}} but "${id}" is not a declared dependency (${fact === "output" ? "answer" : fact} placeholders may only read a node this one waits for).`,
|
|
246
|
+
);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
const cwd = resolve(callerCwd, node.cwd ?? ".");
|
|
250
|
+
let scope: PhaseScope | undefined;
|
|
251
|
+
try {
|
|
252
|
+
scope = normalizePhaseScope(node.scope, cwd);
|
|
253
|
+
} catch (error) {
|
|
254
|
+
problems.push(`${label}.scope: ${error instanceof Error ? error.message : String(error)}`);
|
|
255
|
+
}
|
|
256
|
+
const phaseId = validatePhaseId(node, label);
|
|
257
|
+
nodes.push({
|
|
258
|
+
id: node.id,
|
|
259
|
+
index,
|
|
260
|
+
agent: node.agent.trim(),
|
|
261
|
+
task: node.task,
|
|
262
|
+
dependsOn: [...(direct.get(node.id) ?? [])],
|
|
263
|
+
ancestors: nodeAncestors,
|
|
264
|
+
...(phaseId ? { phaseId } : {}),
|
|
265
|
+
...(scope ? { scope } : {}),
|
|
266
|
+
cwd,
|
|
267
|
+
...(node.isolation ? { isolation: node.isolation } : {}),
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// Only order-independent nodes can contend for the same files. Two nodes
|
|
272
|
+
// with a dependency edge are serialized by the graph itself, so their
|
|
273
|
+
// shared scope is intentional (a fix then its own test file).
|
|
274
|
+
for (let leftIndex = 0; leftIndex < nodes.length; leftIndex++) {
|
|
275
|
+
const left = nodes[leftIndex]!;
|
|
276
|
+
if (!left.scope) continue;
|
|
277
|
+
for (let rightIndex = leftIndex + 1; rightIndex < nodes.length; rightIndex++) {
|
|
278
|
+
const right = nodes[rightIndex]!;
|
|
279
|
+
if (!right.scope) continue;
|
|
280
|
+
if (left.ancestors.includes(right.id) || right.ancestors.includes(left.id)) continue;
|
|
281
|
+
const overlap = findPhaseScopeOverlap(left.scope, right.scope);
|
|
282
|
+
if (overlap) {
|
|
283
|
+
problems.push(
|
|
284
|
+
`nodes "${left.id}" and "${right.id}" declare overlapping writer scope (${overlap.left} vs ${overlap.right}) without a dependency ordering them; give one node the whole scope or add dependsOn.`,
|
|
285
|
+
);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
if (problems.length > 0) throw new Error(problems.join("\n"));
|
|
291
|
+
|
|
292
|
+
return {
|
|
293
|
+
name,
|
|
294
|
+
slug: slugify(name),
|
|
295
|
+
...(input.description && singleLine(input.description)
|
|
296
|
+
? { description: singleLine(input.description) }
|
|
297
|
+
: {}),
|
|
298
|
+
cwd: resolve(callerCwd),
|
|
299
|
+
nodes,
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** What a settled node hands its dependents. */
|
|
304
|
+
export interface UpstreamOutput {
|
|
305
|
+
status: "completed" | "failed" | "blocked" | "stopped";
|
|
306
|
+
output: string;
|
|
307
|
+
runId?: number;
|
|
308
|
+
error?: string;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function boundOutput(output: string): string {
|
|
312
|
+
if (output.length <= UPSTREAM_OUTPUT_MAX_CHARS) return output;
|
|
313
|
+
return `${output.slice(0, UPSTREAM_OUTPUT_MAX_CHARS)}\n… (answer truncated at ${UPSTREAM_OUTPUT_MAX_CHARS} characters; read that node's full result from its own run)`;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** Render a node's brief, substituting facts from the nodes it waited for. */
|
|
317
|
+
export function renderNodeTask(task: string, upstream: ReadonlyMap<string, UpstreamOutput>): string {
|
|
318
|
+
return task.replace(PLACEHOLDER, (whole, rawToken: string) => {
|
|
319
|
+
const { id, fact } = splitPlaceholder(rawToken.trim());
|
|
320
|
+
const view = upstream.get(id);
|
|
321
|
+
if (!view) return whole;
|
|
322
|
+
switch (fact) {
|
|
323
|
+
case "status":
|
|
324
|
+
return view.status;
|
|
325
|
+
case "runId":
|
|
326
|
+
return view.runId === undefined ? "unknown" : `#${view.runId}`;
|
|
327
|
+
case "error":
|
|
328
|
+
return view.error?.trim() || "(no error reported)";
|
|
329
|
+
default:
|
|
330
|
+
return view.output.trim() || "(no output)";
|
|
331
|
+
}
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** Default phase id for a node, kept inside the phase-id contract. */
|
|
336
|
+
export function defaultPhaseId(workflow: CompiledWorkflow, node: CompiledWorkflowNode): string {
|
|
337
|
+
const candidate = `${workflow.slug}.${node.id}`;
|
|
338
|
+
if (candidate.length <= PHASE_ID_MAX_LENGTH && new RegExp(PHASE_ID_PATTERN_SOURCE, "u").test(candidate)) return candidate;
|
|
339
|
+
return `${workflow.slug.slice(0, PHASE_ID_MAX_LENGTH - node.id.length - 1)}.${node.id}`.slice(0, PHASE_ID_MAX_LENGTH);
|
|
340
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Live workflow graph state shared by the runner, the status tool, and the
|
|
3
|
+
* runtime. Kept free of behaviour so the runtime can hold it without importing
|
|
4
|
+
* the engine.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { PhaseScope } from "../delegation/phase-scope.ts";
|
|
8
|
+
import type { SingleResult } from "../execution/spawn.ts";
|
|
9
|
+
import type { RecordedNodeState } from "./durable.ts";
|
|
10
|
+
|
|
11
|
+
export type WorkflowNodeState = RecordedNodeState;
|
|
12
|
+
|
|
13
|
+
export interface WorkflowNodeRun {
|
|
14
|
+
id: string;
|
|
15
|
+
index: number;
|
|
16
|
+
agent: string;
|
|
17
|
+
/** Authored brief, still carrying its result placeholders. */
|
|
18
|
+
task: string;
|
|
19
|
+
/** Brief actually sent, after upstream interpolation. */
|
|
20
|
+
dispatchedTask?: string;
|
|
21
|
+
dependsOn: string[];
|
|
22
|
+
phaseId: string;
|
|
23
|
+
scope?: PhaseScope;
|
|
24
|
+
cwd: string;
|
|
25
|
+
state: WorkflowNodeState;
|
|
26
|
+
runId?: number;
|
|
27
|
+
startedAt?: number;
|
|
28
|
+
endedAt?: number;
|
|
29
|
+
result?: SingleResult;
|
|
30
|
+
error?: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export type WorkflowRunState = "running" | "completed" | "failed" | "stopped" | "interrupted";
|
|
34
|
+
|
|
35
|
+
export interface WorkflowRun {
|
|
36
|
+
id: number;
|
|
37
|
+
name: string;
|
|
38
|
+
slug: string;
|
|
39
|
+
description?: string;
|
|
40
|
+
cwd: string;
|
|
41
|
+
state: WorkflowRunState;
|
|
42
|
+
stopReason?: string;
|
|
43
|
+
startedAt: number;
|
|
44
|
+
endedAt?: number;
|
|
45
|
+
nodes: WorkflowNodeRun[];
|
|
46
|
+
/** Aborts the graph's waiters; node processes are stopped individually. */
|
|
47
|
+
controller: AbortController;
|
|
48
|
+
}
|