diff --git a/AGENTS.md b/AGENTS.md index e2b1eae..e4bef19 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,6 +15,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. - 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. +- `login` accepts an optional clock (`{ now, sleep }`): production uses `node:timers/promises` and `Date.now`, tests an auto-advancing fake. `auth.oauth.login` passes only the interaction, so pi's interface is unchanged. ## Conventions and gotchas diff --git a/index.ts b/index.ts index c745933..92ee14c 100644 --- a/index.ts +++ b/index.ts @@ -107,8 +107,11 @@ export function toCredential(token: TokenResponse, previous?: OAuthCredential): }; } +type Clock = { now: () => number; sleep: (ms: number, signal?: AbortSignal) => Promise }; +// Production adapter: the node:timers/promises sleep, which rejects on abort. Tests pass an auto-advancing fake. +const realClock: Clock = { now: Date.now, sleep: (ms, signal) => sleep(ms, undefined, { signal }) }; -async function login(interaction: ProviderAuthInteraction): Promise { +export async function login(interaction: ProviderAuthInteraction, clock: Clock = realClock): Promise { const { signal } = interaction; const response = await fetch(`${PORTAL}/api/oauth/device/code`, { method: "POST", @@ -130,14 +133,14 @@ 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) { + const nap = () => clock.sleep(Math.min(interval * 1000, deadline - clock.now()), signal); + while (clock.now() < deadline) { try { return toCredential( await tokenRequest({ grant_type: "urn:ietf:params:oauth:grant-type:device_code", device_code: device.device_code }, signal), @@ -161,7 +164,7 @@ const auth: ProviderAuth = { name: "Nous Portal (subscription)", isSubscription: true, loginLabel: "Sign in to Nous Portal (subscription)", - login, + login: (interaction) => login(interaction), refresh: (credential, signal) => tokenRequest({ grant_type: "refresh_token", refresh_token: credential.refresh }, signal).then((t) => toCredential(t, credential)), // The access token is the inference credential; no agent key is minted. diff --git a/tests/AGENTS.md b/tests/AGENTS.md index 9d5f95a..a394794 100644 --- a/tests/AGENTS.md +++ b/tests/AGENTS.md @@ -2,7 +2,7 @@ ## Purpose -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. +Offline unit tests for `index.ts`. They pin the pure logic that has real branching: model mapping, credential construction, the device-code poll loop, model fetching, token-endpoint error handling, and the slash commands (driven through a recording `pi`). No network, no real credentials, no wall-clock time. ## Ownership @@ -15,7 +15,8 @@ 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`, 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`, `login`, `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. +- `login` takes an optional clock (`{ now, sleep }`) and defaults to real timers. Five of the six `login` tests drive it with `driveLogin(t, replies, device)`; the sixth exercises the default clock: an auto-advancing clock (each sleep adds its ms to `now`) plus a mocked device-code and token endpoint, where the last reply repeats and the mock gives up after 100 token polls, so a sleep-less regression fails instead of hanging (the fake clock starves the event loop; no test timeout can fire). Never wait on wall-clock time in tests: `t.mock.timers` does not capture `node:timers/promises` and jiti does not alias `node:` builtins (both probed on Node 26). - 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 21505c9..8530661 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 } = extension; +const { toModel, toCredential, login, 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"); @@ -56,6 +56,62 @@ test("toModel: the catalog tier is a model property, never a header, so nothing assert.equal(toModel({ id: "openai/gpt-5.4-nano" }).catalogTier, undefined, "untiered models carry no tier"); }); +// login() is driven with an auto-advancing clock: each sleep adds its ms to `now` and resolves at once, so the +// deadline falls out of the sleeps themselves. The token endpoint is mocked; the last reply repeats, and the mock +// gives up after 100 polls so a sleep-less regression FAILS instead of hanging (the fake clock starves the event +// loop, so no test timeout can fire). +const DEVICE = { device_code: "d", user_code: "USER-1", verification_uri: "https://portal.nousresearch.com/device", expires_in: 60, interval: 5 }; +const oauthError = (error) => ({ ok: false, status: 400, text: async () => JSON.stringify({ error }) }); +const token = (access_token) => ({ ok: true, text: async () => JSON.stringify({ access_token, expires_in: 3600 }) }); +const driveLogin = (t, replies, device = DEVICE) => { + const sleeps = [], events = []; + let now = 1_000_000, call = 0; + t.mock.method(globalThis, "fetch", async (url) => { + if (String(url).endsWith("/device/code")) return { ok: true, json: async () => device }; + if (call >= 100) throw new Error("runaway poll loop: 100 token polls without reaching the deadline"); + return replies[Math.min(call++, replies.length - 1)]; + }); + const clock = { now: () => now, sleep: async (ms) => { sleeps.push(ms); now += ms; } }; + return { sleeps, events, run: () => login({ notify: (event) => events.push(event), signal: new AbortController().signal }, clock) }; +}; + +test("login: shows the device code once, waits the server interval on pending and 5 s more on slow_down, then returns the credential", async (t) => { + const { run, sleeps, events } = driveLogin(t, [oauthError("authorization_pending"), oauthError("slow_down"), token("tok")]); + const credential = await run(); + assert.deepEqual(sleeps, [5000, 10000]); + assert.deepEqual(events, [{ type: "device_code", userCode: "USER-1", verificationUri: "https://portal.nousresearch.com/device", intervalSeconds: 5, expiresInSeconds: 60 }]); + assert.equal(credential.access, "tok"); +}); + +test("login: a missing interval falls back to 5 s", async (t) => { + const { run, sleeps } = driveLogin(t, [oauthError("authorization_pending"), token("a")], { ...DEVICE, interval: undefined }); + await run(); + assert.deepEqual(sleeps, [5000]); +}); + +test("login: a fractional interval is floored at 1 s", async (t) => { + const { run, sleeps } = driveLogin(t, [oauthError("authorization_pending"), token("b")], { ...DEVICE, interval: 0.5 }); + await run(); + assert.deepEqual(sleeps, [1000]); +}); + +test("login: never sleeps past the deadline; a poll that stays pending times out", async (t) => { + const { run, sleeps } = driveLogin(t, [oauthError("authorization_pending")], { ...DEVICE, expires_in: 12 }); + await assert.rejects(run(), /Nous login timed out/); + assert.deepEqual(sleeps, [5000, 5000, 2000]); +}); + +test("login: a non-retryable OAuth error propagates without sleeping", async (t) => { + const { run, sleeps } = driveLogin(t, [oauthError("expired_token")]); + await assert.rejects(run(), /expired_token/); + assert.deepEqual(sleeps, []); +}); + +test("login: a non-OK device-code response throws with its status (real clock; no sleep is reached)", async (t) => { + t.mock.method(globalThis, "fetch", async () => ({ ok: false, status: 403 })); + await assert.rejects(login({ notify() {}, signal: new AbortController().signal }), /device code request failed: 403/); +}); + 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 });