From 8d91094022cb5042d9f47e9571c11ce8cded668c Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Wed, 25 Nov 2026 10:28:25 +0100 Subject: [PATCH] fix: address round-3 review findings - Strip the catalog-tier header from request options too. pi copies model.headers into options.headers before calling the provider (pi-ai getAuth -> prepareRequest) and the client applies options.headers last, so the header still reached Nous on every free/promo request; the old test pinned the leak. Both sides pinned. - Drop the 'Press Enter' prompt in OAuth login: it cleared pi's device-code confirm action (login-dialog showPrompt), so Enter opened nothing. pi's own dialog shows the code and opens the browser. - Poll interval rejects non-finite values (Node clamps an overflowing setTimeout to 1 ms) and each sleep is capped at the deadline, matching pi-ai's poller. - Tests: 17 (was 14). /nous-free back to full, /nous-catalog cycling, and startup restore of a saved catalog are covered. - Docs: README says the live list overlays the baseline by id (baseline ids that vanish stay listed); AGENTS.md states both strips. --- AGENTS.md | 2 +- README.md | 2 +- index.ts | 34 ++++++++++++++---------- tests/index.test.mjs | 61 ++++++++++++++++++++++++++++++++++++++------ 4 files changed, 75 insertions(+), 24 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ff7b521..11a92f8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,7 +14,7 @@ - Uses the **native** pi-ai `Provider` (`createProvider`) rather than the legacy `ProviderConfig` + `oauth` block. The legacy `getApiKey` contract pushes an extension toward minting an agent key; Nous retired that endpoint (`410 session_key_minting_retired`). Here `OAuthAuth.toAuth` returns the access token itself, and pi owns the locked refresh pattern. See `docs/adr/0001-stack.md`. - Streaming is delegated to pi's built-in `openai-completions` API. No custom wire protocol. -- `Model.headers["x-nous-catalog-tier"]` carries the catalog tier **on the model**, because pi persists and restores model objects across runs and a side table would miss restored entries. `withoutTierHeader` strips it before every request. +- `Model.headers["x-nous-catalog-tier"]` carries the catalog tier **on the model**, because pi persists and restores model objects across runs and a side table would miss restored entries. `withoutTierHeader` strips it from both the model and the request options before every request (pi copies `model.headers` into `options.headers` before calling the provider). ## Conventions and gotchas diff --git a/README.md b/README.md index e15c141..cbfb622 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ The choice is saved in `~/.pi/agent/nous-portal-catalog` and survives restarts. ### Offline baseline -`pi -p` and `pi --list-models` never fetch live catalogs (pi hard-codes `allowModelNetwork: false` there), so the provider ships a small static baseline so it is always usable. Interactive pi replaces it with the live list. +`pi -p` and `pi --list-models` never fetch live catalogs (pi hard-codes `allowModelNetwork: false` there), so the provider ships a small static baseline so it is always usable. Interactive pi overlays the live list on the baseline by model id; a baseline id that disappears from the live catalog stays listed, with its frozen baseline price and context, until the next release. ## Known limits diff --git a/index.ts b/index.ts index 30b7a9c..3736d22 100644 --- a/index.ts +++ b/index.ts @@ -128,12 +128,16 @@ async function login(interaction: ProviderAuthInteraction): Promise 0 ? Math.max(requested, 1) : 5; + // Never sleep past the deadline. + const nap = () => sleep(Math.min(interval * 1000, deadline - Date.now()), undefined, { signal }); while (Date.now() < deadline) { try { return toCredential( @@ -143,10 +147,10 @@ async function login(interaction: ProviderAuthInteraction): Promise m.id && !/hermes/i.test(m.id)).map(toModel); } -// The tier header is metadata only; strip it before the request so it never reaches Nous. +// The tier header is metadata only; strip it before the request so it never reaches Nous. pi copies +// model.headers into options.headers before calling the provider (pi-ai getAuth → prepareRequest) and the +// client applies options.headers last, so BOTH the model and the options must be stripped. // (Nous free/discounted models 500 on an injected `tags.user` body field as of 2026-11-25, so no body -// rewriting happens here — if that changes, wrap stream/streamSimple and chain options.onPayload.) -const untier = (model: Model): Model => { - if (!model.headers?.[TIER_HEADER]) return model; - const headers = { ...model.headers }; +// rewriting happens here — if that changes, chain options.onPayload.) +const untier = } | undefined>(value: T): T => { + if (!value?.headers?.[TIER_HEADER]) return value; + const headers = { ...value.headers }; delete headers[TIER_HEADER]; - return { ...model, headers }; + return { ...value, headers }; }; 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), + stream: (model, context, options) => api.stream(untier(model), context, untier(options)), + streamSimple: (model, context, options) => api.streamSimple(untier(model), context, untier(options)), }; } diff --git a/tests/index.test.mjs b/tests/index.test.mjs index 9fb70ef..f69821f 100644 --- a/tests/index.test.mjs +++ b/tests/index.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, test } from "node:test"; import { createJiti } from "jiti"; -import { mkdirSync, rmSync } from "node:fs"; +import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; @@ -52,7 +52,7 @@ test("toModel: the catalog tier rides on the model as the tier header (pi persis assert.equal(free.contextWindow, 131072); }); -test("withoutTierHeader: strips the tier header on both stream entry points and leaves everything else untouched", async () => { +test("withoutTierHeader: strips the tier header from model AND options on both stream entry points; everything else untouched", async () => { const calls = []; const api = { stream: (m, c, o) => (calls.push(["stream", m, c, o]), "s"), @@ -61,20 +61,31 @@ test("withoutTierHeader: strips the tier header on both stream entry points and const wrapped = withoutTierHeader(api); const tiered = { id: "m", headers: { "x-nous-catalog-tier": "free", "x-keep": "1" } }; const ctx = { messages: [] }; - const opts = { apiKey: "k" }; + // pi copies model.headers into options.headers before calling the provider, so options carry the tier too. + const opts = { apiKey: "k", headers: { "x-nous-catalog-tier": "free", "x-keep": "1" } }; 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.equal(model.headers["x-nous-catalog-tier"], undefined, entry + " model"); + assert.equal(model.headers["x-keep"], "1", "other model headers survive"); assert.notEqual(model, tiered, "original model object is not mutated"); - assert.equal(options, opts, "options pass through untouched"); + assert.equal(options.headers["x-nous-catalog-tier"], undefined, entry + " options"); + assert.equal(options.headers["x-keep"], "1", "other option headers survive"); + assert.equal(options.apiKey, "k"); + assert.notEqual(options, opts, "stripped options are a copy"); assert.equal(tiered.headers["x-nous-catalog-tier"], "free", "caller's model is not mutated"); + assert.equal(opts.headers["x-nous-catalog-tier"], "free", "caller's options are not mutated"); } - // Untiered models take the zero-copy fast path. + // An untiered model is passed through by identity; tiered options are still stripped. const plain = { id: "p" }; wrapped.stream(plain, ctx, opts); assert.equal(calls[2][1], plain); + assert.equal(calls[2][3].headers["x-nous-catalog-tier"], undefined); + // Nothing to strip on either side → both by identity. + const bare = { apiKey: "k" }; + wrapped.stream(plain, ctx, bare); + assert.equal(calls[3][1], plain); + assert.equal(calls[3][3], bare); }); test("toCredential: keeps the previous refresh token when the server rotates only the access token", () => { @@ -129,8 +140,10 @@ test("fetchModels: an API key is sent as the bearer; a non-OK response throws wi }); // Drives the default export with a recording pi, so the slash commands run without a real host. -const drive = () => { +// `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), @@ -181,3 +194,35 @@ test("/nous-free: a failed flag write leaves the catalog unchanged (persist befo 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("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 }); + } +});