Files
nous-portal/index.ts
T
AlexKucera 78e89241a6 fix: address round-4 review findings
- apply(): if a newer invocation changed the catalog while this one
  awaited the model refresh, exit silently. The superseded invocation
  otherwise reported the second's catalog in its notice and could fire
  one extra setModel. Pinned with a deferred-refresh test.
- CITATION.cff: drop date-released while the CHANGELOG is [Unreleased]
  and no release tag exists; version stays 0.1.0.
- Tests: 18 (was 17).
2026-11-25 10:43:26 +01:00

324 lines
15 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 ProviderStreams,
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,
};
}
async function login(interaction: ProviderAuthInteraction): 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 = Date.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 = () => sleep(Math.min(interval * 1000, deadline - Date.now()), undefined, { signal });
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;
// 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,
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<Api> {
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 } } : {}),
};
}
const tierOfModel = (model: Model<Api>) => model.headers?.[TIER_HEADER] as Exclude<Catalog, "full"> | undefined;
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<Catalog, "full"> | 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);
}
// 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 = <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 { ...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<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),
api: {
// Strips the catalog-tier header only; no body rewriting (see untier).
"openai-completions": withoutTierHeader(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;
},
}),
);
}