Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(settings): resolve the provider endpoint from the typed address
vastsae7f47f0a0f2a
diff --git a/apps/desktop/electron/main/ipc/provider-ipc.ts b/apps/desktop/electron/main/ipc/provider-ipc.tsindex 98aafe757..0a2a49251 100644--- a/apps/desktop/electron/main/ipc/provider-ipc.ts+++ b/apps/desktop/electron/main/ipc/provider-ipc.ts@@ -1,14 +1,20 @@import {IPC,ErrorCodes,+ inferEndpointProfile,+ normalizeApiStyle,resolveBindingContextWindow,type ModelBinding,type ProviderReorderInput,type OAuthRespondInput,} from "@pi-desktop/shared";import { OAUTH_AUTH_KIND, type VendorOAuth } from "../oauth";-import { discoverProviderModels } from "../model-discovery";-import { modelConfigWithBinding, mergeProviderHeaders } from "@pi-desktop/agent-runtime";+import { probeModelList } from "../model-discovery";+import {+ probeDiscoveryCandidates,+ type DiscoveryAttempt,+} from "../provider-endpoint-probe";+import { modelConfigWithBinding } from "@pi-desktop/agent-runtime";import {catalogModelConfigFor,modelInfoFromModelsDev,@@ -17,6 +23,21 @@ import {import type { HostProcess } from "../host-process";import type { Logger } from "../logger";import type { IpcRegistrar } from "./types";+/**+ * One line explaining why a candidate sweep found nothing: every endpoint that+ * was tried and what it answered. The list is the explanation the settings+ * dialog shows, so a failed discovery never has to be a silent 404.+ */+function describeSweepFailure(+ attempts: readonly DiscoveryAttempt[],+): string | undefined {+ const failed = attempts.filter((attempt) => attempt.error);+ if (failed.length === 0) return undefined;+ return failed+ .map((attempt) => `${attempt.baseUrl}: ${attempt.error}`)+ .join("; ");+}+type RuntimeProvider = {id: string;@@ -174,7 +195,12 @@ export function registerProviderIpc({);if (!local.ok) return { ...local, network: "skipped" };const detail = await host.call<{- provider?: { baseUrl?: string; authKind?: string; headers?: Record<string, string> };+ provider?: {+ baseUrl?: string;+ authKind?: string;+ apiStyle?: string;+ headers?: Record<string, string>;+ };}>("providers.get", { id });// A vendor account proves itself by resolving auth — refreshing the token// if it has expired — not by probing /models with a key it does not have.@@ -197,31 +223,40 @@ export function registerProviderIpc({const controller = new AbortController();const timer = setTimeout(() => controller.abort(), 8000);try {- const res = await fetch(`${baseUrl.replace(/\/+$/, "")}/models`, {- headers: mergeProviderHeaders(- secret.value ? { Authorization: `Bearer ${secret.value}` } : {},- detail.provider?.headers,- ),+ /*+ The same request builder discovery uses, so "the list loaded" and "the+ connection test passed" can never describe two different endpoints: one+ URL rule, one auth rule, one wire style, for a real at-least-once check.+ */+ const probe = await probeModelList({+ baseUrl,+ apiKey: secret.value,+ apiStyle: detail.provider?.apiStyle,+ headers: detail.provider?.headers,signal: controller.signal,});- if (res.status === 401 || res.status === 403) {+ return { ok: true, network: "ok", status: probe.status };+ } catch (e) {+ const status = (e as { status?: unknown }).status;+ if (status === 401 || status === 403) {return {ok: false,network: "failed",- status: res.status,+ status,errorCode: ErrorCodes.PROVIDER_UNAUTHORIZED,};}- if (res.status === 429) {+ if (status === 429) {return {ok: false,network: "failed",- status: res.status,+ status,errorCode: ErrorCodes.PROVIDER_RATE_LIMITED,};}- return { ok: res.ok, network: res.ok ? "ok" : "failed", status: res.status };- } catch (e) {+ if (typeof status === "number") {+ return { ok: false, network: "failed", status };+ }return {ok: false,network: "failed",@@ -286,6 +321,25 @@ export function registerProviderIpc({: undefined;const baseUrl = (req.baseUrl ?? provider?.baseUrl ?? "").trim();const apiStyle = req.apiStyle ?? provider?.apiStyle ?? "chat_completions";+ /*+ Static endpoint resolution, the same layer the settings dialog uses:+ which URL this row will really address, which wire style the evidence+ implies, and the same-origin addresses worth asking. Pure; no model id+ takes part in it.+ */+ const profile = inferEndpointProfile({+ baseUrl,+ // A persisted style this release does not know is read the way the rest+ // of the row is read: as Chat Completions.+ apiStyle: normalizeApiStyle(apiStyle),+ explicitApiStyle: true,+ providerKey: provider?.vendorKey,+ });+ // The address that answers may be a resolved candidate. The requested URL+ // stays the key for cache writes: the cache belongs to the saved endpoint,+ // not to a suggestion.+ let endpointBaseUrl = profile?.effectiveBaseUrl ?? baseUrl;+// Cache hydration must stay fast; the renderer already requests a live// refresh after it has painted the cached list. Live requests load the// shared models.dev snapshot once; cache reads use only local files.@@ -305,17 +359,19 @@ export function registerProviderIpc({source?: "bundled" | "discovered" | "user";},// Vendor accounts can span wire APIs, so a model may need a style of- // its own rather than the row's.+ // its own rather than the row's. The endpoint is per call too: the live+ // branch decorates with the candidate that answered.modelApiStyle: string = apiStyle,+ catalogBaseUrl: string = endpointBaseUrl,) => {const modelsDevModel = modelsDevCatalog.findModel({vendorKey: provider?.vendorKey || "custom",- baseUrl,+ baseUrl: catalogBaseUrl,modelId: model.modelId,});const catalogModelConfig = catalogModelConfigFor(modelsDevCatalog, {vendorKey: provider?.vendorKey || "custom",- baseUrl,+ baseUrl: catalogBaseUrl,apiStyle: modelApiStyle,modelId: model.modelId,});@@ -509,26 +565,54 @@ export function registerProviderIpc({what came back (`decorate` above). Asking the catalog first would offerevery published model for the vendor, including ones this deploymentdoes not host and ones the key is not entitled to.++ The typed Base URL is a starting point, not the answer: resolution offers+ the same-origin candidates that could serve this row and the sweep asks+ them in order. Whatever answers becomes the effective base URL the row is+ actually ran — automatic, but never hidden.*/let discoveryError: string | undefined;+ let resolution: {+ effectiveBaseUrl?: string;+ discoveryStyle?: string;+ apiStyleHint?: string;+ evidence?: string;+ } = {};if (baseUrl) {try {- const discovered = await discoverProviderModels({- baseUrl,- apiKey,- apiStyle,- headers: req.headers ?? provider?.headers,- });- if (discovered.length > 0) {- const models = discovered.map((model) => decorate(model));+ const sweep = profile+ ? await probeDiscoveryCandidates({+ origin: profile.origin,+ candidates: profile.candidates,+ apiKey,+ headers: req.headers ?? provider?.headers,+ })+ : { attempts: [] };+ const outcome = sweep.outcome;+ if (outcome) {+ endpointBaseUrl = outcome.effectiveBaseUrl;+ resolution = {+ effectiveBaseUrl: outcome.effectiveBaseUrl,+ discoveryStyle: outcome.discoveryStyle,+ ...(outcome.apiStyleHint ? { apiStyleHint: outcome.apiStyleHint } : {}),+ evidence: outcome.evidence.type,+ };+ const models = outcome.models.map((model) => decorate(model));// Only what the endpoint actually served is cached; a configured id// it never offered must not be recorded as discovered.await cacheForCurrentProvider(models);return {models: withConfiguredBindings(models),source: "remote" as const,+ ...resolution,};}+ discoveryError = describeSweepFailure(sweep.attempts);+ if (discoveryError) {+ logger.app("provider", "warn", "model discovery failed", {+ data: { providerId: provider?.id, error: discoveryError },+ });+ }} catch (e) {discoveryError = e instanceof Error ? e.message : String(e);logger.app("provider", "warn", "model discovery failed", {@@ -541,7 +625,7 @@ export function registerProviderIpc({// or an empty list). The catalog is the fallback, not the primary source.const catalogModels = modelsDevCatalog.modelsForProvider({vendorKey: provider?.vendorKey,- baseUrl,+ baseUrl: endpointBaseUrl,providerId: provider?.id ?? "",});if (catalogModels.length > 0) {@@ -550,6 +634,7 @@ export function registerProviderIpc({catalogModels.map((model) => decorate(model)),),source: "catalog" as const,+ ...resolution,...(discoveryError ? { error: discoveryError } : {}),};}@@ -560,7 +645,7 @@ export function registerProviderIpc({const fallback = fallbackModelId? [decorate({ modelId: fallbackModelId, displayName: fallbackModelId })]: [];- return { models: fallback, source: "fallback", error: discoveryError };+ return { models: fallback, source: "fallback", ...resolution, error: discoveryError };},);diff --git a/apps/desktop/electron/main/model-discovery.ts b/apps/desktop/electron/main/model-discovery.tsindex 482b471cb..5ba478346 100644--- a/apps/desktop/electron/main/model-discovery.ts+++ b/apps/desktop/electron/main/model-discovery.ts@@ -1,22 +1,34 @@/**- * Provider model discovery: query the provider's own model-list endpoint so- * users pick real model IDs instead of typing them (settings dialog and the- * composer model menu both consume this).+ * Provider model discovery: ask a service's own model-list endpoint what it+ * serves, so users pick real model IDs instead of typing them.*- * Per apiStyle:- * - chat_completions / responses → GET {base}/models (Bearer auth)- * - anthropic_messages → GET {base}/v1/models (x-api-key)- * - google_generative_ai → GET {base}/models?key=…+ * Three responsibilities, deliberately separate:+ *+ * - `normalizeModelList` turns a response body into rows and is pure;+ * - `modelListRequest` builds the request one endpoint needs;+ * - `probeModelList` performs exactly one request, with redirect safety.+ *+ * The candidate sweep that resolves an unknown Base URL lives in+ * `provider-endpoint-probe.ts` and drives `probeModelList`, so discovery and+ * "Test connection" cannot drift into two different URL or auth rules.*/+import {+ discoveryProbeUrl,+ discoveryStyleForApiStyle,+ type DiscoveryStyle,+} from "@pi-desktop/shared";+export type DiscoveredModel = {modelId: string;displayName: string;};-const DISCOVERY_TIMEOUT_MS = 10_000;+export const DISCOVERY_TIMEOUT_MS = 10_000;+/** Total budget for one endpoint-resolution sweep; its candidates share it. */+export const DISCOVERY_TOTAL_BUDGET_MS = 12_000;const MAX_MODELS = 500;-const OPENCODE_GO_API_STYLE = "opencode_go";+const MAX_REDIRECTS = 3;const RESERVED_DISCOVERY_HEADERS = new Set(["authorization","proxy-authorization",@@ -70,13 +82,21 @@ function dedupeSort(models: DiscoveredModel[]): DiscoveredModel[] {.slice(0, MAX_MODELS);}-/** Normalize a model-list response body for the given apiStyle. Pure. */+/**+ * Normalize a model-list response body. Pure.+ *+ * `style` is either a wire API style or a discovery style; both name the same+ * three response shapes. Two of them nest the rows under a key of their own:+ * Google publishes `{ models: [{ name: "models/…" }] }`, and Zhipu's OpenAI+ * Responses endpoint publishes `{ models: [{ slug }] }` — the same `models`+ * key with a `models/` prefix that never appears there.+ */export function normalizeModelList(- apiStyle: string | undefined,+ style: string | undefined,body: unknown,): DiscoveredModel[] {const record = asRecord(body);- if (apiStyle === "google_generative_ai") {+ if (style === "google_generative_ai" || style === "google_models") {const models = Array.isArray(record?.models) ? record.models : [];return dedupeSort(models.flatMap((entry) => {@@ -93,16 +113,18 @@ export function normalizeModelList();}// OpenAI-style and Anthropic both use { data: [...] }; some gateways return- // the bare array.+ // the bare array, and Zhipu's Responses endpoint wraps the rows in `models`.const data = Array.isArray(record?.data)? record.data: Array.isArray(body)? (body as unknown[])- : [];+ : Array.isArray(record?.models)+ ? record.models+ : [];return dedupeSort(data.flatMap((entry) => {const item = asRecord(entry);- const modelId = typeof item?.id === "string" ? item.id : "";+ const modelId = listedModelId(item);if (!modelId) return [];const displayName =typeof item?.display_name === "string" && item.display_name@@ -113,66 +135,156 @@ export function normalizeModelList();}-/** Build the request for a provider's model-list endpoint. Pure. */+/**+ * The id one row of a model list carries.+ *+ * `id` is the OpenAI and Anthropic shape. `slug` is what Zhipu's OpenAI+ * Responses endpoint returns. The two are mutually exclusive, so either may be+ * read without ambiguity, and the wire id stays exactly as the service spelled+ * it.+ */+function listedModelId(item: Record<string, unknown> | null): string {+ if (typeof item?.id === "string" && item.id) return item.id;+ return typeof item?.slug === "string" ? item.slug : "";+}++/**+ * Build the request for a provider's model-list endpoint. Pure.+ *+ * The URL comes from the shared `discoveryProbeUrl`, so a candidate the+ * resolver offered and the request built for it can never disagree.+ */export function modelListRequest(opts: {baseUrl: string;apiKey?: string;apiStyle?: string;+ discoveryStyle?: DiscoveryStyle;headers?: Record<string, string>;}): { url: string; headers: Record<string, string> } {- const base = opts.baseUrl.trim().replace(/\/+$/, "");const apiKey = opts.apiKey ?? "";+ const discoveryStyle =+ opts.discoveryStyle ?? discoveryStyleForApiStyle(opts.apiStyle);+ const path = discoveryProbeUrl(opts.baseUrl, discoveryStyle);const withHeaders = (headers: Record<string, string>): Record<string, string> =>withCustomHeaders(headers, opts.headers);- if (opts.apiStyle === "google_generative_ai") {++ if (discoveryStyle === "google_models") {const params = new URLSearchParams({ pageSize: "1000" });if (apiKey) params.set("key", apiKey);- return { url: `${base}/models?${params}`, headers: withHeaders({}) };+ return { url: `${path}?${params}`, headers: withHeaders({}) };}- if (opts.apiStyle === "anthropic_messages") {- // Anthropic base URLs conventionally exclude /v1 (runtime appends it).- const root = base.endsWith("/v1") ? base : `${base}/v1`;+ if (discoveryStyle === "anthropic_models") {return {- url: `${root}/models?limit=1000`,+ url: `${path}?limit=1000`,headers: withHeaders({...(apiKey ? { "x-api-key": apiKey } : {}),"anthropic-version": "2023-06-01",}),};}- // OpenCode Go exposes the same authenticated OpenAI-compatible /models- // endpoint as generic Chat Completions, but keeps a distinct UI style.- if (opts.apiStyle === OPENCODE_GO_API_STYLE) {- return {- url: `${base}/models`,- headers: withHeaders(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),- };- }+ // Chat Completions, Responses, OpenCode Go and the Codex account all expose+ // the same authenticated OpenAI-compatible model list.return {- url: `${base}/models`,+ url: path,headers: withHeaders(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),};}-/** Fetch and normalize the provider's model list. Throws on HTTP/network errors. */-export async function discoverProviderModels(opts: {+export type ModelListProbe = {+ /** The URL that answered, after any same-origin redirect. */+ url: string;+ status: number;+ models: DiscoveredModel[];+};++function originOf(value: string): string | undefined {+ try {+ return new URL(value.trim()).origin;+ } catch {+ return undefined;+ }+}++/**+ * One model-list request.+ *+ * Redirects are followed manually so a cross-origin hop can be refused before+ * the credential travels: the `Location` is compared against `allowOrigin`+ * first. Throws on a network error, a refused redirect, or a non-2xx status —+ * `error.status` carries the HTTP status when there was one.+ */+export async function probeModelList(opts: {baseUrl: string;apiKey?: string;apiStyle?: string;+ discoveryStyle?: DiscoveryStyle;headers?: Record<string, string>;-}): Promise<DiscoveredModel[]> {- const { url, headers } = modelListRequest(opts);- const controller = new AbortController();- const timer = setTimeout(() => controller.abort(), DISCOVERY_TIMEOUT_MS);- try {- const res = await fetch(url, { headers, signal: controller.signal });+ /**+ * Credentials may only travel to this origin. Defaults to the configured base+ * URL's own origin, so a caller cannot widen it by accident.+ */+ allowOrigin?: string;+ /**+ * Caller-owned budget. The sweep shares one across its candidates and passes+ * it here; a caller that passes nothing gets the single-request default.+ */+ signal?: AbortSignal;+}): Promise<ModelListProbe> {+ const request = modelListRequest(opts);+ const allowOrigin = opts.allowOrigin ?? originOf(opts.baseUrl);+ const responseSignal = opts.signal ?? defaultTimeoutSignal();+ if (allowOrigin) {+ const origin = originOf(request.url);+ if (origin !== allowOrigin) {+ throw new Error("model list request refused: it left the configured origin");+ }+ }++ let url = request.url;+ for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {+ const res = await fetch(url, {+ headers: request.headers,+ signal: responseSignal,+ // Never let fetch carry the credential to another origin on its own.+ redirect: "manual",+ });+ const location = res.headers.get("location");+ if (res.status >= 300 && res.status < 400 && location) {+ const next = new URL(location, url);+ if (allowOrigin && next.origin !== allowOrigin) {+ throw Object.assign(+ new Error("model list redirect refused: it left the configured origin"),+ { status: res.status },+ );+ }+ url = next.toString();+ continue;+ }if (!res.ok) {throw Object.assign(new Error(`model list request failed (${res.status})`), {status: res.status,});}- return normalizeModelList(opts.apiStyle, await res.json());- } finally {- clearTimeout(timer);+ return {+ url,+ status: res.status,+ models: normalizeModelList(+ opts.discoveryStyle ?? opts.apiStyle,+ await res.json(),+ ),+ };}+ throw new Error("model list request followed too many redirects");+}++/**+ * Abort signal for a single request made without a caller budget.+ *+ * Resolution always passes its shared sweep budget; this keeps a direct caller+ * (a connection test with no budget of its own) from hanging on a silent host.+ */+function defaultTimeoutSignal(): AbortSignal {+ const controller = new AbortController();+ setTimeout(() => controller.abort(), DISCOVERY_TIMEOUT_MS);+ return controller.signal;}diff --git a/apps/desktop/electron/main/models-dev-catalog.ts b/apps/desktop/electron/main/models-dev-catalog.tsindex 039dbbe8b..c38742810 100644--- a/apps/desktop/electron/main/models-dev-catalog.ts+++ b/apps/desktop/electron/main/models-dev-catalog.ts@@ -1,5 +1,10 @@import { readFile } from "node:fs/promises";-import { MODEL_VENDOR_PREFIXES, catalogModelIdsMatch, stripVariantSuffix } from "@pi-desktop/shared";+import {+ MODEL_VENDOR_PREFIXES,+ catalogModelIdsMatch,+ stripReleaseSuffix,+ stripVariantSuffix,+} from "@pi-desktop/shared";import type {ModelCost,ModelCostTier,@@ -838,9 +843,12 @@ class ModelsDevLookupIndex {}}-/** Index only aliases the matcher can accept: exact IDs, full slash-path- * leaves, known-vendor dash/dot prefixes, and the supported suffix variants.- * The matcher remains the final authority (including known-vendor conflicts). */+/** Index only aliases the matcher can accept: exact IDs, the region-stripped+ * form, full slash-path leaves, known-vendor dash/dot prefixes, the supported+ * thinking/agent/latest variants, and published release stamps. The matcher+ * remains the final authority (including known-vendor conflicts), but the index+ * must register every alias the matcher accepts: a key it never indexed is a+ * lookup that can never reach the record. */function candidateKeys(modelId: string): string[] {const normalized = normalizedModelId(modelId);if (!normalized) return [];@@ -863,13 +871,27 @@ function candidateKeys(modelId: string): string[] {}};- // Strip a suffix only after the region, just as catalogModelIdsMatch does. Add- // aliases from both sides so a suffixed catalog ID or request can find its peer.- for (const value of new Set([normalized, base, stripVariantSuffix(base)])) {- add(value);- const slash = value.lastIndexOf("/");- if (slash >= 0 && slash < value.length - 1) add(value.slice(slash + 1));+ /*+ Suffixes are stripped after the region, just as `catalogModelIdsMatch`+ does, and either suffix may be the outer one: `foo-0731-thinking` and+ `foo-thinking-0731` both reach `foo`. Aliases are added from both sides so a+ suffixed catalog id and a suffixed request each find the other.+ */+ const variants = new Set<string>();+ for (const value of [normalized, base]) {+ const withoutVariant = stripVariantSuffix(value);+ const withoutRelease = stripReleaseSuffix(value);+ for (const variant of [+ value,+ withoutVariant,+ withoutRelease,+ stripReleaseSuffix(withoutVariant),+ stripVariantSuffix(withoutRelease),+ ]) {+ variants.add(variant);+ }}+ for (const value of variants) add(value);return [...keys];}@@ -1121,31 +1143,45 @@ export class ModelsDevCatalog {for (const entry of this.lookupIndex.candidates(requested)) {(entry.provider === preferredProvider ? preferred : rest).push(entry);}- const candidates: Array<{ model: ModelsDevModel; score: number }> = [];+ const candidates: Array<{ model: ModelsDevModel; score: number; exact: boolean }> = [];for (const { model, provider } of [...preferred, ...rest]) {// A known endpoint must not inherit another provider's capabilities.if (preferredProvider && provider !== preferredProvider) continue;if (!catalogModelIdsMatch(model.modelId, requested)) continue;- let score = model.modelId.toLowerCase() === requested ? 20 : 10;+ const exact = model.modelId.toLowerCase() === requested;+ let score = exact ? 20 : 10;if (provider === preferredProvider) score += 100;if (apiMatches(input.baseUrl, provider.api)) score += 80;if (modelMatchesProvider(model, input.vendorKey)) score += 60;- candidates.push({ model, score });+ candidates.push({ model, score, exact });}candidates.sort((left, right) =>right.score - left.score || left.model.modelId.length - right.model.modelId.length,);+ /*+ A record the catalog publishes under exactly this id is this id's record.+ Supported aliases — a release stamp, a thinking variant, a route leaf —+ also reach a *shorter* sibling, and answering with that sibling would+ attach another deployment's limits and capabilities to the row. So exact+ candidates discard the alias-derived ones before the ambiguity test, which+ is what keeps `foo-v2-0731` on its own record while a catalog that only+ publishes `foo-v2` still answers it.+ */+ const exactCandidates = candidates.filter((candidate) => candidate.exact);+ const pool = exactCandidates.length > 0 ? exactCandidates : candidates;/* Within the row's own catalog provider this is an exact-provider lookup:the provider identity is known, so its record for the id — a direct hitor a supported alias — is authoritative.With no provider identity the scores prove nothing about identity, so a- catalog answer is only usable when it is unambiguous. Two providers- publishing the same id must not have one of them chosen for the other. */- const resolved = candidates[0]?.model;+ catalog answer is only usable when it is unambiguous — and only over the+ alias-derived pool, since an exact record already outranks its aliases.+ Two providers publishing the same id must not have one chosen for the+ other. */+ const resolved = pool[0]?.model;const result = preferredProvider? resolved- : candidates.length === 1 ? resolved : undefined;+ : pool.length === 1 ? resolved : undefined;/* The row's own catalog provider did not publish this id. Borrowing needs aknown provider identity to anchor on: the row resolved to a catalogprovider whose own records are authoritative, so anything missing from itdiff --git a/apps/desktop/electron/main/provider-endpoint-probe.ts b/apps/desktop/electron/main/provider-endpoint-probe.tsnew file mode 100644index 000000000..ade9b9c27--- /dev/null+++ b/apps/desktop/electron/main/provider-endpoint-probe.ts@@ -0,0 +1,157 @@+/**+ * Endpoint resolution against the network.+ *+ * The static layer (`@pi-desktop/shared/provider-endpoint`) decides which base+ * URLs are worth asking and in which discovery style; this module asks them —+ * one at a time, inside one shared time budget, and only on the origin the user+ * typed.+ *+ * Serial probing is a security decision, not a performance one: every candidate+ * carries the user's API key, so the sweep must not fan the credential out to+ * several servers at once. The first candidate that answers wins and the rest+ * are never contacted.+ */++import type {+ CatalogApiStyle,+ DiscoveryStyle,+ EndpointCandidate,+ EndpointEvidence,+} from "@pi-desktop/shared";+import {+ probeModelList,+ type DiscoveredModel,+} from "./model-discovery";++/** Total budget for the whole sweep; each candidate gets what is left. */+export const DISCOVERY_SWEEP_BUDGET_MS = 12_000;++/** What one candidate produced, so a failure can be explained per URL. */+export type DiscoveryAttempt = {+ baseUrl: string;+ discoveryStyle: DiscoveryStyle;+ url: string;+ status?: number;+ error?: string;+};++export type DiscoveryProbeOutcome = {+ models: DiscoveredModel[];+ /** The base URL that answered: what the row should store and display. */+ effectiveBaseUrl: string;+ discoveryStyle: DiscoveryStyle;+ /** Wire style the winning candidate suggested, if it suggested one. */+ apiStyleHint?: CatalogApiStyle;+ evidence: EndpointEvidence;+ attempts: DiscoveryAttempt[];+};++type ProbeOptions = {+ /** The origin the user typed. Nothing outside it is ever contacted. */+ origin: string;+ candidates: readonly EndpointCandidate[];+ apiKey?: string;+ headers?: Record<string, string>;+ /** Overrides the sweep budget; used by tests. */+ budgetMs?: number;+ now?: () => number;+ probe?: typeof probeModelList;+};++type ProbeResult = {+ outcome?: DiscoveryProbeOutcome;+ attempts: DiscoveryAttempt[];+};++/**+ * Ask each candidate, strongest first, and stop at the first usable answer.+ *+ * A candidate whose base URL left the user's origin is refused without a+ * request, as is a credential-bearing redirect to another origin further down.+ * Everything a candidate did is recorded, so the UI can explain both the URL+ * that was chosen and the ones that were not.+ */+export async function probeDiscoveryCandidates(+ options: ProbeOptions,+): Promise<ProbeResult> {+ const now = options.now ?? (() => Date.now());+ const probe = options.probe ?? probeModelList;+ const deadline = now() + (options.budgetMs ?? DISCOVERY_SWEEP_BUDGET_MS);+ const attempts: DiscoveryAttempt[] = [];++ for (const candidate of options.candidates) {+ const remaining = deadline - now();+ if (remaining <= 0) {+ attempts.push({+ baseUrl: candidate.baseUrl,+ discoveryStyle: candidate.discoveryStyle,+ url: candidate.baseUrl,+ error: "sweep budget exhausted",+ });+ continue;+ }+ const attempt: DiscoveryAttempt = {+ baseUrl: candidate.baseUrl,+ discoveryStyle: candidate.discoveryStyle,+ url: candidate.baseUrl,+ };+ attempts.push(attempt);+ // The resolver already dropped cross-origin candidates; this is the guard+ // that survives a caller passing its own list.+ let candidateOrigin: string | undefined;+ try {+ candidateOrigin = new URL(candidate.baseUrl).origin;+ } catch {+ attempt.error = "invalid base URL";+ continue;+ }+ if (candidateOrigin !== options.origin) {+ attempt.error = "refused: candidate left the configured origin";+ continue;+ }++ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), remaining);+ try {+ const result = await probe({+ baseUrl: candidate.baseUrl,+ apiKey: options.apiKey,+ discoveryStyle: candidate.discoveryStyle,+ headers: options.headers,+ signal: controller.signal,+ allowOrigin: options.origin,+ });+ // `attempt.url` is the URL that finally answered, which a same-origin+ // redirect may have moved. The candidate's own base URL is what the row+ // stores: stripping `/models` off a redirected path would invent a base+ // address this endpoint never named (Anthropic-style bases deliberately+ // exclude `/v1`, and the transport appends it), and a wrong endpoint is+ // worse than an unrefined one.+ attempt.url = result.url;+ attempt.status = result.status;+ if (result.models.length === 0) {+ attempt.error = "the endpoint published no models";+ continue;+ }+ return {+ outcome: {+ models: result.models,+ effectiveBaseUrl: candidate.baseUrl,+ discoveryStyle: candidate.discoveryStyle,+ ...(candidate.apiStyleHint ? { apiStyleHint: candidate.apiStyleHint } : {}),+ evidence: candidate.evidence,+ attempts,+ },+ attempts,+ };+ } catch (error) {+ attempt.error = error instanceof Error ? error.message : String(error);+ const status = (error as { status?: unknown }).status;+ if (typeof status === "number") attempt.status = status;+ } finally {+ clearTimeout(timer);+ }+ }++ return { attempts };+}diff --git a/apps/desktop/src/components/settings/ProviderConnectionFields.tsx b/apps/desktop/src/components/settings/ProviderConnectionFields.tsxindex abb668cf5..70f2055dc 100644--- a/apps/desktop/src/components/settings/ProviderConnectionFields.tsx+++ b/apps/desktop/src/components/settings/ProviderConnectionFields.tsx@@ -87,6 +87,8 @@ export type ProviderConnectionFieldsProps = {baseUrlError?: string;apiStyle: CatalogApiStyle;onApiStyleChange: (value: CatalogApiStyle) => void;+ /** What the endpoint itself said about the format, when it said anything. */+ apiStyleNote?: string;accountOnlyApiStyle: boolean;requiresApiStyleChoice: boolean;status: ReactNode;@@ -112,6 +114,7 @@ export function ProviderConnectionFields({baseUrlError,apiStyle,onApiStyleChange,+ apiStyleNote,accountOnlyApiStyle,requiresApiStyleChoice,status,@@ -220,9 +223,9 @@ export function ProviderConnectionFields({</Field><Fieldlabel={t("settings.apiStyle")}- hint={accountOnlyApiStyle ? t(requiresApiStyleChoice+ hint={apiStyleNote ?? (accountOnlyApiStyle ? t(requiresApiStyleChoice? "settings.apiStyleChooseCustom"- : "settings.apiStyleLegacyAccount") : undefined}+ : "settings.apiStyleLegacyAccount") : undefined)}><SettingsMenuSelectfullWidthdiff --git a/apps/desktop/src/components/settings/ProviderSetupDialog.tsx b/apps/desktop/src/components/settings/ProviderSetupDialog.tsxindex 81bf5a4bb..4cc859f41 100644--- a/apps/desktop/src/components/settings/ProviderSetupDialog.tsx+++ b/apps/desktop/src/components/settings/ProviderSetupDialog.tsx@@ -30,9 +30,19 @@ import { ServiceChooser } from "./ServiceChooser";import { CUSTOM_SERVICE } from "./service-catalog";import { useRecommendedModelSelection } from "./useRecommendedModelSelection";import type { ProviderCopyDraft } from "./provider-copy";-import { isAccountOnlyApiStyle, needsCustomApiStyleChoice, providerSetupPreset } from "./provider-api-style";+import {+ API_STYLE_LABEL_KEYS,+ isAccountOnlyApiStyle,+ needsCustomApiStyleChoice,+ providerSetupPreset,+} from "./provider-api-style";-import { getBaseUrlIssue, normalizeBaseUrlInput } from "./provider-endpoint-guidance";+import {+ endpointsEqual,+ getBaseUrlIssue,+ normalizeBaseUrlInput,+ resolveEndpointDraft,+} from "./provider-endpoint-guidance";import { ProviderEndpointGuidance } from "./ProviderEndpointGuidance";function serviceIdFor(provider?: ProviderPublic | null): string {@@ -92,6 +102,8 @@ export function ProviderSetupDialog({const [error, setError] = useState("");const [testResult, setTestResult] = useState("");const [baseUrlTouched, setBaseUrlTouched] = useState(false);+ // A format the user picked by hand outranks every inference about this row.+ const [apiStyleTouched, setApiStyleTouched] = useState(false);const [choosing, setChoosing] = useState(false);const [managing, setManaging] = useState(false);const customModelRef = useRef<HTMLInputElement>(null);@@ -102,7 +114,26 @@ export function ProviderSetupDialog({const custom = service === CUSTOM_SERVICE;const resolvedName = namedPreset ? name.trim() || namedPreset.name : name;const resolvedBaseUrl = namedPreset?.baseUrl ?? baseUrl;- const resolvedApiStyle: CatalogApiStyle = namedPreset?.apiStyle ?? apiStyle;+ /*+ Endpoint resolution decides the format when the endpoint itself names one:+ a pasted operation, a published service address, or a known host. A format+ that already has an owner — the user's own pick, a named preset's, or the+ one stored on the row being edited — is never overridden. Inference is for+ a row that does not have an answer yet.+ */+ const endpointDraft = resolveEndpointDraft(+ resolvedBaseUrl,+ namedPreset?.apiStyle ?? apiStyle,+ named || editing || Boolean(initialDraft) || apiStyleTouched,+ );+ const resolvedApiStyle: CatalogApiStyle = endpointDraft.apiStyle;+ // Said out loud next to the format selector: an automatic decision the user+ // cannot see would be exactly the hidden rewrite this row must not have.+ const endpointFormatNote = endpointDraft.autoDetected+ ? t("settings.apiStyleAutoDetected", {+ format: t(API_STYLE_LABEL_KEYS[resolvedApiStyle]),+ })+ : undefined;const baseUrlIssue = getBaseUrlIssue(resolvedBaseUrl);const baseUrlError =baseUrlTouched && baseUrlIssue ? t("settings.baseUrlInvalid") : undefined;@@ -138,6 +169,23 @@ export function ProviderSetupDialog({// Every edit made through the picker or the summary ends preselection.const selection = useModelSelection(discovery, models, recommended.setModels);+ /*+ The address that answered is what the field shows and the row saves. Only a+ field still holding the address the answer belongs to is updated: a URL+ typed since that probe belongs to the user, and a named preset carries its+ own address. Comparing against the address the answer was produced for —+ not against the field's rewritten form — is what keeps a fresh paste from+ being reverted to the previous result.+ */+ const discoveredBaseUrl = discovery.effectiveBaseUrl;+ const adoptedFrom = discovery.resolvedFrom;+ useEffect(() => {+ if (named || !discoveredBaseUrl || !adoptedFrom) return;+ setBaseUrl((current) => (endpointsEqual(current, adoptedFrom) ? discoveredBaseUrl : current));+ }, [named, discoveredBaseUrl, adoptedFrom]);+++// A list with nothing to recommend leaves the choice to the user, so the// picker opens instead of an empty summary.useEffect(() => {@@ -174,6 +222,9 @@ export function ProviderSetupDialog({const previous = namedPreset;setService(next);setBaseUrlTouched(false);+ // A format picked for the previous service does not carry over: the new+ // service's own format, or the new address, decides again.+ setApiStyleTouched(false);const preset = NAMED_ENDPOINT_PRESETS.find((item) => item.id === next);if (!preset) {if (next === CUSTOM_SERVICE && apiStyle === OPENCODE_GO_API_STYLE) {@@ -406,7 +457,13 @@ export function ProviderSetupDialog({commitBaseUrl={commitBaseUrl}baseUrlError={baseUrlError}apiStyle={apiStyle}- onApiStyleChange={setApiStyle}+ onApiStyleChange={(value) => {+ // A hand-picked format is the user's answer and outranks the+ // endpoint's own suggestion from here on.+ setApiStyleTouched(true);+ setApiStyle(value);+ }}+ apiStyleNote={endpointFormatNote}accountOnlyApiStyle={accountOnlyApiStyle}requiresApiStyleChoice={requiresApiStyleChoice}status={<ConnectionStatus active={discoveryActive} discovery={discovery} named={named} />}diff --git a/apps/desktop/src/components/settings/provider-endpoint-guidance.ts b/apps/desktop/src/components/settings/provider-endpoint-guidance.tsindex 632a898d4..ce7706f81 100644--- a/apps/desktop/src/components/settings/provider-endpoint-guidance.ts+++ b/apps/desktop/src/components/settings/provider-endpoint-guidance.ts@@ -1,48 +1,122 @@-import type { CatalogApiStyle } from "@pi-desktop/shared";+/**+ * The settings dialog's view of endpoint resolution.+ *+ * All of the rules live in `@pi-desktop/shared/provider-endpoint`; this module+ * is the thin adapter the form uses, so the dialog and the Electron main process+ * cannot answer "which address will this row use?" differently.+ */+import {+ canonicalEndpointUrl,+ inferEndpointProfile,+ matchEndpointOperation,+ parseEndpointInput,+ type CatalogApiStyle,+} from "@pi-desktop/shared";+/**+ * Whether a typed Base URL can be addressed at all.+ *+ * A bare host is valid input: `api.example.com` is completed with `https://`+ * inside the origin the user named, which is input normalization rather than a+ * cross-origin guess. Credentials, query strings and fragments stay refused —+ * a Base URL never carries them.+ */export function getBaseUrlIssue(value: string): "invalid" | null {- if (!value.trim()) return null;- try {- const url = new URL(value.trim());- return !["http:", "https:"].includes(url.protocol) || !url.hostname ||- url.username || url.password || url.search || url.hash ? "invalid" : null;- } catch {- return "invalid";- }+ const trimmed = value.trim();+ if (!trimmed) return null;+ return parseEndpointInput(trimmed) ? null : "invalid";}-const OPERATIONS: ReadonlyArray<readonly [string, CatalogApiStyle]> = [- ["/chat/completions", "chat_completions"],- ["/responses", "responses"],- ["/messages", "anthropic_messages"],-];+export type EndpointDraft = {+ /** The address this row will really use. */+ effectiveBaseUrl: string;+ /** The wire format the endpoint evidence implies. */+ apiStyle: CatalogApiStyle;+ /**+ * True when the endpoint itself decided the format, so the form may say so.+ * False when the value is the generic fallback and nothing was inferred.+ */+ autoDetected: boolean;+ /** `explicit`, `url_suffix`, `known_endpoint`, … — the strongest claim, for display. */+ evidence?: string;+};++/**+ * Resolve a typed Base URL for the form.+ *+ * `apiStyle` is the format currently selected in the form and `explicit` says+ * whether the user chose it. An explicit pick always wins: the endpoint may+ * never quietly change a format the user selected.+ */+export function resolveEndpointDraft(+ value: string,+ apiStyle: CatalogApiStyle,+ explicit: boolean,+): EndpointDraft {+ const profile = inferEndpointProfile({+ baseUrl: value,+ apiStyle,+ explicitApiStyle: explicit,+ });+ if (!profile) return { effectiveBaseUrl: value.trim(), apiStyle, autoDetected: false };+ const strongest = profile.evidence.at(-1);+ const inferred = strongest !== undefined && strongest.type !== "fallback";+ return {+ effectiveBaseUrl: profile.effectiveBaseUrl,+ // An explicit pick, or a format some piece of evidence actually names,+ // replaces the current value. The bare `chat_completions` fallback is not an+ // inference: it must not overwrite a persisted style the user never touched.+ apiStyle: explicit || inferred ? profile.apiStyle : apiStyle,+ autoDetected: !explicit && inferred,+ ...(strongest ? { evidence: strongest.type } : {}),+ };+}-/** URL evidence is a suggestion, never a successful capability probe. */-export function endpointSuggestion(value: string, current: CatalogApiStyle):- { baseUrl: string; apiStyle: CatalogApiStyle } | undefined {- if (!value.trim() || getBaseUrlIssue(value)) return undefined;- const url = new URL(value.trim());- const path = url.pathname.replace(/\/+$/, "");- for (const [suffix, apiStyle] of OPERATIONS) {- if (!path.endsWith(suffix)) continue;- if (current === apiStyle ||- (apiStyle === "chat_completions" && current === "opencode_go") ||- (apiStyle === "responses" && current === "openai_codex_responses") ||- (apiStyle === "anthropic_messages" && current === "pi_messages")) return undefined;- return { baseUrl: `${url.origin}${path.slice(0, -suffix.length)}`, apiStyle };- }- return undefined;+/**+ * URL evidence is a suggestion, never a successful capability probe.+ *+ * Only a pasted operation URL whose format contradicts the selected one is+ * offered: the endpoint's base address plus the format that suffix names.+ */+export function endpointSuggestion(+ value: string,+ current: CatalogApiStyle,+): { baseUrl: string; apiStyle: CatalogApiStyle } | undefined {+ const trimmed = value.trim();+ if (!trimmed || getBaseUrlIssue(trimmed)) return undefined;+ const parsed = parseEndpointInput(trimmed);+ if (!parsed) return undefined;+ const operation = matchEndpointOperation(parsed.pathname);+ if (!operation?.apiStyle) return undefined;+ // The suffix belongs to the selected format, so the form is already right.+ const asSelected = resolveEndpointDraft(trimmed, current, true);+ if (asSelected.effectiveBaseUrl !== parsed.normalizedInput) return undefined;+ const resolved = inferEndpointProfile({ baseUrl: trimmed });+ return {+ baseUrl: resolved?.effectiveBaseUrl ?? parsed.normalizedInput,+ apiStyle: operation.apiStyle,+ };}-/** Strip only operations belonging to the selected protocol. */+/**+ * Strip only operations belonging to the selected protocol.+ *+ * A pasted operation of another format is left in place: it describes a+ * mismatch the user has to resolve, and silently retargeting the row would be a+ * hidden rewrite of what they typed.+ */export function normalizeBaseUrlInput(value: string, apiStyle: CatalogApiStyle): string {const trimmed = value.trim();if (!trimmed || getBaseUrlIssue(trimmed)) return trimmed;- const normalized = trimmed.replace(/\/+$/, "");- const wireStyle = apiStyle === "opencode_go" ? "chat_completions"- : apiStyle === "openai_codex_responses" ? "responses"- : apiStyle === "pi_messages" ? "anthropic_messages" : apiStyle;- const suffixes = [...OPERATIONS.filter(([, style]) => style === wireStyle).map(([suffix]) => suffix), "/models"];- const suffix = suffixes.find((item) => normalized.toLowerCase().endsWith(item));- return suffix ? normalized.slice(0, -suffix.length).replace(/\/+$/, "") : normalized;+ const profile = inferEndpointProfile({+ baseUrl: trimmed,+ apiStyle,+ explicitApiStyle: true,+ });+ return profile ? profile.effectiveBaseUrl : trimmed;+}++/** Whether two typed addresses name the same endpoint. */+export function endpointsEqual(left: string, right: string): boolean {+ return canonicalEndpointUrl(left) === canonicalEndpointUrl(right);}diff --git a/apps/desktop/src/components/settings/useProviderModels.ts b/apps/desktop/src/components/settings/useProviderModels.tsindex 135545d5e..2d13540c0 100644--- a/apps/desktop/src/components/settings/useProviderModels.ts+++ b/apps/desktop/src/components/settings/useProviderModels.ts@@ -19,6 +19,21 @@ export type ProviderModelsState = {/** Message from the failed live call; cached rows stay visible alongside it. */error?: string;source?: ProviderModelsSource;+ /**+ * The base URL the service actually answered on, when a sweep resolved one.+ * The form shows and saves this address rather than a hidden rewrite.+ */+ effectiveBaseUrl?: string;+ /**+ * The base URL this answer belongs to. The form only adopts+ * `effectiveBaseUrl` while its field still holds this address, so a URL typed+ * since the probe is never reverted to an earlier result.+ */+ resolvedFrom?: string;+ /** How the sweep asked, and the evidence behind the candidate that won. */+ discoveryStyle?: string;+ apiStyleHint?: string;+ evidence?: string;};export type ProviderModelsDiscovery = ProviderModelsState & {@@ -127,11 +142,29 @@ export function useProviderModels(...(Object.keys(hdrs ?? {}).length > 0 ? { headers: hdrs } : {}),});if (requestSeq.current !== requestId) return;+ /*+ A resolution result travels with the list: the address that answered and+ the evidence behind it are what the form shows, so automatic endpoint+ completion never becomes invisible behaviour.++ `resolvedFrom` is the address this answer belongs to. The form compares+ a field against it before adopting the answer, which is what keeps a URL+ typed since the probe from being reverted to an earlier result.+ */+ const resolution = {+ ...(result.effectiveBaseUrl+ ? { effectiveBaseUrl: result.effectiveBaseUrl, resolvedFrom: url }+ : {}),+ ...(result.discoveryStyle ? { discoveryStyle: result.discoveryStyle } : {}),+ ...(result.apiStyleHint ? { apiStyleHint: result.apiStyleHint } : {}),+ ...(result.evidence ? { evidence: result.evidence } : {}),+ };if (result.models.length > 0) {setState({status: "ready",models: result.models,source: result.source,+ ...resolution,...(result.error ? { error: result.error } : {}),});} else {@@ -140,6 +173,7 @@ export function useProviderModels(status: "error",models: cachedModels,source: result.source,+ ...resolution,...(result.error ? { error: result.error } : {}),});}diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex ceb3fecb3..3cfd32863 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -683,8 +683,15 @@ export const api = {** `source` reports where the list came from: `remote` is the service's own* answer, `catalog` means the endpoint published nothing and models.dev was+ * `source` reports where the list came from: `remote` is the service's own+ * answer, `catalog` means the endpoint published nothing and models.dev was* used instead, `cache` is the local table, `fallback` is just the configured* model id.+ *+ * The resolution fields let the form show what the probe actually did:+ * `effectiveBaseUrl` is the address that answered (which may be a completed+ * candidate rather than the typed URL), `discoveryStyle` is how it was asked,+ * and `evidence` is the reason the candidate was chosen.*/listProviderModels: (input: {providerId?: string;@@ -698,6 +705,10 @@ export const api = {models: ModelInfo[];source: "cache" | "remote" | "catalog" | "fallback";error?: string;+ effectiveBaseUrl?: string;+ discoveryStyle?: string;+ apiStyleHint?: string;+ evidence?: string;}>(IPC.invoke.providersListModels, input),/*** Look one hand-typed model id up in the local models.dev snapshot.diff --git a/apps/desktop/test/model-discovery-precedence.test.mjs b/apps/desktop/test/model-discovery-precedence.test.mjsindex abe5f3ff2..9e0571978 100644--- a/apps/desktop/test/model-discovery-precedence.test.mjs+++ b/apps/desktop/test/model-discovery-precedence.test.mjs@@ -5,12 +5,12 @@ import { readMainSource } from "./helpers/source-contracts.mjs";* `providersListModels` used to answer from the bundled models.dev snapshot* before it ever contacted the endpoint, which offered every model a vendor* publishes — including ones a given deployment does not host and ones the key- * is not entitled to. These tests pin the corrected order: probe the service,- * enrich what it returned with models.dev, and only fall back to the catalog- * when the endpoint publishes nothing usable.+ * is not entitled to. These tests pin the corrected order: resolve the endpoint,+ * probe the service through that resolution, enrich what it returned with+ * models.dev, and only fall back to the catalog when the endpoint publishes+ * nothing usable.*/import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";import test from "node:test";const mainSource = await readMainSource();@@ -21,13 +21,13 @@ const handler = (() => {assert.notEqual(start, -1, "providersListModels handler not found");// The handler ends at its own fallback return; the next `handle(` registration// is not guaranteed to be the create one.- const end = mainSource.indexOf('source: "fallback", error: discoveryError', start);+ const end = mainSource.indexOf('source: "fallback", ...resolution, error: discoveryError', start);assert.notEqual(end, -1, "could not bound the handler body");return mainSource.slice(start, end);})();test("the live endpoint is probed before the bundled catalog is consulted", () => {- const discovery = handler.indexOf("await discoverProviderModels(");+ const discovery = handler.indexOf("await probeDiscoveryCandidates(");const catalog = handler.indexOf("modelsDevCatalog.modelsForProvider(");assert.notEqual(discovery, -1, "live discovery call missing");assert.notEqual(catalog, -1, "catalog fallback missing");@@ -37,6 +37,17 @@ test("the live endpoint is probed before the bundled catalog is consulted", () =);});+test("the probe asks the resolved candidates, not the typed URL alone", () => {+ // The typed Base URL is a starting point: a bare host must be able to resolve+ // to the path that answers, and every candidate stays on the typed origin.+ assert.match(handler, /inferEndpointProfile\(\{/);+ assert.match(handler, /candidates: profile\.candidates/);+ assert.match(handler, /origin: profile\.origin/);+ // The renderer reads the answer from the IPC result instead of re-deriving it.+ assert.match(handler, /effectiveBaseUrl: outcome\.effectiveBaseUrl/);+ assert.match(handler, /discoveryStyle: outcome\.discoveryStyle/);+});+test("a catalog-derived list is reported as such, not as the service's answer", () => {// The renderer has to be able to tell the user the service published no list.assert.match(handler, /source: "catalog" as const/);@@ -56,19 +67,22 @@ test("only a live answer is written back to the model cache", () => {const catalog = handler.indexOf("modelsDevCatalog.modelsForProvider(");assert.ok(cacheCall < catalog, "the cache write must belong to the live branch");assert.match(handler, /if \(!provider \|\| req\.source === "cache"\) return;/);+ // The cache key stays the saved endpoint, so a resolved candidate never+ // rewrites the cache of a row that has not been saved with it yet.+ assert.match(handler, /const requestBaseUrl = baseUrl\.replace/);});test("every returned model is enriched through models.dev regardless of origin", () => {// `decorate` is what attaches published limits, modalities and thinking// levels, so all three branches must route through it.assert.match(handler, /const modelsDevModel = modelsDevCatalog\.findModel\(/);- assert.match(handler, /discovered\.map\(\(model\) => decorate\(model\)\)/);+ assert.match(handler, /outcome\.models\.map\(\(model\) => decorate\(model\)\)/);assert.match(handler, /catalogModels\.map\(\(model\) => decorate\(model\)\)/);});test("the stored secret is resolved before probing, so edits need no retyped key", () => {const secret = handler.indexOf('"providers.getSecret"');- const discovery = handler.indexOf("await discoverProviderModels(");+ const discovery = handler.indexOf("await probeDiscoveryCandidates(");assert.notEqual(secret, -1, "stored secret lookup missing");assert.ok(secret < discovery, "the key must be resolved before the probe");});diff --git a/apps/desktop/test/model-discovery.test.mjs b/apps/desktop/test/model-discovery.test.mjsindex 858d171f0..5917782c9 100644--- a/apps/desktop/test/model-discovery.test.mjs+++ b/apps/desktop/test/model-discovery.test.mjs@@ -23,6 +23,35 @@ test("openai-style lists normalize, dedupe, and sort", () => {assert.equal(normalizeModelList("responses", [{ id: "o4-mini" }]).length, 1);});+test("a models[] response with slug rows is read as a list too", () => {+ /*+ Zhipu publishes three model-list shapes on one host: OpenAI Responses serves+ `{ models: [{ slug }] }`, Anthropic and the coding plan serve `{ data: [{ id }] }`.+ Reading only `data[].id` left the Responses row with an empty list, and the+ larger sweep then looked for the models somewhere else entirely.+ */+ assert.deepEqual(+ normalizeModelList("responses", {+ models: [+ { slug: "glm-5.3", display_name: "glm-5.3", context_window: 1_048_576, supported_in_api: true },+ { slug: "glm-5.3" },+ ],+ }),+ [{ modelId: "glm-5.3", displayName: "glm-5.3" }],+ );+ // The two id keys are mutually exclusive; `id` wins if a gateway publishes both.+ assert.deepEqual(normalizeModelList("chat_completions", { models: [{ id: "m", slug: "s" }] }), [+ { modelId: "m", displayName: "m" },+ ]);+ // A Google list still takes its own branch and keeps the `models/` prefix off.+ assert.deepEqual(normalizeModelList("google_generative_ai", { models: [{ name: "models/gemini-3" }] }), [+ { modelId: "gemini-3", displayName: "gemini-3" },+ ]);+ // A data list still wins over a models wrapper when both are present.+ assert.deepEqual(normalizeModelList("responses", { data: [{ id: "a" }], models: [{ slug: "b" }] }), [+ { modelId: "a", displayName: "a" },+ ]);+});test("anthropic lists keep display names", () => {const models = normalizeModelList("anthropic_messages", {data: [{ id: "claude-sonnet-5", display_name: "Claude Sonnet 5" }],diff --git a/apps/desktop/test/models-dev-catalog.test.mjs b/apps/desktop/test/models-dev-catalog.test.mjsindex 1d5a7daa8..cd55d5a7e 100644--- a/apps/desktop/test/models-dev-catalog.test.mjs+++ b/apps/desktop/test/models-dev-catalog.test.mjs@@ -4,8 +4,12 @@ import { tmpdir } from "node:os";import { join } from "node:path";import test from "node:test";import { fileURLToPath } from "node:url";-import { apiStyleForAdapter, catalogModelIdsMatch, modelIdsMatch } from "@pi-desktop/shared";-+import {+ apiStyleForAdapter,+ bindingForCustomModelInfo,+ catalogModelIdsMatch,+ modelIdsMatch,+} from "@pi-desktop/shared";import {MODELS_DEV_API_URL,ModelsDevCatalog,@@ -1425,3 +1429,68 @@ test("a resolved catalog record still wins over the Anthropic thinking fallback"assert.equal(config.contextWindow, 200_000);assert.ok(config.reasoningOptions?.some((option) => option.type === "budget_tokens"));});++/*+ Release stamps in the published catalog.++ A gateway serves `mify/mimo-v2.5-pro-0731` while models.dev indexes the model+ under the id that owns the weights. The alias only ever borrows metadata: the+ id the row is addressed with stays the discovery result.+*/+test("a dated snapshot borrows its published model's metadata without changing the wire id", async (t) => {+ const catalog = await loadFixtureCatalog(t, {+ mify: {+ api: "https://api.mify.example/v1",+ models: {+ "mimo-v2.5-pro": {+ id: "mimo-v2.5-pro",+ name: "MiMo v2.5 Pro",+ reasoning: true,+ tool_call: true,+ limit: { context: 262_144, output: 32_768 },+ },+ },+ },+ });+ const model = catalog.findModel({ vendorKey: "mify", modelId: "mify/mimo-v2.5-pro-0731" });+ assert.equal(model?.modelId, "mimo-v2.5-pro");+ assert.equal(model?.limit.context, 262_144);++ const info = modelInfoFromModelsDev(model, "provider-1");+ const binding = bindingForCustomModelInfo("mify/mimo-v2.5-pro-0731", info);+ assert.equal(binding.id, "mify/mimo-v2.5-pro-0731");+ assert.equal(binding.contextWindow, 262_144);+});++test("an exact record answers an id its shorter siblings would only alias", async (t) => {+ const catalog = await loadFixtureCatalog(t, {+ alpha: { api: "https://alpha.example/v1", models: {+ "foo-v2": { id: "foo-v2", limit: { context: 32_000 } },+ "foo-v2-0731": { id: "foo-v2-0731", limit: { context: 128_000 } },+ } },+ beta: { api: "https://beta.example/v1", models: {+ "foo-v2": { id: "foo-v2", limit: { context: 64_000 } },+ } },+ });+ const exact = catalog.findModel({ vendorKey: "alpha", modelId: "foo-v2-0731" });+ assert.equal(exact?.modelId, "foo-v2-0731");+ assert.equal(exact?.limit.context, 128_000);++ // A stamp nothing publishes borrows the model it was cut from.+ const borrowed = catalog.findModel({ vendorKey: "alpha", modelId: "foo-v2-0815" });+ assert.equal(borrowed?.modelId, "foo-v2");++ // Two publishers of the alias cannot answer for an unknown endpoint…+ assert.equal(+ catalog.findModel({ vendorKey: "custom", baseUrl: "https://relay.example/v1", modelId: "foo-v2" }),+ undefined,+ );+ // …but a record the catalog publishes in full answers for itself.+ const published = catalog.findModel({+ vendorKey: "custom",+ baseUrl: "https://relay.example/v1",+ modelId: "foo-v2-0731",+ });+ assert.equal(published?.providerKey, "alpha");+ assert.equal(published?.limit.context, 128_000);+});diff --git a/apps/desktop/test/provider-endpoint-probe.test.mjs b/apps/desktop/test/provider-endpoint-probe.test.mjsnew file mode 100644index 000000000..876d2da9e--- /dev/null+++ b/apps/desktop/test/provider-endpoint-probe.test.mjs@@ -0,0 +1,257 @@+/**+ * Endpoint-resolution probe contract.+ *+ * Resolution is only automatic when it is also explainable: these tests pin the+ * order candidates are asked in, the address that wins, the shared time budget,+ * and the two safety rules — the key never leaves the typed origin, and a+ * redirect may not carry it to another one.+ */+import assert from "node:assert/strict";+import { register } from "node:module";+import test from "node:test";+import { inferEndpointProfile } from "@pi-desktop/shared";++register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));+const {+ DISCOVERY_SWEEP_BUDGET_MS,+ probeDiscoveryCandidates,+} = await import("../electron/main/provider-endpoint-probe.ts");+const { probeModelList } = await import("../electron/main/model-discovery.ts");++function jsonResponse(body, status = 200, headers = {}) {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "content-type": "application/json", ...headers },+ });+}++/** Run `fn` with a stubbed global fetch, restoring it afterwards. */+async function withFetch(handler, fn) {+ const original = globalThis.fetch;+ const calls = [];+ globalThis.fetch = async (url, init) => {+ calls.push({ url: String(url), headers: init?.headers ?? {}, redirect: init?.redirect });+ return handler(String(url), init);+ };+ try {+ return { calls, result: await fn() };+ } finally {+ globalThis.fetch = original;+ }+}++test("a bare host resolves to the path that answers, and the winner is reported", async () => {+ const profile = inferEndpointProfile({ baseUrl: "api.foo.com" });+ assert.deepEqual(profile.candidates.map((candidate) => candidate.baseUrl), [+ "https://api.foo.com",+ "https://api.foo.com/v1",+ ]);++ const { calls, result } = await withFetch(+ (url) => url === "https://api.foo.com/v1/models"+ ? jsonResponse({ data: [{ id: "gateway-model", display_name: "Gateway Model" }] })+ : new Response("not found", { status: 404 }),+ () => probeDiscoveryCandidates({+ origin: profile.origin,+ candidates: profile.candidates,+ apiKey: "sk-secret",+ }),+ );++ assert.deepEqual(calls.map((call) => call.url), [+ "https://api.foo.com/models",+ "https://api.foo.com/v1/models",+ ]);+ assert.equal(result.outcome.effectiveBaseUrl, "https://api.foo.com/v1");+ assert.equal(result.outcome.discoveryStyle, "openai_models");+ assert.deepEqual(result.outcome.models, [+ { modelId: "gateway-model", displayName: "Gateway Model" },+ ]);+ // The first candidate's failure is recorded, so the UI can explain the sweep.+ assert.equal(result.outcome.attempts[0].status, 404);+ assert.equal(result.outcome.attempts[1].status, 200);+});++test("candidates are asked one at a time and the sweep stops at the first answer", async () => {+ const profile = inferEndpointProfile({ baseUrl: "https://api.foo.com" });+ const seen = [];+ let inFlight = 0;+ const { result } = await withFetch((url) => {+ seen.push(url);+ return url.includes("missing") ? new Response("", { status: 404 }) : jsonResponse({ data: [{ id: "only" }] });+ }, () => probeDiscoveryCandidates({+ origin: profile.origin,+ candidates: [+ { ...profile.candidates[0], baseUrl: "https://api.foo.com/missing" },+ profile.candidates[0],+ profile.candidates[1],+ ],+ apiKey: "sk-secret",+ probe: async (options) => {+ inFlight += 1;+ assert.equal(inFlight, 1, "a sweep must never fan the credential out in parallel");+ try {+ return await probeModelList(options);+ } finally {+ inFlight -= 1;+ }+ },+ }));++ assert.deepEqual(seen, ["https://api.foo.com/missing/models", "https://api.foo.com/models"]);+ assert.equal(result.outcome.effectiveBaseUrl, "https://api.foo.com");+});++test("the key never reaches an origin the user did not type", async () => {+ const profile = inferEndpointProfile({ baseUrl: "https://api.foo.com" });+ const { calls, result } = await withFetch(+ () => jsonResponse({ data: [{ id: "m" }] }),+ () => probeDiscoveryCandidates({+ origin: profile.origin,+ candidates: [+ // A caller-supplied list is still refused at the probe boundary.+ { ...profile.candidates[0], baseUrl: "https://api.bar.com/v1" },+ profile.candidates[0],+ ],+ apiKey: "sk-secret",+ }),+ );++ assert.deepEqual(calls.map((call) => new URL(call.url).origin), ["https://api.foo.com"]);+ assert.equal(result.attempts[0].error, "refused: candidate left the configured origin");+ assert.equal(result.outcome.effectiveBaseUrl, "https://api.foo.com");+});++test("the endpoint's own model id is reported unchanged", async () => {+ // `mify/mimo-v2.5-pro-0731` may borrow metadata from `mimo-v2.5-pro`,+ // but the id a request is addressed with is the one the service served.+ const profile = inferEndpointProfile({ baseUrl: "https://api.foo.com" });+ const { result } = await withFetch(+ () => jsonResponse({ data: [{ id: "mify/mimo-v2.5-pro-0731" }] }),+ () => probeDiscoveryCandidates({+ origin: profile.origin,+ candidates: profile.candidates,+ apiKey: "sk-secret",+ }),+ );+ assert.deepEqual(result.outcome.models, [+ { modelId: "mify/mimo-v2.5-pro-0731", displayName: "mify/mimo-v2.5-pro-0731" },+ ]);+});+++test("candidates share one time budget instead of timing out one by one", async () => {+ const profile = inferEndpointProfile({ baseUrl: "https://api.foo.com" });+ const candidates = [+ { ...profile.candidates[0], baseUrl: "https://api.foo.com/a" },+ { ...profile.candidates[0], baseUrl: "https://api.foo.com/b" },+ { ...profile.candidates[0], baseUrl: "https://api.foo.com/c" },+ ];+ let clock = 0;+ const asked = [];+ const { result } = await withFetch(+ () => { throw Object.assign(new Error("timed out"), {}); },+ () => probeDiscoveryCandidates({+ origin: profile.origin,+ candidates,+ apiKey: "sk-secret",+ now: () => clock,+ probe: async (options) => {+ asked.push(options.baseUrl);+ // The first candidate consumes the whole budget.+ clock += options.baseUrl.endsWith("/a") ? DISCOVERY_SWEEP_BUDGET_MS : 1;+ throw new Error("timed out");+ },+ }),+ );++ assert.deepEqual(asked, ["https://api.foo.com/a"]);+ assert.equal(result.outcome, undefined);+ assert.equal(result.attempts.at(-1).error, "sweep budget exhausted");+});++test("a cross-origin redirect is refused before the credential travels", async () => {+ const { calls } = await withFetch(+ () => new Response("", { status: 302, headers: { location: "https://api.bar.com/v1/models" } }),+ async () => {+ await assert.rejects(+ () => probeModelList({ baseUrl: "https://api.foo.com", apiKey: "sk-secret" }),+ /redirect refused/,+ );+ },+ );+ assert.equal(calls.length, 1, "a refused redirect must not be followed");+ assert.equal(calls[0].redirect, "manual");+});++test("a same-origin redirect is followed with the same credential", async () => {+ const { calls } = await withFetch(+ (url) => url.endsWith("/moved")+ ? jsonResponse({ data: [{ id: "after-redirect" }] })+ : new Response("", { status: 307, headers: { location: "https://api.foo.com/v1/moved" } }),+ () => probeModelList({ baseUrl: "https://api.foo.com", apiKey: "sk-secret" }),+ );+ assert.deepEqual(calls.map((call) => call.url), [+ "https://api.foo.com/models",+ "https://api.foo.com/v1/moved",+ ]);+ assert.equal(calls[1].headers.Authorization, "Bearer sk-secret");+});++test("each discovery style uses its own endpoint and auth header", async () => {+ const { calls } = await withFetch(() => jsonResponse({ data: [] }), async () => {+ await probeModelList({ baseUrl: "https://api.anthropic.com", apiKey: "sk-a", apiStyle: "anthropic_messages" });+ await probeModelList({+ baseUrl: "https://generativelanguage.googleapis.com/v1beta",+ apiKey: "g-key",+ apiStyle: "google_generative_ai",+ });+ });+ assert.equal(calls[0].url, "https://api.anthropic.com/v1/models?limit=1000");+ assert.equal(calls[0].headers["x-api-key"], "sk-a");+ assert.equal(calls[0].headers.Authorization, undefined);+ assert.match(calls[1].url, /^https:\/\/generativelanguage\.googleapis\.com\/v1beta\/models\?/);+ assert.match(calls[1].url, /key=g-key/);+});++test("an HTTP failure reports its status so the caller can classify it", async () => {+ await withFetch(() => new Response("unauthorized", { status: 401 }), async () => {+ await assert.rejects(+ () => probeModelList({ baseUrl: "https://api.foo.com", apiKey: "sk-secret" }),+ (error) => error.status === 401,+ );+ });+});++test("a typed path that answers keeps the row, even when a sibling path also answers", async () => {+ /*+ The reported failure: a Zhipu OpenAI Responses row at+ `https://open.bigmodel.cn/api/v1` publishes `{ models: [{ slug }] }`. Reading+ that shape is what keeps the row on the address the user typed; without it+ the sweep would move on and answer from the sibling coding-plan path, with+ the wrong models and a rewritten Base URL.+ */+ const profile = inferEndpointProfile({+ baseUrl: "https://open.bigmodel.cn/api/v1",+ apiStyle: "responses",+ explicitApiStyle: true,+ });+ assert.deepEqual(profile.candidates.map((candidate) => candidate.baseUrl), [+ "https://open.bigmodel.cn/api/v1",+ ]);++ const { calls, result } = await withFetch(+ (url) => url === "https://open.bigmodel.cn/api/v1/models"+ ? jsonResponse({ models: [{ slug: "glm-5.3", display_name: "glm-5.3" }] })+ : jsonResponse({ data: [{ id: "should-not-be-used" }] }),+ () => probeDiscoveryCandidates({+ origin: profile.origin,+ candidates: profile.candidates,+ apiKey: "sk-secret",+ }),+ );+ assert.deepEqual(calls.map((call) => call.url), ["https://open.bigmodel.cn/api/v1/models"]);+ assert.equal(result.outcome.effectiveBaseUrl, "https://open.bigmodel.cn/api/v1");+ assert.deepEqual(result.outcome.models, [{ modelId: "glm-5.3", displayName: "glm-5.3" }]);+});+diff --git a/apps/desktop/test/provider-endpoint-resolution-ui.test.mjs b/apps/desktop/test/provider-endpoint-resolution-ui.test.mjsnew file mode 100644index 000000000..9a808f819--- /dev/null+++ b/apps/desktop/test/provider-endpoint-resolution-ui.test.mjs@@ -0,0 +1,131 @@+/**+ * Endpoint resolution as the setup form uses it.+ *+ * A user should be able to paste `api.example.com` and get a working row; the+ * address that really answered must be the one shown and saved; and a format+ * the user picked by hand must never be changed behind their back. These tests+ * pin those three promises, plus the regression it protects: a named service's+ * own wire format is not re-derived from its URL.+ */+import assert from "node:assert/strict";+import { readFile } from "node:fs/promises";+import { register } from "node:module";+import test from "node:test";++register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));+const {+ endpointSuggestion,+ getBaseUrlIssue,+ normalizeBaseUrlInput,+ resolveEndpointDraft,+} = await import("../src/components/settings/provider-endpoint-guidance.ts");++const setupSource = await readFile(+ new URL("../src/components/settings/ProviderSetupDialog.tsx", import.meta.url),+ "utf8",+);++test("a bare host is accepted and completed inside the origin the user named", () => {+ assert.equal(getBaseUrlIssue("api.example.com"), null);+ assert.equal(normalizeBaseUrlInput("api.example.com", "chat_completions"), "https://api.example.com");+ assert.equal(normalizeBaseUrlInput("api.example.com/", "chat_completions"), "https://api.example.com");+ // Anything that could hide a credential or a query is still refused.+ for (const value of ["https://user:[email protected]", "https://api.example.com?key=x", "not a url"]) {+ assert.equal(getBaseUrlIssue(value), "invalid", value);+ }+});++test("a pasted operation resolves the format and the base address together", () => {+ const draft = resolveEndpointDraft("https://relay.example/v1/responses", "chat_completions", false);+ assert.equal(draft.apiStyle, "responses");+ assert.equal(draft.effectiveBaseUrl, "https://relay.example/v1");+ assert.equal(draft.autoDetected, true);+ assert.equal(draft.evidence, "url_suffix");+});++test("a published service address names its own format", () => {+ const draft = resolveEndpointDraft("https://api.anthropic.com", "chat_completions", false);+ assert.equal(draft.apiStyle, "anthropic_messages");+ assert.equal(draft.autoDetected, true);+});++test("a format the user chose is never changed by the endpoint", () => {+ const explicit = resolveEndpointDraft("https://api.anthropic.com", "chat_completions", true);+ assert.equal(explicit.apiStyle, "chat_completions");+ assert.equal(explicit.autoDetected, false);++ // Nothing is inferred from an unknown address, so a saved legacy format stays.+ const unknown = resolveEndpointDraft("https://relay.example", "pi_messages", false);+ assert.equal(unknown.apiStyle, "pi_messages");+ assert.equal(unknown.autoDetected, false);+});++test("every existing special wire style survives resolution", () => {+ for (const [baseUrl, apiStyle] of [+ ["https://opencode.ai/zen/go/v1", "opencode_go"],+ ["https://api.openai.com/v1", "responses"],+ ["https://api.anthropic.com", "pi_messages"],+ ["https://api.anthropic.com", "openai_codex_responses"],+ ]) {+ assert.equal(+ resolveEndpointDraft(baseUrl, apiStyle, true).apiStyle,+ apiStyle,+ `${baseUrl} ${apiStyle}`,+ );+ }+});++test("a resolved address is stable, so adopting it cannot loop", () => {+ // Discovery resolves https://api.foo.com to .../v1, the form shows and+ // saves that, and probing it again must not extend it further.+ const resolved = "https://api.foo.com/v1";+ assert.equal(normalizeBaseUrlInput(resolved, "chat_completions"), resolved);+ assert.equal(resolveEndpointDraft(resolved, "chat_completions", false).effectiveBaseUrl, resolved);+ // A mismatched operation is preserved until the user resolves it.+ assert.equal(+ normalizeBaseUrlInput("https://api.foo.com/v1/responses", "chat_completions"),+ "https://api.foo.com/v1/responses",+ );+ assert.deepEqual(endpointSuggestion("https://api.foo.com/v1/responses", "chat_completions"), {+ baseUrl: "https://api.foo.com/v1",+ apiStyle: "responses",+ });+});++test("the form adopts the address that answered and says what it detected", () => {+ assert.match(setupSource, /resolveEndpointDraft\(/);+ assert.match(setupSource, /discovery\.effectiveBaseUrl/);+ // The answer belongs to the address it was produced for, so a URL typed since+ // that probe is never reverted to an earlier result.+ assert.match(setupSource, /const adoptedFrom = discovery\.resolvedFrom;/);+ assert.match(setupSource, /endpointsEqual\(current, adoptedFrom\) \? discoveredBaseUrl : current/);+ assert.match(setupSource, /\[named, discoveredBaseUrl, adoptedFrom\]/);+ assert.match(setupSource, /settings\.apiStyleAutoDetected/);+});++test("a format that already has an owner is never re-derived from the address", () => {+ // A stored row's format is the user's answer for that row; inference is for a+ // row that does not have one yet.+ assert.match(setupSource, /named \|\| editing \|\| Boolean\(initialDraft\) \|\| apiStyleTouched/);+ // Which is what keeps this a no-op on an existing custom row.+ const saved = resolveEndpointDraft("https://api.openai.com/v1", "chat_completions", true);+ assert.equal(saved.apiStyle, "chat_completions");+ assert.equal(saved.autoDetected, false);+ // Without that owner the same address is resolved, which is the new-row path.+ assert.equal(resolveEndpointDraft("https://api.openai.com/v1", "chat_completions", false).apiStyle, "responses");+});++test("a hand-picked format outranks the endpoint from then on", () => {+ assert.match(setupSource, /const \[apiStyleTouched, setApiStyleTouched\] = useState\(false\)/);+ assert.match(setupSource, /setApiStyleTouched\(true\);/);+ // Picking another service starts the choice over.+ assert.match(setupSource, /setApiStyleTouched\(false\);/);+});++test("the saved model ids stay the ids the endpoint served", () => {+ // Metadata may be borrowed through an alias, but a binding is addressed+ // with the wire id, so the form must not rewrite one.+ assert.match(setupSource, /const persisted = selection\.bindingsToPersist;/);+ assert.match(setupSource, /models: persisted,/);+ assert.doesNotMatch(setupSource, /\.id\s*=\s*(?!==)/);+});diff --git a/apps/desktop/test/provider-lookup-model-handler.test.mjs b/apps/desktop/test/provider-lookup-model-handler.test.mjsindex d7664208d..c74a21efb 100644--- a/apps/desktop/test/provider-lookup-model-handler.test.mjs+++ b/apps/desktop/test/provider-lookup-model-handler.test.mjs@@ -86,11 +86,20 @@ function harness(realCatalog) {"@pi-desktop/shared": {IPC,ErrorCodes,+ inferEndpointProfile: () => undefined,+ normalizeApiStyle: (value) => value ?? "chat_completions",resolveBindingContextWindow: () => ({}),},"../oauth": { OAUTH_AUTH_KIND: "oauth" },"../model-discovery": {- discoverProviderModels: async () => {+ probeModelList: async () => {+ throw new Error("the lookup must not probe the network");+ },+ },+ "../provider-endpoint-probe": {+ // The lookup handler is a snapshot read: any sweep it started would take+ // the network path this test exists to rule out.+ probeDiscoveryCandidates: async () => {throw new Error("the lookup must not probe the network");},},diff --git a/docs/spec/03-runtime/12-provider-config-schema.md b/docs/spec/03-runtime/12-provider-config-schema.mdindex ba8d60044..ce4026aff 100644--- a/docs/spec/03-runtime/12-provider-config-schema.md+++ b/docs/spec/03-runtime/12-provider-config-schema.md@@ -683,12 +683,51 @@ new IPC field is introduced. Unknown connection formats stay unavailable inthis app; that is not a claim about a vendor website or other API. Some officialsearch APIs require distinct adapters; see the native search provider audit.-For custom endpoints, an explicit `/chat/completions`, `/responses`, or-`/messages` URL can suggest the matching format. Applying that suggestion only-changes the draft format and strips the operation suffix, preserving the-origin. It is not a successful connection/capability probe. A plain base URL-does not prove the protocol. Invalid/credential-bearing URLs give no advice.-OpenCode Go normalizes `/chat/completions`, not `/responses`. Saved explicit-formats take precedence over hostname presets; service names survive edits.-Cancel does not persist draft changes. Full probing and automatic error-driven-fallback from #907 remain separate work.+#### Endpoint resolution++A typed Base URL is resolved before anything is probed. Resolution is one pure+shared layer (`@pi-desktop/shared/provider-endpoint`) that the settings dialog+and Electron main both call, so the address shown, the address probed and the+address saved cannot disagree:++- A bare host is completed with `https://` inside the origin the user named.+ Credentials, queries and fragments are still refused.+- A pasted operation suffix (`/chat/completions`, `/responses`, `/messages`)+ names the format and is stripped from the base endpoint; `/models` only marks+ a discovery URL. A suffix belonging to another format is kept in place — the+ mismatch is the user's to resolve, not a silent retarget of the row.+- The format comes, in order, from the user's own choice, the pasted operation,+ an exact published endpoint, a known host, and the publisher's `npm` adapter,+ falling back to Chat Completions. A model ID never participates: a gateway+ serving `gpt-*`, `claude-*` and `gemini-*` behind one Chat Completions route+ keeps that route.+- When the endpoint decided the format, the custom form says+ "Auto detected: …" next to the selector. A format picked by hand — or a named+ preset's own — outranks every inference from that point on.++Discovery then probes the resolved candidates: at most four, deduplicated, in+confidence order, all on the origin the user typed. The first candidate that+publishes models wins, and the address it answered on becomes the Base URL the+form shows and saves. The sweep shares one 12-second budget rather than giving+each candidate its own, and it runs candidates serially because every request+carries the user's API key. That key never reaches another origin, including+across a redirect: a cross-origin redirect is refused instead of followed.+Provider-specific paths (`/v1beta`, `/compatible-mode/v1`) come from the+endpoint registry, never from a blanket heuristic, and are offered only when the+host was named without a path: a typed path is that deployment's own answer, so+a `/api/v1` that publishes nothing is reported instead of being swapped for the+registry's `/api/paas/v4` sibling. The only generic extra path is `/v1` for an+unknown OpenAI-compatible endpoint. Every published model-list shape is read —+`data[].id`, Google's `models[].name`, and the `models[].slug` rows Zhipu's+OpenAI Responses endpoint returns — so an endpoint that answers is never treated+as empty. Connection testing reuses+the same request builder, so "the model list loaded" and "the connection test+passed" always describe the same URL, auth header and format.++Metadata matching may follow a release stamp: `mify/mimo-v2.5-pro-0731` borrows+the published record of `mimo-v2.5-pro`, and a record the catalog publishes+under exactly the requested ID still wins over such an alias. The alias is+metadata only: a configured binding keeps the wire ID the service served.++Invalid or credential-bearing URLs still give no advice, and Cancel still does+not persist draft changes.diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 60ef9508c..3186bd901 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -794,18 +794,32 @@ identify the platform validation still needed.- **Preconditions**: App running; the add-provider dialog is open with Customendpoint selected.-- **Steps**: 1) Enter a valid gateway URL ending in `/v1/messages`, then leave- the Base URL field. 2) Confirm the field keeps the service base URL ending in- `/v1`, and that its helper identifies the API path that will be targeted. 3)- Replace the value with `ftp://gateway.example.com`, then leave the field.- 4) Enter a valid URL again and confirm model discovery can run; paste a full- `/models` path and leave the field.-- **Expected**: Full operation paths are normalized to the service root on- blur, without changing the selected API style. A non-http(s) URL shows an- inline, accessible error, does not start discovery, and keeps Save disabled.- A valid URL restores discovery; the `/models` suffix is also removed before- the request is made. The long URL field uses a full row on wide dialogs and- stacks cleanly with the other credentials at the responsive breakpoint.+- **Steps**: 1) Enter `api.gateway.example.com` with no scheme and leave the+ Base URL field. 2) Confirm the field settles on+ `https://api.gateway.example.com` and discovery runs. 3) Paste+ `https://api.gateway.example.com/v1/messages` and leave the field. 4) Confirm+ the field settles on `https://api.gateway.example.com/v1`, the API format+ reads Anthropic Messages, and the form says that format was auto detected. 5)+ Change the API format by hand to OpenAI Chat Completions, then paste the+ `/v1/responses` URL: confirm the hand-picked format survives and the operation+ is left in place until the suggestion is applied. 6) Replace the value with+ `ftp://gateway.example.com`, then leave the field. 7) Enter a valid URL again+ and confirm model discovery can run; paste a full `/models` path and leave the+ field. 8) Point the row at a gateway whose `/models` route answers only under+ `/v1` and confirm the field and the saved row show that address.+- **Expected**: A bare host is completed with `https://` inside the origin the+ user typed; credentials, queries and fragments are still refused. A pasted+ operation path names the matching format, selects it and is stripped from the+ base endpoint, and `/models` is removed as well — unless the operation+ contradicts a format the user picked by hand, which is then preserved and+ offered as a suggestion instead. When the endpoint itself decided the format,+ the form says so next to the selector. When only the `/v1` candidate answers,+ the field and the saved row show that address rather than a hidden rewrite,+ and every probed candidate stays on the typed origin. A non-http(s) URL shows+ an inline, accessible error, does not start discovery, and keeps Save+ disabled. A valid URL restores discovery. The long URL field uses a full row+ on wide dialogs and stacks cleanly with the other credentials at the+ responsive breakpoint.- **Specs linked**: `04-ux/06-settings-ia.md`,`03-runtime/12-provider-config-schema.md`- **Acceptance**: B (custom provider configuration)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 6b4917ee9..f47157008 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@@ -478,8 +478,35 @@ Chat Completions 配置使用同源 Responses。关闭搜索后恢复原配置其他尚未集成的搜索格式会说明应用未适配,不代表厂商官网或其他 API 不支持。部分官方搜索需要独立的协议适配,详见搜索服务核查记录。-自定义服务粘贴 `/chat/completions`、`/responses` 或 `/messages` 完整请求地址时,-可显式应用格式建议并移除请求后缀,服务来源不变。这不是联网能力验证;普通基础地址-不触发猜测,无效及带凭据地址不给建议。OpenCode Go 对应 `/chat/completions` 后缀。-已保存的明确格式优先于域名预设,服务备注保留,取消不写入草稿。-#907 的完整探测和错误驱动自动切换仍是独立工作。+#### 端点解析++用户填写的 Base URL 会先被解析,再进行任何探测。解析是 `@pi-desktop/shared/provider-endpoint`+中的一层纯逻辑,设置对话框与 Electron main 共用,因此「显示的地址」「探测的地址」「保存的+地址」不会互相矛盾:++- 裸主机名会补上 `https://`,仍限定在用户填写的来源内;含凭据、查询或片段的地址一律拒绝。+- 粘贴的接口后缀(`/chat/completions`、`/responses`、`/messages`)既指明格式,也会从基础地址中+ 移除;`/models` 只表示粘贴的是发现地址。与所选格式冲突的后缀会原样保留,由用户决定,而不是+ 悄悄改写这一行。+- 格式按以下顺序确定:用户显式选择、粘贴的接口后缀、精确匹配的已发布端点、已知主机、发布方的+ `npm` 适配器,最后回落到 Chat Completions。模型 ID 不参与判断:同一网关用一条 Chat Completions+ 路由提供 `gpt-*`、`claude-*`、`gemini-*` 时,仍保持该路由。+- 当格式来自端点推断时,自定义表单会在选择器旁显示「自动识别:…」。用户手动选择的格式(以及+ 命名预设自身的格式)此后始终优先。++随后发现流程会按置信度顺序探测解析出的候选地址:最多四个、去重、且都限定在用户填写的来源内。+第一个返回模型列表的候选胜出,其应答地址即表单显示并保存的 Base URL。整轮各候选共享 12 秒预算+(而不是每个候选各自计时),并且串行执行,因为每次请求都携带用户的 API Key。该 Key 不会发送到+其他来源,跨来源重定向会被拒绝而不是跟随。`/v1beta`、`/compatible-mode/v1` 等厂商专属路径来自+端点注册表,不做无差别猜测,且只在用户只填了主机名时提供:填了具体路径就是该部署自己的答案,因此+返回空的 `/api/v1` 会照实报告,而不会被换成注册表里的 `/api/paas/v4` 兄弟路径。唯一的通用附加路径+是未知 OpenAI 兼容端点的 `/v1`。三种已发布的模型列表结构都会被读取——`data[].id`、Google 的+`models[].name`,以及智谱 OpenAI Responses 端点返回的 `models[].slug`——因此有应答的端点不会被+当成空列表。连接测试复用同一+套请求构造,因此「模型列表加载成功」与「连接测试通过」描述的始终是同一个地址、认证头与格式。++元数据匹配可以跟随发布日期后缀:`mify/mimo-v2.5-pro-0731` 会借用 `mimo-v2.5-pro` 的发布记录,+但目录中与该 ID 完全一致的记录仍然优先于这类别名。别名只影响元数据:已保存绑定的线上 ID 保持+服务实际返回的原值。++无效或带凭据的地址仍然不给建议,取消仍然不写入草稿。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 82e9eac47..d99086b63 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@@ -360,6 +360,17 @@ task-candidate E2E 从请求工作树运行,但使用主工作区已经准备- **里程碑**:M2- **状态**:单元覆盖(compat 注入 + convertMessages 空/非空补全 + 压缩保留推理上线证明);现场 OpenCode/聚合端验证仍推迟;界面场景待完成+#### E2E-005F:自定义端点输入护栏++- **前提条件**:应用已运行;新增提供商对话框已打开并选中自定义端点。+- **步骤**:1) 只填 `api.gateway.example.com`(不带协议),离开 Base URL 输入框。2) 确认输入框归位为 `https://api.gateway.example.com`,并开始发现。3) 粘贴 `https://api.gateway.example.com/v1/messages` 后离开输入框。4) 确认输入框归位为 `https://api.gateway.example.com/v1`,接口格式显示 Anthropic Messages,且表单提示该格式为自动识别。5) 手动把接口格式改为 OpenAI Chat Completions,再粘贴 `/v1/responses` 地址:确认手动选择的格式保持不变,后缀在应用建议前原样保留。6) 把值改成 `ftp://gateway.example.com` 后离开输入框。7) 重新填入有效地址,确认可以开始发现;粘贴完整 `/models` 路径后离开输入框。8) 指向一个仅在 `/v1` 下响应 `/models` 的网关,确认输入框与保存后的行都显示该地址。+- **预期**:裸主机名会补上 `https://`,仍限定在用户填写的来源内;含凭据、查询或片段的地址一律拒绝。粘贴的接口路径既指明格式并自动选中,也会从基础地址中移除,`/models` 同样移除;只有当它与用户手动选择的格式冲突时才保留,并改为给出建议。当格式来自端点推断时,表单会在选择器旁说明。当只有 `/v1` 候选应答时,输入框与保存的行显示该地址,而不是隐藏改写,且每个被探测的候选都限定在用户填写的来源内。非 http(s) 地址显示内联可访问错误、不启动发现、保持保存禁用;有效地址恢复发现。较长的地址输入框在宽对话框下独占整行,并在响应式断点下与其他凭据自然堆叠。+- **链接规格**:`04-ux/06-settings-ia.md`、+ `03-runtime/12-provider-config-schema.md`+- **验收**:B(自定义提供商配置)+- **里程碑**:M2+- **状态**:单元覆盖(端点解析与候选探测);界面场景待完成+#### E2E-005G:按供应商自定义 HTTP 请求头- **前提条件**:一个 API 密钥 AI 服务(含 OpenCode Go)和一个已登录的厂商 OAuth 账户。diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex d819e2cdc..fe6c3a756 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -1326,6 +1326,7 @@ sklm: {"presetTogether": "Together AI","presetFireworks": "Feuerwerk","presetDeepseek": "DeepSeek",+ apiStyleAutoDetected: "Automatisch erkannt: {{format}}",endpointFormatGuidance: "Diese Anfrage-URL deutet auf {{format}} hin. Übernehmen Sie Format und Basisadresse; dies prüft weder die Verbindung noch die Suchfunktion.",applyEndpointFormat: "Vorgeschlagenes Format übernehmen","presetAlibabaCn": "Qwen (DashScope)",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex d18d00e36..3b9475c20 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -1341,6 +1341,7 @@ sklm: {presetTogether: "Together AI",presetFireworks: "Fireworks",presetDeepseek: "DeepSeek",+ apiStyleAutoDetected: "Auto detected: {{format}}",endpointFormatGuidance: "This request URL suggests {{format}}. Apply the matching format and base address; this is not a connection or search capability test.",applyEndpointFormat: "Apply suggested format",presetAlibabaCn: "Qwen (DashScope)",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 3a2632d3c..3a33a41ab 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -1326,6 +1326,7 @@ sklm: {"presetTogether": "Juntos AI","presetFireworks": "Fuegos artificiales","presetDeepseek": "DeepSeek",+ apiStyleAutoDetected: "Detectado automáticamente: {{format}}",endpointFormatGuidance: "Esta URL de solicitud indica {{format}}. Aplica el formato y la dirección base correspondientes; esto no verifica la conexión ni la capacidad de búsqueda.",applyEndpointFormat: "Aplicar formato sugerido","presetAlibabaCn": "Qwen (DashScope)",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 77d56037b..2b6a3efe0 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -1326,6 +1326,7 @@ sklm: {"presetTogether": "Ensemble AI","presetFireworks": "Feux d'artifice","presetDeepseek": "DeepSeek",+ apiStyleAutoDetected: "Détecté automatiquement : {{format}}",endpointFormatGuidance: "Cette URL de requête indique {{format}}. Appliquez le format et l’adresse de base correspondants ; cela ne vérifie ni la connexion ni la recherche.",applyEndpointFormat: "Appliquer le format suggéré","presetAlibabaCn": "Qwen (DashScope)",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 9e8e1d289..62882121f 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -1339,6 +1339,7 @@ sklm: {presetTogether: "Together AI",presetFireworks: "Fireworks",presetDeepseek: "DeepSeek",+ apiStyleAutoDetected: "자동 감지: {{format}}",endpointFormatGuidance: "이 요청 URL은 {{format}} 형식을 나타냅니다. 해당 형식과 기본 주소를 적용할 수 있지만 연결이나 검색 기능이 검증된 것은 아닙니다.",applyEndpointFormat: "제안된 형식 적용",presetAlibabaCn: "Qwen (DashScope)",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex 15be5c3e8..83270dd5e 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -1290,6 +1290,7 @@ export const ptBR = {presetTogether: "Together AI",presetFireworks: "Fireworks",presetDeepseek: "DeepSeek",+ apiStyleAutoDetected: "Detectado automaticamente: {{format}}",endpointFormatGuidance: "Este URL de solicitação indica {{format}}. Aplique o formato e o endereço base correspondentes; isso não verifica a conexão nem a capacidade de pesquisa.",applyEndpointFormat: "Aplicar formato sugerido",presetAlibabaCn: "Qwen (DashScope)",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex ce71648a1..a2cb55a5f 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -1329,6 +1329,7 @@ sklm: {presetTogether: "Together AI",presetFireworks: "Fireworks",presetDeepseek: "DeepSeek",+ apiStyleAutoDetected: "Otomatik algılandı: {{format}}",endpointFormatGuidance: "Bu istek URL’si {{format}} biçimini gösteriyor. Eşleşen biçimi ve temel adresi uygulayın; bu, bağlantıyı veya arama yeteneğini test etmez.",applyEndpointFormat: "Önerilen biçimi uygula",presetAlibabaCn: "Qwen (DashScope)",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex e9c773f81..60fb87278 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -1313,6 +1313,7 @@ sklm: {presetTogether: "Together AI",presetFireworks: "Fireworks",presetDeepseek: "DeepSeek",+ apiStyleAutoDetected: "自动识别:{{format}}",endpointFormatGuidance: "此请求地址对应 {{format}}。可应用匹配的接口格式和基础地址;这不代表连接或搜索能力已验证。",applyEndpointFormat: "应用建议格式",presetAlibabaCn: "通义千问",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 251f8215a..646fb71ba 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -1313,6 +1313,7 @@ sklm: {presetTogether: "Together AI",presetFireworks: "Fireworks",presetDeepseek: "DeepSeek",+ apiStyleAutoDetected: "自動辨識:{{format}}",endpointFormatGuidance: "此請求位址對應 {{format}}。可套用相符的介面格式和基礎位址;這不代表連線或搜尋能力已驗證。",applyEndpointFormat: "套用建議格式",presetAlibabaCn: "通義千問",diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 6093c777d..6d8ac89ad 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -46,6 +46,7 @@ export * from "./ndjson.js";export * from "./subagent-definition.js";export * from "./subagent-presets.js";export * from "./provider-presets.js";+export * from "./provider-endpoint.js";export * from "./model-catalog.js";export * from "./github-feedback.js";export * from "./network-proxy.js";diff --git a/packages/shared/src/model-identity.test.ts b/packages/shared/src/model-identity.test.tsnew file mode 100644index 000000000..232006d53--- /dev/null+++ b/packages/shared/src/model-identity.test.ts@@ -0,0 +1,61 @@+import { describe, expect, it } from "vitest";+import { catalogModelIdsMatch, modelIdsMatch, stripReleaseSuffix } from "./types/models.js";++describe("release-stamp aliases", () => {+ it("drops a release date from a dated snapshot id", () => {+ expect(stripReleaseSuffix("mify/mimo-v2.5-pro-0731")).toBe("mify/mimo-v2.5-pro");+ expect(stripReleaseSuffix("foo-v2-20250731")).toBe("foo-v2");+ expect(stripReleaseSuffix("foo-v2-2025-07-31")).toBe("foo-v2");+ expect(stripReleaseSuffix("foo-v2-2025_07_31")).toBe("foo-v2");+ expect(stripReleaseSuffix("foo-v2-2025.07.31")).toBe("foo-v2");+ expect(stripReleaseSuffix("gpt-4o-2024-08-06")).toBe("gpt-4o");+ expect(stripReleaseSuffix("claude-3-5-sonnet-20241022")).toBe("claude-3-5-sonnet");+ });++ it("keeps a four-digit tail that is not a calendar month and day", () => {+ for (const value of ["foo-v2-1399", "foo-v2-9999", "foo-v2-0232", "foo-v2-0000", "qwen3-235b-a22b-2507"]) {+ expect(stripReleaseSuffix(value), value).toBe(value);+ }+ });++ it("leaves an id without a release stamp alone", () => {+ for (const value of ["llama-3.1-8b-instant", "gpt-4o", "deepseek-chat", "mify/mimo-v2.5-pro"]) {+ expect(stripReleaseSuffix(value), value).toBe(value);+ }+ });++ it("reads a dated snapshot against the model it was published from", () => {+ expect(catalogModelIdsMatch("mimo-v2.5-pro", "mify/mimo-v2.5-pro-0731")).toBe(true);+ expect(catalogModelIdsMatch("foo-v2", "foo-v2-20250731")).toBe(true);+ expect(catalogModelIdsMatch("foo-v2", "foo-v2-2025-07-31")).toBe(true);+ expect(catalogModelIdsMatch("foo-v2", "foo-v2-2025_07_31")).toBe(true);+ expect(catalogModelIdsMatch("foo-v2", "foo-v2-2025.07.31")).toBe(true);+ // An invalid stamp is part of the id, not an alias of a shorter model.+ expect(catalogModelIdsMatch("foo-v2", "foo-v2-1399")).toBe(false);+ expect(catalogModelIdsMatch("foo-v2", "foo-v2-9999")).toBe(false);+ expect(catalogModelIdsMatch("foo-v2", "foo-v2-0232")).toBe(false);+ });++ it("keeps a dated record from borrowing another publisher's family", () => {+ expect(catalogModelIdsMatch("provider-a/foo-v2", "provider-b/foo-v2-0731")).toBe(false);+ });+});++describe("metadata aliases never redefine the wire id", () => {+ it("resolves a routed snapshot against its published metadata", () => {+ expect(catalogModelIdsMatch("mify/mimo-v2.5-pro", "mify/mimo-v2.5-pro-0731")).toBe(true);+ });++ it("leaves configured-model identity on the complete wire id", () => {+ // A binding id is what a request is addressed with, so the alias rules that+ // catalog metadata may use must not apply to it.+ expect(modelIdsMatch("mify/mimo-v2.5-pro-0731", "mify/mimo-v2.5-pro-0731")).toBe(true);+ expect(modelIdsMatch("mify/mimo-v2.5-pro", "mify/mimo-v2.5-pro-0731")).toBe(false);+ expect(modelIdsMatch("foo-v2", "foo-v2-20250731")).toBe(false);+ });++ it("does not collapse two independently routed leaves", () => {+ expect(catalogModelIdsMatch("provider-a/foo", "gateway/foo")).toBe(false);+ expect(catalogModelIdsMatch("provider-a/foo", "provider-b/foo")).toBe(false);+ });+});diff --git a/packages/shared/src/provider-endpoint.test.ts b/packages/shared/src/provider-endpoint.test.tsnew file mode 100644index 000000000..ec03e8c71--- /dev/null+++ b/packages/shared/src/provider-endpoint.test.ts@@ -0,0 +1,329 @@+import { describe, expect, it } from "vitest";+import {+ ENDPOINT_EVIDENCE_CONFIDENCE,+ MAX_DISCOVERY_CANDIDATES,+ buildDiscoveryCandidates,+ canonicalEndpointUrl,+ discoveryProbeUrl,+ discoveryStyleForApiStyle,+ inferEndpointProfile,+ matchEndpointOperation,+ parseEndpointInput,+} from "./provider-endpoint.js";++const operationInputs: ReadonlyArray<[string, string]> = [+ ["api.foo.com", "https://api.foo.com"],+ ["https://api.foo.com", "https://api.foo.com"],+ ["https://api.foo.com/", "https://api.foo.com"],+ ["https://api.foo.com/v1", "https://api.foo.com/v1"],+ ["https://api.foo.com/v1/models", "https://api.foo.com/v1"],+ ["https://api.foo.com/v1/chat/completions", "https://api.foo.com/v1"],+ ["https://api.foo.com/v1/responses", "https://api.foo.com/v1"],+ ["https://api.foo.com/v1/messages", "https://api.foo.com/v1"],+];++describe("endpoint input parsing", () => {+ it("completes a bare host with https instead of guessing another origin", () => {+ const parsed = parseEndpointInput("api.foo.com");+ expect(parsed?.normalizedInput).toBe("https://api.foo.com");+ expect(parsed?.origin).toBe("https://api.foo.com");+ expect(parsed?.pathname).toBe("");+ });++ it("accepts a base URL, an operation URL and a discovery URL", () => {+ for (const [input, baseUrl] of operationInputs) {+ // No style is selected yet, so a pasted operation is the user saying+ // which route they copied: it is resolved and stripped in one step.+ const profile = inferEndpointProfile({ baseUrl: input });+ expect(profile?.effectiveBaseUrl, input).toBe(baseUrl);+ }+ });++ it("never accepts a URL that could carry a secret of its own", () => {+ for (const value of [+ "",+ " ",+ "not a url",+ "file:///v1/messages",+ "https://user:[email protected]/v1",+ "https://api.foo.com/v1?key=secret",+ "https://api.foo.com/v1#fragment",+ ]) {+ expect(parseEndpointInput(value), value).toBeUndefined();+ expect(inferEndpointProfile({ baseUrl: value }), value).toBeUndefined();+ }+ });+});++describe("operation suffixes", () => {+ it("names the wire style a pasted operation implies", () => {+ expect(matchEndpointOperation("/v1/chat/completions")).toMatchObject({+ suffix: "/chat/completions",+ apiStyle: "chat_completions",+ basePath: "/v1",+ });+ expect(matchEndpointOperation("/v1/responses")).toMatchObject({ apiStyle: "responses", basePath: "/v1" });+ expect(matchEndpointOperation("/v1/messages")).toMatchObject({+ apiStyle: "anthropic_messages",+ basePath: "/v1",+ });+ // A discovery URL names no wire style by itself.+ expect(matchEndpointOperation("/v1/models")).toMatchObject({ suffix: "/models", basePath: "/v1" });+ expect(matchEndpointOperation("/v1/models")?.apiStyle).toBeUndefined();+ expect(matchEndpointOperation("/v1/completions")).toBeUndefined();+ });++ it("keeps an operation that contradicts the selected format until the user resolves it", () => {+ const mismatched = inferEndpointProfile({+ baseUrl: "https://api.foo.com/v1/responses",+ apiStyle: "chat_completions",+ explicitApiStyle: true,+ });+ expect(mismatched?.effectiveBaseUrl).toBe("https://api.foo.com/v1/responses");+ expect(mismatched?.apiStyle).toBe("chat_completions");++ // The same operation matches the OpenCode Go / Codex families, which+ // address Chat Completions and Responses respectively.+ for (const apiStyle of ["opencode_go", "chat_completions"] as const) {+ expect(+ inferEndpointProfile({+ baseUrl: "https://api.foo.com/v1/chat/completions",+ apiStyle,+ explicitApiStyle: true,+ })?.effectiveBaseUrl,+ apiStyle,+ ).toBe("https://api.foo.com/v1");+ }+ expect(+ inferEndpointProfile({+ baseUrl: "https://api.foo.com/v1/responses",+ apiStyle: "openai_codex_responses",+ explicitApiStyle: true,+ })?.effectiveBaseUrl,+ ).toBe("https://api.foo.com/v1");+ });+});++describe("api style inference order", () => {+ it("never lets a known host or published metadata override the user's own choice", () => {+ const profile = inferEndpointProfile({+ baseUrl: "https://api.anthropic.com",+ apiStyle: "chat_completions",+ explicitApiStyle: true,+ providerKey: "anthropic",+ providerApiStyle: "anthropic_messages",+ });+ expect(profile?.apiStyle).toBe("chat_completions");+ expect(profile?.evidence.at(-1)).toMatchObject({+ type: "explicit",+ confidence: ENDPOINT_EVIDENCE_CONFIDENCE.explicit,+ });+ });++ it("lets a pasted operation outrank a known host and published metadata", () => {+ const profile = inferEndpointProfile({+ baseUrl: "https://api.deepseek.com/v1/messages",+ apiStyle: "chat_completions",+ providerApiStyle: "responses",+ });+ expect(profile?.apiStyle).toBe("anthropic_messages");+ expect(profile?.effectiveBaseUrl).toBe("https://api.deepseek.com/v1");+ });++ it("resolves an unknown host from the pasted operation, then from published metadata", () => {+ expect(inferEndpointProfile({ baseUrl: "https://api.foo.com/v1/responses" })?.apiStyle).toBe("responses");+ expect(+ inferEndpointProfile({ baseUrl: "https://api.foo.com", providerApiStyle: "responses" })?.apiStyle,+ ).toBe("responses");+ });++ it("never reads a model id: only the endpoint decides the protocol", () => {+ const gateway = inferEndpointProfile({ baseUrl: "https://gateway.example/v1" });+ expect(gateway?.apiStyle).toBe("chat_completions");+ expect(gateway?.evidence.some((entry) => entry.type === "catalog_model")).toBe(false);+ // The rank exists so a metadata hint can never outrank an endpoint fact.+ expect(ENDPOINT_EVIDENCE_CONFIDENCE.catalog_model).toBeLessThan(+ ENDPOINT_EVIDENCE_CONFIDENCE.discovery,+ );+ });++ it("falls back to Chat Completions and says so", () => {+ const profile = inferEndpointProfile({ baseUrl: "api.foo.com" });+ expect(profile?.apiStyle).toBe("chat_completions");+ expect(profile?.discoveryStyle).toBe("openai_models");+ expect(profile?.evidence[0]).toMatchObject({ type: "fallback", confidence: 0 });+ });++ it("maps wire styles onto the discovery style the transport actually uses", () => {+ expect(discoveryStyleForApiStyle("anthropic_messages")).toBe("anthropic_models");+ expect(discoveryStyleForApiStyle("google_generative_ai")).toBe("google_models");+ expect(discoveryStyleForApiStyle("pi_messages")).toBe("openai_models");+ expect(discoveryStyleForApiStyle("opencode_go")).toBe("openai_models");+ expect(discoveryStyleForApiStyle("openai_codex_responses")).toBe("openai_models");+ expect(discoveryStyleForApiStyle("chat_completions")).toBe("openai_models");+ });+});++describe("discovery candidates", () => {+ it("tries the typed path and then /v1 for an unknown OpenAI-compatible endpoint", () => {+ const profile = inferEndpointProfile({ baseUrl: "https://api.foo.com" });+ expect(profile?.candidates.map((candidate) => candidate.baseUrl)).toEqual([+ "https://api.foo.com",+ "https://api.foo.com/v1",+ ]);+ expect(profile?.candidates.every((candidate) => candidate.discoveryStyle === "openai_models")).toBe(true);+ });++ it("does not extend a base that already addresses /v1 or an operation", () => {+ expect(+ inferEndpointProfile({ baseUrl: "https://api.foo.com/v1" })?.candidates.map((c) => c.baseUrl),+ ).toEqual(["https://api.foo.com/v1"]);+ expect(+ buildDiscoveryCandidates(+ inferEndpointProfile({+ baseUrl: "https://api.foo.com/v1/responses",+ apiStyle: "chat_completions",+ explicitApiStyle: true,+ })!,+ ).map((c) => c.baseUrl),+ ).toEqual(["https://api.foo.com/v1/responses"]);+ });++ it("never guesses a provider-specific path for an unknown host", () => {+ const candidates = inferEndpointProfile({ baseUrl: "https://relay.example" })?.candidates ?? [];+ const urls = candidates.map((candidate) => candidate.baseUrl);+ expect(urls.length).toBe(2);+ for (const forbidden of ["/v1beta", "/compatible-mode/v1", "/zen/go/v1", "/api/paas/v4"]) {+ expect(urls.some((url) => url.includes(forbidden)), forbidden).toBe(false);+ }+ });++ it("keeps every candidate on the origin the user typed", () => {+ for (const baseUrl of [+ "https://api.foo.com",+ "https://api.anthropic.com",+ "https://open.bigmodel.cn",+ "https://generativelanguage.googleapis.com",+ "https://api.z.ai/api/paas/v4",+ "http://192.168.1.9:11434/v1",+ ]) {+ const profile = inferEndpointProfile({ baseUrl, apiStyle: "chat_completions", explicitApiStyle: true });+ expect(profile, baseUrl).toBeDefined();+ for (const candidate of profile!.candidates) {+ expect(new URL(candidate.baseUrl).origin, `${baseUrl} -> ${candidate.baseUrl}`).toBe(profile!.origin);+ }+ }+ });++ it("offers a registry endpoint's own style even when the row speaks another one", () => {+ const profile = inferEndpointProfile({+ baseUrl: "https://api.anthropic.com",+ apiStyle: "chat_completions",+ explicitApiStyle: true,+ });+ expect(profile?.discoveryStyle).toBe("openai_models");+ expect(profile?.candidates.map((candidate) => discoveryProbeUrl(candidate.baseUrl, candidate.discoveryStyle)))+ .toEqual(["https://api.anthropic.com/models", "https://api.anthropic.com/v1/models"]);+ });++ it("uses the registry path and style for a known host typed without its path", () => {+ const profile = inferEndpointProfile({ baseUrl: "https://api.z.ai" });+ expect(profile?.apiStyle).toBe("chat_completions");+ expect(profile?.candidates.map((c) => c.baseUrl)).toContain("https://api.z.ai/api/paas/v4");+ const google = inferEndpointProfile({ baseUrl: "https://generativelanguage.googleapis.com" });+ expect(google?.candidates).toContainEqual(+ expect.objectContaining({ baseUrl: "https://generativelanguage.googleapis.com/v1beta", discoveryStyle: "google_models" }),+ );+ });++ it("never swaps a path the user typed for a registry sibling", () => {+ /*+ Zhipu serves three API styles on three paths of one host. A typed+ `/api/v1` that publishes nothing must not be silently replaced by the+ `/api/paas/v4` sibling: that moves the row to another service while+ keeping its format.+ */+ const typed = inferEndpointProfile({+ baseUrl: "https://open.bigmodel.cn/api/v1",+ apiStyle: "responses",+ explicitApiStyle: true,+ });+ expect(typed?.candidates.map((candidate) => candidate.baseUrl)).toEqual([+ "https://open.bigmodel.cn/api/v1",+ ]);+ expect(+ inferEndpointProfile({ baseUrl: "https://api.z.ai/api/paas/v4" })?.candidates.map(+ (candidate) => candidate.baseUrl,+ ),+ ).toEqual(["https://api.z.ai/api/paas/v4"]);+ // Naming the host alone still gets the registry's own paths.+ expect(+ inferEndpointProfile({ baseUrl: "https://open.bigmodel.cn" })?.candidates.map(+ (candidate) => candidate.baseUrl,+ ),+ ).toContain("https://open.bigmodel.cn/api/paas/v4");+ });++ it("dedupes candidates that would address the same URL", () => {+ const profile = inferEndpointProfile({+ baseUrl: "https://api.anthropic.com",+ apiStyle: "anthropic_messages",+ explicitApiStyle: true,+ });+ const probeUrls = profile!.candidates.map((candidate) =>+ discoveryProbeUrl(candidate.baseUrl, candidate.discoveryStyle),+ );+ expect(new Set(probeUrls).size).toBe(probeUrls.length);+ });++ it("bounds the candidate list", () => {+ for (const baseUrl of ["https://open.bigmodel.cn", "https://api.z.ai", "https://api.foo.com"]) {+ expect(+ inferEndpointProfile({ baseUrl })!.candidates.length,+ baseUrl,+ ).toBeLessThanOrEqual(MAX_DISCOVERY_CANDIDATES);+ }+ });+});++describe("discovery probe urls", () => {+ it("addresses the model list the transport adapter uses", () => {+ expect(discoveryProbeUrl("https://api.foo.com", "openai_models")).toBe("https://api.foo.com/models");+ expect(discoveryProbeUrl("https://api.anthropic.com", "anthropic_models")).toBe(+ "https://api.anthropic.com/v1/models",+ );+ expect(discoveryProbeUrl("https://api.anthropic.com/v1", "anthropic_models")).toBe(+ "https://api.anthropic.com/v1/models",+ );+ expect(discoveryProbeUrl("https://generativelanguage.googleapis.com/v1beta", "google_models")).toBe(+ "https://generativelanguage.googleapis.com/v1beta/models",+ );+ });+});++describe("endpoint presets stay the registry's source of truth", () => {+ it("matches a published endpoint exactly", () => {+ expect(canonicalEndpointUrl("https://api.openai.com/v1/")).toBe("https://api.openai.com/v1");+ const profile = inferEndpointProfile({ baseUrl: "https://api.openai.com/v1" });+ expect(profile?.evidence.some((entry) => entry.type === "known_endpoint")).toBe(true);+ });++ it("resolves every named preset endpoint to its own style", () => {+ const expected: ReadonlyArray<[string, string]> = [+ ["https://api.openai.com/v1", "responses"],+ ["https://api.anthropic.com", "anthropic_messages"],+ ["https://generativelanguage.googleapis.com/v1beta", "google_generative_ai"],+ ["https://openrouter.ai/api/v1", "chat_completions"],+ ["https://api.deepseek.com", "chat_completions"],+ ["https://dashscope.aliyuncs.com/compatible-mode/v1", "chat_completions"],+ ["https://opencode.ai/zen/go/v1", "opencode_go"],+ ["https://api.minimaxi.com/anthropic/v1", "anthropic_messages"],+ ];+ for (const [baseUrl, apiStyle] of expected) {+ const profile = inferEndpointProfile({ baseUrl });+ expect(profile?.apiStyle, baseUrl).toBe(apiStyle);+ expect(profile?.effectiveBaseUrl, baseUrl).toBe(baseUrl);+ expect(profile?.evidence.some((entry) => entry.type === "known_endpoint"), baseUrl).toBe(true);+ }+ });+});diff --git a/packages/shared/src/provider-endpoint.ts b/packages/shared/src/provider-endpoint.tsnew file mode 100644index 000000000..18d84c119--- /dev/null+++ b/packages/shared/src/provider-endpoint.ts@@ -0,0 +1,519 @@+/**+ * Endpoint resolution for the provider setup flow.+ *+ * A user types a Base URL, but the questions that follow from it are four+ * different ones: which URL is actually addressed, what wire format the service+ * speaks, how a model-list probe should ask, and why any of that was decided.+ * This module answers all four from static evidence only — it performs no I/O —+ * so the settings dialog, the Electron main process and the tests share one+ * implementation instead of re-deriving the rules per surface.+ *+ * Two rules hold everywhere here:+ *+ * - The endpoint decides the protocol, never the model id. A gateway can serve+ * `gpt-*`, `claude-*` and `gemini-*` behind a single Chat Completions route,+ * so a model name may not change the wire style.+ * - Nothing automatic may leave the origin the user typed, because the probe+ * carries the user's API key. Cross-origin candidates are dropped rather than+ * probed.+ */++import type { CatalogApiStyle } from "./model-catalog.js";+import { NAMED_ENDPOINT_PRESETS } from "./provider-presets.js";++/**+ * How a model-list probe asks a service what it serves.+ *+ * This is deliberately narrower than {@link CatalogApiStyle}: a successful+ * `GET {base}/models` with `Authorization: Bearer` proves the endpoint answers+ * OpenAI-compatible discovery, and nothing about whether the generation call is+ * `/chat/completions`, `/responses` or something else.+ */+export type DiscoveryStyle = "openai_models" | "anthropic_models" | "google_models";++/** Where a resolved value came from, strongest first in the confidence table. */+export type EndpointEvidenceType =+ | "explicit"+ | "url_suffix"+ | "known_endpoint"+ | "known_host"+ | "provider_metadata"+ | "discovery"+ | "catalog_model"+ | "fallback";++/**+ * Confidence per evidence type. The order is the resolution order: a weaker+ * source never replaces a stronger one.+ */+export const ENDPOINT_EVIDENCE_CONFIDENCE: Readonly<Record<EndpointEvidenceType, number>> = {+ explicit: 100,+ url_suffix: 95,+ known_endpoint: 90,+ known_host: 85,+ provider_metadata: 80,+ discovery: 75,+ // Reserved for a model-metadata hint. The static resolver never emits it: a+ // model id is not allowed to decide the wire protocol, so this rank exists+ // only so a future layer cannot rank such a hint above real endpoint facts.+ catalog_model: 40,+ fallback: 0,+};++export interface EndpointEvidence {+ type: EndpointEvidenceType;+ confidence: number;+ detail?: string;+}++/** One base URL worth probing, with the discovery style it should be asked in. */+export interface EndpointCandidate {+ baseUrl: string;+ discoveryStyle: DiscoveryStyle;+ apiStyleHint?: CatalogApiStyle;+ evidence: EndpointEvidence;+}++export interface EndpointProfile {+ input: string;+ normalizedInput: string;++ origin: string;+ effectiveBaseUrl: string;++ apiStyle: CatalogApiStyle;+ discoveryStyle?: DiscoveryStyle;++ providerKey?: string;++ evidence: EndpointEvidence[];++ candidates: EndpointCandidate[];+}++/** One published provider endpoint, the shared home for what used to be scattered tables. */+export interface ProviderEndpointDefinition {+ providerKey: string;++ hosts?: string[];+ baseUrls?: string[];++ apiStyle?: CatalogApiStyle;+ discoveryStyle?: DiscoveryStyle;++ /** Documented path suffixes for this provider's endpoints. */+ paths?: string[];++ /** models.dev adapter package, when the provider publishes one. */+ npm?: string;+}++export const MAX_DISCOVERY_CANDIDATES = 4;++/** Wire style a discovery probe asks in, mirroring the transport adapter list. */+export function discoveryStyleForApiStyle(apiStyle?: string | null): DiscoveryStyle {+ if (apiStyle === "anthropic_messages") return "anthropic_models";+ if (apiStyle === "google_generative_ai") return "google_models";+ // `pi_messages`, `opencode_go`, `openai_codex_responses` and every+ // OpenAI-compatible style authenticate a model list the same way.+ return "openai_models";+}++/**+ * The URL a discovery probe addresses for one candidate.+ *+ * `modelListRequest` builds its request from this, so a candidate list and the+ * request it produces can never drift apart.+ */+export function discoveryProbeUrl(baseUrl: string, discoveryStyle: DiscoveryStyle): string {+ const base = baseUrl.trim().replace(/\/+$/, "");+ if (discoveryStyle === "anthropic_models") {+ // Anthropic base URLs conventionally exclude /v1; the endpoint appends it.+ return `${base.endsWith("/v1") ? base : `${base}/v1`}/models`;+ }+ return `${base}/models`;+}++function hostOf(value: string | undefined): string | undefined {+ if (!value) return undefined;+ try {+ return new URL(value).host.toLowerCase();+ } catch {+ return undefined;+ }+}++function pathOf(value: string): string | undefined {+ try {+ const pathname = new URL(value).pathname.replace(/\/+$/, "");+ return pathname && pathname !== "/" ? pathname : undefined;+ } catch {+ return undefined;+ }+}++/**+ * Unified endpoint registry.+ *+ * The named presets are the canonical table for first-class services, so the+ * registry is derived from them instead of restating their hosts and paths. A+ * preset's `baseUrl` already carries the provider's special path (`/v1beta`,+ * `/compatible-mode/v1`, `/api/paas/v4`), which is exactly why only registry+ * facts — never a generic heuristic — may produce those paths as candidates.+ */+export const PROVIDER_ENDPOINT_DEFINITIONS: readonly ProviderEndpointDefinition[] =+ NAMED_ENDPOINT_PRESETS.map((preset) => {+ const host = hostOf(preset.baseUrl);+ const path = pathOf(preset.baseUrl);+ return {+ providerKey: preset.vendorKey,+ baseUrls: [preset.baseUrl],+ ...(host ? { hosts: [host] } : {}),+ ...(path ? { paths: [path] } : {}),+ apiStyle: preset.apiStyle,+ discoveryStyle: discoveryStyleForApiStyle(preset.apiStyle),+ };+ });++/** Registry entries addressing this host. */+export function providerEndpointDefinitionsForHost(host: string): readonly ProviderEndpointDefinition[] {+ const normalized = host.trim().toLowerCase();+ if (!normalized) return [];+ return PROVIDER_ENDPOINT_DEFINITIONS.filter((definition) =>+ definition.hosts?.includes(normalized),+ );+}++/** Registry entry a URL addresses exactly, when one does. */+export function providerEndpointDefinitionForUrl(+ url: string,+ normalize: (value: string) => string,+): ProviderEndpointDefinition | undefined {+ const target = normalize(url);+ return PROVIDER_ENDPOINT_DEFINITIONS.find((definition) =>+ definition.baseUrls?.some((baseUrl) => normalize(baseUrl) === target),+ );+}++/** Canonical comparison form of an endpoint: scheme, host and path, no trailing slash. */+export function canonicalEndpointUrl(value: string | undefined): string {+ const raw = value?.trim();+ if (!raw) return "";+ try {+ const parsed = new URL(raw);+ const pathname = parsed.pathname.replace(/\/+$/, "");+ return `${parsed.protocol.toLowerCase()}//${parsed.host.toLowerCase()}${pathname}`;+ } catch {+ return raw.replace(/\/+$/, "").toLowerCase();+ }+}++/**+ * Operation suffixes a pasted URL may carry. `/models` names no wire style: it+ * only says the user pasted a discovery URL rather than a base URL.+ */+const OPERATION_SUFFIXES: ReadonlyArray<{ suffix: string; apiStyle?: CatalogApiStyle }> = [+ { suffix: "/chat/completions", apiStyle: "chat_completions" },+ { suffix: "/responses", apiStyle: "responses" },+ { suffix: "/messages", apiStyle: "anthropic_messages" },+ { suffix: "/models" },+];++/**+ * Wire family a style belongs to for URL normalization: `opencode_go` addresses+ * Chat Completions and `openai_codex_responses` addresses Responses, so a+ * pasted operation of the same family is the user describing the scheme they+ * already selected.+ */+function wireStyleFamily(apiStyle: CatalogApiStyle): CatalogApiStyle {+ if (apiStyle === "opencode_go") return "chat_completions";+ if (apiStyle === "openai_codex_responses") return "responses";+ if (apiStyle === "pi_messages") return "anthropic_messages";+ return apiStyle;+}++export type ParsedEndpointInput = {+ input: string;+ /** Origin plus path, no trailing slash: what the user typed, canonicalized. */+ normalizedInput: string;+ origin: string;+ /** Path without a trailing slash; `""` for a host root. */+ pathname: string;+};++/**+ * Normalize a user-typed address into an absolute one.+ *+ * A bare host is completed with `https://`. That is input normalization inside+ * the origin the user named, not a cross-origin guess. Credentials, query+ * strings and fragments are rejected: a Base URL never carries them, and+ * accepting one would leak into a probe URL.+ */+export function parseEndpointInput(value: string): ParsedEndpointInput | undefined {+ const input = value.trim();+ if (!input) return undefined;+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(input) ? input : `https://${input}`;+ let url: URL;+ try {+ url = new URL(withScheme);+ } catch {+ return undefined;+ }+ if (url.protocol !== "http:" && url.protocol !== "https:") return undefined;+ if (!url.hostname) return undefined;+ if (url.username || url.password || url.search || url.hash) return undefined;+ const pathname = url.pathname.replace(/\/+$/, "");+ return {+ input,+ normalizedInput: `${url.origin}${pathname}`,+ origin: url.origin,+ pathname,+ };+}++/** The operation a pasted URL points at, with the base endpoint it implies. */+export function matchEndpointOperation(pathname: string): {+ suffix: string;+ apiStyle?: CatalogApiStyle;+ basePath: string;+} | undefined {+ const lower = pathname.toLowerCase();+ for (const entry of OPERATION_SUFFIXES) {+ if (!lower.endsWith(entry.suffix)) continue;+ return {+ suffix: entry.suffix,+ ...(entry.apiStyle ? { apiStyle: entry.apiStyle } : {}),+ basePath: pathname.slice(0, -entry.suffix.length).replace(/\/+$/, ""),+ };+ }+ return undefined;+}++export type EndpointProfileInput = {+ baseUrl: string;+ /** Style currently selected in the UI. */+ apiStyle?: CatalogApiStyle | null;+ /** True when the user picked that style, as opposed to inheriting a default. */+ explicitApiStyle?: boolean;+ /** models.dev vendor key of the configured row, when it has one. */+ providerKey?: string | null;+ /** Style implied by the publisher's models.dev `npm` adapter. */+ providerApiStyle?: CatalogApiStyle | null;+};++/** Strongest first-party evidence about the endpoint itself, not about the style. */+function endpointEvidenceOf(evidence: readonly EndpointEvidence[]): EndpointEvidence | undefined {+ const endpointTypes: ReadonlySet<EndpointEvidenceType> = new Set([+ "url_suffix",+ "known_endpoint",+ "known_host",+ "fallback",+ ]);+ return [...evidence]+ .filter((entry) => endpointTypes.has(entry.type))+ .sort((left, right) => right.confidence - left.confidence)[0];+}++/**+ * Resolve a typed Base URL into the endpoint that will really be used.+ *+ * Every claim is recorded as evidence, so the UI can explain the answer instead+ * of performing a hidden rewrite. `apiStyle` follows the documented order:+ * user choice, URL operation suffix, exact known endpoint, known host, then+ * published provider metadata, and finally the Chat Completions fallback.+ */+export function inferEndpointProfile(input: EndpointProfileInput): EndpointProfile | undefined {+ const parsed = parseEndpointInput(input.baseUrl);+ if (!parsed) return undefined;++ const evidence: EndpointEvidence[] = [];+ const operation = matchEndpointOperation(parsed.pathname);+ const registryByUrl = providerEndpointDefinitionForUrl(+ parsed.normalizedInput,+ canonicalEndpointUrl,+ );+ const registryByHost = providerEndpointDefinitionsForHost(new URL(parsed.origin).host);+ const hostDefinition = registryByHost.find(+ (definition) => definition.apiStyle !== undefined,+ );++ if (operation?.apiStyle) {+ evidence.push({+ type: "url_suffix",+ confidence: ENDPOINT_EVIDENCE_CONFIDENCE.url_suffix,+ detail: operation.suffix,+ });+ }+ if (registryByUrl?.apiStyle) {+ evidence.push({+ type: "known_endpoint",+ confidence: ENDPOINT_EVIDENCE_CONFIDENCE.known_endpoint,+ detail: registryByUrl.providerKey,+ });+ } else if (hostDefinition?.apiStyle) {+ evidence.push({+ type: "known_host",+ confidence: ENDPOINT_EVIDENCE_CONFIDENCE.known_host,+ detail: hostDefinition.providerKey,+ });+ }+ if (input.providerApiStyle) {+ evidence.push({+ type: "provider_metadata",+ confidence: ENDPOINT_EVIDENCE_CONFIDENCE.provider_metadata,+ detail: "npm",+ });+ }+ if (input.apiStyle && input.explicitApiStyle) {+ evidence.push({+ type: "explicit",+ confidence: ENDPOINT_EVIDENCE_CONFIDENCE.explicit,+ detail: input.apiStyle,+ });+ }+ evidence.push({+ type: "fallback",+ confidence: ENDPOINT_EVIDENCE_CONFIDENCE.fallback,+ detail: "chat_completions",+ });+ // Weakest first, so `evidence.at(-1)` is the strongest claim.+ evidence.sort((left, right) => left.confidence - right.confidence);++ /*+ Resolution order: the user's own choice, the pasted operation suffix, an+ exact known endpoint, a known host, then published provider metadata. A+ model id never participates, and a weaker source never overrides a stronger+ one — each step only answers when every step above it was silent.+ */+ const apiStyle: CatalogApiStyle =+ (input.apiStyle && input.explicitApiStyle ? input.apiStyle : undefined) ??+ operation?.apiStyle ??+ registryByUrl?.apiStyle ??+ hostDefinition?.apiStyle ??+ input.providerApiStyle ??+ "chat_completions";++ /*+ The pasted operation is stripped only when it belongs to the resolved wire+ format. A user who selected Chat Completions and pasted a `/responses` URL+ is describing a mismatch, not a base endpoint: stripping it would silently+ retarget the row, so the path is kept until they resolve it.+ */+ const operationFamily = operation?.apiStyle+ ? wireStyleFamily(operation.apiStyle)+ : undefined;+ const stripsOperation =+ operation !== undefined &&+ (operationFamily === undefined || operationFamily === wireStyleFamily(apiStyle));+ const effectiveBaseUrl = stripsOperation+ ? `${parsed.origin}${operation.basePath}`+ : parsed.normalizedInput;++ const providerKey = registryByUrl?.providerKey ?? hostDefinition?.providerKey ?? input.providerKey ?? undefined;++ const profile: EndpointProfile = {+ input: parsed.input,+ normalizedInput: parsed.normalizedInput,+ origin: parsed.origin,+ effectiveBaseUrl,+ apiStyle,+ ...(providerKey ? { providerKey } : {}),+ evidence,+ candidates: [],+ };+ /*+ The probe style follows the wire style that will actually be used, so+ "discovery succeeded" and "the row is configured this way" can never+ disagree. A registry entry for the same host may still offer its own style+ as a later candidate (see `buildDiscoveryCandidates`).+ */+ profile.discoveryStyle = discoveryStyleForApiStyle(apiStyle);+ profile.candidates = buildDiscoveryCandidates(profile);+ return profile;+}++/**+ * Base URLs worth probing for a resolved profile, strongest first.+ *+ * At most {@link MAX_DISCOVERY_CANDIDATES}. Every candidate stays on the+ * user-typed origin, because the probe sends the user's API key with it. The+ * only generic extra path is `/v1` for an unknown OpenAI-compatible endpoint;+ * provider-specific paths such as `/v1beta` or `/compatible-mode/v1` come from+ * the registry, never from a blanket heuristic.+ */+export function buildDiscoveryCandidates(profile: EndpointProfile): EndpointCandidate[] {+ const base = profile.effectiveBaseUrl.replace(/\/+$/, "");+ const discoveryStyle = profile.discoveryStyle ?? discoveryStyleForApiStyle(profile.apiStyle);+ const candidates: EndpointCandidate[] = [];+ const seen = new Set<string>();++ const add = (candidate: EndpointCandidate) => {+ const parsed = parseEndpointInput(candidate.baseUrl);+ if (!parsed || parsed.origin !== profile.origin) return;+ const key = `${discoveryProbeUrl(parsed.normalizedInput, candidate.discoveryStyle)}\u0000${candidate.discoveryStyle}`;+ if (seen.has(key)) return;+ seen.add(key);+ candidates.push({ ...candidate, baseUrl: parsed.normalizedInput });+ };++ const primary = endpointEvidenceOf(profile.evidence) ??+ profile.evidence.at(-1) ?? { type: "fallback" as const, confidence: 0 };+ add({+ baseUrl: base,+ discoveryStyle,+ ...(profile.apiStyle ? { apiStyleHint: profile.apiStyle } : {}),+ evidence: primary,+ });++ /*+ Registry paths are offered only for a host named without a path. A typed+ path is an answer about this deployment: Zhipu serves three API styles on+ three paths of one host, and replacing a typed `/api/v1` with its sibling+ `/api/paas/v4` because the first returned nothing would move the row to a+ different service while keeping its format.+ */+ const definitions = providerEndpointDefinitionsForHost(new URL(profile.origin).host);+ const typedPath = parseEndpointInput(profile.effectiveBaseUrl)?.pathname ?? "";+ if (typedPath === "") {+ for (const definition of definitions) {+ for (const baseUrl of definition.baseUrls ?? []) {+ add({+ baseUrl,+ discoveryStyle: definition.discoveryStyle ?? discoveryStyle,+ ...(definition.apiStyle ? { apiStyleHint: definition.apiStyle } : {}),+ evidence: {+ type: "known_host",+ confidence: ENDPOINT_EVIDENCE_CONFIDENCE.known_host,+ detail: definition.providerKey,+ },+ });+ }+ }+ }++ /*+ One generic extension only: an unknown OpenAI-compatible endpoint very+ often serves the same route under /v1. Provider-specific paths (/v1beta,+ /compatible-mode/v1) are registry facts and are never guessed, and a host+ the registry already describes is not extended on a hunch.+ */+ const keepsOperation = matchEndpointOperation(new URL(base).pathname) !== undefined;+ if (+ discoveryStyle === "openai_models" &&+ definitions.length === 0 &&+ !keepsOperation &&+ !base.toLowerCase().endsWith("/v1")+ ) {+ add({+ baseUrl: `${base}/v1`,+ discoveryStyle,+ evidence: {+ type: "fallback",+ confidence: ENDPOINT_EVIDENCE_CONFIDENCE.fallback,+ detail: "/v1",+ },+ });+ }++ return candidates.slice(0, MAX_DISCOVERY_CANDIDATES);+}diff --git a/packages/shared/src/types/models.ts b/packages/shared/src/types/models.tsindex 236ce2598..2f98f97dc 100644--- a/packages/shared/src/types/models.ts+++ b/packages/shared/src/types/models.ts@@ -83,6 +83,45 @@ export function stripVariantSuffix(value: string): string {}return current;}+/**+ * Release-stamp suffixes a publisher appends to a dated snapshot of a model:+ * `-20250731`, `-2025-07-31`, `-2025_07_31`, `-2025.07.31` and the bare+ * `-0731` form.+ *+ * Only a plausible calendar date is stripped. A four-digit tail is read as+ * month/day, so `-1399`, `-9999` and `-0232` are version numbers, not dates,+ * and stay part of the id. This is a metadata alias only: the wire id a request+ * is addressed with is never rewritten.+ */+const RELEASE_SUFFIX_REGEX =+ /[-._](\d{4})[-._](\d{1,2})[-._](\d{1,2})$|[-._](\d{8})$|[-._](\d{2})(\d{2})$/;++function isCalendarDate(month: number, day: number): boolean {+ if (month < 1 || month > 12) return false;+ if (day < 1 || day > 31) return false;+ return day <= new Date(Date.UTC(2000, month, 0)).getUTCDate();+}++/** Drop one trailing release stamp, or return the value unchanged. */+export function stripReleaseSuffix(value: string): string {+ const match = RELEASE_SUFFIX_REGEX.exec(value);+ if (!match) return value;+ const [year, month, day] = match[1]+ ? [Number(match[1]), Number(match[2]), Number(match[3])]+ : match[4]+ ? [+ Number(match[4].slice(0, 4)),+ Number(match[4].slice(4, 6)),+ Number(match[4].slice(6, 8)),+ ]+ : [0, Number(match[5]), Number(match[6])];+ // A compact stamp is year-month-day too; the leading year is what makes+ // `-20250731` a date rather than an arbitrary eight digits only when its+ // month and day are real.+ if (match[4] && (year < 1900 || year > 2999)) return value;+ if (!isCalendarDate(month, day)) return value;+ return value.slice(0, match.index);+}function canonicalVendor(prefix: string): string {if (prefix === "deepseek-ai") return "deepseek";@@ -166,12 +205,22 @@ export function catalogModelIdsMatch(candidate: string, requested: string): boolconst cleanLeft = stripRegion(left);const cleanRight = stripRegion(right);+ // Exact id, known vendor prefix, route leaf, then thinking/agent/latest.if (normalizedMatch(cleanLeft, cleanRight, true)) return true;- const strippedLeft = stripVariantSuffix(cleanLeft);- const strippedRight = stripVariantSuffix(cleanRight);- if (strippedLeft === cleanLeft && strippedRight === cleanRight) return false;- return normalizedMatch(strippedLeft, strippedRight, true);+ const variantLeft = stripVariantSuffix(cleanLeft);+ const variantRight = stripVariantSuffix(cleanRight);+ if (normalizedMatch(variantLeft, variantRight, true)) return true;++ /* Published release stamps are tried last, so a dated snapshot can never+ displace the exact id or a documented alias. A catalog that publishes both+ `foo-v2` and `foo-v2-0731` therefore still answers `foo-v2-0731` with its+ own record: the caller's exact-first ranking decides between them. */+ return normalizedMatch(+ stripReleaseSuffix(variantLeft),+ stripReleaseSuffix(variantRight),+ true,+ );}/**