Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs-site/src/content/docs/es/guides/google-vertex.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ o `$VARIABLE`, el descubrimiento se detiene en lugar de probar otra credencial,
solicitudes se niegan a empezar. Cuando el listado no se puede leer completo, OpenCodex conserva los
modelos anteriores o configurados en lugar de publicar solo una parte.

El descubrimiento en vivo y las pruebas de conexión requieren un endpoint HTTPS de Google:
`aiplatform.googleapis.com` o `<location>-aiplatform.googleapis.com`, con el puerto HTTPS estándar
y sin usuario ni contraseña en la URL. Los endpoints de gateways personalizados no reciben las
credenciales de Vertex. Restablece el endpoint de Google para usar el descubrimiento en vivo;
los modelos configurados siguen disponibles cuando no se puede verificar el destino.

Los niveles de razonamiento siguen el preajuste: Gemini 4 Hydrogen ofrece low, medium, high (el
predeterminado) y xhigh; Gemini 4 Carbon y Argon ofrecen low, medium y high. Un modelo al que el
preajuste no asigna niveles, como `gemini-3-pro`, no muestra ninguno, porque sus solicitudes no
Expand Down
6 changes: 6 additions & 0 deletions docs-site/src/content/docs/guides/google-vertex.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ configured, `GOOGLE_CLOUD_API_KEY` and then Application Default Credentials. If
credential, the same way requests refuse to start. When the listing cannot be read completely,
OpenCodex keeps the previous or configured models rather than publishing part of the list.

Live discovery and connection tests require an HTTPS Google endpoint:
`aiplatform.googleapis.com` or `<location>-aiplatform.googleapis.com`, with the standard HTTPS
port and no URL username or password. Custom gateway endpoints do not receive Vertex credentials.
Restore the Google endpoint to use live discovery; configured models remain available when
discovery cannot verify the destination.

Reasoning levels follow the preset: Gemini 4 Hydrogen offers low, medium, high (the default) and
xhigh; Gemini 4 Carbon and Argon offer low, medium and high. A model the preset gives no levels
to, such as `gemini-3-pro`, shows none, because requests to it carry no thinking level.
Expand Down
10 changes: 5 additions & 5 deletions src/codex/catalog/provider-models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -762,20 +762,20 @@ export async function fetchProviderModelsWithAuth(
// name matches any baseUrl by design. Retargeted or renamed custom rows
// fetch a different URL and keep the rejection.
if (!maySendAnthropicDiscovery()) return observed(withConfiguredRetention(failedDiscoveryConfigured), "degraded");
const outboundDependencies = { isCanonicalUrl: isRegistryModelDiscoveryUrl,
const outboundDependencies = (requestUrl: string) => ({ isCanonicalUrl: isRegistryModelDiscoveryUrl,
beforeSend: () => maySendAnthropicDiscovery()
&& (!vertexSendGuard || (vertexAuth !== undefined && vertexDiscoveryAuthIsCurrent(prov, vertexAuth, headers))) };
&& (!vertexSendGuard || (vertexAuth !== undefined && vertexDiscoveryAuthIsCurrent(prov, vertexAuth, headers, requestUrl))) });
const antigravityObservation = cloudCodeAssist ? captureAntigravityModelObservation() : undefined;
const res = request.method === "POST"
? await providerOutboundPost(name, prov, url, {
headers,
body: JSON.stringify({ project }),
signal: AbortSignal.timeout(8000),
}, outboundDependencies)
}, outboundDependencies(url))
: await providerOutboundGet(name, prov, url, {
headers,
signal: vertexDeadline ?? AbortSignal.timeout(8000),
}, outboundDependencies);
}, outboundDependencies(url));
const redirectError = await providerRedirectError(res, url);
if (redirectError) {
const { models, fallback, shouldLog } = failedDiscoveryFallback({ reason: "http", httpStatus: res.status });
Expand Down Expand Up @@ -876,7 +876,7 @@ export async function fetchProviderModelsWithAuth(
const listing = effectiveGoogleMode(name, prov) === "vertex"
? await collectVertexPublisherModelPages(url, bounded.value,
{ ...discovery, firstPageBytes: vertexFirstPage?.bytes(), signal: vertexDeadline },
(pageUrl, signal) => providerOutboundGet(name, prov, pageUrl, { headers, signal }, outboundDependencies))
(pageUrl, signal) => providerOutboundGet(name, prov, pageUrl, { headers, signal }, outboundDependencies(pageUrl)))
: { ok: true as const, value: bounded.value };
if (!listing.ok) {
const { models, fallback, shouldLog } = failedDiscoveryFallback({ reason: "invalid_response" });
Expand Down
57 changes: 43 additions & 14 deletions src/providers/google-vertex-model-discovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
} from "../lib/gcp-adc";
import type { OcxProviderConfig } from "../types";
import { resolveProviderApiKey } from "./api-key-resolve";
import { googleVertexLocationConfigError } from "./google-vertex-location";
import { captureVertexAmbientKey } from "./vertex-environment-authority";
import { extractGoogleAiStudioModelItems } from "./google-ai-studio-model-discovery";
import {
Expand All @@ -33,6 +34,22 @@ const VERTEX_GENERATIVE_MODEL_ID = /^(?:gemini|gemma)-/i;
const VERTEX_NON_CHAT_SKU = /(?:^|-)embedding(?:-|$)|-tts(?:-|$)|-transcribe(?:-|$)|(?:^|-)live(?:-|$)/i;
const VERTEX_TRAILING_API_VERSION = /\/v1(?:beta1?)?$/i;

/** The same Google authorities inference constructs; a base URL never grants credential access. */
function vertexDiscoveryOrigin(value: string): string | undefined {
try {
const url = new URL(value);
if (url.protocol !== "https:" || url.username || url.password || url.port || url.hash) return undefined;
const host = "aiplatform.googleapis.com";
if (url.hostname === host) return url.origin;
const suffix = `-${host}`;
if (url.hostname.endsWith(suffix)
&& googleVertexLocationConfigError(url.hostname.slice(0, -suffix.length)) === null) return url.origin;
} catch {
// An invalid destination is unavailable discovery, without resolving a credential.
}
return undefined;
}

/** Time budget for one Vertex discovery: ADC token resolution, then every follow-up page. */
export const VERTEX_DISCOVERY_TIMEOUT_MS = 8_000;
/** Request ceiling for one listing, first page included (pageSize=300, so 1,500 rows). */
Expand Down Expand Up @@ -150,9 +167,10 @@ export function resolveObservedVertexDiscoveryToken(provider: OcxProviderConfig)

/** The passive gather's credential with its authority bound, for the same send-time checks. */
export function resolveObservedVertexDiscoveryAuth(provider: OcxProviderConfig): VertexDiscoveryAuth | undefined {
if (provider.authMode === "forward" || isVertexApiKeyPoolPaused(provider)) return undefined;
const origin = vertexDiscoveryOrigin(provider.baseUrl);
if (!origin || provider.authMode === "forward" || isVertexApiKeyPoolPaused(provider)) return undefined;
const selection = selectVertexDiscoveryCredential(provider);
return selection.kind === "api-key" ? apiKeyDiscoveryAuth(selection) : undefined;
return selection.kind === "api-key" ? apiKeyDiscoveryAuth(selection, origin) : undefined;
}

/**
Expand All @@ -175,10 +193,10 @@ function sameVertexSelection(left: VertexDiscoveryCredential, right: VertexDisco
* observed when it was read (`captureVertexAmbientKey`, the record inference binds), so an A→B→A
* change of the variable invalidates it even though the bytes match again.
*/
function apiKeyDiscoveryAuth(selection: { key: string | undefined; ambient?: true }): VertexDiscoveryAuth | undefined {
function apiKeyDiscoveryAuth(selection: { key: string | undefined; ambient?: true }, origin: string): VertexDiscoveryAuth | undefined {
if (!selection.key) return undefined;
const auth: VertexDiscoveryAuth = { token: selection.key, kind: "api-key" };
if (selection.ambient) bindVertexRequestAuthority(auth, "", selection.key, { ambientKey: captureVertexAmbientKey(selection.key) });
if (selection.ambient) bindVertexRequestAuthority(auth, origin, selection.key, { ambientKey: captureVertexAmbientKey(selection.key) });
return auth;
}

Expand All @@ -198,19 +216,21 @@ export async function resolveVertexDiscoveryAuth(
provider: OcxProviderConfig,
signal: AbortSignal = vertexDiscoveryDeadline(),
): Promise<VertexDiscoveryAuth | undefined> {
if (provider.authMode === "forward" || isVertexApiKeyPoolPaused(provider)) return undefined;
const origin = vertexDiscoveryOrigin(provider.baseUrl);
if (!origin || provider.authMode === "forward" || isVertexApiKeyPoolPaused(provider)) return undefined;
const selection = selectVertexDiscoveryCredential(provider);
if (selection.kind === "api-key") return apiKeyDiscoveryAuth(selection);
if (selection.kind === "api-key") return apiKeyDiscoveryAuth(selection, origin);
let authority: Awaited<ReturnType<typeof getVertexAccessTokenWithAuthority>>;
try {
const markerAccount = gcpCredentialMarkerAccount(selection.marker);
authority = await getVertexAccessTokenWithAuthority({ signal, ...(markerAccount ? { markerAccount } : {}) });
} catch {
return undefined;
}
if (!sameVertexSelection(selection, selectVertexDiscoveryCredential(provider))) return undefined;
if (origin !== vertexDiscoveryOrigin(provider.baseUrl)
|| !sameVertexSelection(selection, selectVertexDiscoveryCredential(provider))) return undefined;
const auth: VertexDiscoveryAuth = { token: authority.token, kind: "adc", ...(selection.marker ? { marker: selection.marker } : {}) };
bindVertexRequestAuthority(auth, "", `Bearer ${authority.token}`, {
bindVertexRequestAuthority(auth, origin, `Bearer ${authority.token}`, {
source: authority.source,
generation: authority.generation,
...(authority.markerAccount ? { markerAccount: authority.markerAccount } : {}),
Expand All @@ -227,7 +247,8 @@ export async function resolveVertexDiscoveryToken(
}

/**
* Send-time check, run before every discovery request (`beforeSend`): the row still selects the
* Send-time check, run before every discovery request (`beforeSend`): the actual URL stays on the
* approved Google origin, and the row still selects the
* credential this token came from, an ADC token's source and generation are still current (the
* check inference runs before dispatch), and the outgoing headers carry it in that scheme's header
* and not the other one. Any change cancels the send, first page and follow-up pages alike, so a
Expand All @@ -237,11 +258,14 @@ export function vertexDiscoveryAuthIsCurrent(
provider: OcxProviderConfig,
auth: VertexDiscoveryAuth,
headers: Record<string, string>,
url: string,
): boolean {
if (provider.authMode === "forward" || isVertexApiKeyPoolPaused(provider)) return false;
// ADC source/generation and the ambient-key generation, exactly as inference checks them. Checked
// first so every send-time check also observes the current ambient key, as inference does.
if (!vertexRequestAuthorityIsCurrent(auth)) return false;
const origin = vertexDiscoveryOrigin(provider.baseUrl);
if (!origin || vertexDiscoveryOrigin(url) !== origin
|| provider.authMode === "forward" || isVertexApiKeyPoolPaused(provider)) return false;
// Recheck ADC source/generation and the ambient-key generation after destination admission,
// before comparing the current selection, exactly as inference checks them.
if (!vertexRequestAuthorityIsCurrent(auth, origin)) return false;
const current = selectVertexDiscoveryCredential(provider);
const issued: VertexDiscoveryCredential = auth.kind === "api-key"
? { kind: "api-key", key: auth.token }
Expand All @@ -268,6 +292,11 @@ export function buildVertexModelsDiscoveryRequest(
resolveUrl: (defaultUrl: string) => string,
): { url: string; headers: Record<string, string> } {
const base = effectiveProvider.baseUrl.replace(/\/+$/, "").replace(VERTEX_TRAILING_API_VERSION, "");
// Keep a credential-free request available for catalog capture/fallback, but never attach
// a Google credential to a destination outside the origin admitted before resolution.
const url = resolveUrl(`${base}/v1beta1/publishers/google/models?pageSize=300`);
const origin = vertexDiscoveryOrigin(effectiveProvider.baseUrl);
if (!origin || vertexDiscoveryOrigin(url) !== origin) return { url, headers };
if (usesVertexApiKeyForDiscovery(effectiveProvider)) {
if (apiKey) headers["x-goog-api-key"] = apiKey;
} else {
Expand All @@ -282,7 +311,7 @@ export function buildVertexModelsDiscoveryRequest(
// Vertex ModelGardenService.ListPublisherModels enforces a maximum pageSize of 300
// (values > 300 return HTTP 400 INVALID_ARGUMENT); later pages follow nextPageToken.
return {
url: resolveUrl(`${base}/v1beta1/publishers/google/models?pageSize=300`),
url,
headers,
};
}
Expand Down
12 changes: 6 additions & 6 deletions src/server/management/provider-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1732,21 +1732,21 @@ export async function handleProviderRoutes(ctx: ManagementContext): Promise<Resp
// Same canonical-URL TUN transparency as catalog discovery: the registry's
// own fixed discovery URL survives purely-benchmark (Clash/Surge/Mihomo
// fake-IP) DNS without proxy env.
const outboundDependencies = { isCanonicalUrl: isRegistryModelDiscoveryUrl,
beforeSend: () => (!vertexAuth || vertexDiscoveryAuthIsCurrent(prov, vertexAuth, headers))
const outboundDependencies = (requestUrl: string) => ({ isCanonicalUrl: isRegistryModelDiscoveryUrl,
beforeSend: () => (!vertexAuth || vertexDiscoveryAuthIsCurrent(prov, vertexAuth, headers, requestUrl))
&& (prov.authMode !== "oauth" || (mayResolveModelsOAuth(name, config.providers[name])
&& modelsOAuthTargetMatches(name, config.providers[name], authorizedTarget)
&& (name !== "anthropic2" || new URL(modelsUrl).href === authorizedTarget))) };
&& (name !== "anthropic2" || new URL(requestUrl).href === authorizedTarget))) });
const res = method === "POST"
? await providerOutboundPost(name, prov, modelsUrl, {
headers,
body: JSON.stringify({ project }),
signal: AbortSignal.timeout(8000),
}, outboundDependencies)
}, outboundDependencies(modelsUrl))
: await providerOutboundGet(name, prov, modelsUrl, {
headers,
signal: vertexDeadline ?? AbortSignal.timeout(8000),
}, outboundDependencies);
}, outboundDependencies(modelsUrl));
const latencyMs = Date.now() - started;
const redirectError = await providerRedirectError(res, modelsUrl);
if (redirectError) {
Expand Down Expand Up @@ -1782,7 +1782,7 @@ export async function handleProviderRoutes(ctx: ManagementContext): Promise<Resp
const listing = !ccaModels && vertexDeadline
? await collectVertexPublisherModelPages(modelsUrl, bounded.value,
{ ...discovery, firstPageBytes: vertexFirstPage?.bytes(), signal: vertexDeadline },
(pageUrl, signal) => providerOutboundGet(name, prov, pageUrl, { headers, signal }, outboundDependencies))
(pageUrl, signal) => providerOutboundGet(name, prov, pageUrl, { headers, signal }, outboundDependencies(pageUrl)))
: { ok: true as const, value: bounded.value };
if (!listing.ok) return jsonResponse({ ok: false, latencyMs, error: `upstream Vertex model listing is incomplete: ${listing.diagnostic}` });
// OpenAI-style lists (and Together top-level arrays) use the same validation/dedupe/filter
Expand Down
Loading
Loading