Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: pre-landing review fixes
garrytan05c320febb93
diff --git a/src/core/ai/anthropic-key.ts b/src/core/ai/anthropic-key.tsindex 00a037ec14..49f7c67ebe 100644--- a/src/core/ai/anthropic-key.ts+++ b/src/core/ai/anthropic-key.ts@@ -26,6 +26,7 @@import { loadConfig } from '../config.ts';import { embeddedSettingsRecord } from '../embedded-engine.ts';import { embeddedEngineInScope } from '../engine-scope.ts';+import { engineScopeMissing } from './engine-gateway.ts';/** In an embedded engine's scope (engine-scope.ts): its own `settings.ai` Anthropic key, or null. Undefined outside one. */function engineAnthropicKey(): string | null | undefined {@@ -78,6 +79,19 @@ export function getGatewayAnthropicKeySnapshot(): string | undefined {return _gatewayEnvKeySnapshot;}+/**+ * The options a directly built Anthropic client takes (the legacy subagent path). In an embedded engine's scope, that+ * engine's own key and endpoint, because the SDK falls back to process.env for anything it is not given; an engine+ * without an Anthropic provider refuses `engine_scope_missing`.+ */+export function anthropicClientOptions(): { apiKey?: string; baseURL?: string } {+ const engine = embeddedEngineInScope();+ if (!engine) return { apiKey: resolveAnthropicKey() };+ const provider = embeddedSettingsRecord(engine)?.ai?.providers.anthropic;+ if (!provider?.apiKey) throw engineScopeMissing('anthropic', 'chat');+ return { apiKey: provider.apiKey, baseURL: (provider.baseUrl ?? 'https://api.anthropic.com').replace(/\/+$/, '').replace(/\/v1$/, '') };+}+export function hasAnthropicKey(): boolean {return resolveAnthropicKey() !== undefined;}diff --git a/src/core/ai/engine-gateway.ts b/src/core/ai/engine-gateway.tsindex 21c49a645f..eb80ac951d 100644--- a/src/core/ai/engine-gateway.ts+++ b/src/core/ai/engine-gateway.ts@@ -10,10 +10,11 @@ import { DEFAULT_EMBEDDING_DIMENSIONS, DEFAULT_EMBEDDING_MODEL } from './defaultimport { getRecipe } from './recipes/index.ts';import type { AIGatewayConfig, Recipe } from './types.ts';-const NATIVE_BASE_URL_ENV: Partial<Record<Recipe['implementation'], string>> = {- 'native-openai': 'OPENAI_BASE_URL',- 'native-anthropic': 'ANTHROPIC_BASE_URL',- 'native-google': 'GOOGLE_GENERATIVE_AI_BASE_URL',+/** Each native SDK reads its base URL from this env name when it is not given one, so an engine always gives one. */+const NATIVE_BASE_URL: Partial<Record<Recipe['implementation'], { env: string; url: string }>> = {+ 'native-openai': { env: 'OPENAI_BASE_URL', url: 'https://api.openai.com/v1' },+ 'native-anthropic': { env: 'ANTHROPIC_BASE_URL', url: 'https://api.anthropic.com/v1' },+ 'native-google': { env: 'GOOGLE_GENERATIVE_AI_BASE_URL', url: 'https://generativelanguage.googleapis.com/v1beta' },};/** The env name the gateway reads a recipe's API key from; undefined for a recipe that takes none. */@@ -43,10 +44,9 @@ export function engineGatewayInput(settings: EngineSettings): { config: AIGatewaconst recipe = getRecipe(id)!;const keyEnv = recipeKeyEnv(recipe);if (provider.apiKey && keyEnv) env[keyEnv] = provider.apiKey;- if (!provider.baseUrl) continue;- const nativeEnv = NATIVE_BASE_URL_ENV[recipe.implementation];- if (nativeEnv) env[nativeEnv] = provider.baseUrl;- else base_urls[id] = provider.baseUrl;+ const native = NATIVE_BASE_URL[recipe.implementation];+ if (native) env[native.env] = provider.baseUrl ?? native.url;+ else if (provider.baseUrl) base_urls[id] = provider.baseUrl;}const models = settings.ai?.models ?? {};return {diff --git a/src/core/minions/handlers/subagent.ts b/src/core/minions/handlers/subagent.tsindex 113463cacb..a01f705a1e 100644--- a/src/core/minions/handlers/subagent.ts+++ b/src/core/minions/handlers/subagent.ts@@ -51,7 +51,7 @@ import {} from './subagent-audit.ts';import { resolveModel, isAnthropicProvider, isOpenRouterSubagentFamily, TIER_DEFAULTS } from '../../model-config.ts';import { splitProviderModelId, normalizeModelId } from '../../model-id.ts';-import { resolveAnthropicKey } from '../../ai/anthropic-key.ts';+import { anthropicClientOptions } from '../../ai/anthropic-key.ts';import { buildSystemPrompt, DEFAULT_SUBAGENT_SYSTEM } from '../system-prompt.ts';import { toolLoop as gatewayToolLoop, isThinkingModel, THINKING_MODEL_MAX_OUTPUT_TOKENS } from '../../ai/gateway.ts';import type { ChatToolDef, ChatMessage, ChatBlock, ChatResult, ToolHandler } from '../../ai/gateway.ts';@@ -258,7 +258,7 @@ export function makeSubagentHandler(deps: SubagentDeps) {// Resolve the key env-first, then config (anthropic_api_key) — a bare// new Anthropic() only reads env, so launchd/MCP workers whose key lives// in the gbrain config file would fail auth (#2048).- const makeAnthropic = deps.makeAnthropic ?? (() => new Anthropic({ apiKey: resolveAnthropicKey() }));+ const makeAnthropic = deps.makeAnthropic ?? (() => new Anthropic(anthropicClientOptions()));const client: MessagesClient = deps.client ?? makeAnthropic().messages;const config = deps.config ?? loadConfig() ?? ({ engine: 'postgres' } as GBrainConfig);const rateLeaseKey = deps.rateLeaseKey ?? DEFAULT_RATE_KEY;diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex e99e13cc33..467ee827c4 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -1,5 +1,6 @@import type { BrainEngine, ReservedConnection } from '../engine.ts';import { withoutCallerAccess } from '../search/private-visibility.ts';+import { withEngineScope } from '../engine-scope.ts';import type { GBrainConfig } from '../config.ts';import { claimableWriteSql, foregroundPrioritySql, claimGroupFollowers, claimNextLaneHead, claimNextWrite, publicationGroupKey, syncGroup, floorPreparationAttempts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues, independentGroup, sweepSegmentStorage, yieldToEventLoop } from './journal.ts';import { connectionCapFailure, finishPreparationStalled, finishUnpublishedFailure, preparationAbortReason, recoverPublication, transientDatabaseFailure, type PreparedMutation } from './coordinator.ts';@@ -315,12 +316,13 @@ export class PersistenceConsumer implements PersistenceConsumerLike {if (this.timer) clearTimeout(this.timer);this.timerDueAt = Date.now() + ms;// GBRA-218: a wake from inside a request must not run publication, effects or scans under that caller's access record.- this.timer = withoutCallerAccess(() => setTimeout(() => {+ // Whoever wakes it, the tick runs for this consumer's engine (engine-scope.ts).+ this.timer = withoutCallerAccess(() => withEngineScope(this.engine, () => setTimeout(() => {this.timer = undefined;const afterProgress = this.progressWake;this.progressWake = false;void this.tick(afterProgress).finally(() => { const next = this.nextDelayMs ?? this.pollMs; this.nextDelayMs = undefined; this.schedule(next); });- }, ms));+ }, ms)));this.timer.unref?.();}/**diff --git a/test/engine-gateway.test.ts b/test/engine-gateway.test.tsindex 4e1a074b82..990d385e6d 100644--- a/test/engine-gateway.test.ts+++ b/test/engine-gateway.test.ts@@ -11,7 +11,11 @@ import {__clearQueryEmbedCacheForTests, __setEmbedTransportForTests, __setGenerateTextTransportForTests, __setRerankTransportForTests,chat, configureGateway, embedQuery, requireConfig, rerank, resetGateway,} from '../src/core/ai/gateway.ts';-import { resolveAnthropicKey } from '../src/core/ai/anthropic-key.ts';+import Anthropic from '@anthropic-ai/sdk';+import { anthropicClientOptions, resolveAnthropicKey } from '../src/core/ai/anthropic-key.ts';+import { embeddedEngineInScope } from '../src/core/engine-scope.ts';+import { PersistenceConsumer } from '../src/core/persistence/consumer.ts';+import { startPersistenceConsumer, stopPersistenceConsumer } from '../src/core/persistence/service.ts';import { embeddedSettings, openEngine, withEngineScope, type EngineSettings } from '../src/core/engine-open.ts';import { createEngine } from '../src/core/engine-factory.ts';import { createDegradedEngine } from '../src/core/degraded-engine.ts';@@ -35,7 +39,8 @@ type Sent = { kind: string; url: string; auth: string | null; model: string };const sent: Sent[] = [];async function sentBy(kind: string, model: any): Promise<void> {const headers = await model.config.headers();- sent.push({ kind, model: model.modelId, url: model.config.url({ path: '/x', modelId: model.modelId }), auth: headers.authorization ?? headers.Authorization ?? null });+ const url = model.config.url ? model.config.url({ path: '/x', modelId: model.modelId }) : `${model.config.baseURL}/x`;+ sent.push({ kind, model: model.modelId, url, auth: headers.authorization ?? headers.Authorization ?? headers['x-api-key'] ?? null });}function installStubs(): void {__setEmbedTransportForTests((async ({ model, values }: any) => {@@ -169,6 +174,94 @@ describe('two engines in one process', () => {}, 120_000);});+describe('settings.ai validation', () => {+ test('each malformed ai setting refuses engine_settings_invalid, names the setting and never echoes the key', async () => {+ const canary = key('canary');+ for (const [ai, setting] of [+ [null, 'ai'],+ [{ models: {} }, 'ai'],+ [{ providers: { 'not-a-provider': { apiKey: canary } } }, 'ai.providers.not-a-provider'],+ [{ providers: { openai: canary } }, 'ai.providers.openai'],+ [{ providers: { openai: { apiKey: canary, key: canary } } }, 'ai.providers.openai.key'],+ [{ providers: { openai: { apiKey: '' } } }, 'ai.providers.openai.apiKey'],+ [{ providers: { openai: { apiKey: canary, baseUrl: 'ftp://proxy.example' } } }, 'ai.providers.openai.baseUrl'],+ [{ providers: { openai: { apiKey: canary } }, models: { embedding: 'openai:text-embedding-3-small' } }, 'ai.models.embedding'],+ [{ providers: { openai: { apiKey: canary } }, models: { chat: 'gpt-5.6' } }, 'ai.models.chat'],+ ] as const) {+ const error = await failure(() => openEngine(settingsFor({ ai: ai as never })));+ expect([error?.code, error?.message]).toEqual(['engine_settings_invalid', `The ${setting} setting is invalid.`]);+ expect(JSON.stringify(error) + error!.message + error!.suggestion).not.toContain(canary);+ }+ });+});++describe('process base URLs never reach an engine', () => {+ const PROXY = 'https://process-proxy.invalid';+ const processRoutes = { ...ambient, OPENAI_BASE_URL: `${PROXY}/v1`, ANTHROPIC_BASE_URL: PROXY };++ test('an engine that names a provider without baseUrl calls that provider\'s default endpoint', async () => {+ installStubs();+ await withEnv(processRoutes, async () => {+ const keyA = key('a');+ const engine = await openEngine(settingsFor({ ai: { providers: { openai: { apiKey: keyA }, anthropic: { apiKey: keyA } }, models: { chat: 'anthropic:claude-sonnet-4-6' } } }));+ try {+ await withEngineScope(engine, () => embedQuery('a question'));+ await withEngineScope(engine, () => chat({ messages: [{ role: 'user', content: 'hello' }] }));+ expect(sent.map(s => [s.kind, s.url.slice(0, s.url.lastIndexOf('/'))])).toEqual([['embed', 'https://api.openai.com/v1'], ['chat', 'https://api.anthropic.com/v1']]);+ expect(sent.map(s => s.auth)).toEqual([`Bearer ${keyA}`, keyA]);+ } finally {+ await engine.disconnect();+ }+ });+ });++ test('a directly built Anthropic client takes only the engine\'s key and endpoint, and refuses without its provider', async () => {+ await withEnv(processRoutes, async () => {+ const keyA = key('a');+ const named = await openEngine(settingsFor({ ai: { providers: { anthropic: { apiKey: keyA } } } }));+ const proxied = await openEngine(settingsFor({ ai: { providers: { anthropic: { apiKey: keyA, baseUrl: 'https://engine-proxy.example/v1' } } } }));+ const without = await openEngine(settingsFor({ ai: { providers: { openai: { apiKey: keyA } } } }));+ try {+ const client = withEngineScope(named, () => new Anthropic(anthropicClientOptions()));+ expect([client.apiKey, client.baseURL]).toEqual([keyA, 'https://api.anthropic.com']);+ expect(withEngineScope(proxied, () => new Anthropic(anthropicClientOptions())).baseURL).toBe('https://engine-proxy.example');+ const error = await withEngineScope(without, () => failure(async () => anthropicClientOptions()));+ expect(error?.code).toBe('engine_scope_missing');+ expect(anthropicClientOptions()).toEqual({ apiKey: PROCESS_KEY });+ } finally {+ await Promise.all([named.disconnect(), proxied.disconnect(), without.disconnect()]);+ }+ });+ });+});++describe('the persistence consumer stays in its engine\'s scope', () => {+ test('a wake from outside every scope still ticks for the consumer\'s engine', async () => {+ const engine = await openEngine(settingsFor({ ai: { providers: { openai: { apiKey: key('a') } } } }));+ const scopes: unknown[] = [];+ const tick = PersistenceConsumer.prototype.tick;+ const spy = spyOn(PersistenceConsumer.prototype, 'tick').mockImplementation(function (this: PersistenceConsumer, afterProgress?: boolean) {+ scopes.push(embeddedEngineInScope());+ return tick.call(this, afterProgress);+ });+ try {+ await engine.initSchema();+ const consumer = withEngineScope(engine, () => startPersistenceConsumer(engine, {} as never)) as PersistenceConsumer;+ const idle = async () => { while (scopes.length === 0 || (consumer as unknown as { tickPromise?: unknown }).tickPromise) await Bun.sleep(10); };+ await idle();+ const before = scopes.length;+ consumer.wake();+ while (scopes.length === before) await Bun.sleep(10);+ await idle();+ expect(scopes.slice(before).map(scope => scope === engine)).toEqual(Array(scopes.length - before).fill(true));+ } finally {+ spy.mockRestore();+ await stopPersistenceConsumer(engine);+ await engine.disconnect();+ }+ }, 60_000);+});+describe('the gateway follows engineKey', () => {test('a page transaction, a forwarding proxy and a recovered degraded engine share their engine\'s gateway', async () => {installStubs();