// 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 { 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; } /** Per-model auth, mirroring `ModelRegistry.getApiKeyAndHeaders`. */ export interface ResolvedAuth { ok?: boolean; apiKey?: string; headers?: Record; 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; signal?: AbortSignal; } /** Normalised completion: assistant text + the provider stop reason. */ export interface CompleteResponse { text: string; stopReason?: string; errorMessage?: string; } export type CompleteFn = (req: CompleteRequest) => Promise; /** * 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; steer(text: string): Promise | void; abort(): Promise | void; dispose(): void; } export type SessionFactory = (args: SessionFactoryArgs) => Promise; export type ResolveModel = (model: string | undefined) => unknown; export type ResolveAuth = ( model: unknown, ) => Promise | 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; /** 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; /** 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; } /** 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 = | { 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( work: (signal: AbortSignal) => Promise, timeoutMs: number, externalSignal: AbortSignal | undefined, ): Promise> { if (externalSignal?.aborted) return { outcome: "aborted" }; const controller = new AbortController(); let timeoutId: ReturnType | undefined; let onAbort: (() => void) | undefined; const guard = new Promise>((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> = work(controller.signal).then( (value) => ({ outcome: "done", value }) as GuardOutcome, // 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, ); 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 { const schemaObj = resolveStepSchema(step, opts); const validator = schemaObj ? (compileSchema(schemaObj) as CompiledValidator) : undefined; const timeoutMs = step.timeoutMs ?? opts.defaultTimeoutMs; const usesTools = Array.isArray(step.tools) && step.tools.length > 0; return usesTools ? runToolStep(step, ctxLike, drivers, opts, schemaObj, validator, timeoutMs) : runCompleteStep(step, drivers, opts, validator, timeoutMs); } // ---- tool-less path ------------------------------------------------------- async function runCompleteStep( step: Step, drivers: StepDrivers, opts: RunStepOptions, validator: CompiledValidator | undefined, timeoutMs: number, ): Promise { emitCompleteStart(opts); const model = drivers.resolveModel(step.model); 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): void { opts.onProgress?.({ agentId: opts.agentId, phase: opts.phase, kind: "start", 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, 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 { 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, { 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); } 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, ): 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 } }; } 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, ): Promise { const { agentId, phase, onProgress } = opts; const model = drivers.resolveModel(step.model); // 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 = () => {}; 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) => { const mapped = mapSessionEvent(event, agentId, phase); if (mapped) onProgress?.({ ...mapped, 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 }; 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, }); }