/** * 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 ProviderStreams, type RefreshModelsContext, } from "@earendil-works/pi-ai"; 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"; const POLL_CAP_SECONDS = 10; // 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"; export 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}`); } } async function tokenRequest(body: Record, signal?: AbortSignal): Promise { 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) { const data = JSON.parse(text) as { error?: string; error_description?: string }; 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, }; } function sleep(ms: number, signal: AbortSignal): Promise { return new Promise((resolve, reject) => { if (signal.aborted) return reject(new Error("Nous login cancelled")); const timer = setTimeout(resolve, ms); signal.addEventListener("abort", () => void (clearTimeout(timer), reject(new Error("Nous login cancelled"))), { once: true }); }); } async function login(interaction: ProviderAuthInteraction): Promise { 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 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." }); const deadline = Date.now() + device.expires_in * 1000; let interval = device.interval ?? 5; while (Date.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; if (error.code === "authorization_pending") await sleep(interval * 1000, signal); else if (error.code === "slow_down") interval = Math.min(interval + 5, POLL_CAP_SECONDS); 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, 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 (as an // inert header Nous ignores) rather than in a side table that restored models would miss. const TIER_HEADER = "x-nous-catalog-tier"; export function toModel(item: ModelListItem): Model { 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, ...(tier ? { headers: { [TIER_HEADER]: tier } } : {}), }; } export const tierOfModel = (model: Model) => model.headers?.[TIER_HEADER] as Exclude | undefined; export const CATALOGS = ["full", "free", "promo"] as const; export 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 { 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[]> { const key = credential?.type === "oauth" ? credential.access : (credential?.key || process.env.NOUS_API_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[] }; 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. // (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 }; delete headers[TIER_HEADER]; return { ...model, headers }; }; 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), }; } export default function nousPortal(pi: ExtensionAPI) { let models: Model[] = 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) => 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) => { catalog = next; if (next === "full") rmSync(flagPath, { force: true }); else writeFileSync(flagPath, next); await ctx.modelRegistry.refresh({ providers: [PROVIDER_ID] }); const shown = ctx.modelRegistry.getAvailable().filter((m) => m.provider === PROVIDER_ID && inCatalog(m)); // Keep the session usable if the current model just got filtered out. if (shown.length && !shown.some((m) => m.id === ctx.model?.id)) await pi.setModel(shown[0]); ctx.ui.notify(`Nous catalog: ${next} (${shown.length} models)${shown[0] ? " — using " + shown[0].id : ""}`); }; const cycle: Record = { 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), api: { // Nous free-tier models reject requests without a `tags.user` abuse-tracking tag; the built-in // streamer has no provider-level body hook, so chain onPayload (the one sanctioned injection point). "openai-completions": withoutTierHeader(openAICompletionsApi()), }, async fetchModels(context: RefreshModelsContext) { const fetched = await fetchModels(context.credential, context.signal); if (fetched.length) { models = fetched; await context.publish({ persist: { models: fetched } }); } return models; }, }), ); }