fix: address round-2 review findings

- apply(): only swap the current model when a Nous model was filtered
  out; a session on another provider is left alone, and the notice names
  the model actually in use instead of the first catalog hit.
- Device-code poll floors the interval at 1s and treats a non-numeric
  interval as absent, matching pi-ai's own poller; interval: 0 from the
  server no longer becomes a tight loop.
- Drop the provider's own context.publish: createProvider already
  persists and publishes the fetchModels return value with checkedAt;
  the extra publish was a second, timestamp-less write each refresh.
- tokenRequest tolerates a literal null error body (data.error would
  have thrown TypeError, masking the HTTP status).
- tsconfig: remove allowImportingTsExtensions and baseUrl, both inert.
- .editorconfig covers .mjs.
- Tests: 14 (was 8). tokenRequest is exported and its HTML/null error
  paths are pinned; the no-credential test now sets NOUS_API_KEY so it
  fails if an env fallback returns; the slash commands are driven
  through a recording pi (switch/notice semantics, and persist-before-
  mutate on a failed flag write). Stub returns a private mkdtemp dir.
- CHANGELOG: /nous-catalog entry states the switch semantics.
This commit is contained in:
AlexKucera committed 2026-11-25 10:09:06 +01:00
1 parent 00d50e10de
commit b9065d409c
7 files changed
+117 -26

No files matched your search

+86 -5
View File
@@ -1,6 +1,8 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { after, test } from "node:test";
import { createJiti } from "jiti";
import { mkdirSync, rmSync } 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 —
@@ -14,7 +16,13 @@ const jiti = createJiti(import.meta.url, {
"@earendil-works/pi-coding-agent": stub,
},
});
const { toModel, toCredential, fetchModels, tierOf, withoutTierHeader } = await jiti.import("../index.ts");
const extension = await jiti.import("../index.ts");
const { toModel, toCredential, tokenRequest, fetchModels, tierOf, withoutTierHeader } = 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" } });
@@ -79,7 +87,21 @@ test("toCredential: keeps the previous refresh token when the server rotates onl
assert.ok(kept.expires > Date.now());
});
test("fetchModels: returns [] and never touches the network with no credential", async (t) => {
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 () => "<html>Vercel checkpoint</html>" }));
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);
@@ -96,7 +118,66 @@ test("fetchModels: an OAuth credential is used as the bearer; hermes entries are
assert.deepEqual(models.map((m) => m.id), ["qwen/qwen3.5-35b-a3b"]);
});
test("fetchModels: a non-OK response throws with the status", async (t) => {
t.mock.method(globalThis, "fetch", async () => ({ ok: false, status: 503 }));
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");
});
// Drives the default export with a recording pi, so the slash commands run without a real host.
const drive = () => {
rmSync(flagPath, { force: true, recursive: true });
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) =>
commands[name].handler("", {
model,
modelRegistry: { refresh: async () => {}, getAvailable: () => available },
ui: { notify: (message) => notes.push(message) },
});
return { run, provider, switched, notes };
};
const nous = (id, tier) => ({ id, provider: "nous-portal", ...(tier && { headers: { "x-nous-catalog-tier": 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 });
}
});