repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ultra/spec.ts

Raw
File outline
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { fileURLToPath } from "node:url";
import { Type } from "typebox";
import { Compile } from "typebox/compile";

// ---------------------------------------------------------------------------
// Schemas (TypeBox -> JSON Schema fragments)
// ---------------------------------------------------------------------------

/** Any object accepted as an inline JSON Schema (TypeBox-compatible). */
const JsonSchemaObject = Type.Object({}, { additionalProperties: true });

/** Full `ThinkingLevel` union (correction #8): all six values, incl. `low`. */
export const ThinkingLevelSchema = Type.Union([
	Type.Literal("off"),
	Type.Literal("minimal"),
	Type.Literal("low"),
	Type.Literal("medium"),
	Type.Literal("high"),
	Type.Literal("xhigh"),
]);

/** A step's `schema` is either a named reference (string) or an inline object. */
const StepSchemaRef = Type.Union([Type.String(), JsonSchemaObject]);

export const StepSchema = Type.Object({
	prompt: Type.String(),
	tools: Type.Optional(Type.Array(Type.String())),
	model: Type.Optional(Type.String()),
	thinkingLevel: Type.Optional(ThinkingLevelSchema),
	schema: Type.Optional(StepSchemaRef),
	timeoutMs: Type.Optional(Type.Number()),
});

/** `over` accepts a literal array or an interpolation expression string. */
const OverSchema = Type.Union([Type.Array(Type.Unknown()), Type.String()]);

// 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: Type.String(),
	kind: Type.Literal("single"),
	over: Type.Optional(OverSchema),
	step: StepSchema,
	concurrency: Type.Optional(Type.Number()),
});

const FanoutPhaseSchema = Type.Object({
	id: Type.String(),
	kind: Type.Literal("fanout"),
	over: OverSchema,
	step: StepSchema,
	concurrency: Type.Optional(Type.Number()),
});

export const PhaseSchema = Type.Union([SinglePhaseSchema, FanoutPhaseSchema]);

export const WorkflowSpecSchema = Type.Object({
	name: Type.String({ minLength: 1 }),
	description: Type.Optional(Type.String()),
	args: Type.Optional(
		Type.Object(
			{
				hint: Type.Optional(Type.String()),
				// Declared positional params: a bare `/ultra <name> <tok...>` line
				// maps whitespace tokens to these names in order, exposed as
				// `{args.NAME}`. Names must be interpolation identifiers.
				params: Type.Optional(
					Type.Array(Type.String({ pattern: "^[A-Za-z_][A-Za-z0-9_]*$" })),
				),
			},
			{ additionalProperties: true },
		),
	),
	schemas: Type.Optional(Type.Record(Type.String(), JsonSchemaObject)),
	phases: Type.Array(PhaseSchema, { minItems: 1 }),
	return: Type.Optional(Type.String()),
});

// ---------------------------------------------------------------------------
// Inferred types
// ---------------------------------------------------------------------------

export type ThinkingLevel = Type.Static<typeof ThinkingLevelSchema>;
export type Step = Type.Static<typeof StepSchema>;
export type Phase = Type.Static<typeof PhaseSchema>;
export type WorkflowSpec = Type.Static<typeof WorkflowSpecSchema>;

// ---------------------------------------------------------------------------
// 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 ?? {}));
	for (const phase of spec.phases) {
		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 interface DiscoverOptions {
	/** Override `os.homedir()` (used to locate `~/.pi/agent/workflows`). */
	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 `.pi/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 (`<ext>/workflows`) < global (`~/.pi/agent/workflows`) < project (`<cwd>/.pi/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, ".pi", "workflows");
	const globalDir = path.join(home, ".pi", "agent", "workflows");

	// Build the map lowest-precedence first so later sources overwrite by name.
	const byName = new Map<string, DiscoveredWorkflow>();
	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()];
}