import assert from "node:assert/strict"; import { after, test } from "node:test"; import { createJiti } from "jiti"; import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; // Host packages are not installed here (pi injects them at load time), so import index.ts through jiti — // the same TS loader pi uses — with the host imports aliased to a minimal stub. const stub = fileURLToPath(new URL("./stubs/pi-ai.mjs", import.meta.url)); const jiti = createJiti(import.meta.url, { // Longest-prefix first: pi-ai/compat must precede pi-ai or the bare key swallows the subpath. alias: { "@earendil-works/pi-ai/compat": stub, "@earendil-works/pi-ai": stub, "@earendil-works/pi-coding-agent": stub, }, }); const extension = await jiti.import("../index.ts"); const { toModel, toCredential, login, tokenRequest, fetchModels, tierOf } = extension; // The stub shares its private agent dir through globalThis (see stubs/pi-ai.mjs); the catalog flag lives there. const { agentDir } = await import("./stubs/pi-ai.mjs"); const flagPath = join(agentDir, "nous-portal-catalog"); // The stub creates its private dir at load; remove it once the whole file has run so test runs do not leak dirs. after(() => rmSync(agentDir, { recursive: true, force: true })); test("toModel: per-token price becomes per-million, image input from architecture, reasoning by id", () => { const m = toModel({ id: "OpenAI/GPT-5.4-Nano", context_length: 400000, architecture: { input_modalities: ["text", "image"] }, pricing: { prompt: "0.00000016", completion: "0.000001" } }); assert.equal(m.cost.input, 0.16); assert.equal(m.cost.output, 1); assert.deepEqual(m.input, ["text", "image"]); assert.equal(m.reasoning, true); assert.equal(m.baseUrl, "https://inference-api.nousresearch.com/v1"); assert.equal(m.headers, undefined, "untiered models carry no header"); }); test("tierOf: free by synthesizedFreeVariant or :free suffix, promo only when price dropped, else undefined", () => { assert.equal(tierOf({ id: "tencent/hy4-flash:free" }), "free"); assert.equal(tierOf({ id: "x", synthesizedFreeVariant: true }), "free"); assert.equal(tierOf({ id: "google/gemini-4-carbon", pricing: { prompt: "0.000002", original: { prompt: "0.000004" } } }), "promo"); assert.equal(tierOf({ id: "x", pricing: { prompt: "0.000002", original: { prompt: "0.000002" } } }), undefined, "no discount"); assert.equal(tierOf({ id: "x", pricing: { prompt: "0.000004", original: { prompt: "0.000002" } } }), undefined, "price raised"); assert.equal(tierOf({ id: "x" }), undefined); }); test("toModel: the catalog tier is a model property, never a header, so nothing needs stripping before a request", () => { const free = toModel({ id: "upstage/solar-mini4:free" }); assert.equal(free.catalogTier, "free"); assert.equal(free.headers, undefined); assert.deepEqual(free.input, ["text"]); assert.equal(free.reasoning, false); assert.equal(free.cost.input, 0); assert.equal(free.contextWindow, 131072); const promo = toModel({ id: "google/gemini-4-carbon", pricing: { prompt: "0.000002", original: { prompt: "0.000004" } } }); assert.equal(promo.catalogTier, "promo"); assert.equal(toModel({ id: "openai/gpt-5.4-nano" }).catalogTier, undefined, "untiered models carry no tier"); }); // login() is driven with an auto-advancing clock: each sleep adds its ms to `now` and resolves at once, so the // deadline falls out of the sleeps themselves. The token endpoint is mocked; the last reply repeats, and the mock // gives up after 100 polls so a sleep-less regression FAILS instead of hanging (the fake clock starves the event // loop, so no test timeout can fire). const DEVICE = { device_code: "d", user_code: "USER-1", verification_uri: "https://portal.nousresearch.com/device", expires_in: 60, interval: 5 }; const oauthError = (error) => ({ ok: false, status: 400, text: async () => JSON.stringify({ error }) }); const token = (access_token) => ({ ok: true, text: async () => JSON.stringify({ access_token, expires_in: 3600 }) }); const driveLogin = (t, replies, device = DEVICE) => { const sleeps = [], events = []; let now = 1_000_000, call = 0; t.mock.method(globalThis, "fetch", async (url) => { if (String(url).endsWith("/device/code")) return { ok: true, json: async () => device }; if (call >= 100) throw new Error("runaway poll loop: 100 token polls without reaching the deadline"); return replies[Math.min(call++, replies.length - 1)]; }); const clock = { now: () => now, sleep: async (ms) => { sleeps.push(ms); now += ms; } }; return { sleeps, events, run: () => login({ notify: (event) => events.push(event), signal: new AbortController().signal }, clock) }; }; test("login: shows the device code once, waits the server interval on pending and 5 s more on slow_down, then returns the credential", async (t) => { const { run, sleeps, events } = driveLogin(t, [oauthError("authorization_pending"), oauthError("slow_down"), token("tok")]); const credential = await run(); assert.deepEqual(sleeps, [5000, 10000]); assert.deepEqual(events, [{ type: "device_code", userCode: "USER-1", verificationUri: "https://portal.nousresearch.com/device", intervalSeconds: 5, expiresInSeconds: 60 }]); assert.equal(credential.access, "tok"); }); test("login: a missing interval falls back to 5 s", async (t) => { const { run, sleeps } = driveLogin(t, [oauthError("authorization_pending"), token("a")], { ...DEVICE, interval: undefined }); await run(); assert.deepEqual(sleeps, [5000]); }); test("login: a fractional interval is floored at 1 s", async (t) => { const { run, sleeps } = driveLogin(t, [oauthError("authorization_pending"), token("b")], { ...DEVICE, interval: 0.5 }); await run(); assert.deepEqual(sleeps, [1000]); }); test("login: never sleeps past the deadline; a poll that stays pending times out", async (t) => { const { run, sleeps } = driveLogin(t, [oauthError("authorization_pending")], { ...DEVICE, expires_in: 12 }); await assert.rejects(run(), /Nous login timed out/); assert.deepEqual(sleeps, [5000, 5000, 2000]); }); test("login: a non-retryable OAuth error propagates without sleeping", async (t) => { const { run, sleeps } = driveLogin(t, [oauthError("expired_token")]); await assert.rejects(run(), /expired_token/); assert.deepEqual(sleeps, []); }); test("login: a non-OK device-code response throws with its status (real clock; no sleep is reached)", async (t) => { t.mock.method(globalThis, "fetch", async () => ({ ok: false, status: 403 })); await assert.rejects(login({ notify() {}, signal: new AbortController().signal }), /device code request failed: 403/); }); test("toCredential: keeps the previous refresh token when the server rotates only the access token", () => { const prev = { type: "oauth", access: "old", refresh: "rt_keep", expires: 0 }; const rotated = toCredential({ access_token: "new", expires_in: 100 }); assert.equal(rotated.refresh, ""); const kept = toCredential({ access_token: "new", expires_in: 100 }, prev); assert.equal(kept.refresh, "rt_keep"); assert.equal(kept.access, "new"); assert.ok(kept.expires > Date.now()); }); test("tokenRequest: an HTML error body keeps the HTTP status instead of failing to parse", async (t) => { t.mock.method(globalThis, "fetch", async () => ({ ok: false, status: 403, text: async () => "Vercel checkpoint" })); await assert.rejects(tokenRequest({ grant_type: "device_code" }), /http_error: 403/); }); test("tokenRequest: a literal null error body is reported with its status", async (t) => { t.mock.method(globalThis, "fetch", async () => ({ ok: false, status: 502, text: async () => "null" })); await assert.rejects(tokenRequest({ grant_type: "device_code" }), /http_error: 502/); }); test("fetchModels: no credential means [] and no network, even with $NOUS_API_KEY set", async (t) => { // Pins that the key comes from the credential alone; with an env fallback restored, this test would fetch. const prev = process.env.NOUS_API_KEY; process.env.NOUS_API_KEY = "must-not-leak"; t.after(() => { if (prev === undefined) delete process.env.NOUS_API_KEY; else process.env.NOUS_API_KEY = prev; }); const mocked = t.mock.method(globalThis, "fetch", () => { throw new Error("must not fetch"); }); assert.deepEqual(await fetchModels(undefined, new AbortController().signal), []); assert.equal(mocked.mock.callCount(), 0); }); test("fetchModels: an OAuth credential is used as the bearer; hermes entries are dropped; the rest are mapped", async (t) => { let auth; t.mock.method(globalThis, "fetch", async (url, init) => { auth = init.headers.Authorization; return { ok: true, json: async () => ({ data: [{ id: "hermes/agent" }, { id: "qwen/qwen3.5-35b-a3b" }] }) }; }); const models = await fetchModels({ type: "oauth", access: "tok" }, new AbortController().signal); assert.equal(auth, "Bearer tok"); assert.deepEqual(models.map((m) => m.id), ["qwen/qwen3.5-35b-a3b"]); }); test("fetchModels: an API key is sent as the bearer; a non-OK response throws with the status", async (t) => { let auth; t.mock.method(globalThis, "fetch", async (_url, init) => { auth = init.headers.Authorization; return { ok: false, status: 503 }; }); await assert.rejects(fetchModels({ type: "api_key", key: "k" }, new AbortController().signal), /503/); assert.equal(auth, "Bearer k"); }); test("tokenRequest: a JSON error body maps error → code and error_description → message; a missing description falls back to the body", async (t) => { let body = JSON.stringify({ error: "slow_down", error_description: "SLOW DOWN" }); t.mock.method(globalThis, "fetch", async () => ({ ok: false, status: 400, text: async () => body })); await assert.rejects(tokenRequest({ device_code: "d" }), (error) => error.code === "slow_down" && error.message === "slow_down: 400 SLOW DOWN"); body = JSON.stringify({ error: "expired_token" }); await assert.rejects(tokenRequest({ device_code: "d" }), (error) => error.code === "expired_token" && error.message === 'expired_token: 400 {"error":"expired_token"}'); }); test("provider fetchModels: an empty live list keeps the last good list instead of the baseline", async (t) => { const { provider } = drive(); const ctx = { credential: { type: "api_key", key: "k" }, signal: new AbortController().signal }; let data = [{ id: "qwen/qwen3.5-35b-a3b" }]; t.mock.method(globalThis, "fetch", async () => ({ ok: true, json: async () => ({ data }) })); assert.deepEqual((await provider.fetchModels(ctx)).map((m) => m.id), ["qwen/qwen3.5-35b-a3b"]); data = []; assert.deepEqual((await provider.fetchModels(ctx)).map((m) => m.id), ["qwen/qwen3.5-35b-a3b"]); }); // Drives the default export with a recording pi, so the slash commands run without a real host. // `flag` seeds the saved catalog before load to exercise the startup restore; default is a fresh install. const drive = (flag) => { rmSync(flagPath, { force: true, recursive: true }); if (flag !== undefined) writeFileSync(flagPath, flag); const commands = {}, provider = {}, switched = [], notes = []; extension.default({ registerCommand: (name, def) => (commands[name] = def), registerProvider: (input) => Object.assign(provider, input), setModel: async (model) => switched.push(model), }); const run = (name, model, available, refresh = async () => {}) => commands[name].handler("", { model, modelRegistry: { refresh, getAvailable: () => available }, ui: { notify: (message) => notes.push(message) }, }); return { run, provider, switched, notes }; }; const nous = (id, tier) => ({ id, provider: "nous-portal", ...(tier && { catalogTier: tier }) }); const other = (id) => ({ id, provider: "anthropic" }); test("/nous-free: a session whose model survives the filter is left alone, and the notice names that model", async () => { const { run, switched, notes } = drive(); await run("nous-free", nous("free-b", "free"), [nous("free-a", "free"), nous("free-b", "free"), nous("paid")]); assert.deepEqual(switched, []); assert.match(notes[0], /— using free-b$/); }); test("/nous-free: a Nous model that gets filtered out is replaced by the first model still shown", async () => { const { run, switched, notes } = drive(); await run("nous-free", nous("paid"), [nous("free-a", "free"), nous("paid")]); assert.deepEqual(switched.map((m) => m.id), ["free-a"]); assert.match(notes[0], /— using free-a$/); }); test("/nous-free: a session on another provider is neither switched nor announced, even when ids coincide", async () => { const { run, switched, notes } = drive(); await run("nous-free", other("free-a"), [nous("free-a", "free")]); assert.deepEqual(switched, []); assert.doesNotMatch(notes[0], /using/); }); test("/nous-free: a failed flag write leaves the catalog unchanged (persist before switching memory)", async () => { const { run, provider } = drive(); const all = [nous("free-a", "free"), nous("paid")]; assert.deepEqual(provider.filterModels(all).map((m) => m.id), ["free-a", "paid"]); mkdirSync(flagPath); // a directory where the flag file belongs: the write must fail try { await assert.rejects(run("nous-free", undefined, all)); assert.deepEqual(provider.filterModels(all).map((m) => m.id), ["free-a", "paid"], "still the full catalog"); } finally { rmSync(flagPath, { recursive: true, force: true }); } }); test("/nous-free pressed again returns to full and removes the flag file", async () => { const { run, provider, notes } = drive(); const all = [nous("free-a", "free"), nous("paid")]; await run("nous-free", undefined, all); assert.deepEqual(provider.filterModels(all).map((m) => m.id), ["free-a"]); await run("nous-free", undefined, all); assert.deepEqual(provider.filterModels(all).map((m) => m.id), ["free-a", "paid"]); assert.equal(existsSync(flagPath), false); assert.match(notes[1], /^Nous catalog: full /); }); test("/nous-catalog cycles full → free → promo → full", async () => { const { run, provider, notes } = drive(); const all = [nous("free-a", "free"), nous("promo-a", "promo"), nous("paid")]; for (const expected of ["free", "promo", "full"]) { await run("nous-catalog", undefined, all); assert.match(notes.at(-1), new RegExp("^Nous catalog: " + expected + " ")); const ids = provider.filterModels(all).map((m) => m.id); assert.deepEqual(ids, expected === "full" ? ["free-a", "promo-a", "paid"] : [expected + "-a"]); } }); test("overlapping catalog switches: the invocation superseded while awaiting a slow refresh neither notifies nor switches the model", async () => { const { run, switched, notes } = drive(); const all = [nous("free-a", "free"), nous("promo-a", "promo"), nous("paid")]; let release; const gate = new Promise((resolve) => (release = resolve)); const first = run("nous-free", nous("paid"), all, () => gate); // apply("free"), then awaits a slow refresh await run("nous-catalog", nous("paid"), all); // reads catalog "free" → applies "promo", refresh resolves at once, paid is filtered out → switches release(); await first; assert.deepEqual(notes.map((n) => n.split(" ")[2]), ["promo"]); assert.deepEqual(switched.map((m) => m.id), ["promo-a"]); // only the winning invocation switched }); test("a saved catalog survives restart; a corrupted flag falls back to full", () => { const all = [nous("free-a", "free"), nous("promo-a", "promo"), nous("paid")]; try { assert.deepEqual(drive("promo").provider.filterModels(all).map((m) => m.id), ["promo-a"]); assert.deepEqual(drive("garbage").provider.filterModels(all).map((m) => m.id), ["free-a", "promo-a", "paid"]); } finally { rmSync(flagPath, { force: true }); } });