From cb5aecf815774f3f4dcdf4fdd455d347ef95c884 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Wed, 25 Nov 2026 13:49:58 +0100 Subject: [PATCH] refactor: carry catalog tier on the model Move the catalog tier from the x-nous-catalog-tier request header to a catalogTier property on each model. pi forwards only model.headers to the provider and copies them into the request options, so a header needed stripping on both the model and the options before every request; that adapter leaked for two audit rounds. A property never reaches the wire, survives pi's model store, and needs no wrapper, so TIER_HEADER, untier and withoutTierHeader are deleted and pi's stream passes through untouched. Models stored by the previous version come back without the property until the next interactive start rewrites the store; the CHANGELOG tells the user to start pi once interactively after upgrading. --- AGENTS.md | 2 +- CHANGELOG.md | 4 ++++ index.ts | 43 +++++++++++---------------------------- tests/AGENTS.md | 2 +- tests/index.test.mjs | 48 ++++++++------------------------------------ 5 files changed, 26 insertions(+), 73 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index fa08b82..e2b1eae 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 from both the model and the request options before every request (pi copies `model.headers` into `options.headers` before calling the provider). +- The catalog tier rides **on the model** as the `catalogTier` property, because pi persists and restores model objects across runs and a side table would miss restored entries. It is a property, not a header: pi forwards only `model.headers` to requests (and copies them into the options first), so nothing is stripped before a request. Do not move it into `headers` without bringing back a strip on both the model and the options. The persisted catalog is `/models-store.json` (`ModelsStore`); `models.json` holds only user overrides, so check the store when verifying anything carried on a model. ## Conventions and gotchas diff --git a/CHANGELOG.md b/CHANGELOG.md index 4fd2308..9f60ac2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,3 +10,7 @@ All notable changes to this project will be documented in this file. The format - 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. Switching never touches a session on another provider, and swaps the current model only if it was filtered out. + +### Changed + +- The catalog tier rides on each model as the `catalogTier` property instead of the `x-nous-catalog-tier` request header, so requests are no longer rewritten to strip it. After upgrading, start pi once interactively so persisted models pick up the new carrier; until then, a non-interactive run with the free or promo catalog active lists no Nous models. diff --git a/index.ts b/index.ts index eabd652..c745933 100644 --- a/index.ts +++ b/index.ts @@ -21,7 +21,6 @@ import { type OAuthCredential, type ProviderAuth, type ProviderAuthInteraction, - type ProviderStreams, type RefreshModelsContext, } from "@earendil-works/pi-ai"; import { setTimeout as sleep } from "node:timers/promises"; @@ -173,11 +172,13 @@ const auth: ProviderAuth = { const num = (v: string | number | undefined) => Number(v) || 0; -// Pi persists and restores model objects across runs, so the catalog tier travels ON the model (as an -// inert header Nous ignores) rather than in a side table that restored models would miss. -const TIER_HEADER = "x-nous-catalog-tier"; +// Pi persists and restores model objects across runs, so the catalog tier travels ON the model rather than in a +// side table that restored models would miss. It is a plain property, not a header: pi forwards only `headers` +// to the provider (copying them into the request options too), so a property needs no stripping before a request. +type Tier = Exclude; +type TieredModel = Model & { catalogTier?: Tier }; -export function toModel(item: ModelListItem): Model { +export function toModel(item: ModelListItem): TieredModel { const id = item.id.toLowerCase(); const tier = tierOf(item); const image = item.architecture?.input_modalities?.includes("image") ?? /(claude|gpt|gemini|grok|vl|vision)/.test(id); @@ -193,17 +194,17 @@ export function toModel(item: ModelListItem): Model { cost: { input: num(item.pricing?.prompt) * 1e6, output: num(item.pricing?.completion) * 1e6, cacheRead: 0, cacheWrite: 0 }, contextWindow: item.context_length ?? 131072, maxTokens: 32768, - ...(tier ? { headers: { [TIER_HEADER]: tier } } : {}), + catalogTier: tier, }; } -const tierOfModel = (model: Model) => model.headers?.[TIER_HEADER] as Exclude | undefined; +const tierOfModel = (model: Model) => (model as TieredModel).catalogTier; 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 { +export function tierOf(item: ModelListItem): Tier | undefined { if (item.synthesizedFreeVariant || item.id.toLowerCase().endsWith(":free")) return "free"; const now = Number(item.pricing?.prompt); const was = Number(item.pricing?.original?.prompt); @@ -239,25 +240,6 @@ export async function fetchModels(credential: Credential | undefined, signal: Ab return (payload.data ?? []).filter((m) => 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. 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, 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 { ...value, headers }; -}; - -export function withoutTierHeader(api: ProviderStreams): ProviderStreams { - return { - stream: (model, context, options) => api.stream(untier(model), context, untier(options)), - streamSimple: (model, context, options) => api.streamSimple(untier(model), context, untier(options)), - }; -} - export default function nousPortal(pi: ExtensionAPI) { let models: Model[] = BASELINE.map(toModel); const flagPath = join(getAgentDir(), "nous-portal-catalog"); @@ -307,10 +289,9 @@ export default function nousPortal(pi: ExtensionAPI) { models, // Honored by Models.getAvailable(): /model lists only what this returns. filterModels: (all) => all.filter(inCatalog), - api: { - // Strips the catalog-tier header only; no body rewriting (see untier). - "openai-completions": withoutTierHeader(openAICompletionsApi()), - }, + // pi's stream passes through untouched: no header or body rewriting. Nous free and discounted models + // 500 on an injected `tags.user` body field (2026-11-25); if that changes, chain options.onPayload. + api: { "openai-completions": openAICompletionsApi() }, async fetchModels(context: RefreshModelsContext) { const fetched = await fetchModels(context.credential, context.signal); // Empty live result → keep the last good list. createProvider persists and publishes whatever is diff --git a/tests/AGENTS.md b/tests/AGENTS.md index b38bc23..9d5f95a 100644 --- a/tests/AGENTS.md +++ b/tests/AGENTS.md @@ -15,7 +15,7 @@ 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` 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. `drive(flag)` returns `run(name, model, available, refresh)` — pass a deferred promise as `refresh` to simulate overlapping command invocations, and a Nous `model` when the `setModel` half of a contract is under test — plus the registered `provider`, which is how the provider-level `fetchModels` last-good retention is reached. Anything else is not unit-tested (notably the device-code poll loop inside `login`, which would need timer control and extraction). +- Exported functions under test: `toModel`, `toCredential`, `tokenRequest`, `fetchModels`, `tierOf`, and the default export via the `drive()` harness. `drive(flag)` returns `run(name, model, available, refresh)` — pass a deferred promise as `refresh` to simulate overlapping command invocations, and a Nous `model` when the `setModel` half of a contract is under test — plus the registered `provider`, which is how the provider-level `fetchModels` last-good retention is reached. 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. The one test that touches `process.env` sets it deliberately, to pin that `fetchModels` ignores it; it restores the previous value in `t.after`. diff --git a/tests/index.test.mjs b/tests/index.test.mjs index 60950d3..21505c9 100644 --- a/tests/index.test.mjs +++ b/tests/index.test.mjs @@ -17,7 +17,7 @@ const jiti = createJiti(import.meta.url, { }, }); const extension = await jiti.import("../index.ts"); -const { toModel, toCredential, tokenRequest, fetchModels, tierOf, withoutTierHeader } = extension; +const { toModel, toCredential, 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"); @@ -43,49 +43,17 @@ test("tierOf: free by synthesizedFreeVariant or :free suffix, promo only when pr 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)", () => { +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.headers["x-nous-catalog-tier"], "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); -}); - -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"), - 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: [] }; - // 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 + " 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.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"); - } - // 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); + 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"); }); test("toCredential: keeps the previous refresh token when the server rotates only the access token", () => { @@ -176,7 +144,7 @@ const drive = (flag) => { }); return { run, provider, switched, notes }; }; -const nous = (id, tier) => ({ id, provider: "nous-portal", ...(tier && { headers: { "x-nous-catalog-tier": tier } }) }); +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 () => {