Files
AlexKucera 544af1eeea test: drive login poll loop with a fake clock
Give login an optional clock ({ now, sleep }) with the real timers as
the default, so the device-code poll loop can be tested without
wall-clock time. Neither t.mock.timers nor jiti aliasing reaches
node:timers/promises, so a seam is the only way in; auth.oauth.login
still passes only the interaction, so pi's interface is unchanged.

Six tests cover pending to slow_down to success, the interval fallback
and floor, the deadline cap, a non-retryable error and a non-OK device
code response. The token mock gives up after 100 polls: an
auto-advancing fake starves the event loop, so a sleep-less regression
would otherwise hang the suite with no test timeout able to fire.
2026-11-25 13:50:00 +01:00

308 lines
14 KiB
TypeScript

/**
* Nous Portal provider for pi.
*
* Nous retired Hermes-style agent-key minting (POST /api/oauth/agent-key → 410
* session_key_minting_retired, verified 2026-11-25). The inference API accepts
* the OAuth access token directly as a bearer credential, so this extension
* never mints or stores an agent key: `toAuth` hands the token to inference.
*
* Two /login methods: "Nous Portal (subscription)" runs the device-code OAuth
* flow; "Nous Portal API key" stores an sk-nous key (also read from
* $NOUS_API_KEY). Streaming delegates to pi's built-in openai-completions API.
*/
import { openAICompletionsApi } from "@earendil-works/pi-ai/compat";
import {
createProvider,
envApiKeyAuth,
type Api,
type AuthEvent,
type Credential,
type Model,
type OAuthCredential,
type ProviderAuth,
type ProviderAuthInteraction,
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";
const PORTAL = "https://portal.nousresearch.com";
const INFERENCE = "https://inference-api.nousresearch.com/v1";
const CLIENT_ID = "hermes-cli";
const SCOPE = "inference:mint_agent_key";
const PROVIDER_ID = "nous-portal";
// 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";
type TokenResponse = {
access_token: string;
refresh_token?: string;
expires_in?: number;
};
type DeviceCode = {
device_code: string;
user_code: string;
verification_uri: string;
verification_uri_complete?: string;
expires_in: number;
interval?: number;
};
type ModelListItem = {
id: string;
context_length?: number;
architecture?: { input_modalities?: string[] };
pricing?: { prompt?: string | number; completion?: string | number; original?: { prompt?: string | number } };
synthesizedFreeVariant?: boolean;
};
const formHeaders = {
"User-Agent": UA,
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
Origin: PORTAL,
Referer: `${PORTAL}/`,
};
class OAuthError extends Error {
constructor(
readonly code: string,
description: string,
) {
super(`${code}: ${description}`);
}
}
export async function tokenRequest(body: Record<string, string>, signal?: AbortSignal): Promise<TokenResponse> {
const response = await fetch(`${PORTAL}/api/oauth/token`, {
method: "POST",
headers: formHeaders,
body: new URLSearchParams({ client_id: CLIENT_ID, ...body }).toString(),
signal,
});
const text = await response.text();
if (!response.ok) {
// 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) ?? {}; // a literal `null` body must not turn `data.error` into a TypeError
} 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;
}
export function toCredential(token: TokenResponse, previous?: OAuthCredential): OAuthCredential {
return {
type: "oauth",
access: token.access_token,
refresh: token.refresh_token || previous?.refresh || "",
expires: Date.now() + (token.expires_in ?? 3600) * 1000,
};
}
type Clock = { now: () => number; sleep: (ms: number, signal?: AbortSignal) => Promise<void> };
// 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 }) };
export async function login(interaction: ProviderAuthInteraction, clock: Clock = realClock): Promise<OAuthCredential> {
const { signal } = interaction;
const response = await fetch(`${PORTAL}/api/oauth/device/code`, {
method: "POST",
headers: formHeaders,
body: new URLSearchParams({ client_id: CLIENT_ID, scope: SCOPE }).toString(),
signal,
});
if (!response.ok) throw new Error(`Nous device code request failed: ${response.status}`);
const device = (await response.json()) as DeviceCode;
const event: AuthEvent = {
type: "device_code",
userCode: device.user_code,
verificationUri: device.verification_uri_complete || device.verification_uri,
intervalSeconds: device.interval,
expiresInSeconds: device.expires_in,
};
interaction.notify(event);
// 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 = clock.now() + device.expires_in * 1000;
// 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 = () => 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),
);
} catch (error) {
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 nap();
else if (error.code === "slow_down") {
interval += 5;
await nap();
} else throw error;
}
}
throw new Error("Nous login timed out.");
}
const auth: ProviderAuth = {
oauth: {
name: "Nous Portal (subscription)",
isSubscription: true,
loginLabel: "Sign in to Nous Portal (subscription)",
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.
toAuth: async (credential) => ({ apiKey: credential.access }),
},
apiKey: envApiKeyAuth("Nous Portal API key", ["NOUS_API_KEY"]),
};
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 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<Catalog, "full">;
type TieredModel = Model<Api> & { catalogTier?: Tier };
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);
return {
id: item.id,
api: "openai-completions",
provider: PROVIDER_ID,
baseUrl: INFERENCE,
name: item.id,
reasoning: /(opus|sonnet|gpt-5|codex|gemini|grok|reason|thinking|glm|kimi|qwen3)/.test(id),
input: image ? ["text", "image"] : ["text"],
// Nous lists per-token prices; pi wants per-million.
cost: { input: num(item.pricing?.prompt) * 1e6, output: num(item.pricing?.completion) * 1e6, cacheRead: 0, cacheWrite: 0 },
contextWindow: item.context_length ?? 131072,
maxTokens: 32768,
catalogTier: tier,
};
}
const tierOfModel = (model: Model<Api>) => (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): 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);
if (was > 0 && now < was) return "promo";
return undefined;
}
// Offline baseline so the provider is visible to `pi --list-models` and `pi -p`, which never
// fetch live catalogs (allowModelNetwork is hard-coded false). Interactive startup overlays the live list.
// upstage/solar-mini4:free is deliberately absent: it alone rejects requests without a `tags` body field that
// the other free models 500 on, so no blanket injection can serve both.
const BASELINE: ModelListItem[] = [
{ id: "tencent/hy4-flash:free", context_length: 1048576, synthesizedFreeVariant: true },
{ id: "stepfun/step-3.7-flash:free", context_length: 256000, synthesizedFreeVariant: true },
{ id: "google/gemini-4-carbon", context_length: 1048576, architecture: { input_modalities: ["text", "image"] }, pricing: { prompt: "0.000002", completion: "0.000012", original: { prompt: "0.000004" } } },
{ id: "openai/gpt-5.4-nano", context_length: 400000, architecture: { input_modalities: ["text", "image"] }, pricing: { prompt: "0.00000016", completion: "0.000001" } },
{ id: "anthropic/claude-sonnet-4.6", context_length: 1000000, architecture: { input_modalities: ["text", "image"] }, pricing: { prompt: "0.0000024", completion: "0.000012" } },
{ id: "google/gemini-3.1-pro-preview", context_length: 1048576, architecture: { input_modalities: ["text", "image"] }, pricing: { prompt: "0.000002", completion: "0.000012" } },
{ id: "qwen/qwen3.5-35b-a3b", context_length: 262144, architecture: { input_modalities: ["text", "image"] }, pricing: { prompt: "0.00000014", completion: "0.000001" } },
{ id: "z-ai/glm-5.1", context_length: 204800, pricing: { prompt: "0.0000014", completion: "0.0000044" } },
];
export async function fetchModels(credential: Credential | undefined, signal: AbortSignal): Promise<Model<Api>[]> {
// 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);
}
export default function nousPortal(pi: ExtensionAPI) {
let models: Model<Api>[] = BASELINE.map(toModel);
const flagPath = join(getAgentDir(), "nous-portal-catalog");
let catalog: Catalog = "full";
try {
const saved = readFileSync(flagPath, "utf8").trim() as Catalog;
if (CATALOGS.includes(saved)) catalog = saved;
} catch {
// No saved catalog (first run, or full = file removed) → show everything.
}
const inCatalog = (m: Model<Api>) => catalog === "full" || tierOfModel(m) === catalog;
// One handler, two entry points: /nous-catalog cycles full → free → promo; /nous-free jumps straight to free.
const apply = async (next: Catalog, ctx: ExtensionCommandContext) => {
// 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] });
// A newer invocation may have changed the catalog while we awaited; it reports the final state, so stay silent.
if (catalog !== next) return;
const shown = ctx.modelRegistry.getAvailable().filter((m) => m.provider === PROVIDER_ID && inCatalog(m));
// Keep the session usable only when a Nous model just got filtered out; a session on another provider
// is left alone, and the notice names the model actually in use, not the first hit.
const onNous = ctx.model?.provider === PROVIDER_ID;
const current = onNous ? shown.find((m) => m.id === ctx.model?.id) : undefined;
const switched = shown.length && onNous && !current ? shown[0] : undefined;
if (switched) await pi.setModel(switched);
const inUse = current ?? switched;
ctx.ui.notify(`Nous catalog: ${next} (${shown.length} models)${inUse ? " — using " + inUse.id : ""}`);
};
const cycle: Record<Catalog, Catalog> = { full: "free", free: "promo", promo: "full" };
pi.registerCommand("nous-catalog", {
description: "Cycle Nous /model catalog: full → free → promo",
handler: (_args, ctx) => apply(cycle[catalog], ctx),
});
pi.registerCommand("nous-free", {
description: "Show only Nous free models in /model (again returns to full)",
handler: (_args, ctx) => apply(catalog === "free" ? "full" : "free", ctx),
});
pi.registerProvider(
createProvider({
id: PROVIDER_ID,
name: "Nous Portal",
baseUrl: INFERENCE,
auth,
models,
// Honored by Models.getAvailable(): /model lists only what this returns.
filterModels: (all) => all.filter(inCatalog),
// 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
// returned (pi-ai models.js refreshModels), so no publish here: that was a second, timestamp-less write.
if (fetched.length) models = fetched;
return models;
},
}),
);
}