Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(cycle): keyless skip for any keyed chat provider in propose_takes and patterns (#6705)

time-attackcde24c9d8f43
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.md
index 94e80f48f5..a826ed6ad5 100644
--- a/docs/architecture/key-files/core-ai.md
+++ b/docs/architecture/key-files/core-ai.md
@@ -33,6 +33,7 @@ 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. #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.test.ts`.
+- `src/core/ai/chat-key-probe.ts` — `probeChatModelWithKey(model)`: `probeChatModel` plus an up-front key check for every keyed provider (recipe `auth_env.required` against `mergedProviderEnv` over process env, the gateway env snapshot and the config file; Anthropic keeps `probeChatModel`'s check; keyless recipes pass). The hint names `gbrain config set <key>` only when `CONFIG_API_KEY_ENV` has one. Used by the propose_takes and patterns cheap keyless skips (#6705); `probeChatModel` keeps its lazy A9 contract. Pinned by `test/ai/gateway-probe-chat-model.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.
diff --git a/src/core/ai/chat-key-probe.ts b/src/core/ai/chat-key-probe.ts
new file mode 100644
index 0000000000..1e0778eae4
--- /dev/null
+++ b/src/core/ai/chat-key-probe.ts
@@ -0,0 +1,57 @@
+/**
+ * Provider-agnostic chat-model probe for phases that promise a cheap keyless
+ * skip (#6705): id-validity plus the resolved recipe's `auth_env.required`
+ * keys. Kept out of gateway.ts so the gateway module stays inside its size
+ * ratchet.
+ *
+ * Deliberately NOT folded into `probeChatModel`: its lazy non-Anthropic
+ * behavior is a pinned contract (A9, test/ai/gateway-probe-chat-model.test.ts)
+ * that lets a keyless judge build a client and fail per transcript.
+ */
+
+import { loadConfig } from '../config.ts';
+import { probeChatModel, requireConfig, validateModelId, type ChatModelProbe } from './gateway.ts';
+import { CONFIG_API_KEY_ENV, mergedProviderEnv } from './provider-env.ts';
+
+function gatewayEnv(): Record<string, string | undefined> {
+ try {
+ return requireConfig().env ?? {};
+ } catch {
+ return {};
+ }
+}
+
+/**
+ * Like `probeChatModel`, but every keyed provider is checked up front: the key
+ * planes are process env, the live gateway env snapshot and the config file
+ * (via `mergedProviderEnv`). Anthropic keeps `probeChatModel`'s own check; a
+ * recipe with no required key (ollama, llama-server, litellm, claude-cli)
+ * passes. The hint names `gbrain config set <key>` only for env variables
+ * that have a config-file key.
+ */
+export function probeChatModelWithKey(modelStr: string): ChatModelProbe {
+ const base = probeChatModel(modelStr);
+ if (!base.ok) return base;
+ const v = validateModelId(modelStr);
+ if (!v.ok || v.parsed.providerId === 'anthropic') return base;
+ const required = v.recipe?.auth_env?.required ?? [];
+ if (required.length === 0) return base;
+
+ const env = { ...process.env, ...gatewayEnv() };
+ let merged: Record<string, string>;
+ try {
+ merged = mergedProviderEnv(loadConfig(), env);
+ } catch {
+ merged = mergedProviderEnv(null, env);
+ }
+ const missing = required.filter(name => !merged[name]);
+ if (missing.length === 0) return base;
+
+ const configKeys = missing.flatMap(name => CONFIG_API_KEY_ENV.filter(([, envName]) => envName === name).map(([key]) => key));
+ const configHint = configKeys.length ? ` or run: ${configKeys.map(key => `gbrain config set ${key} ...`).join(' / ')}` : '';
+ return {
+ ok: false,
+ reason: 'unavailable',
+ detail: `no ${v.recipe?.name ?? v.parsed.providerId} API key configured (set ${missing.join(' / ')}${configHint})`,
+ };
+}
diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.ts
index aada7543d2..a522dd3c16 100644
--- a/src/core/cycle/patterns.ts
+++ b/src/core/cycle/patterns.ts
@@ -43,7 +43,7 @@ import type { Page, PageType } from '../types.ts';
// drains its own children the same way.
import { loadAllowedSlugPrefixes, loadOutputRoot, runSubagentsInline } from './synthesize.ts';
import { stampDreamProvenance } from './dream-provenance.ts';
-import { probeChatModel } from '../ai/gateway.ts';
+import { probeChatModelWithKey } from '../ai/chat-key-probe.ts';
import { normalizeModelId } from '../model-id.ts';
import { throwIfAborted } from '../abort-check.ts';
import { resolveCycleDate } from './cycle-date.ts';
@@ -227,13 +227,13 @@ async function runPatternsPass(engine: BrainEngine, opts: PatternsPhaseOpts, con
// hardcoded env gate misclassified non-Anthropic stacks (litellm,
// deepseek, openrouter, ...) as "no upstream" even though the subagent
// routes them through the gateway (agent.use_gateway_loop), and it missed
- // Anthropic keys set via `gbrain config set anthropic_api_key`. Same
- // probe semantics as think/index.ts + synthesize's makeJudgeClient:
- // unknown provider/model or Anthropic-without-key skips cheaply; other
- // providers' auth is checked lazily at dispatch and surfaces in the job
- // outcome. (Takeover of PR #2279's intent by @brettdavies.)
+ // Anthropic keys set via `gbrain config set anthropic_api_key`. Unknown
+ // provider/model or any keyed provider without its key skips cheaply
+ // (#6705: probeChatModelWithKey, not the lazy probeChatModel, so a keyless
+ // non-Anthropic model never submits a subagent that fails at dispatch).
+ // (Takeover of PR #2279's intent by @brettdavies.)
const maintenance = await maintenancePreflight(engine, opts.sourceId ?? 'default', opts.brainDir);
- const probe = probeChatModel(normalizeModelId(config.model));
+ const probe = probeChatModelWithKey(normalizeModelId(config.model));
if (!probe.ok) {
return skipped('no_provider', `pattern detection skipped: ${probe.detail}`);
}
diff --git a/src/core/cycle/propose-takes.ts b/src/core/cycle/propose-takes.ts
index 52493052cc..ca944e23f1 100644
--- a/src/core/cycle/propose-takes.ts
+++ b/src/core/cycle/propose-takes.ts
@@ -45,7 +45,8 @@ import { defaultTimeoutMsFor } from '../minions/handler-timeouts.ts';
import {
PROPOSE_TAKES_CALL_TIMEOUT_KEY, PROPOSE_TAKES_CALL_TIMEOUT_MAX_MS, PROPOSE_TAKES_CALL_TIMEOUT_MIN_MS, readPhaseConfigNumber,
} from './phase-config-values.ts';
-import { chat as gatewayChat, getChatModel, probeChatModel } from '../ai/gateway.ts';
+import { chat as gatewayChat, getChatModel } from '../ai/gateway.ts';
+import { probeChatModelWithKey } from '../ai/chat-key-probe.ts';
import { createGlobalLlmHaltTracker, haltedClassOf, type GlobalLlmErrorClass } from '../ai/errors.ts';
import { normalizeModelId } from '../model-id.ts';
import { writeReceipt } from '../extract/receipt-writer.ts';
@@ -832,13 +833,12 @@ class ProposeTakesPhase extends BaseCyclePhase {
const callTimeout = await readPhaseConfigNumber(engine, PROPOSE_TAKES_CALL_TIMEOUT_KEY); // #5874
// With the default (gateway) extractor, skip cheaply when the resolved
- // model's provider can't run — same probe semantics as patterns.ts /
- // think/index.ts: unknown provider/model or Anthropic-without-key skips;
- // other providers' auth surfaces lazily at chat() time. An injected
+ // model's provider can't run: unknown provider/model, or any keyed provider
+ // without its key (#6705; same probe as patterns.ts). An injected
// extractor bypasses the gateway, so it is never gated. (Takeover of
// PR #1979's intent by @shawnduggan.)
if (!opts.extractor) {
- const probe = probeChatModel(normalizeModelId(modelId));
+ const probe = probeChatModelWithKey(normalizeModelId(modelId));
if (!probe.ok) {
return {
summary: `propose_takes skipped: ${probe.detail}`,
diff --git a/test/ai/gateway-probe-chat-model.test.ts b/test/ai/gateway-probe-chat-model.test.ts
index 2c16130c2a..b31273d046 100644
--- a/test/ai/gateway-probe-chat-model.test.ts
+++ b/test/ai/gateway-probe-chat-model.test.ts
@@ -16,6 +16,7 @@ import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { validateModelId, probeChatModel, configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';
+import { probeChatModelWithKey } from '../../src/core/ai/chat-key-probe.ts';
import { normalizeModelId } from '../../src/core/model-id.ts';
import { withEnv } from '../helpers/with-env.ts';
@@ -158,3 +159,69 @@ describe('probeChatModel gateway-env snapshot (#2119)', () => {
}
});
});
+
+describe('probeChatModelWithKey (provider-agnostic key check, #6705)', () => {
+ const noOpenAiKey = () => ({ OPENAI_API_KEY: undefined, GBRAIN_HOME: emptyHome() });
+
+ test('unavailable: keyed non-Anthropic provider with no key names the env var and its config key', async () => {
+ await withEnv(noOpenAiKey(), async () => {
+ expect(probeChatModelWithKey('openai:gpt-5.6')).toEqual({
+ ok: false, reason: 'unavailable',
+ detail: 'no OpenAI API key configured (set OPENAI_API_KEY or run: gbrain config set openai_api_key ...)',
+ });
+ });
+ });
+
+ test('a provider with no config-file key names only the env var', async () => {
+ await withEnv({ MINIMAX_API_KEY: undefined, GBRAIN_HOME: emptyHome() }, async () => {
+ const p = probeChatModelWithKey('minimax:MiniMax-M2.7');
+ expect(p.ok).toBe(false);
+ if (!p.ok) {
+ expect(p.detail).toContain('set MINIMAX_API_KEY)');
+ expect(p.detail).not.toContain('gbrain config set');
+ }
+ });
+ });
+
+ test('ok: keyed non-Anthropic provider with the key in env', async () => {
+ await withEnv({ OPENAI_API_KEY: 'sk-test', GBRAIN_HOME: emptyHome() }, async () => {
+ expect(probeChatModelWithKey('openai:gpt-5.6').ok).toBe(true);
+ });
+ });
+
+ test('ok: key present only in the gateway env snapshot', async () => {
+ await withEnv(noOpenAiKey(), async () => {
+ configureGateway({ chat_model: 'openai:gpt-5.6', env: { OPENAI_API_KEY: 'sk-test' } });
+ try {
+ expect(probeChatModelWithKey('openai:gpt-5.6').ok).toBe(true);
+ } finally {
+ resetGateway();
+ }
+ });
+ });
+
+ test('ok: a local recipe with no declared key passes keyless', async () => {
+ await withEnv(noOpenAiKey(), async () => {
+ expect(probeChatModelWithKey('ollama:qwen2.5-coder:14b').ok).toBe(true);
+ });
+ });
+
+ test('anthropic keeps probeChatModel\'s answer', async () => {
+ await withEnv(noKeyEnv(), async () => {
+ expect(probeChatModelWithKey(REAL)).toEqual(probeChatModel(REAL));
+ expect(probeChatModelWithKey(REAL).ok).toBe(false);
+ });
+ });
+
+ test('validity still runs first: unknown provider classifies regardless of keys', () => {
+ const p = probeChatModelWithKey('bogusprovider:whatever');
+ expect(p.ok).toBe(false);
+ if (!p.ok) expect(p.reason).toBe('unknown_provider');
+ });
+
+ test('probeChatModel keeps its lazy non-Anthropic contract (A9)', async () => {
+ await withEnv(noOpenAiKey(), async () => {
+ expect(probeChatModel('openai:gpt-5.6').ok).toBe(true);
+ });
+ });
+});
diff --git a/test/cycle-patterns.test.ts b/test/cycle-patterns.test.ts
index 69bef2e5a3..4b6e6673c8 100644
--- a/test/cycle-patterns.test.ts
+++ b/test/cycle-patterns.test.ts
@@ -155,6 +155,25 @@ describe('patterns provider gate (PR #2279)', () => {
expect(r.details.reason).toBe('insufficient_cycle_budget');
});
+ test('a keyed non-Anthropic model with no key skips as no_provider before any submission (#6705)', async () => {
+ await seed(reflections(3));
+ await engine.setConfig('models.dream.patterns', 'openai:gpt-5.4');
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-patterns-keyless-'));
+ try {
+ const r = await noKeys(
+ () => runPhasePatterns(engine, { brainDir: '/tmp', dryRun: false, deadlineAtMs: Date.now() + 600_000 }),
+ { GBRAIN_HOME: home },
+ );
+ expect(r.status).toBe('skipped');
+ expect(r.details.reason).toBe('no_provider');
+ expect(r.summary).toContain('OPENAI_API_KEY');
+ const [jobs] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM minion_jobs');
+ expect(jobs.n).toBe(0);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
test('a bare model id is normalized to its provider before probing', async () => {
await seed(reflections(3));
await engine.setConfig('models.dream.patterns', 'claude-sonnet-4-6');
diff --git a/test/propose-takes.test.ts b/test/propose-takes.test.ts
index abaf721fd3..fc5ef3826f 100644
--- a/test/propose-takes.test.ts
+++ b/test/propose-takes.test.ts
@@ -687,6 +687,25 @@ New prose appended here.`;
});
});
+ test('default extractor skips cleanly when a non-Anthropic chat model has no key (#6705)', async () => {
+ await withEnv({ GBRAIN_HOME: emptyHome(), OPENAI_API_KEY: undefined }, async () => {
+ configureGateway({ chat_model: 'openai:gpt-5.6', env: {} });
+ try {
+ const { engine, captured } = buildMockEngine({
+ pages: [buildPage({ slug: 'wiki/c', body: 'claim-ish prose' })],
+ });
+ const result = await runPhaseProposeTakes(buildCtx(engine));
+
+ expect(result.status).toBe('skipped');
+ expect((result.details as Record<string, unknown>).reason).toBe('no_provider');
+ expect(result.summary).toContain('OPENAI_API_KEY');
+ expect(captured).toHaveLength(0);
+ } finally {
+ resetGateway();
+ }
+ });
+ });
+
test('an injected extractor is never gated on provider availability', async () => {
await withEnv({ GBRAIN_HOME: emptyHome(), ANTHROPIC_API_KEY: undefined }, async () => {
configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: {} });