Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(ai): redact provider keys from upstream errors and report the first embedding 401/403 (#5137)
garrytan8f1b7497750a
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex a595f5e7ab..94734cd684 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -3,7 +3,7 @@# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in# the same commit as any peel (the guard fails on >50 lines of stale slack).# Columns: path max_lines policy note-src/cli.ts 3159 ratchet +1 fix wave 5 (#5401): projections drain help line; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts)+src/cli.ts 3161 ratchet +1 fix wave 5 (#5401): projections drain help line; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts)src/commands/autopilot.ts 1633 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.tssrc/commands/doctor.ts 653 ratchet refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.tssrc/commands/embed.ts 2187 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages@@ -11,7 +11,7 @@ src/commands/extract-conversation-facts.ts 2146 ratchet grown v0.46.x per-providsrc/commands/extract.ts 2621 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blockedsrc/commands/jobs.ts 635 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.tssrc/commands/serve-http.ts 915 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts-src/core/ai/gateway.ts 4358 ratchet +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state)+src/core/ai/gateway.ts 4365 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state)src/commands/sync.ts 472 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary)src/core/cycle.ts 3221 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the mergesrc/core/cycle/synthesize.ts 3291 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the mergediff --git a/src/core/ai/errors.ts b/src/core/ai/errors.tsindex c20d57ea2f..48178a0949 100644--- a/src/core/ai/errors.ts+++ b/src/core/ai/errors.ts@@ -65,7 +65,31 @@ function carryStatusFields(from: unknown, to: AIServiceError): AIServiceError {return to;}-export function normalizeAIError(err: unknown, context?: string): AIServiceError {+/**+ * Scrub upstream text in place along a wrapped error's cause chain (message,+ * stack, the SDK's responseBody and parsed data), keeping status, headers and+ * shape, so `.cause` walkers still classify it and nothing serialized or+ * printed later carries what `redact` removes.+ */+function scrubErrorChain(err: unknown, redact: (text: string) => string): void {+ let cur = err;+ for (let depth = 0; depth < 4 && cur && typeof cur === 'object'; depth++) {+ const node = cur as Record<string, unknown>;+ for (const key of ['message', 'stack', 'responseBody']) {+ if (typeof node[key] === 'string') try { node[key] = redact(node[key] as string); } catch { /* read-only field */ }+ }+ if (node.data && typeof node.data === 'object') try { node.data = JSON.parse(redact(JSON.stringify(node.data))); } catch { /* not plain data */ }+ cur = node.cause;+ }+}++/**+ * `redact` scrubs upstream text before it becomes the message, and in the+ * wrapped error (#5137: the gateway passes its provider-key redactor, since+ * auth errors echo keys).+ */+export function normalizeAIError(err: unknown, context?: string, redact?: (text: string) => string): AIServiceError {+ if (redact) scrubErrorChain(err, redact);if (err instanceof AIServiceError) return err;const anyErr = err as {@@ -84,7 +108,8 @@ export function normalizeAIError(err: unknown, context?: string): AIServiceErroranyErr?.statusCode ??(typeof anyErr?.apiErrorStatus === 'number' ? anyErr.apiErrorStatus : undefined);const name = anyErr?.name ?? '';- const msg = anyErr?.message ?? String(err);+ const raw = anyErr?.message ?? String(err);+ const msg = redact ? redact(raw) : raw;const ctxPrefix = context ? `[${context}] ` : '';// 4xx (except 429) = config-level, non-retryablediff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.tsindex 5ad788eb58..5c3d5424f3 100644--- a/src/core/ai/gateway.ts+++ b/src/core/ai/gateway.ts@@ -64,6 +64,8 @@ import { runGuardrails, hasGuardrails, type GuardrailHook } from '../guardrails.import { loadConfig } from '../config.ts';import type { GBrainConfig } from '../config.ts';import { mergedProviderEnv } from './provider-env.ts';+import { redactProviderKeys } from './key-redact.ts';+import { reportEmbeddingAuthFailure } from './key-warnings.ts';import { buildGatewayConfig, foldNativeBaseUrlsFromFilePlane } from './build-gateway-config.ts';import { invokeAI, sdkInvocationUsage, responseInvocationUsage, hasAIInvocationGuard, isAIInvocationPolicyError } from './invocation-guard.ts';import { createGuardedGeneration, chatInvocation } from './guarded-generation.ts';@@ -123,6 +125,8 @@ const DEFAULT_CHAT_MODEL = 'anthropic:claude-sonnet-4-6';// the mode bundles) — `voyage:rerank-2.5` since v0.48.2.let _config: AIGatewayConfig | null = null;+/** #5137: provider auth errors echo keys; scrub every key in effect before the text leaves the gateway. */+const redactKeys = (text: string): string => redactProviderKeys(text, _config?.env ?? {});const _modelCache = new Map<string, any>();/**@@ -1751,7 +1755,8 @@ async function embedSubBatch(const right = await embedSubBatch(texts.slice(mid), model, providerOpts, expectedDims, recipe, modelId, opts);return [...left, ...right];}- throw normalizeAIError(err, `embed(${recipe.id}:${modelId})`);+ reportEmbeddingAuthFailure(recipe, err);+ throw normalizeAIError(err, `embed(${recipe.id}:${modelId})`, redactKeys);}}@@ -1913,12 +1918,13 @@ export async function embedMultimodal(}), responseInvocationUsage);} catch (err) {if (isAIInvocationPolicyError(err)) throw err;- throw normalizeAIError(err, `embedMultimodal(${recipe.id}:${parsed.modelId})`);+ throw normalizeAIError(err, `embedMultimodal(${recipe.id}:${parsed.modelId})`, redactKeys);}if (!res.ok) {- const text = await res.text().catch(() => '');+ const text = redactKeys(await res.text().catch(() => ''));if (res.status === 401 || res.status === 403) {+ reportEmbeddingAuthFailure(recipe, { status: res.status });throw new AIConfigError(`Voyage multimodal returned ${res.status}: ${text || 'auth failed'}.`,`Re-export ${recipe.auth_env?.required[0]} or rotate the key at ${recipe.auth_env?.setup_url}.`,@@ -2059,12 +2065,13 @@ async function embedMultimodalOpenAICompat(}), responseInvocationUsage);} catch (err) {if (isAIInvocationPolicyError(err)) throw err;- throw normalizeAIError(err, `embedMultimodal(${recipe.id}:${modelId})`);+ throw normalizeAIError(err, `embedMultimodal(${recipe.id}:${modelId})`, redactKeys);}if (!res.ok) {- const text = await res.text().catch(() => '');+ const text = redactKeys(await res.text().catch(() => ''));if (res.status === 401 || res.status === 403) {+ reportEmbeddingAuthFailure(recipe, { status: res.status });const requiredKey = recipe.auth_env?.required[0];throw new AIConfigError(`${recipe.name} multimodal returned ${res.status}: ${text || 'auth failed'}.`,@@ -2531,7 +2538,7 @@ export async function expand(query: string): Promise<string[]> {} catch (err) {if (isAIInvocationPolicyError(err)) throw err;// Expansion is best-effort: on failure, fall back to the original query alone.- const normalized = normalizeAIError(err, 'expand');+ const normalized = normalizeAIError(err, 'expand', redactKeys);if (normalized instanceof AIConfigError) {console.warn(`[ai.gateway] expansion disabled: ${normalized.message}`);}@@ -3690,7 +3697,7 @@ export async function chat(opts: ChatOpts): Promise<ChatResult> {// Pessimistic fallback (A3 amended): when err.usage isn't there, charge// the worst-case ceiling — better to overcount on failure than under._recordBudget(failedCallUsage(err, { inputTokens: estimatedInputTokens, outputTokens: maxOutputTokens }));- throw normalizeAIError(err, `chat(${recipe.id}:${modelId})`);+ throw normalizeAIError(err, `chat(${recipe.id}:${modelId})`, redactKeys);}}diff --git a/src/core/ai/key-redact.ts b/src/core/ai/key-redact.tsnew file mode 100644index 0000000000..c3e467ee0d--- /dev/null+++ b/src/core/ai/key-redact.ts@@ -0,0 +1,18 @@+/**+ * #5137: scrub provider key material from upstream error text before it+ * reaches the CLI, `--json` or a persisted job error. Providers echo keys in+ * auth failures, whole or masked (`sk-...****abcd`).+ */+import { redactSecretsInText } from '../minions/handlers/shell-redact.ts';++const SECRET_ENV = /(?:_API_KEY|_TOKEN|_SECRET|_PASSWORD)$/;++export function redactProviderKeys(text: string, env: Record<string, string | undefined>): string {+ if (!text) return text;+ const secrets = Object.entries(env)+ .filter((entry): entry is [string, string] => SECRET_ENV.test(entry[0]) && typeof entry[1] === 'string' && entry[1].length >= 8)+ .sort(([, a], [, b]) => b.length - a.length);+ return redactSecretsInText(text, secrets)+ .replace(/[A-Za-z0-9_-]*\*{3,}[A-Za-z0-9_-]*/g, '<REDACTED:masked_key>')+ .replace(/[A-Za-z0-9_-]{8,}/g, token => secrets.some(([, value]) => value.includes(token)) ? '<REDACTED:key_fragment>' : token);+}diff --git a/src/core/ai/key-warnings.ts b/src/core/ai/key-warnings.tsnew file mode 100644index 0000000000..e8671b6e10--- /dev/null+++ b/src/core/ai/key-warnings.ts@@ -0,0 +1,91 @@+/**+ * #5137: the two key-source messages, each printed at most once per process+ * through one replaceable sink. Env keeps winning over config keys+ * (mergedProviderEnv); these only say which key is in effect and how to+ * change that. Neither prints a key or any part of one.+ *+ * - warnShadowedProviderKeys: the CLI startup seam (src/cli.ts, which also+ * starts `gbrain serve`) calls it for every command except `gbrain hook`.+ * - reportEmbeddingAuthFailure: the gateway calls it on the first embedding+ * 401/403, so a revoked key no longer fails silently.+ */+import { configPath, loadConfigFileOnly, type GBrainConfig } from '../config.ts';+import { catalogueError } from '../error-catalogue.ts';+import type { OperationError } from '../ops/contract.ts';+import { providerKeyShadows, providerKeySource, type ProviderKeyShadow } from './provider-env.ts';++type Env = Record<string, string | undefined>;+const stderrSink = (line: string) => { process.stderr.write(`${line}\n`); };+let sink: (line: string) => void = stderrSink;+let shadowsWarned = false;+let authFailureReported = false;++/** Test seam: capture lines and reset both once-per-process latches. */+export function _setKeyWarningSinkForTests(next?: (line: string) => void): void {+ sink = next ?? stderrSink;+ shadowsWarned = false;+ authFailureReported = false;+}++const removeVariable = (variable: string) =>+ `To use the config key, remove ${variable} from the environment of the process that reported this (shell profile, ~/.gbrain/.env, or for a daemon its service definition) and restart that process.`;++export function keyShadowWarning(shadow: ProviderKeyShadow, file = configPath()): string {+ return `[gbrain] warning: ${shadow.variable} in this process's environment differs from ${shadow.config_key} in ${file}; the environment value is in effect. `+ + `${removeVariable(shadow.variable)} If the environment key is intended, run \`gbrain config unset ${shadow.config_key}\`, which also stops this warning.`;+}++export function warnShadowedProviderKeys(fileCfg: GBrainConfig | null = loadConfigFileOnly(), env: Env = process.env): void {+ if (shadowsWarned) return;+ shadowsWarned = true;+ try {+ for (const shadow of providerKeyShadows(fileCfg, env)) sink(keyShadowWarning(shadow));+ } catch { /* an invalid GBRAIN_HOME is reported by the command itself */ }+}++export interface AuthFailedProvider { id: string; name: string; auth_env?: { required: readonly string[] } }++/** DX-O8: names the key source in effect and the fixes for it. */+export function embeddingAuthFailedError(provider: AuthFailedProvider, status: number,+ fileCfg: GBrainConfig | null = loadConfigFileOnly(), env: Env = process.env, file = configPath()): OperationError {+ const name = provider.auth_env?.required[0];+ const rejected = `The ${provider.name} embedding provider rejected its key (HTTP ${status})`;+ const backfill = 'Then run `gbrain embed --stale` to embed what was saved while the key was rejected.';+ if (!name) return catalogueError('embedding_auth_failed', `${rejected}.`, `Check the ${provider.name} credentials, restart the process that reported this, then run \`gbrain embed --stale\`.`);+ const source = providerKeySource(fileCfg, env, name);+ if (source.kind === 'config') {+ return catalogueError('embedding_auth_failed',+ `${rejected}; the key in effect is ${source.config_key} in ${file} (${source.variable} is not set).`,+ `Run \`gbrain config set ${source.config_key} <valid key>\` and restart any daemon that uses it. ${backfill}`);+ }+ if (source.kind === 'missing') {+ return catalogueError('embedding_auth_failed', `${rejected}; ${source.variable} is not set in this process, so the key came from the caller's gateway configuration.`,+ `${source.config_key ? `Run \`gbrain config set ${source.config_key} <valid key>\`` : `Set ${source.variable} to a valid key in the environment of the process that reported this`}, restart that process, then run \`gbrain embed --stale\`.`);+ }+ const differs = source.shadows_config && source.config_key ? `, which differs from ${source.config_key} in ${file}` : '';+ const intended = source.config_key+ ? `If the environment key is intended, replace it with a valid key, restart, and run \`gbrain config unset ${source.config_key}\`.`+ : 'Replace it with a valid key and restart that process.';+ return catalogueError('embedding_auth_failed',+ `${rejected}; the key in effect is ${source.variable} from this process's environment${differs}.`,+ `${source.shadows_config ? `${removeVariable(source.variable)} ` : ''}${intended} ${backfill}`);+}++/** The HTTP status of a provider 401/403, from a fetch status or an SDK error (`statusCode`). */+function authFailureStatus(err: unknown): number | undefined {+ const e = err as { status?: unknown; statusCode?: unknown; apiErrorStatus?: unknown } | null;+ const status = [e?.status, e?.statusCode, e?.apiErrorStatus].find(value => typeof value === 'number');+ return status === 401 || status === 403 ? status : undefined;+}++/** Prints embedding_auth_failed for the first embedding 401/403 in this process; anything else is ignored. */+export function reportEmbeddingAuthFailure(provider: AuthFailedProvider, failure: unknown,+ fileCfg?: GBrainConfig | null, env?: Env): void {+ const status = authFailureStatus(failure);+ if (status === undefined || authFailureReported) return;+ authFailureReported = true;+ try {+ const error = embeddingAuthFailedError(provider, status, fileCfg === undefined ? loadConfigFileOnly() : fileCfg, env ?? process.env);+ sink(`[gbrain] Error [${error.code}]: ${error.message}\nFix: ${error.suggestion}\nDocs: ${error.docs}`);+ } catch { /* a diagnostic must never replace the provider error */ }+}diff --git a/src/core/ai/provider-env.ts b/src/core/ai/provider-env.tsindex ef68c7630f..7e4f2bdff1 100644--- a/src/core/ai/provider-env.ts+++ b/src/core/ai/provider-env.ts@@ -28,28 +28,49 @@import type { GBrainConfig } from '../config.ts';-export function mergedProviderEnv(- cfg: GBrainConfig | null,- env: Record<string, string | undefined> = process.env,-): Record<string, string> {- const fromConfig: Record<string, string> = {};- if (cfg?.openai_api_key) fromConfig.OPENAI_API_KEY = cfg.openai_api_key;- if (cfg?.anthropic_api_key) fromConfig.ANTHROPIC_API_KEY = cfg.anthropic_api_key;- if (cfg?.openrouter_api_key) fromConfig.OPENROUTER_API_KEY = cfg.openrouter_api_key;- if (cfg?.voyage_api_key) fromConfig.VOYAGE_API_KEY = cfg.voyage_api_key;- if (cfg?.dashscope_api_key) fromConfig.DASHSCOPE_API_KEY = cfg.dashscope_api_key;- if (cfg?.deepseek_api_key) fromConfig.DEEPSEEK_API_KEY = cfg.deepseek_api_key;+/**+ * File-plane API keys and the env variable each fills. The GEMINI_API_KEY+ * alias also fills GOOGLE_GENERATIVE_AI_API_KEY (see mergedProviderEnv).+ * TypeSafe has no config-plane key: TYPESAFE_API_KEY and its+ * JEV_TYPESAFE_API_KEY alias are read from the environment only.+ */+export const CONFIG_API_KEY_ENV = [+ ['openai_api_key', 'OPENAI_API_KEY'],+ ['anthropic_api_key', 'ANTHROPIC_API_KEY'],+ ['openrouter_api_key', 'OPENROUTER_API_KEY'],+ ['voyage_api_key', 'VOYAGE_API_KEY'],+ ['dashscope_api_key', 'DASHSCOPE_API_KEY'],+ ['deepseek_api_key', 'DEEPSEEK_API_KEY'],// Same seam for LiteLLM + Together, closed alongside litellm's chat// touchpoint (v0.42.61.0 made litellm a full chat provider, so the// config-plane gap started biting daemon/launchd/MCP contexts the same// way voyage's #2662 did).- if (cfg?.litellm_api_key) fromConfig.LITELLM_API_KEY = cfg.litellm_api_key;- if (cfg?.together_api_key) fromConfig.TOGETHER_API_KEY = cfg.together_api_key;- if (cfg?.google_api_key) fromConfig.GOOGLE_GENERATIVE_AI_API_KEY = cfg.google_api_key;+ ['litellm_api_key', 'LITELLM_API_KEY'],+ ['together_api_key', 'TOGETHER_API_KEY'],+ ['google_api_key', 'GOOGLE_GENERATIVE_AI_API_KEY'],// #4031: the Azure key was the only member of the group below left unfolded,// so a config.json-only setup failed every embed from keyless shells// (launchd/cron/MCP) while `config show` looked complete.- if (cfg?.azure_openai_api_key) fromConfig.AZURE_OPENAI_API_KEY = cfg.azure_openai_api_key;+ ['azure_openai_api_key', 'AZURE_OPENAI_API_KEY'],+] as const satisfies ReadonlyArray<readonly [keyof GBrainConfig, string]>;++const realEnv = (env: Record<string, string | undefined>, name: string): string | undefined =>+ env[name] === undefined || env[name] === '' ? undefined : env[name];++/** The env variable that supplies `name`'s value: the canonical name, or the GEMINI alias for Google. */+function suppliedBy(env: Record<string, string | undefined>, name: string): string {+ return name === 'GOOGLE_GENERATIVE_AI_API_KEY' && !realEnv(env, name) && realEnv(env, 'GEMINI_API_KEY') ? 'GEMINI_API_KEY' : name;+}++export function mergedProviderEnv(+ cfg: GBrainConfig | null,+ env: Record<string, string | undefined> = process.env,+): Record<string, string> {+ const fromConfig: Record<string, string> = {};+ for (const [configKey, name] of CONFIG_API_KEY_ENV) {+ const value = cfg?.[configKey];+ if (value) fromConfig[name] = value;+ }if (cfg?.azure_openai_endpoint) fromConfig.AZURE_OPENAI_ENDPOINT = cfg.azure_openai_endpoint;if (cfg?.azure_openai_deployment) fromConfig.AZURE_OPENAI_DEPLOYMENT = cfg.azure_openai_deployment;if (cfg?.azure_openai_use_entra) fromConfig.AZURE_OPENAI_USE_ENTRA = cfg.azure_openai_use_entra;@@ -63,3 +84,49 @@ export function mergedProviderEnv(}return merged;}++/** #5137: an env variable whose real value shadows a different config-plane key. Names only, never values. */+export interface ProviderKeyShadow {+ variable: string;+ config_key: string;+}++/**+ * #5137: every config-plane key that an environment value overrides with a+ * different value (env wins, as in mergedProviderEnv). Pure. `fileCfg` must be+ * the file-only config (`loadConfigFileOnly`): `loadConfig` already folds+ * OPENAI/ANTHROPIC/OPENROUTER env values into the config fields.+ */+export function providerKeyShadows(+ fileCfg: GBrainConfig | null,+ env: Record<string, string | undefined> = process.env,+): ProviderKeyShadow[] {+ const shadows: ProviderKeyShadow[] = [];+ for (const [configKey, name] of CONFIG_API_KEY_ENV) {+ const fromConfig = fileCfg?.[configKey];+ const variable = suppliedBy(env, name);+ const fromEnv = realEnv(env, variable);+ if (fromConfig && fromEnv && fromEnv !== fromConfig) shadows.push({ variable, config_key: configKey });+ }+ return shadows;+}++/** #5137: where the key a recipe reads from `name` comes from, by name only. */+export type ProviderKeySource =+ | { kind: 'env'; variable: string; config_key?: string; shadows_config: boolean }+ | { kind: 'config'; variable: string; config_key: string }+ | { kind: 'missing'; variable: string; config_key?: string };++export function providerKeySource(+ fileCfg: GBrainConfig | null,+ env: Record<string, string | undefined>,+ name: string,+): ProviderKeySource {+ const configKey = CONFIG_API_KEY_ENV.find(([, envName]) => envName === name)?.[0];+ const variable = suppliedBy(env, name);+ const fromEnv = realEnv(env, variable);+ const fromConfig = configKey ? fileCfg?.[configKey] : undefined;+ if (fromEnv) return { kind: 'env', variable, ...(configKey ? { config_key: configKey } : {}), shadows_config: !!fromConfig && fromConfig !== fromEnv };+ if (configKey && fromConfig) return { kind: 'config', variable, config_key: configKey };+ return { kind: 'missing', variable, ...(configKey ? { config_key: configKey } : {}) };+}