Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(oauth): load vendor account models from each vendor
vastsae4900118ce9c
diff --git a/apps/desktop/electron/main/ipc/provider-ipc.ts b/apps/desktop/electron/main/ipc/provider-ipc.tsindex 06a4ec134..8dedf6419 100644--- a/apps/desktop/electron/main/ipc/provider-ipc.ts+++ b/apps/desktop/electron/main/ipc/provider-ipc.ts@@ -398,9 +398,8 @@ export function registerProviderIpc({}};- // A signed-in vendor account has no API key. Copilot and the static- // vendors are listed from pi-ai. xAI instead reads GET /v1/models with- // the account token inside VendorOAuth.listModels.+ // A signed-in vendor account has no API key. VendorOAuth.listModels+ // reads that account's model endpoint; pi-ai is only the fallback.if (req.source !== "cache" && provider?.authKind === OAUTH_AUTH_KIND) {try {const options = await vendorOAuth.listModels(provider.id);diff --git a/apps/desktop/electron/main/oauth.ts b/apps/desktop/electron/main/oauth.tsindex 9d1a34219..783fe2dcb 100644--- a/apps/desktop/electron/main/oauth.ts+++ b/apps/desktop/electron/main/oauth.ts@@ -41,7 +41,14 @@ import {type ModelConfig,type VendorModelBinding,} from "@pi-desktop/agent-runtime";-import { discoverProviderModels } from "./model-discovery.ts";+import {+ isConversationModelId,+ parseVendorModelIds,+ pinnedSiblingId,+ readVendorModelList,+ vendorModelListRequest,+ wireForLiveModel,+} from "./vendor-live-models.ts";import {OAUTH_AUTH_KIND,type OAuthLoginEvent,@@ -91,9 +98,8 @@ export function protocolForApiStyle(apiStyle: string): string {return PROTOCOL_BY_API_STYLE[apiStyle] ?? "openai_compatible";}-const XAI_VENDOR_ID = "xai";-const XAI_MODELS_URL_BASE = "https://api.x.ai/v1";-const XAI_LIVE_MODELS_TTL_MS = 30_000;+const LIVE_MODELS_TTL_MS = 30_000;+const LIVE_MODELS_NEGATIVE_TTL_MS = 15_000;const THINKING_LEVEL_ORDER = ["off","minimal",@@ -104,16 +110,9 @@ const THINKING_LEVEL_ORDER = ["max",] as const satisfies readonly ThinkingLevel[];-/**- * xAI's `/models` list also publishes image and video generators. Those are not- * conversation models; the chat picker and session launch both reject them.- */-const XAI_NON_CONVERSATION_MODEL =- /(?:^|[-_/])(?:imagine|image|video|tts|stt|embed(?:ding)?|whisper|aurora|flux)(?:$|[-_/])/i;-+/** xAI and the other account lists also publish generators. Those are not conversation models. */export function isXaiConversationModel(modelId: string): boolean {- const id = modelId.trim();- return id.length > 0 && !XAI_NON_CONVERSATION_MODEL.test(id);+ return isConversationModelId(modelId);}function thinkingLevelsFromPiModel(model: Model<Api>): ThinkingLevel[] {@@ -171,6 +170,8 @@ export type VendorOAuthDeps = {option: OAuthModelOption;}) => Promise<ModelConfig | undefined>;newId?: () => string;+ /** Test seam. Defaults to the process fetch. */+ fetch?: typeof fetch;};/**@@ -234,8 +235,9 @@ export class VendorOAuth {private readonly logins = new Map<string, LoginSession>();/** One pi-ai collection and credential store per local OAuth account row. */private readonly accountModels = new Map<string, AccountModels>();- /** Successful xAI `/models` responses, so one login does not refetch per model. */- private readonly xaiLiveModels = new Map<string, { at: number; models: OAuthModelOption[] }>();+ /** Successful and failed account model lists, so launch does not refetch per model. */+ private readonly liveModelCache = new Map<string, { at: number; models: OAuthModelOption[] | null }>();+ private readonly liveModelLoads = new Map<string, Promise<OAuthModelOption[] | undefined>>();/** Per-account write chain: `modify` must be a serialized read-modify-write. */private readonly chains = new Map<string, Promise<unknown>>();private catalogPromise?: Promise<MutableModels>;@@ -362,7 +364,8 @@ export class VendorOAuth {await running.finished?.catch(() => undefined);}this.accountModels.delete(providerId);- this.xaiLiveModels.delete(providerId);+ this.liveModelCache.delete(providerId);+ this.liveModelLoads.delete(providerId);await this.deps.call("providers.delete", { id: providerId });}@@ -384,21 +387,17 @@ export class VendorOAuth {/*** Models the signed-in account may actually use.*- * Copilot and the other static vendors still come from pi-ai: `getAvailable`- * applies that vendor's `filterModels`. xAI is different. Its pinned catalog- * stops at whatever shipped in pi-ai, so a model Grok has already entitled- * (grok-4.7 today) never becomes selectable. For that vendor the account's- * own `GET /v1/models` list is the authority, and the pinned catalog is only- * the fallback when that request fails.+ * The account's own model list is the authority. pi-ai (`getAvailable`,+ * including a vendor `filterModels`) is used only when that request cannot+ * be read. Radius keeps its gateway refresh and does not get a second probe.*/async listModels(providerId: string): Promise<OAuthModelOption[]> {return this.withRowHeaders(providerId, async () => {const account = await this.accountForProvider(providerId);if (!account) throw new Error(`unknown vendor account provider: ${providerId}`);- // Dynamic catalogs (radius, Copilot) are empty until refreshed; static and- // unconfigured providers are skipped inside pi-ai.+ // Dynamic catalogs (radius) are empty until refreshed.await account.models.refresh({ providers: [account.vendorId] });- const live = await this.liveXaiModels(account);+ const live = await this.liveAccountModels(account);if (live) return live;const available = await account.models.getAvailable(account.vendorId);return available.map((model) => this.optionFor(model));@@ -439,15 +438,14 @@ export class VendorOAuth {if (!account) return undefined;let model = account.models.getModel(account.vendorId, modelId);if (!model) {- // Dynamic catalogs are empty until the first refresh.await account.models.refresh({ providers: [account.vendorId] });model = account.models.getModel(account.vendorId, modelId);}- const live = await this.liveXaiModels(account);+ const live = await this.liveAccountModels(account);if (live) {const option = live.find((item) => item.modelId === modelId);- // A successful Grok list replaces the pinned catalog. An id it did not- // return is not offered, even when pi-ai still ships that id.+ // A successful account list replaces the pinned catalog. An id it did+ // not return is not offered, even when pi-ai still ships that id.if (!option) return undefined;return this.bindingFromOption(account, option);}@@ -456,52 +454,88 @@ export class VendorOAuth {}/**- * Chat models the signed-in xAI account can call right now.+ * Chat models the signed-in account can call right now.* `undefined` means the live list could not be read; callers keep the- * pinned catalog. Image and video generators are dropped.+ * pinned catalog.*/- private async liveXaiModels(+ private async liveAccountModels(+ account: AccountModels,+ ): Promise<OAuthModelOption[] | undefined> {+ if (account.vendorId === "radius") return undefined;+ const cached = this.liveModelCache.get(account.providerId);+ if (cached) {+ const ttl = cached.models ? LIVE_MODELS_TTL_MS : LIVE_MODELS_NEGATIVE_TTL_MS;+ if (Date.now() - cached.at < ttl) return cached.models ?? undefined;+ }+ const pending = this.liveModelLoads.get(account.providerId);+ if (pending) return pending;+ const load = this.loadLiveAccountModels(account).finally(() => {+ this.liveModelLoads.delete(account.providerId);+ });+ this.liveModelLoads.set(account.providerId, load);+ return load;+ }++ private rememberLiveModels(+ providerId: string,+ models: OAuthModelOption[] | null,+ ): OAuthModelOption[] | undefined {+ this.liveModelCache.set(providerId, { at: Date.now(), models });+ return models ?? undefined;+ }++ private async loadLiveAccountModels(account: AccountModels,): Promise<OAuthModelOption[] | undefined> {- if (account.vendorId !== XAI_VENDOR_ID) return undefined;- const cached = this.xaiLiveModels.get(account.providerId);- if (cached && Date.now() - cached.at < XAI_LIVE_MODELS_TTL_MS) return cached.models;let apiKey: string | undefined;- let baseUrl = XAI_MODELS_URL_BASE;+ let baseUrl: string | undefined;try {const resolved = await account.models.getAuth(account.vendorId);apiKey = resolved?.auth.apiKey;- if (resolved?.auth.baseUrl) baseUrl = resolved.auth.baseUrl.replace(/\/+$/, "");+ baseUrl = resolved?.auth.baseUrl;} catch (error) {- this.log("warn", "xAI account auth unavailable for model list", {+ this.log("warn", "vendor account auth unavailable for model list", {vendorId: account.vendorId,message: error instanceof Error ? error.message : String(error),});return undefined;}- if (!apiKey) return undefined;+ const request = vendorModelListRequest({+ vendorId: account.vendorId,+ apiKey,+ baseUrl,+ });+ if (!request) return undefined;try {- const discovered = await discoverProviderModels({- baseUrl,- apiKey,- apiStyle: "responses",+ const body = await readVendorModelList(request, this.deps.fetch ?? globalThis.fetch);+ const ids = parseVendorModelIds(account.vendorId, body, request.allowPolicyFallback);+ if (!ids || ids.length === 0) return this.rememberLiveModels(account.providerId, null);+ const pinned = await account.models.getAvailable(account.vendorId);+ const known = new Map(pinned.map((model) => [model.id, model]));+ const wires = pinned.map((model) => ({+ id: model.id,+ api: model.api,+ baseUrl: model.baseUrl,+ }));+ const models = ids.flatMap((modelId) => {+ const pinnedModel = known.get(modelId);+ if (pinnedModel) return [this.optionFor(pinnedModel)];+ const wire = wireForLiveModel(account.vendorId, modelId, wires, request.accountBaseUrl);+ if (!wire?.api || !wire.baseUrl) return [];+ return [{+ modelId,+ apiStyle: apiStyleForWireApi(wire.api),+ baseUrl: wire.baseUrl,+ }];});- const models = discovered- .filter((model) => isXaiConversationModel(model.modelId))- .map((model) => ({- modelId: model.modelId,- apiStyle: apiStyleForWireApi("openai-responses"),- baseUrl,- }));- if (models.length === 0) return undefined;- this.xaiLiveModels.set(account.providerId, { at: Date.now(), models });- return models;+ if (models.length === 0) return this.rememberLiveModels(account.providerId, null);+ return this.rememberLiveModels(account.providerId, models);} catch (error) {- this.log("warn", "xAI account model list failed", {+ this.log("warn", "vendor account model list failed", {vendorId: account.vendorId,message: error instanceof Error ? error.message : String(error),});- return undefined;+ return this.rememberLiveModels(account.providerId, null);}}@@ -513,7 +547,7 @@ export class VendorOAuth {vendorKey: account.vendorId,option,}).catch(() => undefined);- const modelConfig = this.withPinnedXaiFallback(account, option, published);+ const modelConfig = await this.withPinnedSiblingFallback(account, option, published);const capabilities = capabilitiesFromModelConfig(modelConfig);return {apiStyle: option.apiStyle,@@ -525,20 +559,25 @@ export class VendorOAuth {/*** models.dev is the metadata source when it already knows the id. A model- * that exists only on the live xAI list (the usual case for a just-released- * Grok) otherwise inherits limits and thinking levels from the newest pinned- * sibling, instead of the 128k generic shape.+ * that exists only on the live list otherwise inherits limits and thinking+ * levels from a pinned sibling of the same tier. xAI uses an explicit+ * newest-first order so pin order cannot pick an older Grok.*/- private withPinnedXaiFallback(+ private async withPinnedSiblingFallback(account: AccountModels,option: OAuthModelOption,published: ModelConfig | undefined,- ): ModelConfig {+ ): Promise<ModelConfig> {const config = published ?? genericModelConfig(option.modelId, option.baseUrl);- if (account.vendorId !== XAI_VENDOR_ID || config.source !== "generic") return config;- const sibling = ["grok-4.6", "grok-4.5", "grok-4.3"]- .map((id) => account.models.getModel(account.vendorId, id))- .find((model) => model !== undefined);+ if (config.source !== "generic") return config;+ const pinned = await account.models.getAvailable(account.vendorId);+ if (pinned.some((model) => model.id === option.modelId)) return config;+ const siblingId = pinnedSiblingId(+ account.vendorId,+ option.modelId,+ pinned.map((model) => model.id),+ );+ const sibling = siblingId ? pinned.find((model) => model.id === siblingId) : undefined;if (!sibling) return config;const input = (sibling.input ?? []).filter((modality): modality is "text" | "image" => modality === "text" || modality === "image",diff --git a/apps/desktop/electron/main/vendor-live-models.ts b/apps/desktop/electron/main/vendor-live-models.tsnew file mode 100644index 000000000..31bad4fa6--- /dev/null+++ b/apps/desktop/electron/main/vendor-live-models.ts@@ -0,0 +1,389 @@+/**+ * Live model lists for signed-in vendor accounts.+ *+ * Each vendor is probed on the endpoint that actually publishes the account's+ * models. pi-ai's pinned catalog is not consulted here; callers use it only+ * when this module cannot return a list.+ */++const LIVE_MODELS_TIMEOUT_MS = 8_000;+const MAX_RETRY_DELAY_MS = 1_000;++const NON_CONVERSATION_MODEL =+ /(?:^|[-_/])(?:imagine|image|video|tts|stt|speech|embed(?:ding)?|whisper|aurora|flux|realtime|moderation)(?:$|[-_/])/i;++const SINGLE_WIRE_API: Record<string, string> = {+ anthropic: "anthropic-messages",+ "kimi-coding": "anthropic-messages",+ meta: "openai-responses",+ "openai-codex": "openai-codex-responses",+ xai: "openai-responses",+};++const DEFAULT_BASE_URL: Record<string, string> = {+ anthropic: "https://api.anthropic.com",+ "github-copilot": "https://api.individual.githubcopilot.com",+ "kimi-coding": "https://api.kimi.com/coding",+ meta: "https://api.meta.ai/v1",+ "openai-codex": "https://chatgpt.com/backend-api",+ openrouter: "https://openrouter.ai/api/v1",+ xai: "https://api.x.ai/v1",+};++const COPILOT_HEADERS = {+ "User-Agent": "GitHubCopilotChat/0.35.0",+ "Editor-Version": "vscode/1.107.0",+ "Editor-Plugin-Version": "copilot-chat/0.35.0",+ "Copilot-Integration-Id": "vscode-chat",+ "X-GitHub-Api-Version": "2026-06-01",+} as const;++const COPILOT_INDIVIDUAL_BASE = "https://api.individual.githubcopilot.com";+const XAI_SIBLING_ORDER = ["grok-4.6", "grok-4.5", "grok-4.3"] as const;+const TIER_TOKENS = new Set([+ "astra",+ "fable",+ "flash",+ "haiku",+ "luna",+ "mini",+ "nano",+ "opus",+ "pro",+ "sol",+ "sonnet",+ "spark",+ "terra",+]);++export type VendorModelListRequest = {+ url: string;+ headers: Record<string, string>;+ /** Host stored on a model the pin does not know yet. */+ accountBaseUrl: string;+ allowPolicyFallback: boolean;+};++export type PinnedWire = {+ id: string;+ api: string;+ baseUrl: string;+};++export function isConversationModelId(modelId: string): boolean {+ const id = modelId.trim();+ return id.length > 0 && !NON_CONVERSATION_MODEL.test(id);+}++function asRecord(value: unknown): Record<string, unknown> | null {+ return value && typeof value === "object" && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : null;+}++function trimBase(url: string | undefined, fallback: string): string {+ const value = (url?.trim() || fallback).replace(/\/+$/, "");+ return value;+}++function chatgptAccountId(token: string): string | undefined {+ const part = token.split(".")[1];+ if (!part) return undefined;+ try {+ const padded = part.replace(/-/g, "+").replace(/_/g, "/");+ const payload = JSON.parse(Buffer.from(padded, "base64").toString("utf8")) as {+ ["https://api.openai.com/auth"]?: { chatgpt_account_id?: unknown };+ };+ const id = payload?.["https://api.openai.com/auth"]?.chatgpt_account_id;+ return typeof id === "string" && id.trim() ? id : undefined;+ } catch {+ return undefined;+ }+}++/** The account's model-list request, or undefined when this vendor has none. */+export function vendorModelListRequest(input: {+ vendorId: string;+ apiKey?: string;+ baseUrl?: string;+}): VendorModelListRequest | undefined {+ const apiKey = input.apiKey?.trim() ?? "";+ if (!apiKey) return undefined;+ const fallback = DEFAULT_BASE_URL[input.vendorId];+ if (!fallback && input.vendorId !== "github-copilot") return undefined;+ const base = trimBase(input.baseUrl, fallback ?? COPILOT_INDIVIDUAL_BASE);+ const bearer = { Authorization: `Bearer ${apiKey}`, Accept: "application/json" };++ if (input.vendorId === "openai-codex") {+ const accountId = chatgptAccountId(apiKey);+ if (!accountId) return undefined;+ return {+ url: `${base}/codex/models`,+ accountBaseUrl: base,+ allowPolicyFallback: false,+ headers: {+ ...bearer,+ "chatgpt-account-id": accountId,+ originator: "pi",+ },+ };+ }++ if (input.vendorId === "github-copilot") {+ return {+ url: `${base}/models`,+ accountBaseUrl: base,+ allowPolicyFallback: base === COPILOT_INDIVIDUAL_BASE,+ headers: { ...bearer, ...COPILOT_HEADERS },+ };+ }++ if (input.vendorId === "anthropic") {+ const root = base.endsWith("/v1") ? base : `${base}/v1`;+ const oauth = apiKey.includes("sk-ant-oat");+ return {+ url: `${root}/models?limit=1000`,+ accountBaseUrl: base.endsWith("/v1") ? base.slice(0, -3) : base,+ allowPolicyFallback: false,+ headers: oauth+ ? {+ ...bearer,+ "anthropic-version": "2023-06-01",+ "anthropic-beta": "claude-code-20250219,oauth-2025-04-20",+ "x-app": "cli",+ "user-agent": "claude-cli/2.1.251",+ }+ : {+ Accept: "application/json",+ "x-api-key": apiKey,+ "anthropic-version": "2023-06-01",+ },+ };+ }++ if (input.vendorId === "kimi-coding") {+ const root = base.endsWith("/v1") ? base : `${base}/v1`;+ return {+ url: `${root}/models?limit=1000`,+ accountBaseUrl: base.endsWith("/v1") ? base.slice(0, -3) : base,+ allowPolicyFallback: false,+ headers: { ...bearer, "anthropic-version": "2023-06-01" },+ };+ }++ if (+ input.vendorId === "xai" ||+ input.vendorId === "meta" ||+ input.vendorId === "openrouter"+ ) {+ return {+ url: `${base}/models`,+ accountBaseUrl: base,+ allowPolicyFallback: false,+ headers: bearer,+ };+ }++ return undefined;+}++function conversationIds(ids: string[]): string[] {+ const seen = new Set<string>();+ const out: string[] = [];+ for (const id of ids) {+ const modelId = id.trim();+ if (!isConversationModelId(modelId) || seen.has(modelId)) continue;+ seen.add(modelId);+ out.push(modelId);+ }+ return out;+}++function parseDataIds(body: unknown): string[] | null {+ const record = asRecord(body);+ const data = Array.isArray(record?.data)+ ? record.data+ : Array.isArray(body)+ ? body+ : null;+ if (!data) return null;+ return conversationIds(+ data.flatMap((entry) => {+ const id = asRecord(entry)?.id;+ return typeof id === "string" ? [id] : [];+ }),+ );+}++function parseCodexIds(body: unknown): string[] | null {+ const models = asRecord(body)?.models;+ if (!Array.isArray(models)) return null;+ return conversationIds(+ models.flatMap((entry) => {+ const item = asRecord(entry);+ const slug = item?.slug ?? item?.id;+ if (!item || typeof slug !== "string") return [];+ const visibility = item.visibility;+ if (visibility === "hide" || visibility === "hidden") return [];+ return [slug];+ }),+ );+}++function parseCopilotIds(body: unknown, allowPolicyFallback: boolean): string[] | null {+ const data = asRecord(body)?.data;+ if (!Array.isArray(data)) return null;+ const accountModels = data.flatMap((entry) => {+ const item = asRecord(entry);+ const id = item?.id;+ if (!item || typeof id !== "string") return [];+ const supports = asRecord(asRecord(item.capabilities)?.supports);+ if (supports?.tool_calls === false) return [];+ const policyState = asRecord(item.policy)?.state;+ return [{+ id,+ pickerEnabled: item.model_picker_enabled === true,+ policyState: typeof policyState === "string" ? policyState : undefined,+ }];+ });+ const pickerIds = accountModels+ .filter((model) => model.pickerEnabled && model.policyState !== "disabled")+ .map((model) => model.id);+ const available = pickerIds.length > 0 || !allowPolicyFallback+ ? pickerIds+ : accountModels+ .filter((model) => model.policyState === "enabled")+ .map((model) => model.id);+ return conversationIds(available);+}++/** Parsed chat-model ids, or null when the payload is not that vendor's list. */+export function parseVendorModelIds(+ vendorId: string,+ body: unknown,+ allowPolicyFallback = false,+): string[] | null {+ if (vendorId === "github-copilot") return parseCopilotIds(body, allowPolicyFallback);+ if (vendorId === "openai-codex") return parseCodexIds(body);+ return parseDataIds(body);+}++export function familyKey(modelId: string): string {+ const slash = modelId.indexOf("/");+ const head = slash > 0 ? modelId.slice(0, slash) : modelId.split("-")[0] ?? "";+ return head.trim().toLowerCase();+}++/**+ * Wire API for an id the pin does not contain.+ * A vendor with one wire API uses that. Copilot and OpenRouter only keep an+ * id whose family already maps to exactly one wire API in the pin.+ */+export function wireForLiveModel(+ vendorId: string,+ modelId: string,+ pinned: readonly PinnedWire[],+ accountBaseUrl: string,+): { api: string; baseUrl: string } | undefined {+ const single = SINGLE_WIRE_API[vendorId];+ if (single) return { api: single, baseUrl: accountBaseUrl };+ const family = familyKey(modelId);+ if (!family) return undefined;+ const same = pinned.filter((model) => familyKey(model.id) === family);+ const apis = new Set(same.map((model) => model.api));+ if (apis.size !== 1) return undefined;+ return {+ api: [...apis][0] ?? "",+ baseUrl: accountBaseUrl || same[0]?.baseUrl || "",+ };+}++function versionKey(id: string): number[] {+ return (id.match(/\d+(?:\.\d+)*/g) ?? []).flatMap((part) =>+ part.split(".").map((piece) => Number(piece)),+ );+}++function newerFirst(a: string, b: string): number {+ const left = versionKey(a);+ const right = versionKey(b);+ const length = Math.max(left.length, right.length);+ for (let index = 0; index < length; index += 1) {+ const delta = (right[index] ?? 0) - (left[index] ?? 0);+ if (delta !== 0) return delta;+ }+ return a.localeCompare(b);+}++function tierToken(modelId: string): string | undefined {+ return modelId+ .toLowerCase()+ .split(/[-/]/)+ .find((part) => TIER_TOKENS.has(part));+}++/**+ * Pinned id whose limits a just-released model may inherit.+ * xAI keeps an explicit newest-first order. Every other vendor inherits only+ * from the same tier (luna, sonnet, …), never from a different flagship.+ */+export function pinnedSiblingId(+ vendorId: string,+ modelId: string,+ pinnedIds: readonly string[],+): string | undefined {+ if (vendorId === "xai" && familyKey(modelId) === "grok") {+ const preferred = XAI_SIBLING_ORDER.find((id) => pinnedIds.includes(id));+ if (preferred) return preferred;+ }+ const tier = tierToken(modelId);+ if (!tier) return undefined;+ const family = familyKey(modelId);+ const candidates = pinnedIds.filter(+ (id) => familyKey(id) === family && tierToken(id) === tier,+ );+ candidates.sort(newerFirst);+ return candidates[0];+}++function retryDelayMs(response: Response): number {+ const header = response.headers.get("retry-after");+ if (!header) return 500;+ const seconds = Number(header);+ const delay = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(header) - Date.now();+ if (!Number.isFinite(delay) || delay < 0) return 500;+ return Math.min(delay, MAX_RETRY_DELAY_MS);+}++/** GET the vendor model list. Retries one HTTP 429, then throws. */+export async function readVendorModelList(+ request: VendorModelListRequest,+ fetchImpl: typeof fetch,+): Promise<unknown> {+ let waitMs = 0;+ for (let attempt = 0; attempt < 2; attempt += 1) {+ if (waitMs > 0) {+ await new Promise((resolve) => setTimeout(resolve, waitMs));+ }+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), LIVE_MODELS_TIMEOUT_MS);+ try {+ const response = await fetchImpl(request.url, {+ headers: request.headers,+ signal: controller.signal,+ });+ if (response.status === 429 && attempt === 0) {+ waitMs = retryDelayMs(response);+ await response.body?.cancel();+ continue;+ }+ if (!response.ok) {+ throw new Error(`model list request failed (${response.status})`);+ }+ return await response.json();+ } finally {+ clearTimeout(timer);+ }+ }+ throw new Error("model list request failed");+}diff --git a/apps/desktop/test/anthropic-oauth-retry.test.mjs b/apps/desktop/test/anthropic-oauth-retry.test.mjsindex 2b200f751..9dbaad2f7 100644--- a/apps/desktop/test/anthropic-oauth-retry.test.mjs+++ b/apps/desktop/test/anthropic-oauth-retry.test.mjs@@ -59,7 +59,10 @@ async function fixture(outcomes, run) {server.once("error", reject); server.listen(0, "127.0.0.1", resolve);});globalThis.fetch = (input, init) => {- assert.equal(String(input), TOKEN_URL, "OAuth fixture must never call an external endpoint");+ const url = String(input);+ if (url !== TOKEN_URL) {+ return Promise.reject(new Error(`blocked ${url}`));+ }return originalFetch(`http://127.0.0.1:${server.address().port}/token`, init);};const host = hostFixture();diff --git a/apps/desktop/test/vendor-live-models.test.mjs b/apps/desktop/test/vendor-live-models.test.mjsnew file mode 100644index 000000000..910468965--- /dev/null+++ b/apps/desktop/test/vendor-live-models.test.mjs@@ -0,0 +1,106 @@+import assert from "node:assert/strict";+import test from "node:test";++import {+ parseVendorModelIds,+ pinnedSiblingId,+ vendorModelListRequest,+ wireForLiveModel,+} from "../electron/main/vendor-live-models.ts";++function codexToken() {+ const payload = Buffer.from(JSON.stringify({+ "https://api.openai.com/auth": { chatgpt_account_id: "acct_123" },+ })).toString("base64url");+ return `header.${payload}.sig`;+}++test("ChatGPT accounts list models from the Codex endpoint, not /models", () => {+ const request = vendorModelListRequest({+ vendorId: "openai-codex",+ apiKey: codexToken(),+ });+ assert.equal(request?.url, "https://chatgpt.com/backend-api/codex/models");+ assert.equal(request?.headers["chatgpt-account-id"], "acct_123");+ assert.equal(parseVendorModelIds("openai-codex", {+ models: [+ { slug: "gpt-6-luna", visibility: "list" },+ { slug: "gpt-6-hidden", visibility: "hide" },+ ],+ })?.join(","), "gpt-6-luna");+ assert.equal(parseVendorModelIds("openai-codex", {+ data: [{ id: "gpt-4o" }],+ }), null);+ assert.equal(vendorModelListRequest({+ vendorId: "openai-codex",+ apiKey: "not-a-jwt",+ }), undefined);+});++test("Copilot keeps picker flags and the API version header", () => {+ const request = vendorModelListRequest({+ vendorId: "github-copilot",+ apiKey: "copilot-token",+ });+ assert.equal(request?.url, "https://api.individual.githubcopilot.com/models");+ assert.equal(request?.headers["X-GitHub-Api-Version"], "2026-06-01");+ assert.deepEqual(parseVendorModelIds("github-copilot", {+ data: [+ { id: "gpt-6-luna", model_picker_enabled: true, policy: { state: "enabled" } },+ { id: "gpt-5.4", policy: { state: "enabled" } },+ {+ id: "gpt-image",+ model_picker_enabled: true,+ capabilities: { supports: { tool_calls: false } },+ },+ ],+ }, true), ["gpt-6-luna"]);+});++test("Anthropic OAuth sends the Claude Code identity headers", () => {+ const request = vendorModelListRequest({+ vendorId: "anthropic",+ apiKey: "sk-ant-oat01-test",+ });+ assert.equal(request?.url, "https://api.anthropic.com/v1/models?limit=1000");+ assert.equal(request?.headers["x-app"], "cli");+ assert.equal(request?.headers.Authorization, "Bearer sk-ant-oat01-test");+ assert.match(request?.headers["anthropic-beta"] ?? "", /oauth-2025-04-20/);+});++test("a new Grok inherits the newest explicit sibling, not pin order", () => {+ assert.equal(+ pinnedSiblingId("xai", "grok-4.7", ["grok-4.3", "grok-4.5", "grok-4.6"]),+ "grok-4.6",+ );+});++test("an unknown Claude does not inherit a different tier", () => {+ assert.equal(+ pinnedSiblingId("anthropic", "claude-3-5-sonnet-20241022", ["claude-fable-5", "claude-sonnet-4-6"]),+ "claude-sonnet-4-6",+ );+ assert.equal(+ pinnedSiblingId("anthropic", "claude-3-5-sonnet-20241022", ["claude-fable-5"]),+ undefined,+ );+});++test("Copilot only keeps a new id when its family has one wire API", () => {+ const pinned = [+ { id: "gpt-5.4", api: "openai-responses", baseUrl: "https://api.individual.githubcopilot.com" },+ { id: "claude-sonnet-4-6", api: "anthropic-messages", baseUrl: "https://api.individual.githubcopilot.com" },+ ];+ assert.equal(+ wireForLiveModel("github-copilot", "gpt-6-luna", pinned, pinned[0].baseUrl)?.api,+ "openai-responses",+ );+ assert.equal(+ wireForLiveModel("github-copilot", "mystery-1", pinned, pinned[0].baseUrl),+ undefined,+ );+ assert.equal(+ wireForLiveModel("openai-codex", "gpt-6-luna", pinned, "https://chatgpt.com/backend-api")?.api,+ "openai-codex-responses",+ );+});diff --git a/apps/desktop/test/vendor-oauth-login.test.mjs b/apps/desktop/test/vendor-oauth-login.test.mjsindex d6722dc14..dd9e507a7 100644--- a/apps/desktop/test/vendor-oauth-login.test.mjs+++ b/apps/desktop/test/vendor-oauth-login.test.mjs@@ -171,6 +171,11 @@ function harness(options = {}) {},modelConfigFor: options.modelConfigFor,newId: () => `id-${++counter}`,+ fetch:+ options.fetch ??+ (async () => {+ throw new Error("live model list disabled in test");+ }),});// The store the module handed pi-ai, so a test can drive it the way a token// refresh would.@@ -602,8 +607,7 @@ test("conversation-model filter drops xAI image and video ids", () => {test("an xAI account offers the chat models its /models endpoint returns", async () => {const seen = [];- const previousFetch = globalThis.fetch;- globalThis.fetch = async (url, init) => {+ const fetchModels = async (url, init) => {seen.push({url: String(url),authorization: init?.headers?.Authorization,@@ -616,6 +620,8 @@ test("an xAI account offers the chat models its /models endpoint returns", async],}), { status: 200, headers: { "content-type": "application/json" } });};+ const previousFetch = globalThis.fetch;+ globalThis.fetch = fetchModels;const xaiModel = {id: "grok-4.6",name: "Grok 4.6",@@ -639,6 +645,7 @@ test("an xAI account offers the chat models its /models endpoint returns", async};try {const { host, events, oauth } = harness({+ fetch: fetchModels,provider: {id: "xai",name: "xAI",@@ -675,3 +682,49 @@ test("an xAI account offers the chat models its /models endpoint returns", asyncglobalThis.fetch = previousFetch;}});++test("a new Grok inherits grok-4.6 even when an older Grok is first in the pin", async () => {+ const fetchModels = async () => new Response(JSON.stringify({+ data: [{ id: "grok-4.7" }],+ }), { status: 200, headers: { "content-type": "application/json" } });+ const older = {+ id: "grok-4.3",+ name: "Grok 4.3",+ api: "openai-responses",+ provider: "xai",+ baseUrl: "https://api.x.ai/v1",+ input: ["text"],+ reasoning: true,+ thinkingLevelMap: { off: "off", low: "low", medium: "medium", high: "high" },+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },+ contextWindow: 1_000_000,+ maxTokens: 30_000,+ };+ const newest = {+ ...older,+ id: "grok-4.6",+ name: "Grok 4.6",+ input: ["text", "image"],+ thinkingLevelMap: { off: null, low: "low", medium: "medium", high: "high", xhigh: "xhigh" },+ contextWindow: 500_000,+ maxTokens: 500_000,+ };+ const { events, oauth } = harness({+ fetch: fetchModels,+ provider: {+ id: "xai",+ name: "xAI",+ baseUrl: "https://api.x.ai/v1",+ auth: { oauth: { name: "xAI", isSubscription: true, loginLabel: "Sign in" } },+ },+ models: [older, newest],+ });+ const { loginId } = await oauth.start("xai");+ const prompt = await waitFor(events, "prompt");+ oauth.respond({ loginId, promptId: prompt.request.promptId, value: "abc" });+ const done = await waitFor(events, "done");+ const binding = await oauth.bindingFor(done.providerId, "grok-4.7");+ assert.equal(binding.modelConfig.contextWindow, 500_000);+ assert.equal(binding.modelConfig.maxTokens, 500_000);+ assert.deepEqual(binding.supportedThinkingLevels, ["low", "medium", "high", "xhigh"]);+});diff --git a/docs/adr/0095-vendor-account-oauth-login.md b/docs/adr/0095-vendor-account-oauth-login.mdindex df21ea834..72a5179b4 100644--- a/docs/adr/0095-vendor-account-oauth-login.md+++ b/docs/adr/0095-vendor-account-oauth-login.md@@ -72,17 +72,18 @@ hand it to the sidecar at launch" pattern was not acceptable for it.of rebuilding it once an hour, or once a turn.6. **Model discovery and connection tests go through the account.** For an- OAuth row, `providers.listModels` reads the authenticated catalog- (`models.getAvailable`, which applies the vendor's own `filterModels`, so- Copilot shows what the subscription actually includes) instead of probing- `/models` with a key it does not have, and the connection test proves the- account by resolving auth. xAI is the exception: the resolved account token- calls `GET /v1/models`, and that chat-model list replaces the pinned catalog- when the request succeeds. Login stores a non-secret account label in the row- config and picks the row's `apiStyle` from the selected model — a vendor may- span wire APIs. The original one-row-per-vendor assumption is amended by- ADR 0098: every login now creates an independent row and credential scope.- Two styles are added for this: `openai_codex_responses` and `pi_messages`.+ OAuth row, `providers.listModels` reads the signed-in account's own model+ endpoint. pi-ai `models.getAvailable` (including the vendor's+ `filterModels`) is the fallback when that request fails. ChatGPT uses+ `GET {base}/codex/models`; Copilot uses `GET {base}/models` and still hides+ models the subscription did not enable; xAI, Anthropic, Kimi, Meta and+ OpenRouter use their own list endpoints. Radius keeps its gateway refresh.+ The connection test proves the account by resolving auth. Login stores a+ non-secret account label in the row config and picks the row's `apiStyle`+ from the selected model — a vendor may span wire APIs. The original+ one-row-per-vendor assumption is amended by ADR 0098: every login now+ creates an independent row and credential scope. Two styles are added for+ this: `openai_codex_responses` and `pi_messages`.## Consequencesdiff --git a/docs/spec/03-runtime/11-provider-model-system.md b/docs/spec/03-runtime/11-provider-model-system.mdindex 318e9ccde..d573957e7 100644--- a/docs/spec/03-runtime/11-provider-model-system.md+++ b/docs/spec/03-runtime/11-provider-model-system.md@@ -447,21 +447,33 @@ nothing may be cached in the payload or the runtime; and because the row'sturns instead of rebuilding it. The sidecar therefore never holds the refreshtoken, and holds an access token only for the provider its session is bound to.-Model discovery for such a row reads the authenticated catalog-(`models.getAvailable`, which applies the vendor's own `filterModels`) rather-than probing `/models`, and the connection test proves the account by resolving-auth. For static OAuth vendors such as ChatGPT Plus/Pro (`openai-codex`), that-catalog is the pinned pi-ai model list rather than a live vendor `/models`-probe, so a newly published account model such as `gpt-6-astra` appears only-after the pin includes it. xAI (`xai`, the Grok/X subscription) is the-exception: a successful `GET /v1/models` with the resolved account token is the-list of conversation models the account may use, including an id the pinned-pi-ai catalog does not know yet. Image and video generators in that payload-are dropped. When the request fails, the pinned catalog remains the fallback.-models.dev still supplies metadata once the ID is available, but it cannot add-the ID to the authenticated list. A vendor may-span wire APIs — Copilot serves Anthropic, Chat Completions and Responses-models — so the row's `apiStyle` follows the selected model.+Model discovery for such a row reads the signed-in account's own model list,+and the connection test still proves the account by resolving auth. pi-ai+(`models.getAvailable`, including that vendor's `filterModels`) is the fallback+when the account request fails or the payload is not a model list. The probe+is the endpoint that vendor actually publishes:++- ChatGPT Plus/Pro (`openai-codex`): `GET {base}/codex/models`, with the+ account id taken from the access token. A `{ data: [...] }` payload is not+ accepted. A newly published id such as `gpt-6-luna` is selectable without a+ client update when that response includes it.+- GitHub Copilot: `GET {base}/models` with the pinned IDE identity headers and+ `X-GitHub-Api-Version`. Only ids with `model_picker_enabled === true` (and+ not policy-disabled) are kept. An id the pin does not know is added only when+ its family already maps to one wire API.+- Anthropic: `GET {base}/v1/models` with the Claude Code OAuth headers+ (`x-app: cli`, OAuth beta) when the token is an OAuth access token.+- Kimi, Meta, xAI and OpenRouter: `GET {base}/models` (Anthropic-style `/v1`+ for Kimi). xAI still drops image and video generators.+- Radius keeps its gateway catalog refresh and is not probed again.++Image, video, speech and embedding ids are dropped. A model models.dev does+not know yet inherits limits from a pinned sibling of the same tier; xAI uses+an explicit newest-first sibling (`grok-4.6`, then `grok-4.5`, then+`grok-4.3`) so pin order cannot select an older Grok. A different tier is not+used. models.dev still cannot add an id the account list did not return. A+vendor may span wire APIs — Copilot serves Anthropic, Chat Completions and+Responses models — so the row's `apiStyle` follows the selected model.Deleting a row calls the normal host `providers.delete` path, which removes itsOAuth secret and metadata; it never logs out or deletes another row with thesame vendor key.diff --git a/docs/spec/03-runtime/12-provider-config-schema.md b/docs/spec/03-runtime/12-provider-config-schema.mdindex 7a7e95b9e..4104de65f 100644--- a/docs/spec/03-runtime/12-provider-config-schema.md+++ b/docs/spec/03-runtime/12-provider-config-schema.md@@ -559,14 +559,13 @@ The canonical DDL lives in [04-data-storage](04-data-storage.md) (D086). Summaryreads the local models.dev snapshot and runs provider endpoint discovery only for IDs absent from it- host RPC in: `{ providerId?: string }`; reads only the Rust-owned `models`table-- for an `authKind: "oauth"` row Electron main reads the authenticated catalog- (`models.getAvailable`, which applies the vendor's own `filterModels`, so a- Copilot account lists what its subscription includes) instead of calling- `/models`; each returned model carries the apiStyle its wire API implies.- Static vendors such as `openai-codex` use the pinned pi-ai catalog (0.86.1- includes `gpt-6-astra`); models.dev does not invent those IDs. `xai` is the- exception: conversation models come from `GET /v1/models` on the resolved- account token, and the pinned catalog is used only when that request fails.+- for an `authKind: "oauth"` row Electron main reads the signed-in account's+ model list (see `03-runtime/11-provider-model-system.md`) instead of the+ pinned catalog. pi-ai `models.getAvailable` is used only when that request+ fails. Each returned model carries the apiStyle its wire API implies.+ `openai-codex` calls `GET {base}/codex/models`, so an account id such as+ `gpt-6-luna` appears without a pin update; models.dev does not invent those+ IDs. Copilot still hides models the account did not enable.- out: `{ models: ModelCatalogItem[] }`; each known model carries the completemodels.dev metadata including `reasoning`, `supportedThinkingLevels`, limits,modalities, output types, and capability tags. Cached/provider claims cannotdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex b65336079..254b73f01 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -10740,8 +10740,9 @@ This test plan spec is accepted when:catalog does not publish. OpenAI Codex's `openai-codex` adapter key resolvesthe matching `openai` models.dev record, so `gpt-6-astra` is not shown withgeneric 128,000 / 8,192 / no-reasoning defaults. The authenticated ChatGPT- list itself comes from the pinned pi-ai catalog (0.86.1 includes- `gpt-6-astra`); models.dev cannot add a missing OAuth ID. A model with no published+ list comes from `GET {base}/codex/models` on the account token, so an id the+ pin does not know yet is selectable when that response includes it; pi-ai is+ only the fallback when the request fails. models.dev cannot add a missing OAuth ID. A model with no publishedrecord keeps its explicit levels and starts with all choices available formanual opt-in. The account's default model stays the head binding.- **Specs linked**: `04-ux/06-settings-ia.md`,diff --git a/docs/zh-CN/spec/03-runtime/11-provider-model-system.md b/docs/zh-CN/spec/03-runtime/11-provider-model-system.mdindex e5cd4ba21..1b9ac4810 100644--- a/docs/zh-CN/spec/03-runtime/11-provider-model-system.md+++ b/docs/zh-CN/spec/03-runtime/11-provider-model-system.md@@ -375,17 +375,20 @@ sidecar 请求因此 sidecar 永远拿不到刷新令牌,拿到的访问令牌也只属于其会话绑定的那个提供商。-这类行的模型发现读取已认证的目录(`models.getAvailable`,它已应用厂商-自己的 `filterModels`),而不是探测 `/models`;连接测试通过解析认证来-证明账户。对 ChatGPT Plus/Pro(`openai-codex`)这类静态 OAuth 厂商,该-目录是已固定的 pi-ai 模型列表,而不是实时 `/models` 探测,因此 `gpt-6-astra`-这类新账户模型只有在 pin 包含它之后才会出现。xAI(Grok/X 订阅)是例外:-用已解析的账户令牌请求 `GET /v1/models` 成功时,返回的对话模型就是该账户-可选的模型,包括 pin 里还没有的 id;图像和视频模型会被丢掉。请求失败时-仍回退到 pin 目录。models.dev 在 ID 可用后仍-提供元数据,但不能把 ID 加进已认证列表。一个厂商可以跨越多种线路 API ——-Copilot 同时提供 Anthropic、Chat Completions 与 Responses 模型 —— 因此行-的 `apiStyle` 跟随所选模型。+这类行的模型发现读取已登录账户自己的模型列表;连接测试仍通过解析认证来证明+账户。请求失败,或返回的不是模型列表时,才回退到 pi-ai(`models.getAvailable`,+含厂商自己的 `filterModels`)。各厂商打自己的接口:ChatGPT Plus/Pro+(`openai-codex`)是 `GET {base}/codex/models`,因此 `gpt-6-luna` 这类账户+已经提供、pin 里还没有的 id 也能出现;普通 `{ data: [...] }` 不当成 Codex+列表。Copilot 是带 IDE 身份头和 `X-GitHub-Api-Version` 的 `GET {base}/models`,+只保留 `model_picker_enabled === true` 且未被策略禁用的 id,pin 不认识的 id+只有在其家族已经对应唯一线路 API 时才加入。Anthropic 用 OAuth 身份头请求+`GET {base}/v1/models`。Kimi、Meta、xAI、OpenRouter 请求 `GET {base}/models`+(Kimi 走 Anthropic 风格的 `/v1`)。Radius 继续用网关目录刷新,不再另打一遍。+图像、视频、语音和嵌入模型会被丢掉。models.dev 不认识的 id 只从同档位的 pin+兄弟继承限额,xAI 按 `grok-4.6`、`grok-4.5`、`grok-4.3` 的固定新到旧顺序,+不按 pin 顺序。models.dev 不能把账户列表里没有的 id 加进去。一个厂商可以+跨越多种线路 API,因此行的 `apiStyle` 跟随所选模型。### Anthropic token 端点限流diff --git a/docs/zh-CN/spec/03-runtime/12-provider-config-schema.md b/docs/zh-CN/spec/03-runtime/12-provider-config-schema.mdindex 777fd13a3..7ff1798a2 100644--- a/docs/zh-CN/spec/03-runtime/12-provider-config-schema.md+++ b/docs/zh-CN/spec/03-runtime/12-provider-config-schema.md@@ -394,11 +394,12 @@ Copilot 的上下文相关请求标头;已保存的同名自定义 header 会在 Electron main 中运行发现- 将 RPC 托管在:`{ providerId?: string }` 中;只读取 Rust 拥有的 `models`表-- 对 `authKind: "oauth"` 行,Electron 主进程读取已认证的目录- (`models.getAvailable`,它已应用厂商自己的 `filterModels`,因此 Copilot- 账户列出的是其订阅包含的模型),而不是调用 `/models`;返回的每个模型都- 带着其线路 API 所隐含的 apiStyle。`openai-codex` 这类静态厂商使用已固定- 的 pi-ai 目录(0.86.1 包含 `gpt-6-astra`);models.dev 不会发明这些 ID。+- 对 `authKind: "oauth"` 行,Electron 主进程读取已登录账户自己的模型列表+ (见 `03-runtime/11-provider-model-system.md`),请求失败才回退到 pi-ai+ 的 `models.getAvailable`。返回的每个模型都带着其线路 API 所隐含的+ apiStyle。`openai-codex` 调用 `GET {base}/codex/models`,因此 `gpt-6-luna`+ 这类账户 id 不需要等 pin 更新;models.dev 不会发明这些 ID。Copilot 仍只列出+ 账户已启用的模型。- 输出:`{ models: ModelCatalogItem[] }`;每个模型都带有 pi-resolved`reasoning` 功能和 `supportedThinkingLevels`。缓存的功能标签旧提供程序字段无法覆盖 pi 模型记录。diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 565bd0436..451c2dfd7 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -6733,8 +6733,8 @@ eleven-tool-round desktop paths are verified by编辑器不再缺少高级设置。在账户模型上启用的等级会持久化,并在重新打开编辑器后依然存在。OpenAI Codex 的 `openai-codex` 适配器键会解析匹配的 `openai`models.dev 记录,因此 `gpt-6-astra` 不会显示为通用的 128,000 / 8,192 /- 无推理默认值。已认证的 ChatGPT 列表本身来自已固定的 pi-ai 目录(0.86.1- 包含 `gpt-6-astra`);models.dev 不能补上缺失的 OAuth ID。没有已发布记录+ 无推理默认值。已认证的 ChatGPT 列表来自账户令牌的 `GET {base}/codex/models`,+ 所以 pin 里还没有的 id 只要响应里有就能选;请求失败才回退到 pi-ai。models.dev 不能补上缺失的 OAuth ID。没有已发布记录的模型则保留其已存等级不变。账户的默认模型仍是首个绑定。- **链接规格**:`04-ux/06-settings-ia.md`、`04-ux/08-component-spec.md` §19、`03-runtime/11-provider-model-system.md` §10、`08-meta/decisions-log.md`