Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
10.7 KB
Raw Blame

Key files: Commands (1/6, 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.

  • src/commands/connect.ts + src/core/connect-probe.ts — gbrain connect <mcp-url> [--token <bearer>] one-command coding-agent onboarding from a bearer token. Turns an MCP URL + token into a paste-ready claude mcp add ... -H "Authorization: Bearer ..." block (default) or, with --install, runs it directly and smoke-tests the token. Direct HTTP MCP — Claude Code talks straight to a remote gbrain serve --http, no local install needed. Token resolution: --token > $GBRAIN_REMOTE_TOKEN > placeholder (print) / error (install). The generated block tells the agent to call get_brain_identity + list_skills (the LEARN_INSTRUCTION export, which names capture — a starter-surface MCP op — alongside put_page for full-control writes) with a core-tools fallback for hosts without skill publishing. URL normalization appends /mcp to a bare host but REJECTS a scheme-less host; the pure registration helpers (normalizeMcpUrl, isLinkLocalOrMetadata, buildClaudeMcpAddArgv with its optional scope param — claude's default is local, so the harness lane passes user explicitly — buildCodexMcpAddArgv, validateToken, redactToken, shellQuote/cmdString, issuerFromMcpUrl, the OAUTH_SECRET_NOTE secret-hygiene constant, and openclawThinClientBlock — the honest openclaw wiring print: a scoped gbrain init --mcp-only thin-client block, deliberately NOT a stdio mcpServers config since that grants full local DB access) live in src/core/mcp-registration.ts (core must not import from commands; connect.ts re-exports them — OAUTH_SECRET_NOTE included — so its surface and tests are unchanged) and are unit-tested. Flags: --token, --name <id> (default gbrain, validated against NAME_RE), --agent claude-code|codex|opencode|perplexity|generic, --install, --yes (the user's approval for --install: installConsent asks through requireConsent, effects credentials + persistent_install, via the isTTY/promptYesNo seams; non-TTY without it exits 3 with the consent payload, whose argv omits the token value), --force, --json (token redacted unless --show-token), --timeout-ms. connect is in CLI_ONLY + CLI_ONLY_SELF_HELP; dispatched in cli.ts:handleCliOnly with no local DB connect. AGENT_SPECS drives per-agent rendering + --install: claude-code → buildClaudeMcpAddArgv (literal -H "Authorization: Bearer <tok>"); codex → buildCodexMcpAddArgv = codex mcp add <name> --url <url> --bearer-token-env-var GBRAIN_REMOTE_TOKEN (on the CONNECT lane Codex reads the token from the env var at runtime, never written to config — the harness lane in src/core/bootstrap/harness.ts is the deliberate exception, writing a managed block with the inline http_headers = { Authorization = "Bearer <t>" } credential (codex-cli >=0.149 rejects inline bearer_token for streamable_http at config load) because framework-spawned codex inherits no shell profile; --install runs it and prints an export GBRAIN_REMOTE_TOKEN hint when missing); opencode → buildOpencodeMcpAddArgv = opencode mcp add <name> --url <url> --header "Authorization=Bearer {env:GBRAIN_REMOTE_TOKEN}" (the interpolation is stored LITERALLY and resolved by opencode at read time — token never in argv/config/--json; --install writes the entry directly through ConnectDeps.writeOpencodeRemoteEntry → opencode-json.ts in env token mode, no binary required; --force maps to the writer's allowReplaceOtherSource so an OURS entry at an old url — a rotated serve — is replaceable, mirroring the exec lanes' --force semantics, while foreign same-name entries still refuse with url-appropriate copy: pick --name); perplexity + generic are installable:false and reject --install. --oauth (supportsOAuth:true = perplexity/generic only) emits an OAuth 2.1 client-credentials connector block (Issuer URL via issuerFromMcpUrl = mcp-url minus /mcp, Client ID, Client Secret) — least-privilege scopes + short-lived rotating tokens vs a long-lived full-access secret. Creds from --client-id/--client-secret (BYO) or --register (deps.registerOAuthClient shells gbrain auth register-client <name> --grant-types client_credentials --scopes <DEFAULT_SCOPES="read write"> --token-endpoint-auth-method client_secret_post and parses Client ID:/Client Secret:); --oauth rejected for claude-code/codex and incompatible with --install. buildJson is a generic shape (agent, command/command_argv null for perplexity/generic, header, env_var, oauth fields with redaction); the codex command carries only the env-var name, never the token. cmdString(binary, argv) POSIX-single-quotes args. ConnectDeps = {isTTY, promptYesNo, hasBinary(bin), runBinary(bin, argv), probe, env(name), registerOAuthClient, writeOpencodeRemoteEntry} — binary-generic so claude and codex share the exec path while opencode rides the writer member; env injectable for tests. Security: rendered command single-quotes the token so shell metacharacters can't run code when pasted; token validated before it lands in an HTTP header; link-local / cloud-metadata addresses (incl. IPv4-mapped IPv6 ::ffff:169.254.x.x and AWS IMDSv2-over-IPv6 fd00:ec2::254) refused as a token-exfil guard while localhost/RFC1918/LAN stay allowed; token redacted from all error output. src/core/connect-probe.ts is the raw-bearer MCP smoke probe backing --install: connects the official MCP SDK Client over StreamableHTTPClientTransport with a STATIC Authorization header (no OAuth/discovery — distinct from mcp-client.ts:callRemoteTool which is OAuth-only and remote-mcp-probe.ts:smokeTestMcp which only sends initialize), runs the full initialize handshake via client.connect(), then calls get_brain_identity (read-scope, non-localOnly) to prove a tool call round-trips. Never throws — every failure maps to { ok: false, reason: 'auth' | 'unreachable' | 'timeout' | 'tool_error' | 'unknown', message } so a wrong/expired token fails at setup, not on the agent's first request. DEFAULT_PROBE_TIMEOUT_MS = 15_000 shared with connect.ts. serve-http.ts adds exported pure skillPublishStatus(publishSkills) for the startup banner Skills: published / not published line + a one-line gbrain config set mcp.publish_skills true stderr nudge when publishing is OFF. Docs: docs/mcp/CODEX.md, docs/mcp/PERPLEXITY.md, docs/mcp/CLAUDE_CODE.md, docs/tutorials/connect-coding-agent.md. Pinned by test/connect.test.ts (pure-helper + render, all five agents incl. the opencode writer-install lane) + test/connect-bearer.test.ts (raw-bearer probe + full OAuth chain register→connect→discovery→/token mint→get_brain_identity, client registered in beforeAll before serve takes the PGLite single-writer lock; drives real claude + codex binaries through connect --install with sandboxed HOME/CODEX_HOME, asserts registration + token never in Codex config, skips when a binary is absent) + test/serve-stdio-roundtrip.test.ts (spawns real gbrain serve stdio against a fresh init --pglite brain, drives the SDK client through initialize→tools/list→tools/call, asserts the advertised core-tool set including capture, a starter-surface MCP op) + test/serve-skills-publish-nudge.test.ts.

  • src/commands/db-repair.ts — gbrain db-repair [--yes] [--apply-rewrites] [--json] [--force] [--undo-last-rewrite] [--dry-run]: ENGINE-FREE Postgres-access repair, sibling of pglite-repair (PGLite brains are redirected there). Never calls connectEngine; default invocation is DIAGNOSE-ONLY (--dry-run is an explicit alias). Consent is tiered and flag-gated, never TTY-dependent: auto tier under --yes (bounded reconnects, pending migrations in-process, CREATE EXTENSION vector, docker start of gbrain's own container via docker-postgres.ts); rewrite tier under --yes --apply-rewrites only (config-file database_url rewrites — pooler form, session pooler, ?sslmode=require — printed first, candidate connect-probed BEFORE persisting, receipted, undo-able); manual tier never applied (credentials/paused-project/env recipes printed — relaying the recipe IS the repair). --apply-rewrites without --yes is an error. Invariants: fix targets derive only from the CURRENT config URL, never error text; the prober uses exactly ONE connection (poolSize: 1 — diagnosing pool exhaustion with a 10-connection pool would worsen the outage); rewrite cooldown is ≤24h per (reason, action) with --force bypass while auto-tier fixes are NEVER cooldown-blocked (availability first); every rewrite stores the prior URL in the 0600 ~/.gbrain/db-repair-undo.json (a secret — never the redacted receipts) and --undo-last-rewrite (--yes-gated) restores it — undo runs INSIDE the advisory lock, emits the same --json envelope, validates the record's postgres:// scheme before restoring, and is itself reversible (the outgoing URL becomes the new undo record); an O_EXCL-created advisory lockfile blocks concurrent double-rewrites (check-then-write race closed; one stale-holder retry; other write failures stay fail-open); a healthy probe exits 0 "nothing to fix" (the forged-marker defense) and additionally REPORTS (never rewrites) stale DB-plane engine/database_url rows; the schema probe treats a ZERO-ROW pg_extension result as pgvector_missing (the query never errors on an absent extension); the docker arm matches the container's REAL inspected host port (deps.docker.hostPort) as well as the default 5434; a successful rewrite prints the "restart long-lived gbrain processes" note (config rewrites reach NEW processes only). Refusals: thin-client (no local DB), non-host brain resolution (a mount outage must never rewrite host config — mount-targeted repair is a filed TODO), PGLite (→ pglite-repair). Injectable DbRepairDeps prober/executor seam for tests; defaultDeps.probeAccess is also reused by the init ladder (one prober, one contract). Pinned by test/db-repair.serial.test.ts. D2 (json: 'document'): a healthy/fixed report is the pretty legacy document; an unfixed one (exit 1) is a one-line database_error envelope leading with the report keys (reason = diagnosis reason, fix = the tier's next step: --yes for auto, --yes --apply-rewrites with consent credentials for rewrite, none for manual); pre-probe refusals keep their stderr line and add an envelope (unknown_flag/invalid_params exit 2, requires_local_engine, config_error, lock_busy, not_found, no_brain). Healthy success shape: test/e2e/cli-json-commands-postgres.test.ts.