repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/ultra/runner.ts
Raw// ultra — step runner (Task 5).
//
// Dispatches a single workflow `Step` to one of two execution paths and returns
// a uniform `RunStepResult`:
//
// - tool-LESS step → `drivers.completeFn` (one-shot JSON generation, the
// goal-judge / devil-synthesis pattern): strip a fenced ```json block,
// parse, schema-validate, retry-with-corrective up to `maxRetries`.
// - tool-USING step → `drivers.sessionFactory` (an ephemeral
// `createAgentSession` sub-agent restricted to `step.tools`): a terminating
// StructuredOutput tool whose validated `details` is the result.
//
// Every external capability is INJECTED via `drivers` + `ctxLike` so this module
// is unit-tested offline with fakes; `index.ts` (Task 9) supplies the real ones
// (wrapping `complete()` from pi-ai and `createAgentSession()` +
// `SessionManager.inMemory(ctx.cwd)`).
//
// CONTRACT — the prompt is NOT interpolated here. `step.prompt` MUST arrive
// already fully resolved by the engine (Task 6), which owns the interpolation
// mini-syntax (it alone holds `args` + prior-phase `results`). The runner uses
// `step.prompt` verbatim; re-resolving it here would mis-parse a resolved
// `{item}` object literal (compact JSON braces) as a template token.
//
// Validated SDK facts honoured (prototypes P1/P4):
// - `createAgentSession`/`prompt` take NO external AbortSignal — the only way
// to stop a running sub-agent is the instance method `session.abort()`, so
// BOTH the timeout and the external-abort paths call it.
// - streaming text arrives on `event.assistantMessageEvent` as
// `{ type:"text_delta", delta }`; a terminating tool's structured payload is
// on `tool_execution_end.result.details` (read by progress.ts's mapper).
import type { AgentSessionEvent } from "@earendil-works/pi-coding-agent";
import {
type AgentControls,
mapSessionEvent,
type UltraProgressEvent,
} from "./progress.ts";
import type { ModelTiers } from "./settings.ts";
import { compileSchema, type Step, type ThinkingLevel } from "./spec.ts";
// ---------------------------------------------------------------------------
// Public result + driver/context contracts (Task 9 supplies real, tests fake)
// ---------------------------------------------------------------------------
/** Uniform outcome of running one step. `value` is `null` when `ok` is false. */
export interface RunStepResult {
ok: boolean;
value: unknown;
reason?: string;
usage?: TokenUsage;
}
/** Per-model auth, mirroring `ModelRegistry.getApiKeyAndHeaders`. */
export interface ResolvedAuth {
ok?: boolean;
apiKey?: string;
headers?: Record<string, string>;
error?: string;
}
/** One turn threaded into the tool-less `completeFn` request. */
export interface CompleteMessage {
role: "user" | "assistant";
content: string;
}
/** What the runner hands the injected `completeFn` (real one wraps pi-ai `complete`). */
export interface CompleteRequest {
model: unknown;
systemPrompt?: string;
messages: CompleteMessage[];
apiKey?: string;
headers?: Record<string, string>;
signal?: AbortSignal;
}
/** Normalised completion: assistant text + the provider stop reason. */
export interface TokenUsage {
input: number;
output: number;
total: number;
cacheRead: number;
cacheWrite: number;
cost: number;
}
export interface CompleteResponse {
text: string;
stopReason?: string;
errorMessage?: string;
usage?: unknown;
}
export type CompleteFn = (req: CompleteRequest) => Promise<CompleteResponse>;
/**
* Minimal structural shape of the terminating StructuredOutput tool the runner
* builds and the session factory forwards into `createAgentSession({ customTools })`.
* Execute positional args match the SDK `ToolDefinition.execute` so a real
* session invokes it unchanged.
*/
export interface StructuredOutputTool {
name: string;
label: string;
description: string;
parameters: object;
execute(
toolCallId: string,
params: unknown,
signal: AbortSignal | undefined,
onUpdate: ((partial: unknown) => void) | undefined,
ctx: unknown,
): Promise<{ content: unknown[]; details: unknown; terminate?: boolean }>;
}
/** Args the runner passes to the injected `sessionFactory`. */
export interface SessionFactoryArgs {
model: unknown;
thinkingLevel?: ThinkingLevel;
/** `[...step.tools, STRUCTURED_OUTPUT_TOOL_NAME]` — name appended (correction #5). */
tools: string[];
/** Contains the terminating StructuredOutput tool. */
customTools: StructuredOutputTool[];
/** A fresh in-memory manager (never a parent-branch fork — correction #2). */
sessionManager: unknown;
}
/** Subset of `AgentSession` the runner drives. */
export interface SessionLike {
subscribe(listener: (event: AgentSessionEvent) => void): () => void;
prompt(text: string, options?: { source?: string }): Promise<void>;
steer(text: string): Promise<void> | void;
abort(): Promise<void> | void;
dispose(): void;
}
export type SessionFactory = (args: SessionFactoryArgs) => Promise<SessionLike>;
export type ResolveModel = (model: string | undefined) => unknown;
export type ResolveAuth = (
model: unknown,
) => Promise<ResolvedAuth> | ResolvedAuth;
/** The injected drivers — fakes in tests, real wrappers in `index.ts`. */
export interface StepDrivers {
completeFn: CompleteFn;
sessionFactory: SessionFactory;
resolveModel: ResolveModel;
resolveAuth: ResolveAuth;
}
/**
* Context-like capabilities the runner needs beyond the drivers. `newSessionManager`
* mints a fresh, clean in-memory manager per tool-using sub-agent; `index.ts`
* supplies `() => SessionManager.inMemory(ctx.cwd)`.
*/
export interface RunnerContext {
newSessionManager: () => unknown;
}
/** Run-level options closed over by `makeStepRunner`. */
export interface BaseStepOptions {
maxRetries: number;
defaultTimeoutMs: number;
/** Named schemas (`spec.schemas`) for resolving a `step.schema` string ref. */
schemas?: Record<string, object>;
/** Optional local aliases used by step.model: small|medium|big. */
modelTiers?: ModelTiers;
/** Optional extra system-prompt text for the tool-less path. */
systemPrompt?: string;
}
/** Full options for one `runStep` call (run-level ⊕ per-call). */
export interface RunStepOptions extends BaseStepOptions {
/** Current fanout item — metadata only; the prompt is already resolved. */
item?: unknown;
phase: string;
agentId: string;
signal?: AbortSignal;
onProgress?: (event: UltraProgressEvent) => void;
}
/** Per-call args the engine passes to a `StepRunner`. */
export interface StepRunnerArgs {
step: Step;
item?: unknown;
phase: string;
agentId: string;
signal?: AbortSignal;
onProgress?: (event: UltraProgressEvent) => void;
}
/** The single function shape the engine (Task 6) consumes. */
export type StepRunner = (args: StepRunnerArgs) => Promise<RunStepResult>;
/** Name of the injected terminating StructuredOutput tool (appended to the allowlist). */
export const STRUCTURED_OUTPUT_TOOL_NAME = "structured_output";
/** ultra's own model-callable tools, stripped from every sub-agent allowlist so
* a sub-agent (which may load ultra when `subagentExtensions: "all"`) can never
* re-enter the workflow engine, regardless of what a step lists. */
export const ULTRA_OWN_TOOL_NAMES = ["workflow"] as const;
function sanitizeSubagentTools(tools: string[] | undefined): string[] {
const own = ULTRA_OWN_TOOL_NAMES as readonly string[];
return (tools ?? []).filter((t) => !own.includes(t));
}
// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------
/** A compiled validator (subset of `compileSchema`'s return). */
interface CompiledValidator {
Check(value: unknown): boolean;
Errors(value: unknown): { instancePath?: string; message?: string }[];
}
/** No-op controls for the tool-less `complete()` path (no live session to drive). */
const NOOP_CONTROLS: AgentControls = {
steer: () => {},
abort: () => {},
};
/**
* Resolve a step's `schema` to a concrete JSON Schema object: a string is a
* named reference into `opts.schemas`; an object is an inline schema; `undefined`
* means "no validation". A dangling named ref is treated as "no validation"
* here (the spec parser already rejects unknown names at load time).
*/
function resolveStepSchema(
step: Step,
opts: BaseStepOptions,
): object | undefined {
const ref = step.schema;
if (ref === undefined) return undefined;
if (typeof ref === "string") return opts.schemas?.[ref];
return ref;
}
function isModelTierName(value: string): value is keyof ModelTiers {
return value === "small" || value === "medium" || value === "big";
}
function splitTierSpec(spec: string): {
model: string;
thinkingLevel?: ThinkingLevel;
} {
const match = spec.match(/^(.*):(off|minimal|low|medium|high|xhigh)$/);
if (!match) return { model: spec };
return { model: match[1], thinkingLevel: match[2] as ThinkingLevel };
}
function requestedTier(step: Step): string | undefined {
return step.model && isModelTierName(step.model) ? step.model : undefined;
}
function modelLabel(
model: unknown,
fallback: string | undefined,
): string | undefined {
if (model && typeof model === "object") {
const value = model as { provider?: unknown; id?: unknown };
if (typeof value.provider === "string" && typeof value.id === "string")
return `${value.provider}/${value.id}`;
if (typeof value.id === "string") return fallback ?? value.id;
}
return fallback;
}
function resolveModelTier(step: Step, tiers: ModelTiers | undefined): Step {
if (!step.model || !isModelTierName(step.model)) return step;
const tier = tiers?.[step.model];
if (!tier) {
const { model: _model, ...withoutModel } = step;
return withoutModel;
}
const resolved = splitTierSpec(tier);
return {
...step,
model: resolved.model,
thinkingLevel: step.thinkingLevel ?? resolved.thinkingLevel,
};
}
function number(value: unknown): number {
const n = Number(value ?? 0);
return Number.isFinite(n) ? n : 0;
}
function usageCost(usage: Record<string, unknown>): number {
const cost = usage.cost;
return typeof cost === "object" && cost !== null
? number((cost as Record<string, unknown>).total)
: number(cost);
}
function normalizeUsage(usage: unknown): TokenUsage | undefined {
if (!usage || typeof usage !== "object" || Array.isArray(usage))
return undefined;
const u = usage as Record<string, unknown>;
const input = number(u.input);
const output = number(u.output);
const total = number(u.total ?? u.totalTokens ?? input + output);
return {
input,
output,
total,
cacheRead: number(u.cacheRead),
cacheWrite: number(u.cacheWrite),
cost: usageCost(u),
};
}
function lastAssistantUsage(messages: unknown): TokenUsage | undefined {
if (!Array.isArray(messages)) return undefined;
for (let i = messages.length - 1; i >= 0; i--) {
const message = messages[i];
if (!message || typeof message !== "object") continue;
const m = message as Record<string, unknown>;
if (m.role === "assistant") return normalizeUsage(m.usage);
}
return undefined;
}
/** Strip a leading ```json (or ```) fence and a trailing ``` fence (angel's behavior). */
function stripFences(raw: string): string {
const FENCE_OPEN = /^\s*`{3}(?:json)?\s*\n?/i;
const FENCE_CLOSE = /\n?`{3}\s*$/;
return raw.replace(FENCE_OPEN, "").replace(FENCE_CLOSE, "").trim();
}
type ParseResult = { ok: true; value: unknown } | { ok: false; reason: string };
/** Fence-strip + parse the first JSON object found in a completion. */
function parseJsonObject(text: string): ParseResult {
const stripped = stripFences(text);
const first = stripped.indexOf("{");
if (first === -1) return { ok: false, reason: "no JSON object in response" };
try {
return { ok: true, value: JSON.parse(stripped.slice(first)) };
} catch (err) {
const reason = err instanceof Error ? err.message : String(err);
return { ok: false, reason: `invalid JSON: ${reason}` };
}
}
/** Render a validator's errors as a single human-readable line. */
function formatValidatorErrors(
validator: CompiledValidator,
value: unknown,
): string {
return validator
.Errors(value)
.map((e) => `${e.instancePath || "(root)"}: ${e.message ?? "invalid"}`)
.join("; ");
}
type GuardOutcome<T> =
| { outcome: "done"; value: T; error?: unknown }
| { outcome: "timeout" }
| { outcome: "aborted" };
/**
* Race `work` against a per-call timeout and an external abort signal. `work`
* receives an internal `AbortSignal` that fires on timeout/abort — the tool-less
* `complete()` path threads it through; the session path ignores it (sessions
* accept no external signal — P1) and the caller calls `session.abort()` itself.
* Resolves (never rejects); a thrown `work` is reported as `done` with `value`
* left `undefined` so the caller can retry/drop.
*/
async function raceGuards<T>(
work: (signal: AbortSignal) => Promise<T>,
timeoutMs: number,
externalSignal: AbortSignal | undefined,
): Promise<GuardOutcome<T>> {
if (externalSignal?.aborted) return { outcome: "aborted" };
const controller = new AbortController();
let timeoutId: ReturnType<typeof setTimeout> | undefined;
let onAbort: (() => void) | undefined;
const guard = new Promise<GuardOutcome<T>>((resolve) => {
timeoutId = setTimeout(() => {
controller.abort();
resolve({ outcome: "timeout" });
}, timeoutMs);
if (externalSignal) {
onAbort = () => {
controller.abort();
resolve({ outcome: "aborted" });
};
externalSignal.addEventListener("abort", onAbort, { once: true });
}
});
const workP: Promise<GuardOutcome<T>> = work(controller.signal).then(
(value) => ({ outcome: "done", value }) as GuardOutcome<T>,
// A thrown `work` is reported as `done` with no `value` so the caller can
// retry/drop — but the error rides along on `error` so the drop reason can
// name the real failure (an API/auth throw from `complete`) instead of the
// misleading downstream "no JSON object in response".
(error) =>
({
outcome: "done",
value: undefined as unknown as T,
error,
}) as GuardOutcome<T>,
);
try {
return await Promise.race([workP, guard]);
} finally {
if (timeoutId) clearTimeout(timeoutId);
if (externalSignal && onAbort)
externalSignal.removeEventListener("abort", onAbort);
}
}
// ---------------------------------------------------------------------------
// runStep
// ---------------------------------------------------------------------------
export async function runStep(
step: Step,
ctxLike: RunnerContext,
drivers: StepDrivers,
opts: RunStepOptions,
): Promise<RunStepResult> {
const tier = requestedTier(step);
const resolvedStep = resolveModelTier(step, opts.modelTiers);
const schemaObj = resolveStepSchema(resolvedStep, opts);
const validator = schemaObj
? (compileSchema(schemaObj) as CompiledValidator)
: undefined;
const timeoutMs = resolvedStep.timeoutMs ?? opts.defaultTimeoutMs;
const usesTools =
Array.isArray(resolvedStep.tools) && resolvedStep.tools.length > 0;
return usesTools
? runToolStep(
resolvedStep,
ctxLike,
drivers,
opts,
schemaObj,
validator,
timeoutMs,
tier,
)
: runCompleteStep(resolvedStep, drivers, opts, validator, timeoutMs, tier);
}
// ---- tool-less path -------------------------------------------------------
async function runCompleteStep(
step: Step,
drivers: StepDrivers,
opts: RunStepOptions,
validator: CompiledValidator | undefined,
timeoutMs: number,
tier: string | undefined,
): Promise<RunStepResult> {
const startedAt = Date.now();
const model = drivers.resolveModel(step.model);
emitCompleteStart(opts, {
tier,
model: modelLabel(model, step.model),
thinkingLevel: step.thinkingLevel,
startedAt,
});
const auth = await drivers.resolveAuth(model);
if (!auth.ok) {
return finishComplete(opts, {
ok: false,
value: null,
reason: auth.error ?? "model auth unavailable",
});
}
const messages: CompleteMessage[] = [{ role: "user", content: step.prompt }];
let lastReason = "schema validation failed";
for (let attempt = 0; attempt <= opts.maxRetries; attempt++) {
const attemptResult = await completeAttempt({
drivers,
model,
auth,
messages,
validator,
systemPrompt: completeSystemPrompt(opts.systemPrompt),
timeoutMs,
signal: opts.signal,
});
if (attemptResult.done) return finishComplete(opts, attemptResult.result);
lastReason = attemptResult.reason;
if (attempt < opts.maxRetries)
appendCorrection(messages, attemptResult.text, lastReason);
}
return finishComplete(opts, { ok: false, value: null, reason: lastReason });
}
function emitCompleteStart(
opts: RunStepOptions,
meta: Pick<
UltraProgressEvent,
"tier" | "model" | "thinkingLevel" | "startedAt"
>,
): void {
opts.onProgress?.({
agentId: opts.agentId,
phase: opts.phase,
kind: "start",
...meta,
controls: NOOP_CONTROLS,
});
}
function finishComplete(
opts: RunStepOptions,
result: RunStepResult,
): RunStepResult {
// `status` must be a reducer token. The free-form reason rides on `text`.
opts.onProgress?.({
agentId: opts.agentId,
phase: opts.phase,
kind: "end",
status: result.ok ? "done" : "dropped",
text: result.ok ? undefined : result.reason,
usage: result.usage,
controls: NOOP_CONTROLS,
});
return result;
}
function completeSystemPrompt(extra: string | undefined): string {
return [
extra,
"Respond with ONLY a single JSON object — no prose, no markdown code fences.",
]
.filter(Boolean)
.join("\n\n");
}
type CompleteAttempt =
| { done: true; result: RunStepResult }
| { done: false; reason: string; text: string };
interface CompleteAttemptInput {
drivers: StepDrivers;
model: unknown;
auth: ResolvedAuth;
messages: CompleteMessage[];
validator: CompiledValidator | undefined;
systemPrompt: string;
timeoutMs: number;
signal?: AbortSignal;
}
async function completeAttempt(
input: CompleteAttemptInput,
): Promise<CompleteAttempt> {
const guarded = await raceGuards(
(signal) =>
input.drivers.completeFn({
model: input.model,
systemPrompt: input.systemPrompt,
messages: input.messages,
apiKey: input.auth.apiKey,
headers: input.auth.headers,
signal,
}),
input.timeoutMs,
input.signal,
);
if (guarded.outcome === "timeout")
return {
done: true,
result: { ok: false, value: null, reason: "timeout" },
};
if (guarded.outcome === "aborted")
return {
done: true,
result: { ok: false, value: null, reason: "aborted" },
};
return evaluateCompletion(guarded, input.validator);
}
function evaluateCompletion(
guarded: Extract<GuardOutcome<CompleteResponse>, { outcome: "done" }>,
validator: CompiledValidator | undefined,
): CompleteAttempt {
const response = guarded.value;
const text = response?.text ?? "";
const transportFailure = completionFailureReason(response, guarded.error);
if (transportFailure) return { done: false, reason: transportFailure, text };
return evaluateJson(text, validator, normalizeUsage(response.usage));
}
function completionFailureReason(
response: CompleteResponse | undefined,
error: unknown,
): string | undefined {
if (!response || error !== undefined) {
return error instanceof Error
? `completion failed: ${error.message}`
: "completion failed (no response)";
}
return response.errorMessage
? `model error: ${response.errorMessage}`
: undefined;
}
function evaluateJson(
text: string,
validator: CompiledValidator | undefined,
usage: TokenUsage | undefined,
): CompleteAttempt {
const parsed = parseJsonObject(text);
if (!parsed.ok) return { done: false, reason: parsed.reason, text };
if (validator && !validator.Check(parsed.value)) {
return {
done: false,
reason: `schema validation failed: ${formatValidatorErrors(validator, parsed.value)}`,
text,
};
}
return { done: true, result: { ok: true, value: parsed.value, usage } };
}
function appendCorrection(
messages: CompleteMessage[],
badText: string,
reason: string,
): void {
messages.push({ role: "assistant", content: badText });
messages.push({
role: "user",
content: `Your previous response was invalid (${reason}). Respond again with ONLY a valid JSON object matching the required schema.`,
});
}
// ---- tool-using path ------------------------------------------------------
async function runToolStep(
step: Step,
ctxLike: RunnerContext,
drivers: StepDrivers,
opts: RunStepOptions,
schemaObj: object | undefined,
validator: CompiledValidator | undefined,
timeoutMs: number,
tier: string | undefined,
): Promise<RunStepResult> {
const { agentId, phase, onProgress } = opts;
const startedAt = Date.now();
const model = drivers.resolveModel(step.model);
const meta = {
tier,
model: modelLabel(model, step.model),
thinkingLevel: step.thinkingLevel,
startedAt,
};
// The terminating StructuredOutput tool: validates the model's call against
// the step schema, captures the validated payload as the step result, and
// ends the sub-agent loop via `terminate: true`. An invalid call throws,
// surfacing a retryable tool-error to the model (the in-session retry).
let captured: { value: unknown } | undefined;
const structuredOutputTool: StructuredOutputTool = {
name: STRUCTURED_OUTPUT_TOOL_NAME,
label: "Structured Output",
description: "Return the final structured result for this step and finish.",
parameters: schemaObj ?? { type: "object", additionalProperties: true },
async execute(_toolCallId, params) {
if (validator && !validator.Check(params)) {
throw new Error(
`${STRUCTURED_OUTPUT_TOOL_NAME}: schema validation failed: ${formatValidatorErrors(validator, params)}`,
);
}
captured = { value: params };
return {
content: [{ type: "text", text: "Structured output recorded." }],
details: params,
terminate: true,
};
},
};
const sessionManager = ctxLike.newSessionManager();
let session: SessionLike | undefined;
let unsubscribe: () => void = () => {};
let usage: TokenUsage | undefined;
try {
session = await drivers.sessionFactory({
model,
thinkingLevel: step.thinkingLevel,
// The structured-output tool name is APPENDED to the step allowlist
// (correction #5) — it must be present or the registry filters it out.
// ultra's own `workflow` tool is stripped first (recursion defense).
tools: [
...sanitizeSubagentTools(step.tools),
STRUCTURED_OUTPUT_TOOL_NAME,
],
customTools: [structuredOutputTool],
sessionManager,
});
const live = session;
const controls: AgentControls = {
steer: (text: string) =>
Promise.resolve(live.steer(text)).catch(() => {}),
abort: () => Promise.resolve(live.abort()).catch(() => {}),
};
unsubscribe = session.subscribe((event) => {
if (event.type === "agent_end") {
usage = lastAssistantUsage((event as { messages?: unknown }).messages);
}
const mapped = mapSessionEvent(event, agentId, phase);
if (mapped)
onProgress?.({
...mapped,
...meta,
usage: mapped.kind === "end" ? usage : undefined,
controls,
});
});
const guarded = await raceGuards(
() => live.prompt(step.prompt, { source: "extension" }),
timeoutMs,
opts.signal,
);
if (guarded.outcome !== "done") {
// Sessions accept no external signal (P1) — the ONLY way to stop a
// running sub-agent is its own `abort()`, on both timeout and abort.
await Promise.resolve(live.abort()).catch(() => {});
return { ok: false, value: null, reason: guarded.outcome };
}
if (captured) return { ok: true, value: captured.value, usage };
return { ok: false, value: null, reason: "no structured output produced" };
} finally {
unsubscribe();
session?.dispose();
}
}
// ---------------------------------------------------------------------------
// makeStepRunner
// ---------------------------------------------------------------------------
export function makeStepRunner(
drivers: StepDrivers,
ctxLike: RunnerContext,
baseOpts: BaseStepOptions,
): StepRunner {
return (args: StepRunnerArgs) =>
runStep(args.step, ctxLike, drivers, {
...baseOpts,
item: args.item,
phase: args.phase,
agentId: args.agentId,
signal: args.signal,
onProgress: args.onProgress,
});
}