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.
This commit is contained in:
AlexKucera committed 2026-11-25 10:28:25 +01:00
1 parent b9065d409c
commit 8d91094022
4 files changed
+75 -24

No files matched your search

+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
+20 -14
View File
@@ -128,12 +128,16 @@ async function login(interaction: ProviderAuthInteraction): Promise<OAuthCredent
expiresInSeconds: device.expires_in,
};
interaction.notify(event);
// pi shows the code and opens the browser on Enter; the prompt resolves once the user confirms.
await interaction.prompt({ type: "text", message: "Press Enter to open the Nous Portal sign-in page." });
// pi's dialog shows the code and opens the browser on Enter. Do NOT prompt here: a prompt clears that
// confirm action (login-dialog.js showPrompt → clearDeviceCodeAction), so Enter would open nothing.
const deadline = Date.now() + device.expires_in * 1000;
// 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);
// Floor at 1 s and reject non-finite values like pi-ai's own poller: a missing, zero, non-numeric or
// overflowing interval must not become a tight loop (Node clamps an overflowing setTimeout to 1 ms).
const requested = Number(device.interval);
let interval = Number.isFinite(requested) && requested > 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<OAuthCredent
if (!(error instanceof OAuthError)) throw error;
// RFC 8628: pending → wait the server's interval; slow_down → wait longer. Never poll again without sleeping,
// or a repeat slow_down turns into a tight loop against the token endpoint. The deadline bounds the total.
if (error.code === "authorization_pending") await sleep(interval * 1000, undefined, { signal });
if (error.code === "authorization_pending") await nap();
else if (error.code === "slow_down") {
interval += 5;
await sleep(interval * 1000, undefined, { signal });
await nap();
} else throw error;
}
}
@@ -235,20 +239,22 @@ 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.
// 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<Api>): Model<Api> => {
if (!model.headers?.[TIER_HEADER]) return model;
const headers = { ...model.headers };
// rewriting happens here — if that changes, chain options.onPayload.)
const untier = <T extends { headers?: Record<string, string | null> } | 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)),
};
}
+53 -8
View File
@@ -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 });
}
});