Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(cli,doctor): warn once when an env key shadows a different config key (#5137)

garrytanf9794bd7ee4a
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.md
index 6566ec5a3a..210b9de498 100644
--- a/docs/architecture/key-files/core-ai.md
+++ b/docs/architecture/key-files/core-ai.md
@@ -22,7 +22,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ai/openrouter-families.ts` — single source of truth for which OpenRouter model families may drive the subagent (tool) loop: `OPENROUTER_SUBAGENT_FAMILIES` (currently `anthropic/` + `deepseek/`, each backed by a live abort/retry replay pin under `test/e2e/`) + `openrouterModelSupportsSubagentLoop(modelId)` (takes the bare OpenRouter id, no `openrouter:` prefix). Shared by the openrouter recipe's predicate and the subagent handler's auto-route so the two can never disagree; a new family gets its own live pin before joining the list.
-- `src/core/ai/provider-env.ts` — `mergedProviderEnv(cfg, env)`: THE canonical provider-key/env fold. Maps file-plane config keys (openai/anthropic/openrouter/voyage/dashscope/deepseek/litellm/together/google/azure_openai + azure endpoint/deployment/entra) to the env names recipes read, merges env on top (env wins ONLY for keys carrying a real value — '' and undefined dropped), then applies the `GEMINI_API_KEY → GOOGLE_GENERATIVE_AI_API_KEY` alias (canonical env name > alias > config fallback). Three consumers: `buildGatewayConfig` (gateway env), `detectCapabilities` (capability probe), `resolveTierDefault`/`resolveEffectiveChatModel` (key-aware model resolution) — so gateway env and the capability probe cannot drift.
+- `src/core/ai/provider-env.ts` — `mergedProviderEnv(cfg, env)`: THE canonical provider-key/env fold. Maps file-plane config keys (openai/anthropic/openrouter/voyage/dashscope/deepseek/litellm/together/google/azure_openai + azure endpoint/deployment/entra) to the env names recipes read, merges env on top (env wins ONLY for keys carrying a real value — '' and undefined dropped), then applies the `GEMINI_API_KEY → GOOGLE_GENERATIVE_AI_API_KEY` alias (canonical env name > alias > config fallback). Three consumers: `buildGatewayConfig` (gateway env), `detectCapabilities` (capability probe), `resolveTierDefault`/`resolveEffectiveChatModel` (key-aware model resolution) — so gateway env and the capability probe cannot drift. #5137: the fold reads the `CONFIG_API_KEY_ENV` table; `providerKeyShadows(fileCfg, env)` (pure, names only) lists env values that override a different config-plane key, and `providerKeySource` names where a recipe's key comes from. Both take the FILE-only config (`loadConfigFileOnly`), because `loadConfig` already folds OPENAI/ANTHROPIC/OPENROUTER env values into the config fields. TypeSafe has no config key, so its env alias never shadows. Tests: `embedding-key-source.test.ts`, `embedding-key-source-cli.serial.test.ts`.
+- `src/core/ai/key-warnings.ts` — #5137 print seam with one replaceable sink and two once-per-process latches: `warnShadowedProviderKeys` (called from `src/cli.ts` for every command except `gbrain hook`; `gbrain serve` starts through the same path) names the variable, the config key, that env is in effect, and both fixes (remove the variable from that process's environment and restart it, or `gbrain config unset <key>`, which also silences it); `reportEmbeddingAuthFailure` prints `embedding_auth_failed` (catalogue entry) on the first embedding 401/403, naming the key source in effect and the fix plus `gbrain embed --stale`. Never prints a key or fragment. Doctor `embedding_key_source` (`src/commands/doctor/checks/embedding-health.ts`, engine-free filesystem-lane entry `embeddingKeySourceEntry`) reports the same shadows and the embedding key's source, and says it sees only the environment doctor runs in.
+- `src/core/ai/key-redact.ts` — `redactProviderKeys(text, env)`: scrubs every `*_API_KEY`/`*_TOKEN`/`*_SECRET`/`*_PASSWORD` value in the gateway env, masked echoes (`sk-...****abcd`) and 8+ character key fragments from upstream error text. The gateway passes it to `normalizeAIError` (which also scrubs the wrapped error's cause chain in place, keeping status and headers for `.cause` walkers) on embed, multimodal, expand and chat errors, and applies it to multimodal response bodies.
- `src/core/ai/providers/claude-cli-language-model.ts` (+ recipe `src/core/ai/recipes/claude-cli.ts`) — ai-sdk LanguageModel adapter that shells out to the locally-installed `claude` CLI in print mode (OAuth-subscription lane, no API key; `claude-cli:<model>` is config-portable with `anthropic:<model>`). Tool use is system-prompt-instructed JSON emission: the recipe teaches the model the `<use_tools>[{name,input}]</use_tools>` format and the adapter parses those blocks back into ai-sdk `tool-call` parts. An entry that carries its arguments flat beside `name` (no `input` wrapper, the Anthropic tool_use shape with the wrapper dropped) is accepted: every key other than `name`/`input` and the Anthropic tool_use leftovers (`type: "tool_use"`, a `toolu_*` `id`) becomes the input — any other `type`/`id` value is a real argument (e.g. `list_pages`' `type` filter) and stays — and a present `input` wins verbatim over stray sibling keys. Tool-call ids are ALWAYS gbrain-minted (`toolu_claude_cli_<uuidv7>`) — never model-authored: each doGenerate is a fresh subprocess replayed from an id-stripped transcript, so the model structurally cannot keep ids unique across turns (a model-authored id echoes the prompt's example entropy-free and collides); the prompt does not ask for an id, and a stray `id` field is deliberately ignored (nothing round-trips it — the loop pairs results in-memory within one turn). doStream not implemented; callers (gateway.toolLoop) use doGenerate. The recipe declares `chat` + `expansion` touchpoints (no embedding; the expansion list leads with the cheap haiku id and carries the same 30s `default_timeout_ms` as chat for the subprocess cold start); `gateway.expand()` routes `claude-cli` through the schemaless `viaText` path because the adapter ignores `responseFormat` (generateObject would throw NoObjectGeneratedError on the fenced-JSON text). Pinned by `test/claude-cli-recipe.test.ts` + `test/ai/claude-cli-expansion.test.ts`.
diff --git a/src/cli.ts b/src/cli.ts
index 069c79db18..fd72ec9400 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -330,6 +330,8 @@ async function main() {
const { maybeEmitBackupNag } = await import('./core/backup/status-file.ts');
maybeEmitBackupNag(command, { quiet: getCliOptions().quiet === true });
}
+ // #5137: once per process, when an env key shadows a different config key; never from hook commands.
+ if (command !== 'hook') (await import('./core/ai/key-warnings.ts')).warnShadowedProviderKeys();
const subArgs = args.slice(1);
diff --git a/src/commands/doctor/checks/embedding-health.ts b/src/commands/doctor/checks/embedding-health.ts
index e08facceca..64319405d7 100644
--- a/src/commands/doctor/checks/embedding-health.ts
+++ b/src/commands/doctor/checks/embedding-health.ts
@@ -9,6 +9,11 @@
import { hnswIndexExpected, hnswMaxDimsForType } from '../../../core/vector-index.ts';
import { checkEmbeddingEnvOverride, checkEmbeddingMigrationState } from './search-eval.ts';
+import type { GBrainConfig } from '../../../core/config.ts';
+import { DEFAULT_EMBEDDING_MODEL } from '../../../core/ai/defaults.ts';
+import { providerKeyShadows, providerKeySource } from '../../../core/ai/provider-env.ts';
+import { keyShadowWarning } from '../../../core/ai/key-warnings.ts';
+import { getRecipe } from '../../../core/ai/recipes/index.ts';
import type { Check } from '../../doctor.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
@@ -433,3 +438,47 @@ export const embeddingEnvOverrideEntry: DoctorEntry = {
emits: ['embedding_env_override', 'embedding_migration_state'],
run: runEmbeddingEnvOverride,
};
+
+/**
+ * Doctor `embedding_key_source` (#5137, DX-O8): which provider keys come from
+ * the environment and override a different config-plane key, and where the
+ * embedding key in effect comes from. Names only, never key values. It sees
+ * only the environment `gbrain doctor` runs in, not a daemon's. Engine-free
+ * filesystem-lane entry (also under `--fast`).
+ */
+const KEY_SOURCE_DOCS = 'docs/guides/repair.md#embedding-key-source';
+const KEY_SOURCE_SCOPE = 'This check sees only the environment `gbrain doctor` runs in; a daemon (gbrain serve, autopilot) has its own, and reports a mismatch in its log with a startup warning or embedding_auth_failed.';
+
+export function embeddingKeySource(fileCfg: GBrainConfig | null, env: Record<string, string | undefined>, file: string): Pick<Check, 'status' | 'message' | 'details'> {
+ const shadows = providerKeyShadows(fileCfg, env);
+ const model = fileCfg?.embedding_model ?? DEFAULT_EMBEDDING_MODEL;
+ const variable = getRecipe(model.split(':')[0] ?? '')?.auth_env?.required[0];
+ const source = variable ? providerKeySource(fileCfg, env, variable) : null;
+ const inEffect = !source ? `The embedding model ${model} reads no API key.`
+ : source.kind === 'env' ? `The embedding key in effect is ${source.variable} from this environment.`
+ : source.kind === 'config' ? `The embedding key in effect is ${source.config_key} in ${file}.`
+ : `No embedding key is set here (${source.variable}${source.config_key ? ` or ${source.config_key}` : ''}).`;
+ const details = { shadows: shadows.map(shadow => ({ ...shadow, in_effect: 'env' as const })),
+ embedding_model: model, embedding_key: source ? { kind: source.kind, variable: source.variable, config_key: source.config_key ?? null } : null, docs: KEY_SOURCE_DOCS };
+ if (!shadows.length) return { status: 'ok', message: `${inEffect} No environment variable overrides a different config-plane provider key. ${KEY_SOURCE_SCOPE}`, details };
+ return {
+ status: 'warn',
+ message: `${inEffect} ${shadows.map(shadow => keyShadowWarning(shadow, file).replace('[gbrain] warning: ', '')).join(' ')} ${KEY_SOURCE_SCOPE}`,
+ details,
+ };
+}
+
+async function runEmbeddingKeySource(_ctx: DoctorContext): Promise<Check[]> {
+ const checks: Check[] = [];
+ const { configPath, loadConfigFileOnly } = await import('../../../core/config.ts');
+ let file = 'config.json';
+ try { file = configPath(); } catch { /* invalid GBRAIN_HOME: doctor reports it elsewhere */ }
+ checks.push({ name: 'embedding_key_source', ...embeddingKeySource(loadConfigFileOnly(), process.env, file) });
+ return checks;
+}
+
+export const embeddingKeySourceEntry: DoctorEntry = {
+ name: 'embedding_key_source',
+ emits: ['embedding_key_source'],
+ run: runEmbeddingKeySource,
+};
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 7a41442fee..5d176fbf51 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -85,6 +85,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'embed_staleness',
'embedding_column_registry',
'embedding_env_override',
+ // #5137: an env provider key shadowing a different config key.
+ 'embedding_key_source',
'embedding_migration_state',
'embedding_provider',
// #5691: query-instruction advisory for instruction-style embedding models.
diff --git a/test/embedding-key-source-cli.serial.test.ts b/test/embedding-key-source-cli.serial.test.ts
new file mode 100644
index 0000000000..85b5af887c
--- /dev/null
+++ b/test/embedding-key-source-cli.serial.test.ts
@@ -0,0 +1,44 @@
+/**
+ * #5137 through the real CLI entrypoint: the key-shadow warning prints once
+ * per process from ordinary commands, never from `gbrain hook`, carries no
+ * key bytes, and `gbrain config unset <key>` (the documented fix for an
+ * intended env key) stops it.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { runCli } from './helpers/cli-spawn.ts';
+
+const ENV_KEY = 'sk-test-ENVKEYexample0123456789abcdefWXYZ';
+const CONFIG_KEY = 'sk-test-CONFIGKEYexample9876543210fedcbaQRST';
+const home = mkdtempSync(join(tmpdir(), 'gbrain-key-shadow-cli-'));
+const configFile = join(home, '.gbrain', 'config.json');
+const opts = { home, env: { OPENAI_API_KEY: ENV_KEY } };
+const leaked = (text: string) => [ENV_KEY, CONFIG_KEY, ENV_KEY.slice(0, 16), CONFIG_KEY.slice(-12)].filter(fragment => text.includes(fragment));
+const warnings = (stderr: string) => stderr.split('\n').filter(line => line.includes('differs from openai_api_key'));
+
+beforeAll(() => {
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(configFile, JSON.stringify({ engine: 'pglite', database_path: join(home, '.gbrain', 'brain.pglite'), openai_api_key: CONFIG_KEY }));
+});
+afterAll(() => rmSync(home, { recursive: true, force: true }));
+
+test('an ordinary command warns once on stderr and leaks no key bytes; a hook command never warns', async () => {
+ const command = await runCli(['engine', '--help'], opts);
+ expect(command.exitCode).toBe(0);
+ expect(warnings(command.stderr)).toEqual([expect.stringContaining('[gbrain] warning: OPENAI_API_KEY in this process\'s environment differs from openai_api_key')]);
+ expect(leaked(command.stdout + command.stderr)).toEqual([]);
+ const hook = await runCli(['hook', '--help'], opts);
+ expect(warnings(hook.stderr)).toEqual([]);
+ expect(leaked(hook.stdout + hook.stderr)).toEqual([]);
+}, 120_000);
+
+test('`gbrain config unset openai_api_key` keeps the env key in effect and stops the warning', async () => {
+ const unset = await runCli(['config', 'unset', 'openai_api_key'], opts);
+ expect(unset.exitCode).toBe(0);
+ expect(leaked(unset.stdout + unset.stderr)).toEqual([]);
+ expect(JSON.parse(readFileSync(configFile, 'utf8')).openai_api_key).toBeUndefined();
+ const after = await runCli(['engine', '--help'], opts);
+ expect(warnings(after.stderr)).toEqual([]);
+}, 120_000);
diff --git a/test/embedding-key-source.test.ts b/test/embedding-key-source.test.ts
new file mode 100644
index 0000000000..b0bb1a1092
--- /dev/null
+++ b/test/embedding-key-source.test.ts
@@ -0,0 +1,164 @@
+/**
+ * #5137: env provider keys keep winning over config keys, but a different
+ * config key shadowed by the environment is reported once per process, doctor
+ * `embedding_key_source` reports the same, and the first embedding 401/403
+ * prints embedding_auth_failed naming the key source. No key value or
+ * fragment reaches any output.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { mergedProviderEnv, providerKeyShadows, providerKeySource } from '../src/core/ai/provider-env.ts';
+import { _setKeyWarningSinkForTests, embeddingAuthFailedError, warnShadowedProviderKeys } from '../src/core/ai/key-warnings.ts';
+import { redactProviderKeys } from '../src/core/ai/key-redact.ts';
+import { configureGateway, embed, resetGateway } from '../src/core/ai/gateway.ts';
+import { embeddingKeySource } from '../src/commands/doctor/checks/embedding-health.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const ENV_KEY = 'sk-test-ENVKEYexample0123456789abcdefWXYZ';
+const CONFIG_KEY = 'sk-test-CONFIGKEYexample9876543210fedcbaQRST';
+const fragments = (key: string) => [key, key.slice(0, 16), key.slice(-12)];
+const cfg = (extra: Partial<GBrainConfig> = {}) => ({ engine: 'pglite', openai_api_key: CONFIG_KEY, ...extra }) as GBrainConfig;
+const leaks = (text: string) => [...fragments(ENV_KEY), ...fragments(CONFIG_KEY)].filter(fragment => text.includes(fragment));
+
+const lines: string[] = [];
+afterEach(() => { _setKeyWarningSinkForTests(); lines.length = 0; resetGateway(); });
+
+describe('providerKeyShadows (pure)', () => {
+ test('reports an env value that differs from the config key, by name only', () => {
+ expect(providerKeyShadows(cfg(), { OPENAI_API_KEY: ENV_KEY })).toEqual([{ variable: 'OPENAI_API_KEY', config_key: 'openai_api_key' }]);
+ expect(providerKeyShadows(cfg(), { OPENAI_API_KEY: CONFIG_KEY })).toEqual([]);
+ expect(providerKeyShadows(cfg(), { OPENAI_API_KEY: '' })).toEqual([]);
+ expect(providerKeyShadows(cfg(), {})).toEqual([]);
+ expect(providerKeyShadows(null, { OPENAI_API_KEY: ENV_KEY })).toEqual([]);
+ expect(mergedProviderEnv(cfg(), { OPENAI_API_KEY: ENV_KEY }).OPENAI_API_KEY).toBe(ENV_KEY);
+ });
+
+ test('the GEMINI alias counts as the env key for google_api_key; TypeSafe has no config key, so its alias never warns', () => {
+ const google = cfg({ google_api_key: CONFIG_KEY } as Partial<GBrainConfig>);
+ expect(providerKeyShadows(google, { GEMINI_API_KEY: ENV_KEY })).toEqual([{ variable: 'GEMINI_API_KEY', config_key: 'google_api_key' }]);
+ expect(providerKeyShadows(google, { GOOGLE_GENERATIVE_AI_API_KEY: ENV_KEY, GEMINI_API_KEY: CONFIG_KEY }))
+ .toEqual([{ variable: 'GOOGLE_GENERATIVE_AI_API_KEY', config_key: 'google_api_key' }]);
+ expect(providerKeyShadows(cfg(), { JEV_TYPESAFE_API_KEY: ENV_KEY })).toEqual([]);
+ expect(providerKeyShadows(cfg(), { TYPESAFE_API_KEY: ENV_KEY, JEV_TYPESAFE_API_KEY: CONFIG_KEY })).toEqual([]);
+ });
+
+ test('providerKeySource names where the key in effect comes from', () => {
+ expect(providerKeySource(cfg(), { OPENAI_API_KEY: ENV_KEY }, 'OPENAI_API_KEY')).toEqual({ kind: 'env', variable: 'OPENAI_API_KEY', config_key: 'openai_api_key', shadows_config: true });
+ expect(providerKeySource(cfg(), {}, 'OPENAI_API_KEY')).toEqual({ kind: 'config', variable: 'OPENAI_API_KEY', config_key: 'openai_api_key' });
+ expect(providerKeySource(null, {}, 'ZEROENTROPY_API_KEY')).toEqual({ kind: 'missing', variable: 'ZEROENTROPY_API_KEY' });
+ });
+});
+
+describe('the shadow warning', () => {
+ test('prints once per process, names the variable, the config key, which is in effect and both fixes, and no key bytes', () => {
+ _setKeyWarningSinkForTests(line => lines.push(line));
+ warnShadowedProviderKeys(cfg(), { OPENAI_API_KEY: ENV_KEY });
+ warnShadowedProviderKeys(cfg(), { OPENAI_API_KEY: ENV_KEY });
+ expect(lines).toHaveLength(1);
+ expect(lines[0]).toContain('OPENAI_API_KEY in this process\'s environment differs from openai_api_key in');
+ expect(lines[0]).toContain('the environment value is in effect');
+ expect(lines[0]).toContain('remove OPENAI_API_KEY from the environment of the process that reported this');
+ expect(lines[0]).toContain('for a daemon its service definition) and restart that process');
+ expect(lines[0]).toContain('run `gbrain config unset openai_api_key`, which also stops this warning');
+ expect(leaks(lines[0])).toEqual([]);
+ });
+
+ test('a matching or absent env key prints nothing', () => {
+ _setKeyWarningSinkForTests(line => lines.push(line));
+ warnShadowedProviderKeys(cfg(), { OPENAI_API_KEY: CONFIG_KEY });
+ expect(lines).toEqual([]);
+ });
+});
+
+describe('doctor embedding_key_source', () => {
+ test('warns on a shadowed key, names the embedding key source, scopes itself to doctor\'s environment, and leaks no key', () => {
+ const check = embeddingKeySource(cfg({ embedding_model: 'openai:text-embedding-3-small' }), { OPENAI_API_KEY: ENV_KEY }, '/home/example/.gbrain/config.json');
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('The embedding key in effect is OPENAI_API_KEY from this environment.');
+ expect(check.message).toContain('differs from openai_api_key in /home/example/.gbrain/config.json');
+ expect(check.message).toContain('This check sees only the environment `gbrain doctor` runs in');
+ expect(check.details).toMatchObject({ shadows: [{ variable: 'OPENAI_API_KEY', config_key: 'openai_api_key', in_effect: 'env' }],
+ embedding_key: { kind: 'env', variable: 'OPENAI_API_KEY', config_key: 'openai_api_key' }, docs: 'docs/guides/repair.md#embedding-key-source' });
+ expect(leaks(JSON.stringify(check))).toEqual([]);
+ });
+
+ test('is ok without a shadow and reports a config-plane embedding key', () => {
+ const check = embeddingKeySource(cfg({ embedding_model: 'openai:text-embedding-3-small' }), {}, '/home/example/.gbrain/config.json');
+ expect(check.status).toBe('ok');
+ expect(check.message).toContain('The embedding key in effect is openai_api_key in /home/example/.gbrain/config.json.');
+ expect(leaks(JSON.stringify(check))).toEqual([]);
+ });
+});
+
+test('redactProviderKeys removes a key in effect, a masked echo and a key fragment, and keeps ordinary text', () => {
+ const text = `Incorrect API key provided: ${ENV_KEY}. Also seen: sk-test-****************WXYZ and ${ENV_KEY.slice(4, 20)} for model text-embedding-3-small.`;
+ const redacted = redactProviderKeys(text, { OPENAI_API_KEY: ENV_KEY, OPENAI_BASE_URL: 'http://127.0.0.1:1/v1' });
+ expect(leaks(redacted)).toEqual([]);
+ expect(redacted).not.toContain('****');
+ expect(redacted).toContain('<REDACTED:OPENAI_API_KEY>');
+ expect(redacted).toContain('for model text-embedding-3-small.');
+});
+
+describe('embedding_auth_failed against a provider that rejects the env key', () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-key-source-'));
+ let server: ReturnType<typeof Bun.serve>;
+ const requests: string[] = [];
+ beforeAll(() => {
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', openai_api_key: CONFIG_KEY }));
+ server = Bun.serve({ port: 0, hostname: '127.0.0.1', async fetch(req) {
+ const key = (req.headers.get('authorization') ?? '').replace(/^Bearer /, '');
+ requests.push(key === CONFIG_KEY ? 'config' : key === ENV_KEY ? 'env' : 'other');
+ if (key !== CONFIG_KEY) {
+ return Response.json({ error: { message: `Incorrect API key provided: ${key}. You passed ${key.slice(0, 16)}...${key.slice(-12)} (sk-test-****${key.slice(-4)}).`, type: 'invalid_request_error', code: 'invalid_api_key' } }, { status: 401 });
+ }
+ const body = await req.json() as { input: string[] };
+ return Response.json({ object: 'list', model: 'text-embedding-3-small', usage: { prompt_tokens: 1, total_tokens: 1 },
+ data: body.input.map((_, index) => ({ object: 'embedding', index, embedding: Array.from({ length: 1536 }, (_, i) => (i % 7) + 1) })) });
+ } });
+ });
+ afterAll(() => { server.stop(true); rmSync(home, { recursive: true, force: true }); });
+
+ const configureFromEnv = async () => {
+ const { loadConfigFileOnly } = await import('../src/core/config.ts');
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536,
+ env: { ...mergedProviderEnv(loadConfigFileOnly(), process.env), OPENAI_BASE_URL: `http://127.0.0.1:${server.port}/v1` } });
+ };
+
+ test('the first 401 prints one error naming the env key source and its fixes; following the fix makes the embedding succeed', async () => {
+ _setKeyWarningSinkForTests(line => lines.push(line));
+ let failure: unknown;
+ await withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: ENV_KEY }, async () => {
+ await configureFromEnv();
+ failure = await embed(['example text'], { maxRetries: 0 }).then(() => null, error => error);
+ expect(await embed(['second example'], { maxRetries: 0 }).then(() => null, error => error)).toBeInstanceOf(Error);
+ });
+ expect(failure).toBeInstanceOf(Error);
+ expect(requests).toContain('env');
+ expect(leaks(String((failure as Error).message))).toEqual([]);
+ expect(leaks(JSON.stringify({ error: (failure as Error).message, ...(failure as object) }))).toEqual([]);
+ expect(lines).toHaveLength(1);
+ expect(lines[0]).toStartWith('[gbrain] Error [embedding_auth_failed]: The OpenAI embedding provider rejected its key (HTTP 401); the key in effect is OPENAI_API_KEY from this process\'s environment, which differs from openai_api_key in');
+ expect(lines[0]).toContain('Fix: To use the config key, remove OPENAI_API_KEY from the environment of the process that reported this');
+ expect(lines[0]).toContain('run `gbrain config unset openai_api_key`');
+ expect(lines[0]).toContain('Docs: docs/guides/write-refusals.md#embedding_auth_failed');
+ expect(leaks(lines.join('\n'))).toEqual([]);
+
+ await withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: undefined }, async () => {
+ await configureFromEnv();
+ const [vector] = await embed(['example text'], { maxRetries: 0 });
+ expect(vector).toHaveLength(1536);
+ });
+ expect(requests.at(-1)).toBe('config');
+ }, 60_000);
+
+ test('a rejected config key names the config key and its fix', () => {
+ const error = embeddingAuthFailedError({ id: 'openai', name: 'OpenAI', auth_env: { required: ['OPENAI_API_KEY'] } }, 403, cfg(), {}, '/home/example/.gbrain/config.json');
+ expect(error.toJSON()).toMatchObject({ error: 'embedding_auth_failed', docs: 'docs/guides/write-refusals.md#embedding_auth_failed',
+ message: 'The OpenAI embedding provider rejected its key (HTTP 403); the key in effect is openai_api_key in /home/example/.gbrain/config.json (OPENAI_API_KEY is not set).',
+ suggestion: 'Run `gbrain config set openai_api_key <valid key>` and restart any daemon that uses it. Then run `gbrain embed --stale` to embed what was saved while the key was rejected.' });
+ });
+});