Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Revert "feat(providers): show the resolved base URL with provenance in providers env (#5714)"

time-attack430493a164c2
diff --git a/src/commands/providers.ts b/src/commands/providers.ts
index 32d6a996bc..8ed5cc384e 100644
--- a/src/commands/providers.ts
+++ b/src/commands/providers.ts
@@ -2,17 +2,14 @@
* `gbrain providers` CLI — list, test, env, explain.
*
* This command operates WITHOUT a brain connection (no engine needed) so
- * users can verify provider setup before `gbrain init`. The one exception:
- * `providers env` reads DB-plane `provider_base_urls.*` best-effort when a
- * brain is configured and free, and says so when it could not.
+ * users can verify provider setup before `gbrain init`.
*/
import { listRecipes, getRecipe } from '../core/ai/recipes/index.ts';
-import { applyOpenAICompatConfig, configureGateway, embedOne, isAvailable as gwIsAvailable, chat as gwChat, resolveNativeBaseUrl } from '../core/ai/gateway.ts';
-import { buildGatewayConfig, COMPAT_BASE_URL_ENVS } from '../core/ai/build-gateway-config.ts';
+import { configureGateway, embedOne, isAvailable as gwIsAvailable, chat as gwChat } from '../core/ai/gateway.ts';
+import { buildGatewayConfig } from '../core/ai/build-gateway-config.ts';
import { probeOllama, probeLMStudio } from '../core/ai/probes.ts';
-import { loadConfig, type GBrainConfig } from '../core/config.ts';
-import { readDbPlaneConfig, type DbPlaneRead } from '../core/ai/db-plane-config-read.ts';
+import { loadConfig } from '../core/config.ts';
import { AIConfigError, AITransientError } from '../core/ai/errors.ts';
import { lookupEmbeddingPrice } from '../core/embedding-pricing.ts';
import type { Recipe } from '../core/ai/types.ts';
@@ -54,88 +51,7 @@ export function envReady(recipe: Recipe, env: NodeJS.ProcessEnv = process.env):
return required.every(k => !!env[k]);
}
-/** Where `providers env` found the base URL a recipe's calls go to (#5302). */
-export interface ProviderEndpoint {
- /** The URL the gateway resolves; null when it uses the provider SDK's default or none is configured. */
- url: string | null;
- source: string;
- /** Override hint for this recipe. */
- override: string;
- /** DB-plane disclosure line. */
- dbPlane: string;
-}
-
-const NATIVE_BASE_URL_ENVS: Readonly<Record<string, 'anthropic' | 'openai'>> = { anthropic: 'anthropic', openai: 'openai' };
-
-/**
- * Display form of a configured URL: userinfo, query and fragment can carry
- * credentials, so they are removed and named; an unparseable value prints a
- * fixed marker and none of its text.
- */
-export function redactBaseUrlForDisplay(raw: string): string {
- try {
- const u = new URL(raw);
- const scrubbed: string[] = [];
- if (u.username || u.password) { u.username = ''; u.password = ''; scrubbed.push('userinfo'); }
- if (u.search) { u.search = ''; scrubbed.push('query'); }
- if (u.hash) { u.hash = ''; scrubbed.push('fragment'); }
- return scrubbed.length ? `${u.toString()} (${scrubbed.join('/')} redacted)` : raw;
- } catch {
- return '(invalid URL; value redacted)';
- }
-}
-
-/**
- * The base URL a recipe's calls use, computed by the gateway's own
- * resolution: buildGatewayConfig over the runtime config (file plane, plus
- * the DB plane when it was read, merged exactly as loadConfigWithEngine
- * does), then resolveNativeBaseUrl for native providers or
- * applyOpenAICompatConfig for openai-compatible ones. Only the provenance
- * label is derived here. Native providers never read DB-plane base URLs
- * (mount safety); one that exists is reported as not used.
- */
-export function resolveProviderEndpoint(recipe: Recipe, fileCfg: GBrainConfig | null, db: DbPlaneRead): ProviderEndpoint {
- const runtimeCfg = db.read ? db.merged : (fileCfg ?? ({} as GBrainConfig));
- const gw = buildGatewayConfig(runtimeCfg);
- const key = `provider_base_urls.${recipe.id}`;
- const fileUrls = fileCfg?.provider_base_urls ?? {};
- const runtimeUrls = runtimeCfg.provider_base_urls ?? {};
- const dbOnly = db.read && !(recipe.id in fileUrls) && recipe.id in runtimeUrls ? runtimeUrls[recipe.id] : undefined;
-
- const native = NATIVE_BASE_URL_ENVS[recipe.id];
- if (recipe.tier === 'native') {
- const envKey = native === 'anthropic' ? 'ANTHROPIC_BASE_URL' : native === 'openai' ? 'OPENAI_BASE_URL' : undefined;
- const url = native ? resolveNativeBaseUrl(native, gw) ?? null : null;
- const source = !url ? 'provider SDK default'
- : envKey && process.env[envKey]?.trim() ? `${envKey} env var` : `${key} (file plane)`;
- return {
- url, source,
- override: envKey ? `the ${envKey} env var, or a file-plane \`${key}\` value.` : 'none; this provider uses its SDK endpoint.',
- dbPlane: dbOnly !== undefined
- ? `DB-plane ${key} ${redactBaseUrlForDisplay(dbOnly)}: not used (mount safety; native providers read only env and file plane).`
- : `DB-plane ${key} is never used for this provider (mount safety).`,
- };
- }
-
- const envKey = COMPAT_BASE_URL_ENVS[recipe.id];
- let url: string | null = null;
- try { url = applyOpenAICompatConfig(recipe, gw).baseURL; } catch { url = null; }
- const source = recipe.resolveOpenAICompatConfig ? (url ? 'recipe endpoint settings (env)' : 'not configured')
- : !url ? 'not configured'
- : recipe.id in fileUrls ? `${key} (file plane)`
- : recipe.id in runtimeUrls ? `${key} (db plane)`
- : envKey && process.env[envKey] ? `${envKey} env var` : 'recipe default';
- return {
- url, source,
- override: recipe.resolveOpenAICompatConfig
- ? 'set this recipe\'s endpoint env vars (see Setup below).'
- : `\`gbrain config set ${key} <url>\`${envKey ? `, or the ${envKey} env var` : ''}.`,
- dbPlane: db.read ? 'DB plane read: provider_base_urls overrides are included.'
- : `DB plane not read (${db.reason}): a \`gbrain config set ${key} <url>\` value applies when no file-plane value exists; check it with \`gbrain config get ${key}\`.`,
- };
-}
-
-export function formatEnvOutput(recipe: Recipe, env: NodeJS.ProcessEnv = process.env, endpoint?: ProviderEndpoint): string {
+export function formatEnvOutput(recipe: Recipe, env: NodeJS.ProcessEnv = process.env): string {
const lines: string[] = [];
lines.push(`${recipe.name} (${recipe.id})`);
lines.push('');
@@ -156,12 +72,6 @@ export function formatEnvOutput(recipe: Recipe, env: NodeJS.ProcessEnv = process
lines.push(` ${k.padEnd(32)} ${env[k] ? '✓ set' : '✗ not set'}`);
}
}
- if (endpoint) {
- lines.push('');
- lines.push(`Base URL: ${endpoint.url ? redactBaseUrlForDisplay(endpoint.url) : '(none)'} (${endpoint.source})`);
- lines.push(` Override: ${endpoint.override}`);
- lines.push(` ${endpoint.dbPlane}`);
- }
if (recipe.auth_env?.setup_url) {
lines.push('');
lines.push(`Setup: ${recipe.auth_env.setup_url}`);
@@ -387,7 +297,7 @@ async function runTest(args: string[]): Promise<void> {
}
}
-async function runEnv(args: string[]): Promise<void> {
+function runEnv(args: string[]): void {
const id = args[0];
if (!id) {
console.error('Usage: gbrain providers env <id>');
@@ -398,9 +308,7 @@ async function runEnv(args: string[]): Promise<void> {
console.error(`Unknown provider: ${id}. Run \`gbrain providers list\` to see known providers.`);
process.exit(1);
}
- let fileCfg: GBrainConfig | null = null;
- try { fileCfg = loadConfig(); } catch { fileCfg = null; }
- console.log(formatEnvOutput(recipe, process.env, resolveProviderEndpoint(recipe, fileCfg, await readDbPlaneConfig(fileCfg))));
+ console.log(formatEnvOutput(recipe));
}
async function runExplain(args: string[]): Promise<void> {
diff --git a/src/core/ai/build-gateway-config.ts b/src/core/ai/build-gateway-config.ts
index b7f13f8b62..039a7054fd 100644
--- a/src/core/ai/build-gateway-config.ts
+++ b/src/core/ai/build-gateway-config.ts
@@ -41,24 +41,6 @@ export function foldNativeBaseUrlsFromFilePlane(
return out;
}
-/**
- * Openai-compatible recipes whose `*_BASE_URL` env var buildGatewayConfig
- * threads into `base_urls` (config values win). v0.32 codex finding #4+#5:
- * without this, `LLAMA_SERVER_BASE_URL=http://localhost:9000` let the probe
- * reach :9000 while embed calls still went to the recipe default. The
- * reranker sibling has its own var because llama-server's --reranking and
- * --embeddings modes run as separate processes. `providers env` reads the
- * same table to name the env var it reports.
- */
-export const COMPAT_BASE_URL_ENVS: Readonly<Record<string, string>> = {
- 'llama-server': 'LLAMA_SERVER_BASE_URL',
- 'llama-server-reranker': 'LLAMA_SERVER_RERANKER_BASE_URL',
- ollama: 'OLLAMA_BASE_URL',
- lmstudio: 'LMSTUDIO_BASE_URL',
- litellm: 'LITELLM_BASE_URL',
- openrouter: 'OPENROUTER_BASE_URL',
-};
-
export function buildGatewayConfig(c: GBrainConfig): AIGatewayConfig {
// The file-plane key fold + env merge live in mergedProviderEnv
// (src/core/ai/provider-env.ts) — the single canonical mapping shared with
@@ -66,13 +48,23 @@ export function buildGatewayConfig(c: GBrainConfig): AIGatewayConfig {
// fallback for daemons / launchd-spawned subprocesses that don't propagate
// ~/.zshrc-sourced keys; process env wins for keys carrying a real value.
- // Local-server *_BASE_URL env vars (COMPAT_BASE_URL_ENVS) feed base_urls;
- // caller-provided cfg.provider_base_urls wins.
+ // v0.32 codex finding #4+#5 fix: thread local-server _BASE_URL env vars
+ // into base_urls so the gateway hits the user's configured port. Without
+ // this, `LLAMA_SERVER_BASE_URL=http://localhost:9000` would let the probe
+ // succeed against :9000 but the actual embed call would still go to the
+ // recipe's base_url_default (localhost:8080). Same fix applies to
+ // OLLAMA_BASE_URL. Caller-provided cfg.provider_base_urls wins.
const envBaseUrls: Record<string, string> = {};
- for (const [recipeId, envKey] of Object.entries(COMPAT_BASE_URL_ENVS)) {
- const value = process.env[envKey];
- if (value) envBaseUrls[recipeId] = value;
- }
+ if (process.env.LLAMA_SERVER_BASE_URL) envBaseUrls['llama-server'] = process.env.LLAMA_SERVER_BASE_URL;
+ // v0.40.6.1: sibling recipe for llama-server in reranking mode. Separate
+ // env var because --reranking and --embeddings are mutually exclusive at
+ // server launch — users running both will have two llama-server processes
+ // on different ports.
+ if (process.env.LLAMA_SERVER_RERANKER_BASE_URL) envBaseUrls['llama-server-reranker'] = process.env.LLAMA_SERVER_RERANKER_BASE_URL;
+ if (process.env.OLLAMA_BASE_URL) envBaseUrls['ollama'] = process.env.OLLAMA_BASE_URL;
+ if (process.env.LMSTUDIO_BASE_URL) envBaseUrls['lmstudio'] = process.env.LMSTUDIO_BASE_URL;
+ if (process.env.LITELLM_BASE_URL) envBaseUrls['litellm'] = process.env.LITELLM_BASE_URL;
+ if (process.env.OPENROUTER_BASE_URL) envBaseUrls['openrouter'] = process.env.OPENROUTER_BASE_URL;
// #3350: native base-URL fold — MUST read the file plane directly, not `c`
// (callers can pass a DB-merged config; see foldNativeBaseUrlsFromFilePlane's
diff --git a/src/core/ai/db-plane-config-read.ts b/src/core/ai/db-plane-config-read.ts
deleted file mode 100644
index 834fd58d7b..0000000000
--- a/src/core/ai/db-plane-config-read.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * Best-effort DB-plane config read for engine-free diagnostics (`gbrain
- * providers env`, #5302). Opens the configured brain only when that cannot
- * wait on another process (a held PGLite lock is reported, not waited out),
- * skips thin clients (the remote brain owns its DB plane), merges with
- * loadConfigWithEngine exactly as connectEngine does, and always disconnects.
- */
-import { isThinClient, loadConfigWithEngine, toEngineConfig, type GBrainConfig } from '../config.ts';
-
-/** The runtime-merged config, or why the DB plane was not read. */
-export type DbPlaneRead = { read: true; merged: GBrainConfig } | { read: false; reason: string };
-
-export async function readDbPlaneConfig(fileCfg: GBrainConfig | null): Promise<DbPlaneRead> {
- if (!fileCfg) return { read: false, reason: 'no brain configured' };
- if (isThinClient(fileCfg)) return { read: false, reason: 'thin client; the remote brain owns its DB plane' };
- if (fileCfg.engine === 'pglite') {
- const { peekLock } = await import('../pglite-lock.ts');
- if (peekLock(fileCfg.database_path).held) return { read: false, reason: 'the brain is in use by another gbrain process' };
- }
- try {
- const { createEngine } = await import('../engine-factory.ts');
- const engineCfg = toEngineConfig(fileCfg);
- const engine = await createEngine(engineCfg);
- await engine.connect(engineCfg);
- try {
- const merged = await loadConfigWithEngine(engine, fileCfg);
- return merged ? { read: true, merged } : { read: false, reason: 'the brain returned no config' };
- } finally {
- await engine.disconnect().catch(() => {});
- }
- } catch {
- return { read: false, reason: 'the brain could not be opened' };
- }
-}
diff --git a/src/core/ai/recipes/mistral.ts b/src/core/ai/recipes/mistral.ts
index dda989d538..3b0d235a81 100644
--- a/src/core/ai/recipes/mistral.ts
+++ b/src/core/ai/recipes/mistral.ts
@@ -6,15 +6,6 @@ import type { Recipe } from '../types.ts';
* exists: a brain that must stay inside EU jurisdiction can run embed +
* expansion + chat on a single provider without a US hop.
*
- * REGIONAL ENDPOINT (#5302): Mistral's docs say the global endpoint
- * (api.mistral.ai, the default here) carries no inference-location
- * commitment; the EU regional endpoint `https://api.eu.mistral.ai/v1`
- * supports processing within the EU, carries a regional upcharge, and serves
- * only models hosted in that region
- * (https://docs.mistral.ai/inference/regional-inference). Select it with
- * `gbrain config set provider_base_urls.mistral https://api.eu.mistral.ai/v1`
- * and confirm the endpoint with `gbrain providers env mistral`.
- *
* Verified against the live API on 2026-07-19 (model catalog, embedding
* dimensions, dimension-parameter rejection, and the batch ceiling — see
* the notes on each field below).
diff --git a/test/providers-env-cli.test.ts b/test/providers-env-cli.test.ts
deleted file mode 100644
index 953112c798..0000000000
--- a/test/providers-env-cli.test.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-/**
- * `gbrain providers env <id>` reads the DB plane of a configured, free brain
- * (#5302). Protects: an operator sees the endpoint a `gbrain config set
- * provider_base_urls.<id>` row actually selects, and is told when the DB plane
- * was not read. Fails when the command prints the recipe default while a DB
- * row is in force. The pure resolver is covered in providers.test.ts; this is
- * the only test of the engine open and its disclosure.
- *
- * Real CLI subprocesses against one temp PGLite brain.
- */
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
-import { mkdtempSync, rmSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { gb } from './helpers/agent-journey.ts';
-
-describe('providers env reads the DB plane (#5302)', () => {
- let home = '';
- let empty = '';
- beforeAll(async () => {
- home = mkdtempSync(join(tmpdir(), 'gbrain-providers-env-'));
- empty = mkdtempSync(join(tmpdir(), 'gbrain-providers-env-empty-'));
- expect((await gb(home, ['init', '--pglite', '--no-embedding', '--json'], { timeoutMs: 120_000 })).exitCode).toBe(0);
- }, 150_000);
- afterAll(() => {
- rmSync(home, { recursive: true, force: true });
- rmSync(empty, { recursive: true, force: true });
- });
-
- test('a DB-plane provider_base_urls row is the displayed URL, labelled db plane', async () => {
- const set = await gb(home, ['config', 'set', 'provider_base_urls.mistral', 'https://api.eu.mistral.ai/v1']);
- expect(set.exitCode, set.stderr.slice(-1500)).toBe(0);
- const r = await gb(home, ['providers', 'env', 'mistral']);
- expect(r.exitCode, r.stderr.slice(-1500)).toBe(0);
- expect(r.stdout).toContain('Base URL: https://api.eu.mistral.ai/v1 (provider_base_urls.mistral (db plane))');
- expect(r.stdout).toContain('DB plane read: provider_base_urls overrides are included.');
- }, 120_000);
-
- test('with no brain configured it prints the recipe default and says the DB plane was not read', async () => {
- const r = await gb(empty, ['providers', 'env', 'mistral']);
- expect(r.exitCode, r.stderr.slice(-1500)).toBe(0);
- expect(r.stdout).toContain('Base URL: https://api.mistral.ai/v1 (recipe default)');
- expect(r.stdout).toContain('DB plane not read (no brain configured)');
- }, 120_000);
-});
diff --git a/test/providers.test.ts b/test/providers.test.ts
index 36aabeb5ad..53d7442e47 100644
--- a/test/providers.test.ts
+++ b/test/providers.test.ts
@@ -5,16 +5,8 @@
* gateway / loadConfig; E2E exercises those.
*/
-import { describe, test, expect, afterAll } from 'bun:test';
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { formatRecipeTable, formatEnvOutput, envReady, resolveProviderEndpoint, redactBaseUrlForDisplay } from '../src/commands/providers.ts';
-import type { DbPlaneRead } from '../src/core/ai/db-plane-config-read.ts';
-import { applyOpenAICompatConfig, resolveNativeBaseUrl } from '../src/core/ai/gateway.ts';
-import { buildGatewayConfig, COMPAT_BASE_URL_ENVS } from '../src/core/ai/build-gateway-config.ts';
-import { loadConfig, loadConfigWithEngine, type GBrainConfig } from '../src/core/config.ts';
-import { withEnv } from './helpers/with-env.ts';
+import { describe, test, expect } from 'bun:test';
+import { formatRecipeTable, formatEnvOutput, envReady } from '../src/commands/providers.ts';
import { listRecipes, getRecipe } from '../src/core/ai/recipes/index.ts';
import type { Recipe } from '../src/core/ai/types.ts';
@@ -153,133 +145,3 @@ describe('formatEnvOutput (providers env <id>)', () => {
expect(out).toContain('Get a key at example.com.');
});
});
-
-// ── #5302: resolved base URL with provenance ──────────────────────────────────
-
-const homeRoot = mkdtempSync(join(tmpdir(), 'gbrain-providers-endpoint-'));
-afterAll(() => rmSync(homeRoot, { recursive: true, force: true }));
-let homeN = 0;
-
-/** Every env var that can steer a base URL, cleared so ambient values never leak in. */
-const BASE_URL_ENV_KEYS = [...Object.values(COMPAT_BASE_URL_ENVS), 'ANTHROPIC_BASE_URL', 'OPENAI_BASE_URL',
- 'AZURE_OPENAI_ENDPOINT', 'AZURE_OPENAI_DEPLOYMENT', 'AZURE_OPENAI_API_VERSION'];
-
-function nativeProvider(recipe: Recipe): 'anthropic' | 'openai' | undefined {
- return recipe.id === 'anthropic' || recipe.id === 'openai' ? recipe.id : undefined;
-}
-
-/** The URL the gateway's call sites use for `recipe` under `cfg` (native: resolveNativeBaseUrl; compat: applyOpenAICompatConfig). */
-function gatewayUrl(recipe: Recipe, cfg: GBrainConfig): string | null {
- const gw = buildGatewayConfig(cfg);
- const native = nativeProvider(recipe);
- if (recipe.tier === 'native') return native ? resolveNativeBaseUrl(native, gw) ?? null : null;
- try { return applyOpenAICompatConfig(recipe, gw).baseURL; } catch { return null; }
-}
-
-/** A config-table reader holding the given DB-plane rows. */
-function dbReader(rows: Record<string, string>) {
- return {
- getConfig: async (k: string) => rows[k] ?? null,
- listConfigKeys: async (prefix: string) => Object.keys(rows).filter(k => k.startsWith(prefix)),
- };
-}
-
-type Plane = 'env' | 'file' | 'db' | 'none';
-
-/** Run `fn` with a temp GBRAIN_HOME holding `file` and only `env` among the base-URL vars. */
-async function inBrain<T>(file: GBrainConfig, env: Record<string, string>, fn: () => Promise<T>): Promise<T> {
- const home = join(homeRoot, `h${homeN++}`);
- mkdirSync(join(home, '.gbrain'), { recursive: true });
- writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify(file));
- const overrides: Record<string, string | undefined> = { GBRAIN_HOME: home, GBRAIN_DATABASE_URL: undefined, DATABASE_URL: undefined };
- for (const k of BASE_URL_ENV_KEYS) overrides[k] = env[k];
- return withEnv(overrides, fn);
-}
-
-describe('providers env base URL parity with the gateway (#5302)', () => {
- const recipes = listRecipes();
- const planes: Plane[] = ['env', 'file', 'db', 'none'];
- const cases = recipes.flatMap(r => planes.map(plane => ({ id: r.id, plane })));
-
- test.each(cases)('$id × $plane: displayed URL equals the URL the gateway calls', async ({ id, plane }) => {
- const recipe = getRecipe(id)!;
- const url = `https://${plane}.example.invalid/v1`;
- const envKey = COMPAT_BASE_URL_ENVS[id] ?? (nativeProvider(recipe) ? `${id.toUpperCase()}_BASE_URL` : undefined);
- const file: GBrainConfig = { engine: 'pglite', ...(plane === 'file' ? { provider_base_urls: { [id]: url } } : {}) } as GBrainConfig;
- const env = plane === 'env' && envKey ? { [envKey]: url } : {};
- const rows = plane === 'db' ? { [`provider_base_urls.${id}`]: url } : {};
- await inBrain(file, env, async () => {
- const fileCfg = loadConfig();
- const merged = (await loadConfigWithEngine(dbReader(rows), fileCfg))!;
- const db: DbPlaneRead = { read: true, merged };
- const endpoint = resolveProviderEndpoint(recipe, fileCfg, db);
- expect(endpoint.url).toBe(gatewayUrl(recipe, merged));
-
- const native = recipe.tier === 'native';
- if (plane === 'none') expect(endpoint.source).toBe(native ? 'provider SDK default' : recipe.resolveOpenAICompatConfig ? 'not configured' : 'recipe default');
- if (plane === 'file' && !recipe.resolveOpenAICompatConfig && (!native || nativeProvider(recipe))) {
- expect(endpoint.source).toBe(`provider_base_urls.${id} (file plane)`);
- }
- if (plane === 'env' && envKey && !recipe.resolveOpenAICompatConfig) expect(endpoint.source).toBe(`${envKey} env var`);
- if (plane === 'db' && !native && !recipe.resolveOpenAICompatConfig) expect(endpoint.source).toBe(`provider_base_urls.${id} (db plane)`);
- if (plane === 'db' && native) {
- expect(endpoint.url).toBeNull();
- expect(endpoint.dbPlane).toContain('not used (mount safety');
- }
- });
- });
-});
-
-describe('providers env base URL display (#5302)', () => {
- const mistral = () => getRecipe('mistral')!;
-
- test('the recipe default prints with provenance, the override and the DB-not-read disclosure', async () => {
- await inBrain({ engine: 'pglite' } as GBrainConfig, {}, async () => {
- const endpoint = resolveProviderEndpoint(mistral(), loadConfig(), { read: false, reason: 'no brain configured' });
- const out = formatEnvOutput(mistral(), {}, endpoint);
- expect(out).toContain('Base URL: https://api.mistral.ai/v1 (recipe default)');
- expect(out).toContain('Override: `gbrain config set provider_base_urls.mistral <url>`.');
- expect(out).toContain('DB plane not read (no brain configured)');
- expect(out).toContain('gbrain config get provider_base_urls.mistral');
- });
- });
-
- test('the override names an env var only when the gateway reads one for the recipe', async () => {
- await inBrain({ engine: 'pglite' } as GBrainConfig, {}, async () => {
- const ollama = resolveProviderEndpoint(getRecipe('ollama')!, loadConfig(), { read: false, reason: 'x' });
- expect(ollama.override).toContain('OLLAMA_BASE_URL');
- expect(resolveProviderEndpoint(mistral(), loadConfig(), { read: false, reason: 'x' }).override).not.toContain('MISTRAL_BASE_URL');
- });
- });
-
- test('a native provider normalizes /v1 like the gateway and reports a DB-plane value as not used', async () => {
- await inBrain({ engine: 'pglite' } as GBrainConfig, { ANTHROPIC_BASE_URL: 'https://proxy.example.invalid' }, async () => {
- const fileCfg = loadConfig();
- const merged = (await loadConfigWithEngine(dbReader({ 'provider_base_urls.anthropic': 'https://db.example.invalid/v1' }), fileCfg))!;
- const endpoint = resolveProviderEndpoint(getRecipe('anthropic')!, fileCfg, { read: true, merged });
- expect(endpoint).toMatchObject({ url: 'https://proxy.example.invalid/v1', source: 'ANTHROPIC_BASE_URL env var' });
- expect(endpoint.dbPlane).toBe('DB-plane provider_base_urls.anthropic https://db.example.invalid/v1: not used (mount safety; native providers read only env and file plane).');
- });
- });
-
- test('the file plane beats the DB plane for openai-compatible recipes, as at runtime', async () => {
- await inBrain({ engine: 'pglite', provider_base_urls: { mistral: 'https://api.eu.mistral.ai/v1' } } as GBrainConfig, {}, async () => {
- const fileCfg = loadConfig();
- const merged = (await loadConfigWithEngine(dbReader({ 'provider_base_urls.mistral': 'https://db.example.invalid/v1' }), fileCfg))!;
- const endpoint = resolveProviderEndpoint(mistral(), fileCfg, { read: true, merged });
- expect(endpoint).toMatchObject({ url: 'https://api.eu.mistral.ai/v1', source: 'provider_base_urls.mistral (file plane)' });
- expect(endpoint.dbPlane).toBe('DB plane read: provider_base_urls overrides are included.');
- });
- });
-
- test('displayed URLs never carry userinfo, query or fragment, and an unparseable value prints nothing of itself', async () => {
- const secret = 'https://alice-example:[email protected]/v1?key=sk-secret#frag-secret';
- expect(redactBaseUrlForDisplay(secret)).toBe('https://api.example.invalid/v1 (userinfo/query/fragment redacted)');
- expect(redactBaseUrlForDisplay('not a url hunter2-secret')).toBe('(invalid URL; value redacted)');
- await inBrain({ engine: 'pglite', provider_base_urls: { mistral: secret } } as GBrainConfig, {}, async () => {
- const out = formatEnvOutput(mistral(), {}, resolveProviderEndpoint(mistral(), loadConfig(), { read: false, reason: 'x' }));
- expect(out).toContain('Base URL: https://api.example.invalid/v1 (userinfo/query/fragment redacted)');
- expect(out).not.toContain('secret');
- });
- });
-});