Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(agent): provider-neutral help + one truthiness parser for the gateway-loop toggle (#2753) (#3437)
Masa5ecab70a2172
diff --git a/src/commands/agent.ts b/src/commands/agent.tsindex f0a7e37ceb..deebbfc323 100644--- a/src/commands/agent.ts+++ b/src/commands/agent.ts@@ -66,7 +66,9 @@ USAGESUBMITTINGgbrain agent run <prompt>--subagent-def <name> Named plugin subagent (from GBRAIN_PLUGIN_PATH)- --model <id> Anthropic model id (defaults to sonnet)+ --model <id> Model id as provider:model (default: subagent tier model,+ anthropic:claude-sonnet-4-6). Non-Anthropic providers need+ agent.use_gateway_loop enabled — see NOTES below.--max-turns <n> Max assistant turns (default 20)--tools a,b,c Subset of registered tool names (comma list)--timeout-ms <n> Per-job wall-clock timeout@@ -87,9 +89,22 @@ VIEWING--since <spec> ISO-8601 timestamp OR relative ("5m","1h","2d")NOTES- Submitting subagent jobs is trusted-only; MCP submitters receive- permission_denied. The worker needs ANTHROPIC_API_KEY set, or the- first LLM turn of a claimed job fails.+ This CLI path is trusted-only. (Remote MCP callers reach subagents through+ the scoped submit_agent operation, not through this command.)++ By default the worker runs the legacy Anthropic-direct path, which needs an+ Anthropic key — from ANTHROPIC_API_KEY or from anthropic_api_key in+ ~/.gbrain/config.json — or the first LLM turn of a claimed job fails.++ To run --model on a non-Anthropic provider, enable the provider-neutral+ gateway loop first, then supply whatever credential that provider needs+ (an API key for most; some recipes use OAuth or a local endpoint):+ gbrain config set agent.use_gateway_loop true+ Accepted values: true / 1 / yes / on.++ The gateway loop needs a provider whose recipe supports chat WITH tool+ calling — not every recipe under src/core/ai/recipes/ qualifies. A model+ that cannot call tools is refused at job start with the reason named.`);}diff --git a/src/commands/doctor.ts b/src/commands/doctor.tsindex 79cc55ec65..04c77d6aae 100644--- a/src/commands/doctor.ts+++ b/src/commands/doctor.ts@@ -3111,9 +3111,9 @@ export async function checkSubagentCapability(engine: BrainEngine): Promise<Checconst { loadConfig } = await import('../core/config.ts');const cfg = loadConfig();const chatModel = cfg?.chat_model;+ const { isConfigTruthy } = await import('../core/config.ts');const gatewayLoopRaw = await engine.getConfig('agent.use_gateway_loop').catch(() => null);- const gatewayLoopEnabled = typeof gatewayLoopRaw === 'string'- && ['true', '1', 'yes', 'on'].includes(gatewayLoopRaw.trim().toLowerCase());+ const gatewayLoopEnabled = isConfigTruthy(gatewayLoopRaw);const { isAnthropicProvider } = await import('../core/model-config.ts');if (chatModel && !isAnthropicProvider(chatModel) && !process.env.ANTHROPIC_API_KEY && !gatewayLoopEnabled) {return {diff --git a/src/core/config.ts b/src/core/config.tsindex 190485d55a..590a936cab 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1085,6 +1085,27 @@ export const KNOWN_CONFIG_KEY_PREFIXES: readonly string[] = ['self_upgrade.', // v0.42 self-upgrade (mode, quiet_hours, state)];+/**+ * Canonical truthiness for DB-plane boolean config values (#2753).+ *+ * Config values arrive as opaque strings from `gbrain config set`, so every+ * reader has to decide what counts as "on". Left to each call site those sets+ * drift, and the drift is silent in the worst possible way: the doctor accepted+ * `yes`/`on` while the subagent worker accepted only `true`/`1`, so+ * `gbrain config set agent.use_gateway_loop yes` produced a healthy doctor+ * report AND a runtime refusal of the very job the setting was supposed to+ * enable. One parser, used by every reader, is what keeps a green health check+ * honest.+ *+ * Accepts `true` / `1` / `yes` / `on` (case-insensitive, surrounding whitespace+ * trimmed). Everything else — including `null`, non-strings, and the empty+ * string — is false, so an unset or garbled value fails closed.+ */+export function isConfigTruthy(raw: unknown): boolean {+ return typeof raw === 'string'+ && ['true', '1', 'yes', 'on'].includes(raw.trim().toLowerCase());+}+export function saveConfig(config: GBrainConfig): void {mkdirSync(getConfigDir(), { recursive: true });writeFileSync(getConfigPath(), JSON.stringify(config, null, 2) + '\n', { mode: 0o600 });diff --git a/src/core/minions/handlers/subagent.ts b/src/core/minions/handlers/subagent.tsindex d9102dacc3..a490900f3d 100644--- a/src/core/minions/handlers/subagent.ts+++ b/src/core/minions/handlers/subagent.ts@@ -36,7 +36,7 @@ import type {} from '../types.ts';import type { BrainEngine } from '../../engine.ts';import type { GBrainConfig } from '../../config.ts';-import { loadConfig } from '../../config.ts';+import { loadConfig, isConfigTruthy } from '../../config.ts';import { buildBrainTools, filterAllowedTools } from '../tools/brain-allowlist.ts';import {acquireLease,@@ -253,8 +253,10 @@ export function makeSubagentHandler(deps: SubagentDeps) {// provider in src/core/ai/recipes/). When OFF, route through the legacy// Anthropic-direct path AND refuse non-Anthropic models loudly.const useGatewayLoopRaw = await engine.getConfig('agent.use_gateway_loop').catch(() => null);- const useGatewayLoop = typeof useGatewayLoopRaw === 'string' &&- (useGatewayLoopRaw === 'true' || useGatewayLoopRaw === '1');+ // #2753: share the doctor's truthiness set. Before this, the doctor accepted+ // yes/on but the worker did not, so `config set ... yes` reported healthy+ // here and still refused the job below.+ const useGatewayLoop = isConfigTruthy(useGatewayLoopRaw);if (!useGatewayLoop && !isAnthropicProvider(model)) {throw new Error(`subagent job: resolved model "${model}" is non-Anthropic but agent.use_gateway_loop is not enabled. ` +diff --git a/test/config-set.test.ts b/test/config-set.test.tsindex d4abefbb3d..648d3b932b 100644--- a/test/config-set.test.ts+++ b/test/config-set.test.ts@@ -6,9 +6,16 @@* integration that calls `engine.setConfig` is exercised E2E in T12.*/-import { describe, test, expect } from 'bun:test';-import { KNOWN_CONFIG_KEYS, KNOWN_CONFIG_KEY_PREFIXES } from '../src/core/config.ts';+import { describe, test, expect, spyOn } from 'bun:test';+import { mkdtempSync, writeFileSync, mkdirSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { KNOWN_CONFIG_KEYS, KNOWN_CONFIG_KEY_PREFIXES, isConfigTruthy } from '../src/core/config.ts';import { suggestNearest } from '../src/core/levenshtein.ts';+import { runConfig } from '../src/commands/config.ts';+import { checkSubagentCapability } from '../src/commands/doctor.ts';+import { withEnv } from './helpers/with-env.ts';+import type { BrainEngine } from '../src/core/engine.ts';describe('KNOWN_CONFIG_KEYS', () => {test('contains the canonical embedding keys', () => {@@ -162,3 +169,112 @@ describe('prefix vs known-key gate logic (mirrored from runConfig)', () => {expect(gate('embedding.dimensions')).toBe('unknown');});});++describe('#2753 — the doctor-proposed gateway-loop command is accepted by `config set`', () => {+ // Pre-fix: `gbrain doctor --full` told users to run `gbrain config set+ // agent.use_gateway_loop true`, but the key wasn't in KNOWN_CONFIG_KEYS,+ // so the exact command doctor recommended failed with "Unknown config+ // key" (or silently no-opped under --force with a false "nothing reads+ // this" warning). This test drives `checkSubagentCapability` (the doctor+ // check that emits the recommendation) end to end, extracts the literal+ // command from its message, and feeds it into the real `runConfig` CLI+ // entry point — so a future edit that lets the two drift apart again+ // fails here instead of shipping.+ const home = mkdtempSync(join(tmpdir(), 'gbrain-config-set-'));+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(+ join(home, '.gbrain', 'config.json'),+ JSON.stringify({ engine: 'pglite', chat_model: 'openai:gpt-5' }),+ );++ function doctorStubEngine(): BrainEngine {+ // models.tier.subagent, models.default, agent.use_gateway_loop: all unset.+ return { getConfig: async () => null } as unknown as BrainEngine;+ }++ function setStubEngine(): { engine: BrainEngine; setCalls: Array<[string, string]> } {+ const setCalls: Array<[string, string]> = [];+ const engine = {+ getConfig: async () => null,+ setConfig: async (key: string, value: string) => { setCalls.push([key, value]); },+ } as unknown as BrainEngine;+ return { engine, setCalls };+ }++ /** Run `runConfig(engine, args)`, capturing console output + exit code+ * the way `config-get-plane.test.ts` does for the `get` subcommand. */+ async function runConfigCapture(+ engine: BrainEngine,+ args: string[],+ ): Promise<{ logs: string[]; errs: string[]; exit: number | null }> {+ const logs: string[] = [];+ const errs: string[] = [];+ let exit: number | null = null;+ const logSpy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { logs.push(a.join(' ')); });+ const errSpy = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { errs.push(a.join(' ')); });+ const exitSpy = spyOn(process, 'exit').mockImplementation(((code?: number) => {+ exit = code ?? 0;+ throw new Error(`EXIT:${code}`);+ }) as never);+ try {+ await runConfig(engine, args);+ } catch (e) {+ if (!(e as Error).message.startsWith('EXIT:')) throw e;+ } finally {+ logSpy.mockRestore();+ errSpy.mockRestore();+ exitSpy.mockRestore();+ }+ return { logs, errs, exit };+ }++ test('doctor-proposed command round-trips through `config set` without --force', async () => {+ const check = await withEnv(+ { GBRAIN_HOME: home, GBRAIN_CHAT_MODEL: undefined, ANTHROPIC_API_KEY: undefined },+ () => checkSubagentCapability(doctorStubEngine()),+ );+ expect(check.status).toBe('warn');+ expect(check.message).toContain('agent.use_gateway_loop');++ // Pull the exact backtick-quoted command out of the doctor message+ // instead of hardcoding it, so the two call sites can't silently drift.+ const match = check.message.match(/`(gbrain config set [^`]+)`/);+ expect(match).not.toBeNull();++ // Tokenize the WHOLE command and feed every argument through, rather than+ // destructuring the first two and dropping the rest. If doctor ever starts+ // recommending a trailing `--force`, that has to fail here — the entire+ // point of #2753 is that the recommended command works without it.+ const tokens = match![1].trim().split(/\s+/);+ expect(tokens.slice(0, 3)).toEqual(['gbrain', 'config', 'set']);+ expect(tokens).not.toContain('--force');+ const args = tokens.slice(1); // ['config','set',key,value,...]+ expect(args).toEqual(['config', 'set', 'agent.use_gateway_loop', 'true']);++ const { engine, setCalls } = setStubEngine();+ const { logs, errs, exit } = await runConfigCapture(engine, args.slice(1));+ expect(exit).toBeNull();+ expect(errs.join('\n')).not.toContain('Unknown config key');+ expect(errs.join('\n')).not.toContain('Nothing in gbrain reads this');+ expect(setCalls).toEqual([['agent.use_gateway_loop', 'true']]);+ expect(logs.join('\n')).toContain('Set agent.use_gateway_loop = true');+ });+});++describe('#2753 — doctor and the subagent worker share one truthiness set', () => {+ // The doctor accepted true/1/yes/on; the worker accepted only true/1. So+ // `gbrain config set agent.use_gateway_loop yes` produced a HEALTHY doctor+ // report and a runtime refusal of the exact job the setting enables. Both+ // now route through isConfigTruthy, so this asserts the shared contract.+ test('accepts the documented on-values, case- and whitespace-insensitively', () => {+ for (const v of ['true', '1', 'yes', 'on', 'TRUE', 'Yes', 'ON', ' true ', '\tyes\n']) {+ expect(isConfigTruthy(v)).toBe(true);+ }+ });++ test('fails closed on unset, non-string, and anything else', () => {+ for (const v of [null, undefined, '', ' ', 'false', '0', 'no', 'off', 'maybe', 1, true, {}]) {+ expect(isConfigTruthy(v)).toBe(false);+ }+ });+});