fix: address round-1 review findings
- slow_down now sleeps (and waits longer) instead of re-polling at once; the interval cap that could lower a server interval is gone. The deadline already bounds the loop. - Non-JSON error bodies from gateways and the Vercel checkpoint no longer surface as SyntaxError; the HTTP status is preserved. - Drop the dead process.env.NOUS_API_KEY fallback in fetchModels: envApiKeyAuth already resolves it into the credential upstream. - apply() persists the catalog flag before mutating memory, so a read-only agent dir cannot leave the two out of step. - sleep() replaced with node:timers/promises; three unused exports removed; stale tags.user comment corrected; hermes filter explained. - Tests: 8 (was 4). Pin tierOf, the tier header, and withoutTierHeader on both stream entry points; t.mock.method replaces hand-rolled fetch swaps; stub gains getAgentDir. - Docs: README covers install lockfile flag, hermes row, browser-UA posture, and typecheck path pinning; AGENTS.md allowlist includes pi-coding-agent; tests/AGENTS.md contracts updated.
This commit is contained in:
1 parent
8bbece7613
commit
00d50e10de
7 files changed
+102
-50
No files matched your search
@@ -24,6 +24,7 @@ import {
|
||||
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";
|
||||
@@ -33,12 +34,11 @@ 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 = {
|
||||
type TokenResponse = {
|
||||
access_token: string;
|
||||
refresh_token?: string;
|
||||
expires_in?: number;
|
||||
@@ -87,7 +87,13 @@ async function tokenRequest(body: Record<string, string>, signal?: AbortSignal):
|
||||
});
|
||||
const text = await response.text();
|
||||
if (!response.ok) {
|
||||
const data = JSON.parse(text) as { error?: string; error_description?: string };
|
||||
// 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);
|
||||
} 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;
|
||||
@@ -102,13 +108,6 @@ export function toCredential(token: TokenResponse, previous?: OAuthCredential):
|
||||
};
|
||||
}
|
||||
|
||||
function sleep(ms: number, signal: AbortSignal): Promise<void> {
|
||||
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<OAuthCredential> {
|
||||
const { signal } = interaction;
|
||||
@@ -141,9 +140,13 @@ async function login(interaction: ProviderAuthInteraction): Promise<OAuthCredent
|
||||
);
|
||||
} 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;
|
||||
// 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 });
|
||||
else if (error.code === "slow_down") {
|
||||
interval += 5;
|
||||
await sleep(interval * 1000, undefined, { signal });
|
||||
} else throw error;
|
||||
}
|
||||
}
|
||||
throw new Error("Nous login timed out.");
|
||||
@@ -189,10 +192,10 @@ export function toModel(item: ModelListItem): Model<Api> {
|
||||
};
|
||||
}
|
||||
|
||||
export const tierOfModel = (model: Model<Api>) => model.headers?.[TIER_HEADER] as Exclude<Catalog, "full"> | undefined;
|
||||
const tierOfModel = (model: Model<Api>) => model.headers?.[TIER_HEADER] as Exclude<Catalog, "full"> | undefined;
|
||||
|
||||
export const CATALOGS = ["full", "free", "promo"] as const;
|
||||
export type Catalog = (typeof CATALOGS)[number];
|
||||
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 {
|
||||
@@ -219,11 +222,15 @@ const BASELINE: ModelListItem[] = [
|
||||
];
|
||||
|
||||
export async function fetchModels(credential: Credential | undefined, signal: AbortSignal): Promise<Model<Api>[]> {
|
||||
const key = credential?.type === "oauth" ? credential.access : (credential?.key || process.env.NOUS_API_KEY);
|
||||
// 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);
|
||||
}
|
||||
|
||||
@@ -237,7 +244,7 @@ const untier = (model: Model<Api>): Model<Api> => {
|
||||
return { ...model, headers };
|
||||
};
|
||||
|
||||
function withoutTierHeader(api: ProviderStreams): ProviderStreams {
|
||||
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),
|
||||
@@ -258,9 +265,10 @@ export default function nousPortal(pi: ExtensionAPI) {
|
||||
|
||||
// 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;
|
||||
// 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] });
|
||||
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.
|
||||
@@ -286,8 +294,7 @@ export default function nousPortal(pi: ExtensionAPI) {
|
||||
// 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).
|
||||
// Strips the catalog-tier header only; no body rewriting (see untier).
|
||||
"openai-completions": withoutTierHeader(openAICompletionsApi()),
|
||||
},
|
||||
async fetchModels(context: RefreshModelsContext) {
|
||||
|
||||
Reference in new issue
Block a user