repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ultra/__tests__/drivers.test.ts

Raw
File outline
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",
			modelRegistry: { id: "registry" },
		});

		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<string, unknown>;
		expect(opts.cwd).toBe("/work");
		expect(opts.model).toEqual({ id: "m" });
		expect(opts.modelRegistry).toEqual({ id: "registry" });
		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("loadExtensions:true flips noExtensions to false; other isolation flags stay true", async () => {
		const loaderOpts: Record<string, unknown>[] = [];
		class FakeLoader {
			reload = vi.fn().mockResolvedValue(undefined);
			constructor(opts: Record<string, unknown>) {
				loaderOpts.push(opts);
			}
		}
		const createAgentSession = vi.fn(async () => ({ session: fakeSession }));

		const factory = makeSessionFactory({
			createAgentSession,
			DefaultResourceLoader: FakeLoader as any,
			getAgentDir: () => "/agent",
			cwd: "/work",
			modelRegistry: {},
			loadExtensions: true,
		});
		await factory({
			model: {},
			tools: ["web_search", "structured_output"],
			customTools: [],
			sessionManager: {},
		});

		// only noExtensions flips; the other isolation flags are untouched.
		expect(loaderOpts[0].noExtensions).toBe(false);
		expect(loaderOpts[0].noSkills).toBe(true);
		expect(loaderOpts[0].noPromptTemplates).toBe(true);
		expect(loaderOpts[0].noThemes).toBe(true);
		expect(loaderOpts[0].noContextFiles).toBe(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-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-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);
	});
});