Garry's Opinionated OpenClaw/Hermes Agent Brain
Key files: Core Ai (continued)
Subsystem index · Previous entries. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG. Provider adapters, recipes and the Voyage width plumbing.
src/core/ai/providers/claude-cli-language-model.ts(+ recipesrc/core/ai/recipes/claude-cli.ts) — ai-sdk LanguageModel adapter over the localclaudeCLI in print mode (OAuth-subscription lane, no API key;claude-cli:<model>is config-portable withanthropic:<model>). Tool use is system-prompt JSON: the recipe teaches the model the<use_tools>[{name,input}]</use_tools>format and the adapter parses those blocks back into ai-sdktool-callparts. A reply with no parsable<use_tools>block that still carries the model's native tool-call markup outside code spans and blocks, on a call that offered tools, throws a transient error instead of returning prose, so the job's attempt limit bounds the retries (#9085,test/claude-cli-stop-reason.test.ts). An entry that carries its arguments flat besidename(noinputwrapper, the Anthropic tool_use shape with the wrapper dropped) is accepted: every key other thanname/inputand the Anthropic tool_use leftovers (type: "tool_use", atoolu_*id) becomes the input — any othertype/idvalue is a real argument (e.g.list_pages'typefilter) and stays — and a presentinputwins verbatim over stray sibling keys. Tool-call ids are ALWAYS gbrain-minted (toolu_claude_cli_<uuidv7>) — never model-authored: each doGenerate is a fresh subprocess replayed from an id-stripped transcript, so the model structurally cannot keep ids unique across turns (a model-authored id echoes the prompt's example entropy-free and collides); the prompt asks for no id and a strayidis ignored (nothing round-trips it; the loop pairs results in memory within one turn). Every child gets--settings '{"disableAllHooks":true}'(#5820: user/project hooks never run, so gbrain's own Stop hook cannot bank the call; login is untouched; managed-policy hooks still run on 2.1.287), and a CLI atSETTING_SOURCES_MIN_VERSION(2.1.314) or newer also gets--setting-sources ""(#8342: no user CLAUDE.md, memory or settings.json; oneclaude --versionper binary per process, killed at 5 s, false when unreadable, and a probe that exited non-zero is tried again on the next call;GBRAIN_CLAUDE_CLI_USER_SETTINGS=1skips flag and probe). A CLI that rejects any flag (unknown option) fails withclaude CLI 2.0.60 or newer required (found <version>)(MIN_CLAUDE_CLI_VERSION, probed: 2.0.59 rejects--disable-slash-commands). No doStream: gateway.toolLoop uses doGenerate. The recipe declareschat+expansiontouchpoints (no embedding; the expansion list leads with the cheap haiku id and carries the same 30sdefault_timeout_msas chat for the subprocess cold start);gateway.expand()routesclaude-clithrough the schemalessviaTextpath because the adapter ignoresresponseFormat(generateObject would throw on the fenced-JSON text). Pinned bytest/claude-cli-recipe.test.ts+test/ai/claude-cli-expansion.test.ts.claudeCliFinishReasonmaps the CLI'sstop_reasonto the finish reason (max_tokens→length,refusal→content-filter, parsed tool calls →tool-calls, anything else →stop), so callers can refuse clipped answers (test/claude-cli-stop-reason.test.ts).renderPromptreplays an earlier tool call with its input as JSON ([tool_use name({...})]). #6424: a positive integermaxOutputTokensreaches the child asCLAUDE_CODE_MAX_OUTPUT_TOKENS(env,--settingsenv). #6523: the CLI reports a response that hit that cap (or its own default) as anis_errorenvelope whoseresultstartsAPI Error: Claude's response exceeded the N output token maximum;isOutputCapEnvelope(anchored prefix,is_error: true, noapi_error_status, stringresult, any cap, any exit code) resolves it as a success with empty text andstop_reason: 'max_tokens', so callers seelengthand their escalation ladders run (loops_extract 2048 → 8192, facts/extract 1× → 2×); every other error envelope staysClaudeCliProcessError(test/claude-cli-output-cap.test.ts). #6791: every child also gets--verbose, so the json stdout is the session's event array;doGeneratetakes its text fromresolveClaudeCliAnswer(claude-cli-continuation.ts) and, when that refuses a continued answer, returns empty text, no tool calls, finishlengthandproviderMetadata['claude-cli'] = { code: 'continuation_unproven', reason }before any<use_tools>block is parsed.src/core/ai/providers/claude-cli-continuation.ts— what text a claude-cli print-mode run answered. Claude Code continues a response that hit its output cap on its own (meta "Resume directly" nudge, second request), and the envelope'sresult/stop_reasonare then only the continuation's.resolveClaudeCliAnswer(run, requestedCap)keeps the enveloperesultwhen there was no continuation (or the envelope already saysmax_tokens); otherwise it rebuilds the answer from the call's own events (consecutive assistant events sharing amessage.idare one segment;<synthetic>error messages are skipped), joining the segments' text in order. A rebuild needs the last segment's final text block to equalresult, notombstoneevent, every earlier text-bearing segment to reportmax_tokensor no stop reason, and every user event between segments to be a "Resume directly" nudge; anything else iscontinuation_unprovenwith reasonsegments_unmatched. Without events (a bare envelope) a continuation is inferred fromnum_turns > 1or output tokens above the cap (the forwarded positive-integermaxOutputTokens, elseCLAUDE_CLI_DEFAULT_OUTPUT_CAP= 32000) and refused asevents_missing; an event array with no assistant message under those signals isno_assistant_events; one segment with output above a requested cap issegments_unmatched. Each reason's first refusal in a process writes one notice naming its remedy (CONTINUATION_UNPROVEN_REMEDY: upgrade the CLI for the first two, raise the caller's output cap for the third). Nothing is read from disk, so a hermeticCLAUDE_CONFIG_DIRchanges nothing. The notice is one[claude-cli] continuation_unproven (<reason>)stderr line;continuationUnprovenMetadatabuilds the provider metadata. Pinned bytest/claude-cli-continuation-6791.test.ts.src/core/ai/providers/claude-cli-scratch.ts— the claude-cli provider's per-PID scratch dirs (claudeCliCwdDir/claudeCliConfigDiroff theCLAUDE_CLI_CWD_PREFIX/CLAUDE_CLI_CONFIG_PREFIXbasename constants, plussweepDeadClaudeCliScratchDirs), split into a dependency-light module so transcript discovery (src/core/transcripts/discover.ts) can callisClaudeCliSelfTranscriptPath(path)WITHOUT importing the provider's @ai-sdk surface. Eachclaude --printsubprocess runs with cwd = a per-PID scratch dir (context isolation — no local CLAUDE.md auto-discovery), and Claude Code records a session transcript for that cwd under~/.claude/projects/<slugified-cwd>/; those sessions are gbrain's OWN internal LLM calls, and importing them back is a self-ingestion feedback loop (prompt scaffolding + page content re-entering as "conversations"). The prefix is lowercase[a-z-]only, so it survives Claude Code's cwd slugification verbatim and a substring match on the discovered path is a reliable self-exclusion fingerprint.claudeCliSelfSessionIds(projectsRoot = claudeProjectsDir())lists the session ids of those harness transcripts;isClaudeCliSelfSessionId(id, projectDirs = claudeCliSelfProjectDirs())is the single-session classifier (#5820) shared by the serve-side writeback harvest and the sweep: one listing of the projects root, then an existence check per prefix-matched scratch project (path-shaped ids are refused);claudeCliSelfSessions(projectsRoot)maps each self session id to the first scratch project holding it from one listing per project, and the bulk classifiers (doctorself_capture,classifyCapturedFacts) look ids up there, so their filesystem reads do not grow with the number of items (#7343,test/doctor-only-wave-7343.test.ts); the session-end hook named each corpus file<session id>.txt, so dream discovery and the sweep's corpus pass use the set to skip self-captures written before the hook refused them (best-effort: a pruned harness transcript leaves its capture unclassifiable). Pinned bytest/transcripts-self-exclusion.test.ts.src/core/ai/recipes/anthropic.ts— Anthropic recipe (chat + expansion touchpoints). Canonical id isclaude-sonnet-4-6(no date suffix); a reverse aliasclaude-sonnet-4-6-20250929 → claude-sonnet-4-6keeps stale user configs working (rescuesfacts.extraction_modelandmodels.dream.synthesize). Recipe shape pinned bytest/anthropic-model-ids.test.ts.src/core/ai/recipes/llama-server-reranker.ts— sibling ofllama-server(the embedding recipe) for llama.cpp in--rerankingmode. Distinct recipe rather than dual-touchpoint extension because--rerankingand--embeddingsare mutually exclusive at server-launch time, so the two backends need independent base URLs (default 8081 here vs 8080 there). Declaresrerankertouchpoint withmodels: [](user-provided id matching the--aliasthe user launched with),path: '/rerank'(leaf-only; consumesRerankerTouchpoint.pathoverride; gateway concatenates withbase_url_defaultwhich ends in/v1, producing…/v1/rerank),default_timeout_ms: 30_000(consumed bysrc/core/search/mode.ts's reranker timeout chain — CPU-only first-call warmup headroom; the 5s mode-bundle default would fail-open astimeout),cost_per_1m_tokens_usd: 0(recognized byFREE_LOCAL_RERANK_PROVIDERSinsrc/core/budget/budget-tracker.tsso--max-costcallers don't hard-fail on local rerank). Setup hint emphasizes--aliasbecause llama-server's/v1/modelsdefaults model id to the gguf file path without it. Covers Qwen3-Reranker via llama.cpp; the user supplies the matching--modeland--aliasat launch. Pinned bytest/ai/recipe-llama-server-reranker.test.ts. Voyage / Cohere / vLLM rerankers stay out of scope (different wire shapes). Companion surfaces:path?: string+default_timeout_ms?: numberonRerankerTouchpointinsrc/core/ai/types.ts; consumed by the URL build atsrc/core/ai/gateway.ts:rerank()and by mode-resolution atsrc/core/search/mode.ts:resolveSearchMode(precedence: per-call > config-key > recipe touchpoint default > mode bundle);LLAMA_SERVER_RERANKER_BASE_URLenv passthrough insrc/cli.ts:buildGatewayConfig;FREE_LOCAL_RERANK_PROVIDERSset insrc/core/budget/budget-tracker.ts:lookupPricing(rerank-kind-only zero-pricing for the local provider prefix); doctor-fix atsrc/commands/models.ts:probeRerankerConfigreadssearch.reranker.modelvialoadSearchModeConfig+resolveSearchMode(so doctor and live search read the same resolution and the file plane / DB plane cannot diverge — the field-planegetRerankerModel()reads nothing writes);probeRerankerReachabilityreads the recipe'sdefault_timeout_msso CPU-only cold-start doesn't false-fail.src/core/ai/recipes/lmstudio.ts— LM Studio local OpenAI-compatible recipe (embedding touchpoint only; default base URLhttp://localhost:1234/v1, envLMSTUDIO_BASE_URL). Shipsmodels: []like llama-server — the model identity is whatever the user loaded in the app, so--embedding-model lmstudio:<id>+--embedding-dimensions <N>are required (the wizard refuses implicit defaults). Its own provider id keepsopenai:pointed at OpenAI (complement of the keylessOPENAI_BASE_URLroute). Documented operational failure mode: a degraded loaded instance passes the reachability probe but misses the query-embed deadline — queries degrade to keyword-only with theembed_timeoutstamp, reload the model to recover.src/core/ai/recipes/nan.ts— nan.builders openai-compatible reranker recipe.POST {base}/v1/rerank→results[{index, relevance_score}], leaf-only (base_url_defaultends/v1; bare/rerankand/compatible-api/v1/reranksboth 404). Model id is the literalrerank(a Qwen3-Reranker-8B deployment).auth_env.required: ['NAN_API_KEY'].src/core/ai/recipes/ollama.ts— the Ollama local recipe.thinking_by_defaultis a per-family predicate over the model id (qwen3 with a boundary soqwen2.5-*is never swallowed and a-coderexclusion — the instruct-only variant has no thinking mode; deepseek-r*, gpt-oss, magistral, phi*-reasoning including the-mini-reasoningtags), not a recipe-wide boolean, so non-reasoning local models keep the conservative default. The chat touchpoint declaressupports_structured_outputs: true(Ollama enforcesresponse_format: json_schemaserver-side via grammar-constrained decoding, model-independent — unlike tools, which stayfalse), sochat()sends a caller'sresponseSchemato Ollama (facts extraction) andexpand()routesollama:*expansion models through the strict generateObject lane with its existing rejected-recipe fallback.src/core/ai/recipes/openrouter.ts— OpenRouter openai-compatible recipe: single key, many providers viaopenrouter:<provider>/<model>strings.base_url_default: 'https://openrouter.ai/api/v1'. Embedding touchpoint: default modelopenai/text-embedding-3-small; per-modelmodel_dimscarries verified native widths (text-embedding-3-small 1536, text-embedding-3-large 3072, qwen/qwen3-embedding-8b 4096, bge-m3 + baai/bge-m3 1024) withdefault_dims: 0so an UNLISTED proxied id has NO silent default — it errors until the user supplies explicit dims (--embedding-dimensions/embedding_dimensions), whichtrust_custom_dims: trueaccepts (gemini-embedding-2-preview is deliberately unlisted — width unverified). Matryoshkadims_options: [512, 768, 1024, 1536]still governs the default model's shrink steps;max_batch_tokens: 300_000= OpenAI's aggregate-per-request token cap (NOT per-input). Chat touchpoint declares 8 curated entry points (gpt-5.2, gpt-5.2-chat, gpt-5.5, claude-haiku-4.5, claude-sonnet-4.6, claude-opus-4.7, gemini-3-flash-preview, deepseek-chat) but openai-compat tier accepts any model ID; deliberately nomax_context_tokensbecause OR's catalog spans 128K to 1M+.supports_subagent_loop: falseis enforced byclassifyCapabilities()insrc/core/ai/capabilities.ts(verdictunusable:no_subagent_loop—enforceSubagentCapable()insrc/core/model-config.tsconsumes the verdict: tool-less/unknown models fall back toTIER_DEFAULTS.subagentwith a warn; tool-capable providers without prompt caching run with a once-per-model cost warn); the legacy Anthropic-direct path additionally gates onisAnthropicProvider()insrc/core/model-config.tswhenagent.use_gateway_loopis off. DeclaresresolveDefaultHeaders(env)returning OR's three attribution headers:HTTP-Referer(required for OR app-attribution),X-OpenRouter-Title(preferred),X-Title(back-compat alias); defaults tohttps://gbrain.ai/gbrain; forks override viaOPENROUTER_REFERER/OPENROUTER_TITLEenv vars. OpenRouter reports upstream rate limits and some outages as anerrorobject inside an HTTP 200 body;rewriteOpenRouterErrorEnvelopeStatus(composed intoopenrouterCompatFetch) gives a 200application/jsonbody with an integererror.codeof 429 or 5xx that status, keeping an existingRetry-Afterand promoting a finite non-negativeerror.metadata.retry_after/retryAfterwhen absent, so the AI SDK's status-keyed retry and gbrain's classification see it; success, 4xx, unparseable and SSE responses pass through untouched. Smoke-tested bytest/ai/recipe-openrouter.test.ts(incl. the shape guard: every model in the chat list matches^[a-z0-9-]+\/[a-z0-9._-]+$).src/core/ai/recipes/voyage.ts— Voyage AI openai-compatible recipe, home of the new-install default stack. Embedding touchpoint declaresdefault_model: 'voyage-4'+default_dims: 1024— the canonical pick for every "choose a model for the user" surface (models[0]staysvoyage-4-largein quality order; the new-install default isvoyage-4for price/quality balance and the shared v4 embedding space — seeNEW_INSTALL_DEFAULT_EMBEDDING_MODELinai/defaults.ts). Reranker touchpoint (the mode-bundle default viaDEFAULT_RERANKER_MODEL, sameVOYAGE_API_KEYas embeddings) allowlists Voyage's currentrerank-3($0.05/M) +rerank-3-lite($0.02/M) and the olderrerank-2.5($0.05/M) +rerank-2.5-lite($0.02/M) (prices verified 2026-10-14);default_modelisrerank-3-lite, matchingDEFAULT_RERANKER_MODEL(gbrain-evals #148: 60% cheaper thanrerank-2.5at 50 × 1,400, quality within noise). The array is the opt-in surface for every enforcement point (gateway.rerank()'stp.models.includesguard,gbrain models doctor'sreranker_configprobe,rerankerReadiness); a brain with an explicitsearch.reranker.modelrow keeps that model when the default moves. All four share one wire:path: '/rerank',top_param: 'top_k'(responses accept{data: [{index, relevance_score}]}or the compatibleresultsarray), 5MB byte-proxy payload cap. Declareschars_per_token=1+safety_factor=0.5so the gateway pre-splits Voyage batches at a 60K-character budget (50% of 120K-token cap with the dense-tokenizer ratio), since tiktoken-grounded budgeting undercounts Voyage's actual token usage. Declaresmultimodal_models: ['voyage-multimodal-3']so the gateway rejects text-only Voyage models pointed at the multimodal endpoint with a clearAIConfigErrorinstead of waiting for Voyage's HTTP 400. The hosted flexible-dim models that acceptoutput_dimensionlive inVOYAGE_OUTPUT_DIMENSION_MODELSinsrc/core/ai/dims.ts(v4 trio,voyage-code-4,voyage-3-large,voyage-3.5,voyage-3.5-lite,voyage-code-3; valid widths 256/512/1024/2048);voyage-4-nanois the open-weight variant fixed at 1024-dim that does NOT accept the parameter (negative assertion intest/ai/gateway.test.ts:dimsProviderOptionsreturnsundefinedforvoyage-4-nano).voyage-code-3is the recommended embedding model for gstack per-worktree code brains (Topology 3 indocs/architecture/topologies.md;voyage-code-4is the flexible-dim hosted code model, $0.12/M); discoverability surfaces: decision-tree branch indocs/integrations/embedding-providers.md, Topology 3 "Recommended embedding model" subsection, runtime nudge fromgbrain reindex-codeagainst non-code-tuned models. Recipe shape pinned bytest/ai/voyage-code-3-recipe.test.ts.src/core/ai/voyage-gateway.ts— Voyage width plumbing forvoyageCompatFetch(#6061).applyVoyageOutputDimension(body, input, dims)always sets rootoutput_dimensionand addsproviderOptions.voyage.outputDimensiononly when the request URL's hostname is exactlyai-gateway.vercel.sh(the Vercel AI Gateway reads only that; Voyage's own API answers 400 onproviderOptions; look-alike hosts, suffixes and path mentions never match).embeddingDimMismatchError(...)builds the dim-mismatchAIConfigError: with a non-defaultprovider_base_urls.<provider>it names that host as the likely cause (a proxy dropping the width), says nothing was written and points at fixing the proxy plusgbrain doctor --only embedding_provider --probe --jsonbefore a migration; the default route keeps thegbrain migrate --embedding-model … --embedding-dimensions …hint. Pinned intest/ai/gateway.test.ts(Voyage shim describe).