repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/ultra/engine.ts
RawFile outline
- EngineDeps line 45
- stepRunner line 46
- concurrency line 48
- signal line 52
- onProgress line 54
- PhaseResult line 58
- id line 59
- ran line 61
- ok line 63
- dropped line 65
- PhaseSlotResult line 68
- ok line 69
- value line 70
- reason line 71
- WorkflowResult line 75
- workflow line 76
- phases line 77
- phaseResults line 79
- result line 80
- steered line 81
- runWorkflow line 95
- phaseItems line 206
- resolveStep line 212
- makeForwarder line 218
- wrapControls line 236
// 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 }`.
//
// 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 { StepRunner } 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 EngineDeps {
stepRunner: StepRunner;
/** Default max in-flight steps per phase (a phase may override via `concurrency`). */
concurrency: number;
/** 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;
}
// ---------------------------------------------------------------------------
// 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 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 res = await deps.stepRunner({
step,
item,
phase: phase.id,
agentId,
signal: deps.signal,
onProgress: forward,
});
// 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;
}
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];
return {
workflow: spec.name,
phases,
phaseResults,
result,
steered: steeredBox.value,
};
}
// ---------------------------------------------------------------------------
// Internals
// ---------------------------------------------------------------------------
/** 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(),
};
}