import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { DefaultResourceLoader } from "@earendil-works/pi-coding-agent"; import { describe, expect, it, vi } from "vitest"; import { makeCompleteFn, makeNewSessionManager, makeResolveAuth, makeResolveModel, makeSessionFactory, } from "../drivers.ts"; import type { SessionLike } from "../runner.ts"; // These tests assert the OPTION CONSTRUCTION + request/response MAPPING of the // real drivers — the place every correction (#2 fresh inMemory manager, #3/#5 // tools allowlist, #4 auth threading, the P1 resourceLoader isolation // requirement) lives — by injecting fake SDK constructors/functions and // inspecting how they're called. Actually spawning a session, loading // resources, or hitting a model is the deferred Task-10 live gate; a fake proves // only that the wiring passes the right shapes, which is exactly the bug class // the corrections guard. const fakeSession: SessionLike = { subscribe: () => () => {}, prompt: async () => {}, steer: () => {}, abort: () => {}, dispose: () => {}, }; describe("makeSessionFactory", () => { it("constructs an isolated, reloaded session with the goal-proven option set", async () => { const reload = vi.fn().mockResolvedValue(undefined); const loaderOpts: unknown[] = []; class FakeLoader { reload = reload; constructor(opts: unknown) { loaderOpts.push(opts); } } // The real createAgentSession resolves to `{ session }` (destructured). const createAgentSession = vi.fn(async () => ({ session: fakeSession })); const factory = makeSessionFactory({ createAgentSession, DefaultResourceLoader: FakeLoader as any, getAgentDir: () => "/agent", cwd: "/work", }); const sessionManager = { id: "fresh-inmemory" }; const customTools = [{ name: "structured_output" }]; const session = await factory({ model: { id: "m" }, thinkingLevel: "low", tools: ["read", "structured_output"], customTools: customTools as any, sessionManager, }); // resourceLoader REQUIRED, isolated (every no* flag), reload() awaited BEFORE construction. expect(loaderOpts[0]).toEqual({ cwd: "/work", agentDir: "/agent", noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true, }); expect(reload).toHaveBeenCalledTimes(1); expect(reload.mock.invocationCallOrder[0]).toBeLessThan( createAgentSession.mock.invocationCallOrder[0], ); // The full option set, with every correction asserted. const opts = createAgentSession.mock.calls[0][0] as Record; expect(opts.cwd).toBe("/work"); expect(opts.model).toEqual({ id: "m" }); expect(opts).not.toHaveProperty("modelRegistry"); expect(opts.resourceLoader).toBeInstanceOf(FakeLoader); expect(opts.thinkingLevel).toBe("low"); expect(opts.sessionManager).toBe(sessionManager); // fresh inMemory, NOT a branch fork (#2) expect(opts.tools).toEqual(["read", "structured_output"]); // [...step.tools, name] (#3/#5) expect(opts.customTools).toBe(customTools); // Returns the destructured `.session`, not the wrapper. expect(session).toBe(fakeSession); }); it("loads extensions and skills independently while preserving other isolation", async () => { const loaderOpts: Record[] = []; class FakeLoader { reload = vi.fn().mockResolvedValue(undefined); constructor(opts: Record) { loaderOpts.push(opts); } } const createAgentSession = vi.fn(async () => ({ session: fakeSession })); const factory = makeSessionFactory({ createAgentSession, DefaultResourceLoader: FakeLoader as any, getAgentDir: () => "/agent", cwd: "/work", loadExtensions: true, loadSkills: true, }); await factory({ model: {}, tools: ["web_search", "structured_output"], customTools: [], sessionManager: {}, }); expect(loaderOpts[0].noExtensions).toBe(false); expect(loaderOpts[0].noSkills).toBe(false); expect(createAgentSession.mock.calls[0][0].tools).toEqual([ "web_search", "structured_output", "read", ]); expect(loaderOpts[0].noPromptTemplates).toBe(true); expect(loaderOpts[0].noThemes).toBe(true); expect(loaderOpts[0].noContextFiles).toBe(true); }); }); describe("sub-agent skill discovery", () => { it("loads skills by default and supports complete opt-out", async () => { const root = await mkdtemp(join(tmpdir(), "ultra-skills-")); const agentDir = join(root, "agent"); const skillDir = join(agentDir, "skills", "ultra-skill-probe"); await mkdir(skillDir, { recursive: true }); await writeFile( join(skillDir, "SKILL.md"), "---\nname: ultra-skill-probe\ndescription: Verifies Ultra skill discovery.\n---\n\n# Probe\n", ); try { const loader = new DefaultResourceLoader({ cwd: root, agentDir, noExtensions: true, noSkills: false, noPromptTemplates: true, noThemes: true, noContextFiles: true, }); await loader.reload(); expect(loader.getSkills().skills.map((skill) => skill.name)).toContain( "ultra-skill-probe", ); const disabled = new DefaultResourceLoader({ cwd: root, agentDir, noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true, }); await disabled.reload(); expect(disabled.getSkills().skills).toEqual([]); } finally { await rm(root, { recursive: true, force: true }); } }); }); describe("makeNewSessionManager", () => { it("mints a fresh in-memory manager bound to cwd on every call", () => { const made: unknown[] = []; const SessionManager = { inMemory: vi.fn((cwd: string) => { const m = { cwd, n: made.length }; made.push(m); return m; }), }; const mint = makeNewSessionManager({ SessionManager, cwd: "/work" }); const a = mint(); const b = mint(); expect(SessionManager.inMemory).toHaveBeenCalledTimes(2); expect(SessionManager.inMemory).toHaveBeenCalledWith("/work"); expect(a).not.toBe(b); // a fresh manager each time (never shared, never a fork) }); }); describe("makeCompleteFn", () => { it("maps the runner's request into the pi-ai shape, threads auth, and extracts text", async () => { const complete = vi.fn(async () => ({ stopReason: "stop", content: [ { type: "text", text: "hello " }, { type: "text", text: "world" }, { type: "thinking", text: "ignored" }, ], })); const fn = makeCompleteFn({ complete }); const signal = new AbortController().signal; const res = await fn({ model: { id: "m" }, systemPrompt: "SYS", messages: [{ role: "user", content: "hi" }], apiKey: "sk-123", headers: { "x-delete": null, "x-h": "1" }, signal, }); expect(complete).toHaveBeenCalledTimes(1); const [model, request, options] = complete.mock.calls[0]; expect(model).toEqual({ id: "m" }); // resolved model object, not a string expect(request.systemPrompt).toBe("SYS"); expect(request.messages).toEqual([ { role: "user", content: [{ type: "text", text: "hi" }], timestamp: expect.any(Number), }, ]); expect(options.apiKey).toBe("sk-123"); // #4 auth threaded expect(options.headers).toEqual({ "x-delete": null, "x-h": "1" }); expect(options.signal).toBe(signal); expect(options.cacheRetention).toBe("none"); // Only text parts concatenated; thinking dropped. expect(res).toEqual({ text: "hello world", stopReason: "stop", errorMessage: undefined, }); }); it("surfaces an error response's stopReason + errorMessage", async () => { const complete = vi.fn(async () => ({ stopReason: "error", errorMessage: "boom", content: [], })); const fn = makeCompleteFn({ complete }); const res = await fn({ model: {}, messages: [] }); expect(res).toEqual({ text: "", stopReason: "error", errorMessage: "boom", }); }); }); describe("makeResolveModel", () => { it("returns the default model when no ref is given", () => { const find = vi.fn(); const resolve = makeResolveModel({ modelRegistry: { find }, defaultModel: { id: "host" }, }); expect(resolve(undefined)).toEqual({ id: "host" }); expect(find).not.toHaveBeenCalled(); }); it("parses a provider/model ref and looks it up in the registry", () => { const found = { id: "MiniMax-M2" }; const find = vi.fn(() => found); const resolve = makeResolveModel({ modelRegistry: { find }, defaultModel: { id: "host" }, }); expect(resolve("minimax/MiniMax-M2")).toBe(found); expect(find).toHaveBeenCalledWith("minimax", "MiniMax-M2"); }); it("throws on an unresolvable ref and on a malformed ref", () => { const resolve = makeResolveModel({ modelRegistry: { find: () => undefined }, defaultModel: {}, }); expect(() => resolve("minimax/nope")).toThrow(/not found/); expect(() => resolve("noslash")).toThrow(/provider\/model/); expect(() => resolve("/leading")).toThrow(/provider\/model/); expect(() => resolve("trailing/")).toThrow(/provider\/model/); }); }); describe("makeResolveAuth", () => { it("delegates to modelRegistry.getApiKeyAndHeaders for the given model", async () => { const auth = { ok: true, apiKey: "sk", headers: { a: "b" } }; const getApiKeyAndHeaders = vi.fn(async () => auth); const resolve = makeResolveAuth({ modelRegistry: { getApiKeyAndHeaders } }); const model = { id: "m" }; await expect(resolve(model)).resolves.toBe(auth); expect(getApiKeyAndHeaders).toHaveBeenCalledWith(model); }); });