repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ultra/interp.ts

Raw
File outline
// ultra — interpolation resolver (Task 3).
//
// A closed, deliberately tiny mini-syntax: NOT a general expression evaluator
// and NO `eval`. Every token is parsed against a fixed grammar; anything
// outside it raises a `SpecValidationError`. See the design's
// "Interpolation mini-syntax" section for the authoritative semantics.
//
//   {args.NAME}                 — workflow input value
//   {item}                      — current fanout item (string verbatim; else compact JSON)
//   {PHASE.results}             — a prior phase's results array (nulls RETAINED positionally)
//   {PHASE.failures}            — a prior phase's typed failure array
//   {PHASE.results[].FIELD[]}   — flatten: concat each result's FIELD array (null elems / missing FIELDs SKIPPED)
//   {EXPR | where FIELD}        — keep elements whose boolean FIELD is truthy (null elems / missing FIELD SKIPPED)
//
// Pure module: no SDK imports.

/** Raised when a template/selector falls outside the documented v1 grammar. */
export class SpecValidationError extends Error {
	constructor(message: string) {
		super(message);
		this.name = "SpecValidationError";
	}
}

/**
 * Resolution context. This shape is the contract the phase engine (Task 6)
 * populates: `args` from the workflow inputs, `item` for the current fanout
 * element, and `results` mapping each prior phase id to its results array.
 * The three namespaces are segregated so a phase named `args` or `item`
 * cannot collide with the reserved roots.
 */
export interface InterpContext {
	args?: Record<string, unknown>;
	item?: unknown;
	results?: Record<string, unknown[]>;
	failures?: Record<string, unknown[]>;
}

const IDENT = "[A-Za-z_][A-Za-z0-9_]*";
const RE_ARGS = new RegExp(`^args\\.(${IDENT})$`);
const RE_RESULTS = new RegExp(`^(${IDENT})\\.results$`);
const RE_FAILURES = new RegExp(`^(${IDENT})\\.failures$`);
const RE_FLATTEN = new RegExp(
	`^(${IDENT})\\.results\\[\\]\\.(${IDENT})\\[\\]$`,
);
const RE_WHERE = new RegExp(`^where\\s+(${IDENT})$`);
// A selector value (`over`/`return`) is exactly one braced token, no nesting.
const RE_SINGLE_TOKEN = /^\{([^{}]*)\}$/;
// Template token scanner: every `{...}` (no nesting in v1).
const RE_TOKEN = /\{([^{}]*)\}/g;

type Base =
	| { kind: "args"; name: string }
	| { kind: "item" }
	| { kind: "results"; phase: string }
	| { kind: "failures"; phase: string }
	| { kind: "flatten"; phase: string; field: string };

type Expr = Base | { kind: "where"; base: Base; field: string };

function isRecord(value: unknown): value is Record<string, unknown> {
	return typeof value === "object" && value !== null && !Array.isArray(value);
}

function parseBase(raw: string): Base {
	const s = raw.trim();
	if (s === "item") return { kind: "item" };

	const args = s.match(RE_ARGS);
	if (args) return { kind: "args", name: args[1] };

	const results = s.match(RE_RESULTS);
	if (results) return { kind: "results", phase: results[1] };

	const failures = s.match(RE_FAILURES);
	if (failures) return { kind: "failures", phase: failures[1] };

	const flatten = s.match(RE_FLATTEN);
	if (flatten) {
		return { kind: "flatten", phase: flatten[1], field: flatten[2] };
	}

	throw new SpecValidationError(
		`unknown interpolation token "{${raw}}" (outside the v1 grammar; allowed: args.NAME, item, PHASE.results, PHASE.failures, PHASE.results[].FIELD[])`,
	);
}

function parseExpr(inner: string): Expr {
	const trimmed = inner.trim();
	if (trimmed === "") {
		throw new SpecValidationError('empty interpolation token "{}"');
	}

	const pipeIdx = trimmed.indexOf("|");
	if (pipeIdx === -1) return parseBase(trimmed);

	const left = trimmed.slice(0, pipeIdx).trim();
	const right = trimmed.slice(pipeIdx + 1).trim();
	if (right.includes("|")) {
		throw new SpecValidationError(
			`only a single "| where FIELD" filter is allowed in "{${trimmed}}"`,
		);
	}
	const filter = right.match(RE_WHERE);
	if (!filter) {
		throw new SpecValidationError(
			`unsupported filter "${right}" in "{${trimmed}}" (only "| where FIELD" is allowed)`,
		);
	}
	return { kind: "where", base: parseBase(left), field: filter[1] };
}

function getResults(ctx: InterpContext, phase: string): unknown[] {
	const results = ctx.results?.[phase];
	if (results === undefined) {
		throw new SpecValidationError(
			`interpolation references unknown phase "${phase}"`,
		);
	}
	if (!Array.isArray(results)) {
		throw new SpecValidationError(`phase "${phase}" results is not an array`);
	}
	return results;
}

function getFailures(ctx: InterpContext, phase: string): unknown[] {
	const failures = ctx.failures?.[phase];
	if (failures === undefined) {
		throw new SpecValidationError(
			`interpolation references unknown phase "${phase}"`,
		);
	}
	if (!Array.isArray(failures)) {
		throw new SpecValidationError(`phase "${phase}" failures is not an array`);
	}
	return failures;
}

function resolveBase(base: Base, ctx: InterpContext): unknown {
	switch (base.kind) {
		case "item":
			return ctx.item;
		case "args":
			return ctx.args?.[base.name];
		case "results":
			// Retain nulls positionally — callers depend on length.
			return getResults(ctx, base.phase);
		case "failures":
			return getFailures(ctx, base.phase);
		case "flatten": {
			const out: unknown[] = [];
			for (const el of getResults(ctx, base.phase)) {
				if (el === null || el === undefined) continue; // skip null elements
				if (!isRecord(el)) continue;
				const field = el[base.field];
				// Only arrays contribute; missing / null / non-array FIELDs skipped.
				if (Array.isArray(field)) out.push(...field);
			}
			return out;
		}
	}
}

function resolveExpr(expr: Expr, ctx: InterpContext): unknown {
	if (expr.kind === "where") {
		const source = resolveBase(expr.base, ctx);
		if (!Array.isArray(source)) {
			throw new SpecValidationError(
				`"| where ${expr.field}" requires an array on its left-hand side`,
			);
		}
		const out: unknown[] = [];
		for (const el of source) {
			if (el === null || el === undefined) continue; // skip null elements
			if (!isRecord(el)) continue; // missing FIELD (not dereferenceable)
			if (el[expr.field]) out.push(el); // keep truthy FIELD
		}
		return out;
	}
	return resolveBase(expr, ctx);
}

/** Render a resolved value into template text: strings verbatim, else compact JSON. */
function renderValue(value: unknown): string {
	if (typeof value === "string") return value;
	if (value === undefined) return "";
	return JSON.stringify(value);
}

/**
 * Substitute every `{...}` token in a prompt template. Each token is resolved
 * against the grammar and rendered (strings verbatim, objects/arrays/scalars as
 * compact JSON). An out-of-grammar token throws.
 */
export function resolveTemplate(template: string, ctx: InterpContext): string {
	return template.replace(RE_TOKEN, (_match, inner: string) =>
		renderValue(resolveExpr(parseExpr(inner), ctx)),
	);
}

/**
 * Resolve a single braced selector expression (`over` / `return`) to its raw
 * value. The whole input must be exactly one `{...}` token.
 */
export function resolveSelector(selector: string, ctx: InterpContext): unknown {
	const match = selector.trim().match(RE_SINGLE_TOKEN);
	if (!match) {
		throw new SpecValidationError(
			`selector must be a single brace-wrapped token, got "${selector}"`,
		);
	}
	return resolveExpr(parseExpr(match[1]), ctx);
}

/**
 * Resolve a `fanout` `over`: an array literal is returned as-is; a string is an
 * interpolation expression that must resolve to an array.
 */
export function resolveOver(over: unknown, ctx: InterpContext): unknown[] {
	if (Array.isArray(over)) return over;
	if (typeof over === "string") {
		const resolved = resolveSelector(over, ctx);
		if (!Array.isArray(resolved)) {
			throw new SpecValidationError(
				`"over" interpolation "${over}" did not resolve to an array`,
			);
		}
		return resolved;
	}
	throw new SpecValidationError(
		`"over" must be an array literal or an interpolation string, got ${typeof over}`,
	);
}