Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
19.3 KB
Raw Blame

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 (+ recipe src/core/ai/recipes/claude-cli.ts) — ai-sdk LanguageModel adapter over the local claude CLI in print mode (OAuth-subscription lane, no API key; claude-cli:<model> is config-portable with anthropic:<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-sdk tool-call parts. 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 beside name (no input wrapper, the Anthropic tool_use shape with the wrapper dropped) is accepted: every key other than name/input and the Anthropic tool_use leftovers (type: "tool_use", a toolu_* id) becomes the input — any other type/id value is a real argument (e.g. list_pages' type filter) and stays — and a present input wins 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 stray id is 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 at SETTING_SOURCES_MIN_VERSION (2.1.314) or newer also gets --setting-sources "" (#8342: no user CLAUDE.md, memory or settings.json; one claude --version per 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=1 skips flag and probe). A CLI that rejects any flag (unknown option) fails with claude 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 declares chat + expansion touchpoints (no embedding; the expansion list leads with the cheap haiku id and carries the same 30s default_timeout_ms as chat for the subprocess cold start); gateway.expand() routes claude-cli through the schemaless viaText path because the adapter ignores responseFormat (generateObject would throw on the fenced-JSON text). Pinned by test/claude-cli-recipe.test.ts + test/ai/claude-cli-expansion.test.ts. claudeCliFinishReason maps the CLI's stop_reason to 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). renderPrompt replays an earlier tool call with its input as JSON ([tool_use name({...})]). #6424: a positive integer maxOutputTokens reaches the child as CLAUDE_CODE_MAX_OUTPUT_TOKENS (env, --settings env). #6523: the CLI reports a response that hit that cap (or its own default) as an is_error envelope whose result starts API Error: Claude's response exceeded the N output token maximum; isOutputCapEnvelope (anchored prefix, is_error: true, no api_error_status, string result, any cap, any exit code) resolves it as a success with empty text and stop_reason: 'max_tokens', so callers see length and their escalation ladders run (loops_extract 2048 → 8192, facts/extract 1× → 2×); every other error envelope stays ClaudeCliProcessError (test/claude-cli-output-cap.test.ts). #6791: every child also gets --verbose, so the json stdout is the session's event array; doGenerate takes its text from resolveClaudeCliAnswer (claude-cli-continuation.ts) and, when that refuses a continued answer, returns empty text, no tool calls, finish length and providerMetadata['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's result / stop_reason are then only the continuation's. resolveClaudeCliAnswer(run, requestedCap) keeps the envelope result when there was no continuation (or the envelope already says max_tokens); otherwise it rebuilds the answer from the call's own events (consecutive assistant events sharing a message.id are one segment; <synthetic> error messages are skipped), joining the segments' text in order. A rebuild needs the last segment's final text block to equal result, no tombstone event, every earlier text-bearing segment to report max_tokens or no stop reason, and every user event between segments to be a "Resume directly" nudge; anything else is continuation_unproven with reason segments_unmatched. Without events (a bare envelope) a continuation is inferred from num_turns > 1 or output tokens above the cap (the forwarded positive-integer maxOutputTokens, else CLAUDE_CLI_DEFAULT_OUTPUT_CAP = 32000) and refused as events_missing; an event array with no assistant message under those signals is no_assistant_events; one segment with output above a requested cap is segments_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 hermetic CLAUDE_CONFIG_DIR changes nothing. The notice is one [claude-cli] continuation_unproven (<reason>) stderr line; continuationUnprovenMetadata builds the provider metadata. Pinned by test/claude-cli-continuation-6791.test.ts.

  • src/core/ai/providers/claude-cli-scratch.ts — the claude-cli provider's per-PID scratch dirs (claudeCliCwdDir/claudeCliConfigDir off the CLAUDE_CLI_CWD_PREFIX/CLAUDE_CLI_CONFIG_PREFIX basename constants, plus sweepDeadClaudeCliScratchDirs), split into a dependency-light module so transcript discovery (src/core/transcripts/discover.ts) can call isClaudeCliSelfTranscriptPath(path) WITHOUT importing the provider's @ai-sdk surface. Each claude --print subprocess 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 (doctor self_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 by test/transcripts-self-exclusion.test.ts.

  • src/core/ai/recipes/anthropic.ts — Anthropic recipe (chat + expansion touchpoints). Canonical id is claude-sonnet-4-6 (no date suffix); a reverse alias claude-sonnet-4-6-20250929 → claude-sonnet-4-6 keeps stale user configs working (rescues facts.extraction_model and models.dream.synthesize). Recipe shape pinned by test/anthropic-model-ids.test.ts.

  • src/core/ai/recipes/llama-server-reranker.ts — sibling of llama-server (the embedding recipe) for llama.cpp in --reranking mode. Distinct recipe rather than dual-touchpoint extension because --reranking and --embeddings are mutually exclusive at server-launch time, so the two backends need independent base URLs (default 8081 here vs 8080 there). Declares reranker touchpoint with models: [] (user-provided id matching the --alias the user launched with), path: '/rerank' (leaf-only; consumes RerankerTouchpoint.path override; gateway concatenates with base_url_default which ends in /v1, producing …/v1/rerank), default_timeout_ms: 30_000 (consumed by src/core/search/mode.ts's reranker timeout chain — CPU-only first-call warmup headroom; the 5s mode-bundle default would fail-open as timeout), cost_per_1m_tokens_usd: 0 (recognized by FREE_LOCAL_RERANK_PROVIDERS in src/core/budget/budget-tracker.ts so --max-cost callers don't hard-fail on local rerank). Setup hint emphasizes --alias because llama-server's /v1/models defaults model id to the gguf file path without it. Covers Qwen3-Reranker via llama.cpp; the user supplies the matching --model and --alias at launch. Pinned by test/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?: number on RerankerTouchpoint in src/core/ai/types.ts; consumed by the URL build at src/core/ai/gateway.ts:rerank() and by mode-resolution at src/core/search/mode.ts:resolveSearchMode (precedence: per-call > config-key > recipe touchpoint default > mode bundle); LLAMA_SERVER_RERANKER_BASE_URL env passthrough in src/cli.ts:buildGatewayConfig; FREE_LOCAL_RERANK_PROVIDERS set in src/core/budget/budget-tracker.ts:lookupPricing (rerank-kind-only zero-pricing for the local provider prefix); doctor-fix at src/commands/models.ts:probeRerankerConfig reads search.reranker.model via loadSearchModeConfig + resolveSearchMode (so doctor and live search read the same resolution and the file plane / DB plane cannot diverge — the field-plane getRerankerModel() reads nothing writes); probeRerankerReachability reads the recipe's default_timeout_ms so 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 URL http://localhost:1234/v1, env LMSTUDIO_BASE_URL). Ships models: [] 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 keeps openai: pointed at OpenAI (complement of the keyless OPENAI_BASE_URL route). Documented operational failure mode: a degraded loaded instance passes the reachability probe but misses the query-embed deadline — queries degrade to keyword-only with the embed_timeout stamp, 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_default ends /v1; bare /rerank and /compatible-api/v1/reranks both 404). Model id is the literal rerank (a Qwen3-Reranker-8B deployment). auth_env.required: ['NAN_API_KEY'].

  • src/core/ai/recipes/ollama.ts — the Ollama local recipe. thinking_by_default is a per-family predicate over the model id (qwen3 with a boundary so qwen2.5-* is never swallowed and a -coder exclusion — the instruct-only variant has no thinking mode; deepseek-r*, gpt-oss, magistral, phi*-reasoning including the -mini-reasoning tags), not a recipe-wide boolean, so non-reasoning local models keep the conservative default. The chat touchpoint declares supports_structured_outputs: true (Ollama enforces response_format: json_schema server-side via grammar-constrained decoding, model-independent — unlike tools, which stay false), so chat() sends a caller's responseSchema to Ollama (facts extraction) and expand() routes ollama:* 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 via openrouter:<provider>/<model> strings. base_url_default: 'https://openrouter.ai/api/v1'. Embedding touchpoint: default model openai/text-embedding-3-small; per-model model_dims carries verified native widths (text-embedding-3-small 1536, text-embedding-3-large 3072, qwen/qwen3-embedding-8b 4096, bge-m3 + baai/bge-m3 1024) with default_dims: 0 so an UNLISTED proxied id has NO silent default — it errors until the user supplies explicit dims (--embedding-dimensions / embedding_dimensions), which trust_custom_dims: true accepts (gemini-embedding-2-preview is deliberately unlisted — width unverified). Matryoshka dims_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 no max_context_tokens because OR's catalog spans 128K to 1M+. supports_subagent_loop: false is enforced by classifyCapabilities() in src/core/ai/capabilities.ts (verdict unusable:no_subagent_loop — enforceSubagentCapable() in src/core/model-config.ts consumes the verdict: tool-less/unknown models fall back to TIER_DEFAULTS.subagent with a warn; tool-capable providers without prompt caching run with a once-per-model cost warn); the legacy Anthropic-direct path additionally gates on isAnthropicProvider() in src/core/model-config.ts when agent.use_gateway_loop is off. Declares resolveDefaultHeaders(env) returning OR's three attribution headers: HTTP-Referer (required for OR app-attribution), X-OpenRouter-Title (preferred), X-Title (back-compat alias); defaults to https://gbrain.ai / gbrain; forks override via OPENROUTER_REFERER / OPENROUTER_TITLE env vars. OpenRouter reports upstream rate limits and some outages as an error object inside an HTTP 200 body; rewriteOpenRouterErrorEnvelopeStatus (composed into openrouterCompatFetch) gives a 200 application/json body with an integer error.code of 429 or 5xx that status, keeping an existing Retry-After and promoting a finite non-negative error.metadata.retry_after/retryAfter when 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 by test/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 declares default_model: 'voyage-4' + default_dims: 1024 — the canonical pick for every "choose a model for the user" surface (models[0] stays voyage-4-large in quality order; the new-install default is voyage-4 for price/quality balance and the shared v4 embedding space — see NEW_INSTALL_DEFAULT_EMBEDDING_MODEL in ai/defaults.ts). Reranker touchpoint (the mode-bundle default via DEFAULT_RERANKER_MODEL, same VOYAGE_API_KEY as embeddings) allowlists Voyage's current rerank-3 ($0.05/M) + rerank-3-lite ($0.02/M) and the older rerank-2.5 ($0.05/M) + rerank-2.5-lite ($0.02/M) (prices verified 2026-10-14); default_model is rerank-3-lite, matching DEFAULT_RERANKER_MODEL (gbrain-evals #148: 60% cheaper than rerank-2.5 at 50 × 1,400, quality within noise). The array is the opt-in surface for every enforcement point (gateway.rerank()'s tp.models.includes guard, gbrain models doctor's reranker_config probe, rerankerReadiness); a brain with an explicit search.reranker.model row 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 compatible results array), 5MB byte-proxy payload cap. Declares chars_per_token=1 + safety_factor=0.5 so 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. Declares multimodal_models: ['voyage-multimodal-3'] so the gateway rejects text-only Voyage models pointed at the multimodal endpoint with a clear AIConfigError instead of waiting for Voyage's HTTP 400. The hosted flexible-dim models that accept output_dimension live in VOYAGE_OUTPUT_DIMENSION_MODELS in src/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-nano is the open-weight variant fixed at 1024-dim that does NOT accept the parameter (negative assertion in test/ai/gateway.test.ts: dimsProviderOptions returns undefined for voyage-4-nano). voyage-code-3 is the recommended embedding model for gstack per-worktree code brains (Topology 3 in docs/architecture/topologies.md; voyage-code-4 is the flexible-dim hosted code model, $0.12/M); discoverability surfaces: decision-tree branch in docs/integrations/embedding-providers.md, Topology 3 "Recommended embedding model" subsection, runtime nudge from gbrain reindex-code against non-code-tuned models. Recipe shape pinned by test/ai/voyage-code-3-recipe.test.ts.

  • src/core/ai/voyage-gateway.ts — Voyage width plumbing for voyageCompatFetch (#6061). applyVoyageOutputDimension(body, input, dims) always sets root output_dimension and adds providerOptions.voyage.outputDimension only when the request URL's hostname is exactly ai-gateway.vercel.sh (the Vercel AI Gateway reads only that; Voyage's own API answers 400 on providerOptions; look-alike hosts, suffixes and path mentions never match). embeddingDimMismatchError(...) builds the dim-mismatch AIConfigError: with a non-default provider_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 plus gbrain doctor --only embedding_provider --probe --json before a migration; the default route keeps the gbrain migrate --embedding-model … --embedding-dimensions … hint. Pinned in test/ai/gateway.test.ts (Voyage shim describe).