Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(init,mcp): seed init AI options from env on cold install; whoami reports stdio transport (#3091)
Time Attakc872d4eebb51f
diff --git a/src/commands/init.ts b/src/commands/init.tsindex 5e64292934..14e33f6cfe 100644--- a/src/commands/init.ts+++ b/src/commands/init.ts@@ -161,7 +161,7 @@ interface ResolveAIOptionsArgs {nonInteractive: boolean; // --non-interactive (forces D3 fail-loud, no picker)}-interface ResolvedAIOptions {+export interface ResolvedAIOptions {embedding_model?: string;embedding_dimensions?: number;expansion_model?: string;@@ -170,6 +170,41 @@ interface ResolvedAIOptions {noEmbedding?: boolean;}+/**+ * Seed init's AI options from persisted config, falling back to the raw env+ * vars when loadConfig() returned null (#1058). On a cold install (no+ * config.json AND no DATABASE_URL) loadConfig short-circuits BEFORE its env+ * merge, so GBRAIN_EMBEDDING_MODEL / GBRAIN_EMBEDDING_DIMENSIONS /+ * GBRAIN_EXPANSION_MODEL / GBRAIN_CHAT_MODEL were silently ignored by init+ * and Tier-3 detection auto-picked by API key instead. Exported for unit+ * tests (env injectable).+ */+export function seedAIOptionsFromConfig(+ cfg: GBrainConfig | null,+ env: NodeJS.ProcessEnv = process.env,+): ResolvedAIOptions {+ const envDims = env.GBRAIN_EMBEDDING_DIMENSIONS+ ? parseInt(env.GBRAIN_EMBEDDING_DIMENSIONS, 10)+ : NaN;+ const seed = cfg ?? {+ embedding_disabled: undefined,+ embedding_model: env.GBRAIN_EMBEDDING_MODEL,+ embedding_dimensions: Number.isFinite(envDims) ? envDims : undefined,+ expansion_model: env.GBRAIN_EXPANSION_MODEL,+ chat_model: env.GBRAIN_CHAT_MODEL,+ };+ const out: ResolvedAIOptions = {};+ if (seed.embedding_disabled) {+ out.noEmbedding = true;+ } else if (seed.embedding_model) {+ out.embedding_model = seed.embedding_model;+ if (seed.embedding_dimensions) out.embedding_dimensions = seed.embedding_dimensions;+ }+ if (seed.expansion_model) out.expansion_model = seed.expansion_model;+ if (seed.chat_model) out.chat_model = seed.chat_model;+ return out;+}+/*** Resolve AI provider options for `gbrain init`.*@@ -203,18 +238,13 @@ async function resolveAIOptions(opts: ResolveAIOptionsArgs): Promise<ResolvedAIO// user already opted into deferred mode.try {const { loadConfig } = await import('../core/config.ts');- const cfg = loadConfig();- if (cfg?.embedding_disabled) {- out.noEmbedding = true;- } else if (cfg?.embedding_model) {- out.embedding_model = cfg.embedding_model;- if (cfg.embedding_dimensions) out.embedding_dimensions = cfg.embedding_dimensions;- }- if (cfg?.expansion_model) out.expansion_model = cfg.expansion_model;- if (cfg?.chat_model) out.chat_model = cfg.chat_model;+ // #1058: loadConfig() returns null on a cold install (no config.json AND+ // no DATABASE_URL) — before it ever reaches its env merge. The seed helper+ // falls back to the same GBRAIN_* env vars directly in that case.+ Object.assign(out, seedAIOptionsFromConfig(loadConfig()));} catch {- // loadConfig throws when no brain configured — first-time install, fall- // through to env detection.+ // loadConfig threw — treat as first-time install, fall through to env+ // detection.}// --- Tier 1+2: explicit flags ---------------------------------------------diff --git a/src/core/operations.ts b/src/core/operations.tsindex ca442c6876..c8940d0376 100644--- a/src/core/operations.ts+++ b/src/core/operations.ts@@ -331,6 +331,15 @@ export interface OperationContext {* remote/untrusted (defense in depth in case the type is bypassed via cast).*/remote: boolean;+ /**+ * Transport marker for auth-less remote surfaces (#1061). The stdio MCP+ * dispatch sets 'stdio' — it is deliberately `remote: true` (agent-facing,+ * untrusted) but has no per-token auth (local pipe), so identity ops like+ * whoami need a way to distinguish "known auth-less transport" from "a+ * transport bug forgot to thread ctx.auth". Trust decisions MUST NOT key+ * off this field — only `ctx.remote === false` grants trust.+ */+ transport?: 'stdio';/*** Subagent runtime context (v0.16+). Set by the subagent tool dispatcher when* dispatching an op as a tool call from an LLM loop. Used to enforce per-op@@ -3756,9 +3765,10 @@ const whoami: Operation = {'Introspect the calling identity. Returns one of three transport shapes: ' +'{transport: "oauth", client_id, client_name, scopes, expires_at}, ' +'{transport: "legacy", token_name, scopes, expires_at: null}, or ' +- '{transport: "local", scopes: []}. Throws unknown_transport when the ' +- 'context is ambiguous (remote=true without auth) — fail-closed posture ' +- 'mirroring the v0.26.9 trust-boundary contract.',+ '{transport: "local", scopes: []}, or {transport: "stdio", scopes: []} ' ++ 'for the auth-less stdio MCP pipe. Throws unknown_transport when the ' ++ 'context is ambiguous (remote=true without auth and no transport marker) ' ++ '— fail-closed posture mirroring the v0.26.9 trust-boundary contract.',params: {},scope: 'read',handler: async (ctx) => {@@ -3770,6 +3780,12 @@ const whoami: Operation = {if (ctx.remote === false) {return { transport: 'local', scopes: [] };}+ // #1061: stdio MCP is remote/untrusted by design but has no per-token+ // auth (local pipe) — a known transport, not a bug. Report it instead of+ // throwing. Empty scopes: nothing here may be used to gate anything.+ if (!ctx.auth && ctx.transport === 'stdio') {+ return { transport: 'stdio', scopes: [] };+ }if (!ctx.auth) {throw new OperationError('unknown_transport',diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 4840fc565d..a37e23c92c 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -32,6 +32,12 @@ export interface DispatchOpts {remote?: boolean;/** Override the default stderr logger (e.g. CLI uses console.* directly). */logger?: OperationContext['logger'];+ /**+ * #1061: transport marker for auth-less remote surfaces. The stdio MCP+ * server passes 'stdio' so identity ops (whoami) can report the transport+ * instead of throwing unknown_transport. Never used for trust decisions.+ */+ transport?: OperationContext['transport'];/*** v0.28: per-token allow-list for the takes.holder field. Threaded by* the HTTP/stdio transport from `access_tokens.permissions.takes_holders`.@@ -203,6 +209,7 @@ export function buildOperationContext(logger: opts.logger || stderrLogger,dryRun: !!params.dry_run,remote: opts.remote ?? true,+ transport: opts.transport,takesHoldersAllowList: opts.takesHoldersAllowList,// v0.34 D4: sourceId is REQUIRED at the type level. Auto-fill 'default'// for single-source brains and any caller who didn't resolve a sourceId.diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex ae5ab4c3fe..6f98b01dcf 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -42,6 +42,10 @@ export async function startMcpServer(engine: BrainEngine) {// `gbrain call <op>` (sets remote=false in src/cli.ts).return dispatchToolCall(engine, name, params, {remote: true,+ // #1061: mark the transport so whoami can report {transport: 'stdio'}+ // instead of throwing unknown_transport. Trust posture unchanged —+ // stdio stays remote/untrusted.+ transport: 'stdio',takesHoldersAllowList: ['world'],// v0.31: source defaults to 'default' for stdio (no per-token scope).// Operators who want a different source on stdio MCP should setdiff --git a/test/init-env-detection.test.ts b/test/init-env-detection.test.tsindex ed17217732..8b4359a890 100644--- a/test/init-env-detection.test.ts+++ b/test/init-env-detection.test.ts@@ -12,7 +12,7 @@*/import { describe, test, expect } from 'bun:test';-import { groupReadyByProvider, findEnvKeyTypos } from '../src/commands/init.ts';+import { groupReadyByProvider, findEnvKeyTypos, seedAIOptionsFromConfig } from '../src/commands/init.ts';describe('groupReadyByProvider — embedding touchpoint', () => {test('OPENAI_API_KEY alone → openai is ready', async () => {@@ -149,3 +149,47 @@ describe('findEnvKeyTypos', () => {expect(got.find(t => t.userSet === 'COMPLETELY_UNRELATED_KEY')).toBeUndefined();});});++describe('seedAIOptionsFromConfig — #1058 cold-install env fallback', () => {+ test('null config (no config.json, no DATABASE_URL) falls back to GBRAIN_* env vars', () => {+ const got = seedAIOptionsFromConfig(null, {+ GBRAIN_EMBEDDING_MODEL: 'voyage:voyage-3-large',+ GBRAIN_EMBEDDING_DIMENSIONS: '1024',+ GBRAIN_EXPANSION_MODEL: 'openai:gpt-5-mini',+ GBRAIN_CHAT_MODEL: 'anthropic:claude-sonnet-4-6',+ });+ expect(got.embedding_model).toBe('voyage:voyage-3-large');+ expect(got.embedding_dimensions).toBe(1024);+ expect(got.expansion_model).toBe('openai:gpt-5-mini');+ expect(got.chat_model).toBe('anthropic:claude-sonnet-4-6');+ });++ test('null config + no env vars → empty seed (Tier-3 detection takes over)', () => {+ const got = seedAIOptionsFromConfig(null, {});+ expect(got).toEqual({});+ });++ test('persisted config wins (loadConfig already merged env when non-null)', () => {+ const got = seedAIOptionsFromConfig(+ { engine: 'pglite', embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536 } as any,+ { GBRAIN_EMBEDDING_MODEL: 'voyage:voyage-3-large' },+ );+ expect(got.embedding_model).toBe('openai:text-embedding-3-small');+ expect(got.embedding_dimensions).toBe(1536);+ });++ test('embedding_disabled sentinel honored on re-init', () => {+ const got = seedAIOptionsFromConfig({ engine: 'pglite', embedding_disabled: true } as any, {});+ expect(got.noEmbedding).toBe(true);+ expect(got.embedding_model).toBeUndefined();+ });++ test('non-numeric GBRAIN_EMBEDDING_DIMENSIONS ignored, model still seeds', () => {+ const got = seedAIOptionsFromConfig(null, {+ GBRAIN_EMBEDDING_MODEL: 'voyage:voyage-3-large',+ GBRAIN_EMBEDDING_DIMENSIONS: 'not-a-number',+ });+ expect(got.embedding_model).toBe('voyage:voyage-3-large');+ expect(got.embedding_dimensions).toBeUndefined();+ });+});diff --git a/test/whoami.test.ts b/test/whoami.test.tsindex 53d0c150ca..73aef61711 100644--- a/test/whoami.test.ts+++ b/test/whoami.test.ts@@ -94,6 +94,35 @@ describe('whoami op contract', () => {expect(result.expires_at).toBeNull();});+ // #1061: stdio MCP is remote/untrusted by design but has no per-token auth+ // (local pipe). The stdio dispatch marks ctx.transport='stdio'; whoami+ // reports it instead of throwing unknown_transport.+ test('stdio transport (remote=true, no auth, transport marker) reports stdio', async () => {+ const result = (await whoami.handler(+ ctxWith({ remote: true, auth: undefined, transport: 'stdio' }),+ {},+ )) as any;+ expect(result.transport).toBe('stdio');+ expect(result.scopes).toEqual([]);+ });++ test('stdio marker does not mask real auth (auth still wins)', async () => {+ const result = (await whoami.handler(+ ctxWith({+ remote: true,+ transport: 'stdio',+ auth: {+ token: 'gbrain_at_xxx',+ clientId: 'gbrain_cl_abc',+ scopes: ['read'],+ expiresAt: 1,+ } as AuthInfo,+ }),+ {},+ )) as any;+ expect(result.transport).toBe('oauth');+ });+// Q3: ambiguous transport — fail-closed. The footgun this guards against// is a future transport that lands without threading auth, where a buggy// caller might trust whoami's output to gate sensitive ops.