From 00d50e10dee753cfc64fc63ef0c8918b62458126 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Wed, 25 Nov 2026 09:48:55 +0100 Subject: [PATCH] fix: address round-1 review findings - slow_down now sleeps (and waits longer) instead of re-polling at once; the interval cap that could lower a server interval is gone. The deadline already bounds the loop. - Non-JSON error bodies from gateways and the Vercel checkpoint no longer surface as SyntaxError; the HTTP status is preserved. - Drop the dead process.env.NOUS_API_KEY fallback in fetchModels: envApiKeyAuth already resolves it into the credential upstream. - apply() persists the catalog flag before mutating memory, so a read-only agent dir cannot leave the two out of step. - sleep() replaced with node:timers/promises; three unused exports removed; stale tags.user comment corrected; hermes filter explained. - Tests: 8 (was 4). Pin tierOf, the tier header, and withoutTierHeader on both stream entry points; t.mock.method replaces hand-rolled fetch swaps; stub gains getAgentDir. - Docs: README covers install lockfile flag, hermes row, browser-UA posture, and typecheck path pinning; AGENTS.md allowlist includes pi-coding-agent; tests/AGENTS.md contracts updated. --- .gitignore | 3 ++ AGENTS.md | 2 +- README.md | 7 ++-- index.ts | 49 +++++++++++++++------------ tests/AGENTS.md | 8 ++--- tests/index.test.mjs | 79 +++++++++++++++++++++++++++++++------------ tests/stubs/pi-ai.mjs | 4 ++- 7 files changed, 102 insertions(+), 50 deletions(-) diff --git a/.gitignore b/.gitignore index 89fe249..ac942f8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ node_modules/ *.tsbuildinfo .DS_Store + +# local review scratch +_code_review/ diff --git a/AGENTS.md b/AGENTS.md index e185bd1..ff7b521 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,7 +18,7 @@ ## Conventions and gotchas -- **Host imports are allowlisted.** pi's extension loader aliases only `@earendil-works/pi-ai`, `/models`, `/oauth`, `/compat`, `/providers/all`. Import `openAICompletionsApi` from `@earendil-works/pi-ai/compat`; the `./api/*` subpath typechecks but fails at load. +- **Host imports are allowlisted.** pi's extension loader aliases only `@earendil-works/pi-coding-agent` and `@earendil-works/pi-ai` plus its `/models`, `/oauth`, `/compat`, `/providers/all` subpaths. Import `openAICompletionsApi` from `@earendil-works/pi-ai/compat`; the `./api/*` subpath typechecks but fails at load. - **`ctx` vs `pi`:** `setModel`, `registerCommand`, `registerProvider` are on `pi`; `ui.notify`, `model`, `modelRegistry` are on the handler's `ctx`. Check with `tsc` rather than guessing. - **`pi -p` and `--list-models` never fetch live catalogs** (`allowModelNetwork` is hard-coded `false`). That is why the provider ships `BASELINE`; interactive startup overlays the live list. - **Tests load `index.ts` through jiti with the host packages aliased to `tests/stubs/pi-ai.mjs`.** Alias keys are longest-prefix first, so `pi-ai/compat` must precede `pi-ai` or the bare key swallows the subpath. diff --git a/README.md b/README.md index d328815..e15c141 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ Then in pi: | Catalog | Live signal | Models | |---|---|---| -| full | everything | 409 | +| full | every chat model except Hermes-branded ids (none in the catalog as of 2026-11-25) | 409 | | free | `synthesizedFreeVariant`, also suffixed `:free` | 3 | | promo | `pricing.original` above the current price | 42 | @@ -48,14 +48,17 @@ The choice is saved in `~/.pi/agent/nous-portal-catalog` and survives restarts. - `upstage/solar-mini4:free` is left out of the baseline on purpose: it alone requires a `tags` body field that the other free models reject with a 500, so no single request shape serves all of them. - Subscription quota is per day. When the "Today" gauge is exhausted, inference returns `503 ChatGPT subscription inference is temporarily unavailable`. Purchased credits keep the API-key route working. +- Requests to the portal's OAuth endpoints send a browser-like `User-Agent`, `Origin` and `Referer` (only to `portal.nousresearch.com`, never to inference). This gets past the Vercel browser checkpoint that otherwise rejects CLI clients. It is a robustness and terms-of-use risk, not a security one: if Nous tightens the checkpoint or treats the client as evasion, login can break or the account can be flagged. ## Development ```bash -npm install --legacy-peer-deps # typescript + jiti only; pi injects @earendil-works/* at load time +npm install --legacy-peer-deps --no-package-lock # typescript + jiti only; pi injects @earendil-works/* at load time npm run check # tsc --noEmit + node --test ``` +Typechecking needs a local pi install: `tsconfig.json` `paths` point `@earendil-works/pi-ai` and `pi-coding-agent` at the type declarations under `~/.pi/agent/install/releases//`. Update those three paths when pi is upgraded. The extension itself runs against any pi with the native provider interface; only `tsc` is pinned. + ## License GPL-3.0-or-later. See [LICENSE](LICENSE). diff --git a/index.ts b/index.ts index 8a4e14c..e429bc4 100644 --- a/index.ts +++ b/index.ts @@ -24,6 +24,7 @@ import { type ProviderStreams, type RefreshModelsContext, } from "@earendil-works/pi-ai"; +import { setTimeout as sleep } from "node:timers/promises"; import { readFileSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { getAgentDir, type ExtensionAPI, type ExtensionCommandContext } from "@earendil-works/pi-coding-agent"; @@ -33,12 +34,11 @@ const INFERENCE = "https://inference-api.nousresearch.com/v1"; const CLIENT_ID = "hermes-cli"; const SCOPE = "inference:mint_agent_key"; const PROVIDER_ID = "nous-portal"; -const POLL_CAP_SECONDS = 10; // shortcut: portal pages sit behind a Vercel checkpoint that rejects non-browser UAs; drop if Nous removes it. const UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36"; -export type TokenResponse = { +type TokenResponse = { access_token: string; refresh_token?: string; expires_in?: number; @@ -87,7 +87,13 @@ async function tokenRequest(body: Record, signal?: AbortSignal): }); const text = await response.text(); if (!response.ok) { - const data = JSON.parse(text) as { error?: string; error_description?: string }; + // 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); + } catch { + // non-JSON body: report the status and a short excerpt only + } throw new OAuthError(data.error ?? "http_error", `${response.status} ${data.error_description ?? text.slice(0, 200)}`); } return JSON.parse(text) as TokenResponse; @@ -102,13 +108,6 @@ export function toCredential(token: TokenResponse, previous?: OAuthCredential): }; } -function sleep(ms: number, signal: AbortSignal): Promise { - return new Promise((resolve, reject) => { - if (signal.aborted) return reject(new Error("Nous login cancelled")); - const timer = setTimeout(resolve, ms); - signal.addEventListener("abort", () => void (clearTimeout(timer), reject(new Error("Nous login cancelled"))), { once: true }); - }); -} async function login(interaction: ProviderAuthInteraction): Promise { const { signal } = interaction; @@ -141,9 +140,13 @@ async function login(interaction: ProviderAuthInteraction): Promise { }; } -export const tierOfModel = (model: Model) => model.headers?.[TIER_HEADER] as Exclude | undefined; +const tierOfModel = (model: Model) => model.headers?.[TIER_HEADER] as Exclude | undefined; -export const CATALOGS = ["full", "free", "promo"] as const; -export type Catalog = (typeof CATALOGS)[number]; +const CATALOGS = ["full", "free", "promo"] as const; +type Catalog = (typeof CATALOGS)[number]; /** Classify a live catalog entry. Nous marks free models with synthesizedFreeVariant and discounts with pricing.original. */ export function tierOf(item: ModelListItem): Exclude | undefined { @@ -219,11 +222,15 @@ const BASELINE: ModelListItem[] = [ ]; export async function fetchModels(credential: Credential | undefined, signal: AbortSignal): Promise[]> { - const key = credential?.type === "oauth" ? credential.access : (credential?.key || process.env.NOUS_API_KEY); + // Env resolution is envApiKeyAuth's job: for the api-key route pi already hands us a credential whose + // `key` is the stored key or $NOUS_API_KEY, so no env lookup belongs here. + const key = credential?.type === "oauth" ? credential.access : credential?.key; if (!key) return []; const response = await fetch(`${INFERENCE}/models`, { headers: { Authorization: `Bearer ${key}` }, signal }); if (!response.ok) throw new Error(`Nous models request failed: ${response.status}`); const payload = (await response.json()) as { data?: ModelListItem[] }; + // Hermes-branded ids are non-chat entries when they appear (none in the catalog as of 2026-11-25); keep the + // guard so they never reach the picker if Nous lists them again. return (payload.data ?? []).filter((m) => m.id && !/hermes/i.test(m.id)).map(toModel); } @@ -237,7 +244,7 @@ const untier = (model: Model): Model => { return { ...model, headers }; }; -function withoutTierHeader(api: ProviderStreams): ProviderStreams { +export function withoutTierHeader(api: ProviderStreams): ProviderStreams { return { stream: (model, context, options) => api.stream(untier(model), context, options), streamSimple: (model, context, options) => api.streamSimple(untier(model), context, options), @@ -258,9 +265,10 @@ export default function nousPortal(pi: ExtensionAPI) { // One handler, two entry points: /nous-catalog cycles full → free → promo; /nous-free jumps straight to free. const apply = async (next: Catalog, ctx: ExtensionCommandContext) => { - catalog = next; + // Persist first: a failed write (read-only agent dir) must throw before memory and disk disagree. if (next === "full") rmSync(flagPath, { force: true }); else writeFileSync(flagPath, next); + 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. @@ -286,8 +294,7 @@ export default function nousPortal(pi: ExtensionAPI) { // Honored by Models.getAvailable(): /model lists only what this returns. filterModels: (all) => all.filter(inCatalog), api: { - // Nous free-tier models reject requests without a `tags.user` abuse-tracking tag; the built-in - // streamer has no provider-level body hook, so chain onPayload (the one sanctioned injection point). + // Strips the catalog-tier header only; no body rewriting (see untier). "openai-completions": withoutTierHeader(openAICompletionsApi()), }, async fetchModels(context: RefreshModelsContext) { diff --git a/tests/AGENTS.md b/tests/AGENTS.md index 1a8cc73..169ff4c 100644 --- a/tests/AGENTS.md +++ b/tests/AGENTS.md @@ -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 import time: `envApiKeyAuth`, `createProvider`, `openAICompletionsApi`. 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`. Anything not exported is not unit-tested. -- Network calls are replaced by assigning `globalThis.fetch` and restored in `finally`. -- `fetchModels` falls back to `process.env.NOUS_API_KEY`, so tests that assert "no network" must delete that variable for the duration and restore it afterwards. +- `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. +- 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`. ## Work Guidance diff --git a/tests/index.test.mjs b/tests/index.test.mjs index 7975ce8..eec9c94 100644 --- a/tests/index.test.mjs +++ b/tests/index.test.mjs @@ -14,7 +14,7 @@ const jiti = createJiti(import.meta.url, { "@earendil-works/pi-coding-agent": stub, }, }); -const { toModel, toCredential, fetchModels } = await jiti.import("../index.ts"); +const { toModel, toCredential, fetchModels, tierOf, withoutTierHeader } = await jiti.import("../index.ts"); 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" } }); @@ -23,13 +23,52 @@ test("toModel: per-token price becomes per-million, image input from architectur 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 rides on the model as the tier header (pi persists and restores model objects)", () => { const free = toModel({ id: "upstage/solar-mini4:free" }); + assert.equal(free.headers["x-nous-catalog-tier"], "free"); assert.deepEqual(free.input, ["text"]); assert.equal(free.reasoning, false); assert.equal(free.cost.input, 0); assert.equal(free.contextWindow, 131072); }); +test("withoutTierHeader: strips the tier header on both stream entry points and leaves everything else untouched", async () => { + const calls = []; + const api = { + stream: (m, c, o) => (calls.push(["stream", m, c, o]), "s"), + streamSimple: (m, c, o) => (calls.push(["streamSimple", m, c, o]), "ss"), + }; + const wrapped = withoutTierHeader(api); + const tiered = { id: "m", headers: { "x-nous-catalog-tier": "free", "x-keep": "1" } }; + const ctx = { messages: [] }; + const opts = { apiKey: "k" }; + assert.equal(await wrapped.stream(tiered, ctx, opts), "s"); + assert.equal(await wrapped.streamSimple(tiered, ctx, opts), "ss"); + for (const [entry, model, , options] of calls) { + assert.equal(model.headers["x-nous-catalog-tier"], undefined, entry); + assert.equal(model.headers["x-keep"], "1", "other headers survive"); + assert.notEqual(model, tiered, "original model object is not mutated"); + assert.equal(options, opts, "options pass through untouched"); + assert.equal(tiered.headers["x-nous-catalog-tier"], "free", "caller's model is not mutated"); + } + // Untiered models take the zero-copy fast path. + const plain = { id: "p" }; + wrapped.stream(plain, ctx, opts); + assert.equal(calls[2][1], plain); +}); + 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 }); @@ -40,26 +79,24 @@ 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 when neither a credential nor $NOUS_API_KEY is set", async () => { - const before = globalThis.fetch; - const saved = process.env.NOUS_API_KEY; - delete process.env.NOUS_API_KEY; - globalThis.fetch = () => { throw new Error("must not fetch"); }; - try { - assert.deepEqual(await fetchModels(undefined, new AbortController().signal), []); - } finally { - if (saved !== undefined) process.env.NOUS_API_KEY = saved; - globalThis.fetch = before; - } +test("fetchModels: returns [] and never touches the network with no credential", async (t) => { + 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: drops hermes entries and maps the rest", async () => { - const before = globalThis.fetch; - globalThis.fetch = async () => ({ ok: true, json: async () => ({ data: [{ id: "hermes/agent" }, { id: "qwen/qwen3.5-35b-a3b" }] }) }); - try { - const models = await fetchModels({ type: "api_key", key: "k" }, new AbortController().signal); - assert.deepEqual(models.map((m) => m.id), ["qwen/qwen3.5-35b-a3b"]); - } finally { - globalThis.fetch = before; - } +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: a non-OK response throws with the status", async (t) => { + t.mock.method(globalThis, "fetch", async () => ({ ok: false, status: 503 })); + await assert.rejects(fetchModels({ type: "api_key", key: "k" }, new AbortController().signal), /503/); }); diff --git a/tests/stubs/pi-ai.mjs b/tests/stubs/pi-ai.mjs index 9084bcd..5b9f87e 100644 --- a/tests/stubs/pi-ai.mjs +++ b/tests/stubs/pi-ai.mjs @@ -1,4 +1,6 @@ -// Minimal stand-in for the host-injected @earendil-works/* packages; only what index.ts touches at import time. +// Minimal stand-in for the host-injected @earendil-works/* packages; only what index.ts touches at module load. 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";