import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; import { fileURLToPath } from "node:url"; import { CONFIG_DIR_NAME, getAgentDir } from "@earendil-works/pi-coding-agent"; import { Type } from "typebox"; import { Compile } from "typebox/compile"; // --------------------------------------------------------------------------- // Schemas (TypeBox -> JSON Schema fragments) // --------------------------------------------------------------------------- const INTERPOLATION_GRAMMAR = "Closed grammar: {args.NAME}, {item}, {PHASE.results}, {PHASE.failures}, " + "{PHASE.results[].FIELD[]}, or {EXPR | where FIELD}."; const SELECTOR_GUIDANCE = `Use exactly one single brace-wrapped selector. ${INTERPOLATION_GRAMMAR}`; /** Any object accepted as an inline JSON Schema (TypeBox-compatible). */ const JsonSchemaObject = Type.Object( {}, { additionalProperties: true, description: "An inline JSON Schema object for this step's JSON output.", }, ); /** Full `ThinkingLevel` union. */ export const ThinkingLevelSchema = Type.Union( [ Type.Literal("off"), Type.Literal("minimal"), Type.Literal("low"), Type.Literal("medium"), Type.Literal("high"), Type.Literal("xhigh"), Type.Literal("max"), ], { description: "Reasoning budget: off, minimal, low, medium, high, xhigh, or max. " + "max is the highest opt-in level and requires model support.", }, ); /** A step's `schema` is either a named reference (string) or an inline object. */ const StepSchemaRef = Type.Union( [ Type.String({ description: "A named output schema reference: use the exact key in top-level schemas, not a JSON Schema type or label.", }), JsonSchemaObject, ], { description: "Constrains the JSON object returned by this step. Use an exact named reference or an inline JSON Schema object.", }, ); export const StepSchema = Type.Object( { summary: Type.String({ minLength: 1, description: `One short progress-UI sentence describing this sub-agent's task. May embed the same grammar tokens as prompt. ${INTERPOLATION_GRAMMAR}`, }), prompt: Type.String({ description: `Sub-agent instruction. May embed grammar tokens in text; {item} is meaningful only in fanout. ${INTERPOLATION_GRAMMAR} ` + "Do not use literal braces for any other purpose.", }), tools: Type.Optional( Type.Array(Type.String(), { description: "Sub-agent tool allowlist. Every listed tool must be available or Ultra refuses to start. Fanout may use only read, grep, find, ls, bash, web_search, web_fetch, and web_map, and its prompt must forbid mutation. Put writing tools in a single phase.", }), ), model: Type.Optional( Type.String({ description: "Model provider/id or configured tier small, medium, or big. Set deliberately for every authored step.", }), ), thinkingLevel: Type.Optional(ThinkingLevelSchema), schema: Type.Optional(StepSchemaRef), }, { additionalProperties: false, description: "One sub-agent invocation. Every step must return a JSON object; schema makes its output shape stable.", }, ); /** `over` accepts a literal array or an interpolation expression string. */ const OverSchema = Type.Union( [ Type.Array(Type.Unknown(), { description: "Literal items for one fanout agent per array element.", }), Type.String({ description: `${SELECTOR_GUIDANCE} Use args or prior phase results/failures; the resolved value must be an array.`, }), ], { description: "Fanout input: a literal array or one selector that resolves to an array.", }, ); const PhaseIdSchema = Type.String({ pattern: "^[A-Za-z_][A-Za-z0-9_]*$", description: "Unique interpolation identifier for this phase. The reserved identifier args is forbidden.", }); const WhenSchema = Type.Optional( Type.String({ description: `${SELECTOR_GUIDANCE} Use args or prior phase results/failures; false, null, undefined, an empty string, or an empty array skips the phase.`, }), ); const ConcurrencySchema = Type.Optional( Type.Number({ description: "Optional maximum concurrent agents for this phase.", }), ); // Phase is a discriminated union so `over` is *structurally* required for // `fanout` and absent-tolerant for `single` — a fanout without `over` is // rejected by TypeBox itself, no extra semantic pass needed. const SinglePhaseSchema = Type.Object( { id: PhaseIdSchema, kind: Type.Literal("single", { description: "Run one synthesis, judge, or writing step. Any over value is ignored.", }), when: WhenSchema, over: Type.Optional(OverSchema), step: StepSchema, concurrency: ConcurrencySchema, }, { description: "A phase that invokes one sub-agent." }, ); const FanoutPhaseSchema = Type.Object( { id: PhaseIdSchema, kind: Type.Literal("fanout", { description: "Run one read-only sub-agent per over item.", }), when: WhenSchema, over: OverSchema, step: StepSchema, concurrency: ConcurrencySchema, }, { description: "A phase that invokes parallel read-only sub-agents." }, ); export const PhaseSchema = Type.Union([SinglePhaseSchema, FanoutPhaseSchema], { description: "An ordered single or fanout workflow phase.", }); export const WorkflowSpecSchema = Type.Object( { name: Type.String({ minLength: 1, description: "Non-empty workflow identifier.", }), description: Type.Optional( Type.String({ description: "One-line workflow purpose." }), ), args: Type.Optional( Type.Object( { hint: Type.Optional( Type.String({ description: "Human-facing argument usage hint." }), ), params: Type.Optional( Type.Array(Type.String({ pattern: "^[A-Za-z_][A-Za-z0-9_]*$" }), { description: "Ordered positional input names exposed as {args.NAME}; the last name absorbs remaining command text.", }), ), }, { additionalProperties: true, description: "Workflow input declaration.", }, ), ), schemas: Type.Optional( Type.Record(Type.String(), JsonSchemaObject, { description: "Named JSON output schemas. Every string step.schema must exactly match one key here.", }), ), phases: Type.Array(PhaseSchema, { minItems: 1, description: "Ordered phases. Prompts and selectors may reference only prior phases; return runs after all phases.", }), return: Type.Optional( Type.String({ description: `${SELECTOR_GUIDANCE} Use args or any completed phase results/failures; the selected value may have any type.`, }), ), }, { description: "Inline declarative workflow spec. Follow every field description; malformed semantic references fail before agents run.", }, ); // --------------------------------------------------------------------------- // Inferred types // --------------------------------------------------------------------------- export type ThinkingLevel = Type.Static; export type Step = Type.Static; export type Phase = Type.Static; export type WorkflowSpec = Type.Static; // --------------------------------------------------------------------------- // Compilation // --------------------------------------------------------------------------- /** * Compile a JSON Schema (a named schema from a spec's `schemas` map, or an * inline step schema object) into a high-performance TypeBox validator with * `.Check`, `.Parse`, and `.Errors`. */ export function compileSchema(jsonSchema: object) { return Compile(jsonSchema); } // Precompiled once: validates a whole workflow spec. const workflowValidator = Compile(WorkflowSpecSchema); // --------------------------------------------------------------------------- // parseWorkflow // --------------------------------------------------------------------------- function formatErrors(value: unknown): string { return workflowValidator .Errors(value) .map((e) => `${e.instancePath || "(root)"}: ${e.message}`) .join("; "); } /** * Validate untrusted workflow data (a parsed object or a JSON string) against * the workflow schema. THROWS (never returns) on invalid input, surfacing the * underlying TypeBox error message. Returns the typed spec on success. */ export function parseWorkflow(json: unknown): WorkflowSpec { let value: unknown = json; if (typeof json === "string") { try { value = JSON.parse(json); } catch (err) { const reason = err instanceof Error ? err.message : String(err); throw new Error(`Invalid workflow spec: not valid JSON (${reason})`); } } if (!workflowValidator.Check(value)) { throw new Error(`Invalid workflow spec: ${formatErrors(value)}`); } // Semantic check beyond structure: a string `schema` is a name reference and // must resolve against the spec's `schemas` map. const spec = value as WorkflowSpec; const schemaNames = new Set(Object.keys(spec.schemas ?? {})); const phaseIds = new Set(); for (const phase of spec.phases) { if (phase.id === "args") { throw new Error('Invalid workflow spec: reserved phase id "args".'); } if (phaseIds.has(phase.id)) { throw new Error( `Invalid workflow spec: duplicate phase id "${phase.id}".`, ); } phaseIds.add(phase.id); const ref = phase.step.schema; if (typeof ref === "string" && !schemaNames.has(ref)) { const known = schemaNames.size > 0 ? [...schemaNames].join(", ") : "(none)"; throw new Error( `Invalid workflow spec: phase "${phase.id}" references unknown schema "${ref}". ` + `Known schemas: ${known}.`, ); } } return spec; } // --------------------------------------------------------------------------- // Discovery // --------------------------------------------------------------------------- export type WorkflowSource = "project" | "global" | "bundled"; export interface DiscoveredWorkflow { name: string; source: WorkflowSource; path: string; spec: WorkflowSpec; } export function missingWorkflowTools( spec: WorkflowSpec, availableTools: Iterable, ): string[] { const available = new Set(availableTools); return [...new Set(spec.phases.flatMap((phase) => phase.step.tools ?? []))] .filter((tool) => !available.has(tool)) .sort(); } export interface DiscoverOptions { /** Override the home directory for global workflow discovery in tests. */ home?: string; /** Override the extension's bundled `workflows/` directory. */ bundledDir?: string; } function bundledWorkflowsDir(): string { const here = fs.realpathSync(path.dirname(fileURLToPath(import.meta.url))); return path.join(here, "workflows"); } function readWorkflowsFromDir( dir: string, source: WorkflowSource, ): DiscoveredWorkflow[] { let entries: string[]; try { entries = fs.readdirSync(dir); } catch { // Missing directory is the normal state (e.g. no project workflows, or the // bundled dir not yet shipped) — silently contribute nothing. return []; } const out: DiscoveredWorkflow[] = []; for (const entry of entries) { if (!entry.endsWith(".json")) continue; const filePath = path.join(dir, entry); let parsed: unknown; try { parsed = JSON.parse(fs.readFileSync(filePath, "utf8")); } catch { continue; // skip unreadable / malformed files } const name = (parsed as { name?: unknown })?.name; if (typeof name !== "string" || name.length === 0) continue; out.push({ name, source, path: filePath, spec: parsed as WorkflowSpec }); } return out; } /** * Discover workflows from disk, lowest-to-highest precedence: * bundled (`/workflows`) < global agent workflows < project workflows. * A project/global name overrides a bundled name of the same id. Missing * directories are tolerated. Uses Node `fs`/`path` only. */ export function discoverWorkflows( cwd: string, opts: DiscoverOptions = {}, ): DiscoveredWorkflow[] { const home = opts.home ?? os.homedir(); const bundledDir = opts.bundledDir ?? bundledWorkflowsDir(); const projectDir = path.join(cwd, CONFIG_DIR_NAME, "workflows"); const globalDir = opts.home ? path.join(home, CONFIG_DIR_NAME, "agent", "workflows") : path.join(getAgentDir(), "workflows"); // Build the map lowest-precedence first so later sources overwrite by name. const byName = new Map(); for (const wf of readWorkflowsFromDir(bundledDir, "bundled")) byName.set(wf.name, wf); for (const wf of readWorkflowsFromDir(globalDir, "global")) byName.set(wf.name, wf); for (const wf of readWorkflowsFromDir(projectDir, "project")) byName.set(wf.name, wf); return [...byName.values()]; }