repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ultra/engine.ts

Raw
File outline
// ultra — phase engine (Task 6).
//
// Sequences a workflow's phases, owns the interpolation mini-syntax (it alone
// holds `args` + prior-phase `results`), fans each phase out through the
// concurrency pool, normalises drops/aborts, resolves the `return` selector, and
// produces the documented aggregate `{ workflow, phases, phaseResults, result, steered, tokenUsage }`.
//
// Everything model/network-touching is behind the injected `stepRunner` (Task
// 5's `StepRunner` shape), so this module is fully offline-testable with a fake
// runner. The engine never constructs a session or calls a model itself.
//
// CONTRACT NOTES
//   - The engine resolves `step.prompt` and forwards it to the runner ALREADY
//     RESOLVED; the runner uses it verbatim (runner.ts top-of-file contract).
//   - The engine generates each launched step's `agentId` (`<phase>#<index>`),
//     so it — and only it — can distinguish a launched-but-failed step from an
//     un-launched (aborted) slot. A tool-using step that times out leaves a
//     phantom "running" board row (the hung session never maps `agent_end`), so
//     the engine closes that row with a synthetic `end` carrying a DROP_STATUSES
//     token (`"dropped"`) — NOT the free-form reason (a free-form `status` would
//     be miscounted as "done" by the reducer). The reason rides along as `text`.
//     Idempotent against any `end` the runner already emitted.
//   - The authoritative per-phase `dropped` count is derived from the step
//     results (`isAborted` ∥ `!ok`), independent of the progress stream — the
//     synthetic `end` is board-only.

import {
	type InterpContext,
	resolveOver,
	resolveSelector,
	resolveTemplate,
} from "./interp.ts";
import { isAborted, mapWithConcurrency } from "./pool.ts";
import type { AgentControls, UltraProgressEvent } from "./progress.ts";
import type { RunStepResult, StepRunner, TokenUsage } from "./runner.ts";
import type { Phase, Step, WorkflowSpec } from "./spec.ts";

// ---------------------------------------------------------------------------
// Public contract
// ---------------------------------------------------------------------------

/** Injected engine dependencies — a fake `stepRunner` in tests, the real
 * driver-backed runner in `index.ts`. The engine does not own retries
 * (`maxRetries` lives inside the runner, closed over at `makeStepRunner`). */
export interface WorkflowJournal {
	get(
		key: string,
	): RunStepResult | undefined | Promise<RunStepResult | undefined>;
	set(key: string, result: RunStepResult): void | Promise<void>;
	complete?(): void | Promise<void>;
}

export interface EngineDeps {
	stepRunner: StepRunner;
	/** Default max in-flight steps per phase (a phase may override via `concurrency`). */
	concurrency: number;
	/** Optional resume journal: successful step results are reused by stable step key. */
	journal?: WorkflowJournal;
	/** Abort signal threaded into the pool (stops launching) and the runner
	 * (which fans `session.abort()` to each live session — the signal never
	 * reaches a session itself, validated P1). */
	signal?: AbortSignal;
	/** Live progress sink (overlay or tool surface); absent ⇒ headless no-op. */
	onProgress?: (event: UltraProgressEvent) => void;
}

/** Per-phase tally in the aggregate result. */
export interface PhaseResult {
	id: string;
	/** Steps actually launched (un-launched aborted slots excluded). */
	ran: number;
	/** Launched steps that produced a usable result. */
	ok: number;
	/** Steps that produced no usable result: un-launched (aborted) + launched `ok:false`. */
	dropped: number;
}

export interface PhaseSlotResult {
	ok: boolean;
	value: unknown;
	reason?: string;
}

/** The documented aggregate the `workflow` tool / `/ultra` command returns. */
export interface WorkflowResult {
	workflow: string;
	phases: PhaseResult[];
	/** Full positional step outcomes for every phase, including drop reasons. */
	phaseResults: Record<string, PhaseSlotResult[]>;
	result: unknown;
	steered: boolean;
	tokenUsage: TokenUsage;
}

// ---------------------------------------------------------------------------
// runWorkflow
// ---------------------------------------------------------------------------

/**
 * Run a validated workflow spec to completion. Phases run in order; each phase's
 * `results` (nulls retained positionally) feed the next phase's interpolation.
 * Returns the aggregate result; never throws on a step drop or an abort (those
 * are normalised into the counts). A malformed interpolation token IS a spec
 * authoring error and propagates (fail-fast), not a runtime drop.
 */
export async function runWorkflow(
	spec: WorkflowSpec,
	args: Record<string, unknown> | undefined,
	deps: EngineDeps,
): Promise<WorkflowResult> {
	const results: Record<string, unknown[]> = {};
	const phaseResults: Record<string, PhaseSlotResult[]> = {};
	const phases: PhaseResult[] = [];
	const tokenUsage = zeroUsage();
	const steeredBox = { value: false };
	const forward = makeForwarder(deps, steeredBox);

	for (const phase of spec.phases) {
		// Resolve `over` and every prompt up-front. Both own the interpolation
		// grammar; a bad token throws here (spec authoring error), before any step
		// launches — it is deliberately not a runtime drop.
		const items = phaseItems(phase, { args, results });
		const resolved = items.map((item) => ({
			item,
			step: resolveStep(phase.step, { args, results, item }),
		}));

		const cap = phase.concurrency ?? deps.concurrency;
		const slots = await mapWithConcurrency(
			resolved,
			cap,
			async ({ item, step }, index) => {
				const agentId = `${phase.id}#${index}`;
				const key = stepKey(phase.id, index, item, step);
				const cached = await deps.journal?.get(key);
				if (cached?.ok) {
					forward({ agentId, phase: phase.id, kind: "start", text: "cached" });
					forward({ agentId, phase: phase.id, kind: "end", status: "done" });
					return { ...cached, usage: undefined };
				}
				const res = await deps.stepRunner({
					step,
					item,
					phase: phase.id,
					agentId,
					signal: deps.signal,
					onProgress: forward,
				});
				if (res.ok) await deps.journal?.set(key, res);
				// Launched-but-failed: close the (possibly phantom) board row. Only
				// reached for launched steps — un-launched aborted slots never run
				// this fn, so they correctly get no synthetic end.
				if (!res.ok) {
					forward({
						agentId,
						phase: phase.id,
						kind: "end",
						status: "dropped",
						text: res.reason,
					});
				}
				return res;
			},
			deps.signal,
		);

		// Normalise: aborted (never launched) and `ok:false` both → null value +
		// counted as dropped. Nulls are RETAINED positionally so a later phase's
		// `{PHASE.results}` keeps length/order (interp skips nulls itself).
		let ran = 0;
		let ok = 0;
		let dropped = 0;
		const values: unknown[] = [];
		const outcomeSlots: PhaseSlotResult[] = [];
		for (const slot of slots) {
			if (isAborted(slot)) {
				dropped++;
				values.push(null);
				outcomeSlots.push({ ok: false, value: null, reason: "aborted" });
				continue;
			}
			addUsage(tokenUsage, slot.usage);
			ran++;
			if (slot.ok) {
				ok++;
				values.push(slot.value);
				outcomeSlots.push({ ok: true, value: slot.value });
				continue;
			}
			dropped++;
			values.push(null);
			outcomeSlots.push({
				ok: false,
				value: null,
				reason: slot.reason ?? "dropped",
			});
		}

		results[phase.id] = values;
		phaseResults[phase.id] = outcomeSlots;
		phases.push({ id: phase.id, ran, ok, dropped });
		// An all-dropped phase (`ok === 0`) is left visible in these counts and the
		// workflow continues — a later phase may legitimately act on an empty set.
	}

	const lastPhase = spec.phases[spec.phases.length - 1];
	const result =
		spec.return !== undefined
			? resolveSelector(spec.return, { args, results })
			: results[lastPhase.id];

	if (!deps.signal?.aborted) await deps.journal?.complete?.();

	return {
		workflow: spec.name,
		phases,
		phaseResults,
		result,
		steered: steeredBox.value,
		tokenUsage,
	};
}

// ---------------------------------------------------------------------------
// Internals
// ---------------------------------------------------------------------------

function zeroUsage(): TokenUsage {
	return {
		input: 0,
		output: 0,
		total: 0,
		cacheRead: 0,
		cacheWrite: 0,
		cost: 0,
	};
}

function addUsage(into: TokenUsage, usage: TokenUsage | undefined): void {
	if (!usage) return;
	into.input += usage.input;
	into.output += usage.output;
	into.total += usage.total;
	into.cacheRead += usage.cacheRead;
	into.cacheWrite += usage.cacheWrite;
	into.cost += usage.cost;
}

function stepKey(
	phase: string,
	index: number,
	item: unknown,
	step: Step,
): string {
	return JSON.stringify({ phase, index, item, step });
}

/** The fanout/single item list. `single` runs its step exactly once (any `over`
 * is ignored in v1); `fanout` resolves `over` to its element array. */
function phaseItems(phase: Phase, ctx: InterpContext): unknown[] {
	if (phase.kind === "fanout") return resolveOver(phase.over, ctx);
	return [undefined];
}

/** Resolve a step's prompt template; the runner receives the result verbatim. */
function resolveStep(step: Step, ctx: InterpContext): Step {
	return { ...step, prompt: resolveTemplate(step.prompt, ctx) };
}

/** Build the progress forwarder: forwards every runner event to `deps.onProgress`,
 * wrapping any attached `controls` so the engine learns of a human steer. */
function makeForwarder(
	deps: EngineDeps,
	steeredBox: { value: boolean },
): (event: UltraProgressEvent) => void {
	return (event) => {
		const sink = deps.onProgress;
		if (!sink) return;
		if (event.controls) {
			sink({ ...event, controls: wrapControls(event.controls, steeredBox) });
		} else {
			sink(event);
		}
	};
}

/** Wrap runner-bound controls so a steer flips the aggregate `steered` flag at
 * call time (enqueue-time taint semantics, Task 7c) while still delegating to
 * the underlying control. `abort` passes through unchanged. */
function wrapControls(
	controls: AgentControls,
	steeredBox: { value: boolean },
): AgentControls {
	return {
		steer: (text: string) => {
			steeredBox.value = true;
			return controls.steer(text);
		},
		abort: () => controls.abort(),
	};
}