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

+1 -1
View File
@@ -1,3 +1,3 @@
[*.{ts,tsx,js}]
[*.{ts,tsx,js,mjs}]
indent_style = space
indent_size = 2
+1 -1
View File
@@ -9,4 +9,4 @@ All notable changes to this project will be documented in this file. The format
- Native `nous-portal` provider: device-code OAuth (subscription) and API-key login, with the OAuth access token used directly as the inference bearer credential.
- Live model discovery from `inference-api.nousresearch.com/v1/models`, delegated to pi's built-in `openai-completions` streaming.
- Offline baseline catalog so `pi -p` and `pi --list-models` stay usable without a network fetch.
- `/nous-catalog` cycles `/model` between full, free and promo catalogs; `/nous-free` jumps to free.
- `/nous-catalog` cycles `/model` between full, free and promo catalogs; `/nous-free` jumps to free. Switching never touches a session on another provider, and swaps the current model only if it was filtered out.
+15 -10
View File
@@ -78,7 +78,7 @@ class OAuthError extends Error {
}
}
async function tokenRequest(body: Record<string, string>, signal?: AbortSignal): Promise<TokenResponse> {
export async function tokenRequest(body: Record<string, string>, signal?: AbortSignal): Promise<TokenResponse> {
const response = await fetch(`${PORTAL}/api/oauth/token`, {
method: "POST",
headers: formHeaders,
@@ -90,7 +90,7 @@ async function tokenRequest(body: Record<string, string>, signal?: AbortSignal):
// Gateways and the Vercel checkpoint return HTML; never let JSON.parse mask the HTTP status.
let data: { error?: string; error_description?: string } = {};
try {
data = JSON.parse(text);
data = JSON.parse(text) ?? {}; // a literal `null` body must not turn `data.error` into a TypeError
} catch {
// non-JSON body: report the status and a short excerpt only
}
@@ -132,7 +132,8 @@ async function login(interaction: ProviderAuthInteraction): Promise<OAuthCredent
await interaction.prompt({ type: "text", message: "Press Enter to open the Nous Portal sign-in page." });
const deadline = Date.now() + device.expires_in * 1000;
let interval = device.interval ?? 5;
// Floor at 1 s like pi-ai's own poller: a missing, zero or non-numeric interval must not become a tight loop.
let interval = Math.max(Number(device.interval) || 5, 1);
while (Date.now() < deadline) {
try {
return toCredential(
@@ -271,9 +272,14 @@ export default function nousPortal(pi: ExtensionAPI) {
catalog = next;
await ctx.modelRegistry.refresh({ providers: [PROVIDER_ID] });
const shown = ctx.modelRegistry.getAvailable().filter((m) => m.provider === PROVIDER_ID && inCatalog(m));
// Keep the session usable if the current model just got filtered out.
if (shown.length && !shown.some((m) => m.id === ctx.model?.id)) await pi.setModel(shown[0]);
ctx.ui.notify(`Nous catalog: ${next} (${shown.length} models)${shown[0] ? " — using " + shown[0].id : ""}`);
// Keep the session usable only when a Nous model just got filtered out; a session on another provider
// is left alone, and the notice names the model actually in use, not the first hit.
const onNous = ctx.model?.provider === PROVIDER_ID;
const current = onNous ? shown.find((m) => m.id === ctx.model?.id) : undefined;
const switched = shown.length && onNous && !current ? shown[0] : undefined;
if (switched) await pi.setModel(switched);
const inUse = current ?? switched;
ctx.ui.notify(`Nous catalog: ${next} (${shown.length} models)${inUse ? " — using " + inUse.id : ""}`);
};
const cycle: Record<Catalog, Catalog> = { full: "free", free: "promo", promo: "full" };
pi.registerCommand("nous-catalog", {
@@ -299,10 +305,9 @@ export default function nousPortal(pi: ExtensionAPI) {
},
async fetchModels(context: RefreshModelsContext) {
const fetched = await fetchModels(context.credential, context.signal);
if (fetched.length) {
models = fetched;
await context.publish({ persist: { models: fetched } });
}
// Empty live result → keep the last good list. createProvider persists and publishes whatever is
// returned (pi-ai models.js refreshModels), so no publish here: that was a second, timestamp-less write.
if (fetched.length) models = fetched;
return models;
},
}),
+4 -4
View File
@@ -2,7 +2,7 @@
## Purpose
Offline unit tests for `index.ts`. They pin the pure logic that has real branching: model mapping, credential construction, and model fetching. No network, no real credentials.
Offline unit tests for `index.ts`. They pin the pure logic that has real branching: model mapping, credential construction, model fetching, token-endpoint error handling, and the slash commands (driven through a recording `pi`). No network, no real credentials.
## Ownership
@@ -14,10 +14,10 @@ Offline unit tests for `index.ts`. They pin the pure logic that has real branchi
- `index.test.mjs` loads `index.ts` through jiti, the same TS loader pi uses, because the host packages are not installed in `node_modules`.
- Host imports are aliased to `stubs/pi-ai.mjs`. Alias keys are matched longest-prefix first: `@earendil-works/pi-ai/compat` must be listed before `@earendil-works/pi-ai`, or the bare key swallows the subpath and resolution fails.
- `stubs/pi-ai.mjs` exports only what `index.ts` touches at module load: `envApiKeyAuth`, `createProvider`, `openAICompletionsApi`, `getAgentDir`. It is a type-less stub; correctness of those functions is pi's concern and is verified live, not here.
- Exported functions under test: `toModel`, `toCredential`, `fetchModels`, `tierOf`, `withoutTierHeader`. Anything not exported is not unit-tested.
- `stubs/pi-ai.mjs` exports only what `index.ts` imports: `envApiKeyAuth`, `createProvider`, `openAICompletionsApi`, `getAgentDir` (plus `agentDir` so tests can find the flag file). `getAgentDir` is called inside the default export, so it is reached only by tests that drive the commands; it returns a private `mkdtemp` dir per run, shared through `globalThis` because jiti loads the stub as a separate instance from a native import. It is a type-less stub; correctness of those functions is pi's concern and is verified live, not here.
- Exported functions under test: `toModel`, `toCredential`, `tokenRequest`, `fetchModels`, `tierOf`, `withoutTierHeader`, and the default export via the `drive()` harness. Anything else is not unit-tested (notably the device-code poll loop inside `login`, which would need timer control and extraction).
- Network calls are replaced with `t.mock.method(globalThis, "fetch", …)` from `node:test`, which restores itself when the test ends. Do not hand-roll a `globalThis.fetch` swap.
- `fetchModels` reads a key only from the `credential` argument. Env resolution of `$NOUS_API_KEY` is `envApiKeyAuth`'s job upstream, so tests never need to touch `process.env`.
- `fetchModels` reads a key only from the `credential` argument. Env resolution of `$NOUS_API_KEY` is `envApiKeyAuth`'s job upstream. The one test that touches `process.env` sets it deliberately, to pin that `fetchModels` ignores it; it restores the previous value in `t.after`.
## Work Guidance
+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 });
}
});
+10 -3
View File
@@ -1,6 +1,13 @@
// Minimal stand-in for the host-injected @earendil-works/* packages; only what index.ts touches at module load.
// Minimal stand-in for the host-injected @earendil-works/* packages; only what index.ts imports.
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
export const envApiKeyAuth = (name, envVars) => ({ name, envVars });
export const createProvider = (input) => input;
export const openAICompletionsApi = () => ({ stream() {}, streamSimple() {} });
// Used only when a test drives the default export (nousPortal), which resolves the catalog flag path at load.
export const getAgentDir = () => "/tmp";
// getAgentDir is called by the default export to locate the catalog flag, so tests that drive the slash
// commands need a real, writable dir: one private dir per run, never /tmp directly. Shared through
// globalThis because jiti evaluates this file as a separate instance from a native import.
export const agentDir = (globalThis.__nousStubAgentDir ??= mkdtempSync(join(tmpdir(), "nous-portal-stub-")));
export const getAgentDir = () => agentDir;
-2
View File
@@ -6,7 +6,6 @@
"target": "ES2022",
"noEmit": true,
"skipLibCheck": true,
"allowImportingTsExtensions": true,
"types": [
"node"
],
@@ -21,6 +20,5 @@
"/Users/alex/.pi/agent/install/releases/1.6.0/node_modules/@earendil-works/pi-coding-agent/dist/index.d.ts"
]
},
"baseUrl": "."
}
}