// ultra — real SDK drivers (Task 9). // // The five capabilities the runner injects (`StepDrivers` + `RunnerContext`), // wrapped around the real Pi SDK. Each factory takes its SDK constructor / // function as a PARAMETER so the option construction + request/response mapping // — where every correction lives (#2 fresh inMemory manager, #3/#5 tools // allowlist, #4 auth threading, the P1 resourceLoader isolation requirement) — // is unit-tested offline with fakes. `index.ts` supplies the real // `createAgentSession` / `SessionManager` / `DefaultResourceLoader` / `complete` // imports + the per-call `ctx`. Actually spawning a session, loading resources, // or hitting a model is the deferred Task-10 live gate. // // SDK shapes verified against the in-repo reference call sites: // - createAgentSession resolves to `{ session }` (goal/index.ts:1952). // - DefaultResourceLoader options incl. `noPromptTemplates` (resource-loader.d.ts:37). // - complete(model, {systemPrompt, messages:[{role,content:[{type:"text",text}],timestamp}]}, // {apiKey, headers, signal, cacheRetention}) → {stopReason?, errorMessage?, content:[{type,text}]} // (angel/index.ts:471, devil/index.ts:731, goal/index.ts:2108). // - modelRegistry.find(provider, id) / getApiKeyAndHeaders(model) (goal/index.ts:1752, :2081). import type { CompleteFn, ResolveAuth, ResolvedAuth, ResolveModel, SessionFactory, SessionLike, } from "./runner.ts"; // --------------------------------------------------------------------------- // sessionFactory — wraps createAgentSession with an isolated resource loader // --------------------------------------------------------------------------- /** The subset of the SDK the session factory needs (injected for testing). */ export interface SessionFactoryDeps { createAgentSession: ( opts: Record, ) => Promise<{ session: SessionLike }> | { session: SessionLike }; DefaultResourceLoader: new ( opts: Record, ) => { reload(): Promise }; getAgentDir: () => string; cwd: string; modelRegistry: unknown; /** When true, sub-agents load host extensions (their tools become grantable). * Omitted/false ⇒ isolated (`noExtensions: true`), today's behaviour. */ loadExtensions?: boolean; } export function makeSessionFactory(deps: SessionFactoryDeps): SessionFactory { return async ({ model, thinkingLevel, tools, customTools, sessionManager, }) => { // resourceLoader is REQUIRED for isolation (P1): without it every sub-agent // loads the host repo's extensions (incl. ultra itself), skills, prompt // templates, themes, and context files. reload() MUST complete before the // session is constructed. const resourceLoader = new deps.DefaultResourceLoader({ cwd: deps.cwd, agentDir: deps.getAgentDir(), // Only this flag flips with the setting; the rest stay isolated so // sub-agents never inherit host skills/prompts/themes/context files. noExtensions: !deps.loadExtensions, noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true, }); await resourceLoader.reload(); const { session } = await deps.createAgentSession({ cwd: deps.cwd, model, modelRegistry: deps.modelRegistry, resourceLoader, thinkingLevel, sessionManager, // the fresh inMemory manager (#2 — never a parent-branch fork) tools, // [...step.tools, structuredOutputName] (#3/#5 — filter + active set) customTools, // [structuredOutputTool] — built by the runner from the step schema }); return session; }; } // --------------------------------------------------------------------------- // newSessionManager — a fresh clean in-memory manager per sub-agent // --------------------------------------------------------------------------- export interface NewSessionManagerDeps { SessionManager: { inMemory(cwd: string): unknown }; cwd: string; } /** `RunnerContext.newSessionManager`: mints a fresh in-memory manager per * tool-using sub-agent (never shared, never a branch fork — #2). */ export function makeNewSessionManager( deps: NewSessionManagerDeps, ): () => unknown { return () => deps.SessionManager.inMemory(deps.cwd); } // --------------------------------------------------------------------------- // completeFn — wraps pi-ai `complete` for the tool-less one-shot path // --------------------------------------------------------------------------- interface CompleteApiResponse { stopReason?: string; errorMessage?: string; content?: { type: string; text?: string }[]; usage?: unknown; } export type CompleteApi = ( model: unknown, request: { systemPrompt?: string; messages: { role: "user" | "assistant"; content: { type: "text"; text: string }[]; timestamp: number; }[]; }, options: { apiKey?: string; headers?: Record; signal?: AbortSignal; cacheRetention?: string; }, ) => Promise; export interface CompleteFnDeps { complete: CompleteApi; } export function makeCompleteFn(deps: CompleteFnDeps): CompleteFn { return async (req) => { const res = await deps.complete( req.model, { systemPrompt: req.systemPrompt, messages: req.messages.map((m) => ({ role: m.role, content: [{ type: "text", text: m.content }], timestamp: Date.now(), })), }, { apiKey: req.apiKey, headers: req.headers, signal: req.signal, cacheRetention: "none", }, ); const text = (res.content ?? []) .filter( (c): c is { type: string; text: string } => c.type === "text" && typeof c.text === "string", ) .map((c) => c.text) .join(""); return { text, stopReason: res.stopReason, errorMessage: res.errorMessage, usage: res.usage, }; }; } // --------------------------------------------------------------------------- // resolveModel — "provider/model" ref → Model object, else the host default // --------------------------------------------------------------------------- /** Split a `provider/model` ref on the first slash (goal/index.ts:1745). */ function parseModelRef(ref: string): { provider: string; model: string } { const i = ref.indexOf("/"); if (i <= 0 || i === ref.length - 1) { throw new Error( `ultra: invalid model ref "${ref}" — use "provider/model".`, ); } return { provider: ref.slice(0, i), model: ref.slice(i + 1) }; } export interface ResolveModelDeps { modelRegistry: { find(provider: string, modelId: string): unknown }; /** The host's current model (`ctx.model`) — the default when a step omits `model`. */ defaultModel: unknown; } export function makeResolveModel(deps: ResolveModelDeps): ResolveModel { return (modelRef) => { if (!modelRef) return deps.defaultModel; const { provider, model } = parseModelRef(modelRef); const found = deps.modelRegistry.find(provider, model); if (!found) throw new Error(`ultra: model not found: ${modelRef}`); return found; }; } // --------------------------------------------------------------------------- // resolveAuth — per-model api key + headers // --------------------------------------------------------------------------- export interface ResolveAuthDeps { modelRegistry: { getApiKeyAndHeaders(model: unknown): Promise | ResolvedAuth; }; } export function makeResolveAuth(deps: ResolveAuthDeps): ResolveAuth { return (model) => deps.modelRegistry.getApiKeyAndHeaders(model); }