Garry's Opinionated OpenClaw/Hermes Agent Brain
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-readyclaude 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 remotegbrain serve --http, no local install needed. Token resolution:--token>$GBRAIN_REMOTE_TOKEN> placeholder (print) / error (install). The generated block tells the agent to callget_brain_identity+list_skills(theLEARN_INSTRUCTIONexport, which namescapture— a starter-surface MCP op — alongsideput_pagefor full-control writes) with a core-tools fallback for hosts without skill publishing. URL normalization appends/mcpto a bare host but REJECTS a scheme-less host; the pure registration helpers (normalizeMcpUrl,isLinkLocalOrMetadata,buildClaudeMcpAddArgvwith its optional scope param — claude's default islocal, so the harness lane passesuserexplicitly —buildCodexMcpAddArgv,validateToken,redactToken,shellQuote/cmdString,issuerFromMcpUrl, theOAUTH_SECRET_NOTEsecret-hygiene constant, andopenclawThinClientBlock— the honest openclaw wiring print: a scopedgbrain init --mcp-onlythin-client block, deliberately NOT a stdio mcpServers config since that grants full local DB access) live insrc/core/mcp-registration.ts(core must not import from commands; connect.ts re-exports them —OAUTH_SECRET_NOTEincluded — so its surface and tests are unchanged) and are unit-tested. Flags:--token,--name <id>(defaultgbrain, validated againstNAME_RE),--agent claude-code|codex|opencode|perplexity|generic,--install,--yes(the user's approval for--install:installConsentasks throughrequireConsent, effectscredentials+persistent_install, via theisTTY/promptYesNoseams; 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.connectis inCLI_ONLY+CLI_ONLY_SELF_HELP; dispatched incli.ts:handleCliOnlywith no local DB connect.AGENT_SPECSdrives 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 insrc/core/bootstrap/harness.tsis the deliberate exception, writing a managed block with the inlinehttp_headers = { Authorization = "Bearer <t>" }credential (codex-cli >=0.149 rejects inlinebearer_tokenfor streamable_http at config load) because framework-spawned codex inherits no shell profile;--installruns it and prints anexport GBRAIN_REMOTE_TOKENhint 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;--installwrites the entry directly throughConnectDeps.writeOpencodeRemoteEntry→opencode-json.tsin env token mode, no binary required;--forcemaps to the writer'sallowReplaceOtherSourceso an OURS entry at an old url — a rotated serve — is replaceable, mirroring the exec lanes'--forcesemantics, while foreign same-name entries still refuse with url-appropriate copy: pick--name);perplexity+genericareinstallable:falseand reject--install.--oauth(supportsOAuth:true= perplexity/generic only) emits an OAuth 2.1 client-credentials connector block (Issuer URL viaissuerFromMcpUrl= 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.registerOAuthClientshellsgbrain auth register-client <name> --grant-types client_credentials --scopes <DEFAULT_SCOPES="read write"> --token-endpoint-auth-method client_secret_postand parsesClient ID:/Client Secret:);--oauthrejected for claude-code/codex and incompatible with--install.buildJsonis a generic shape (agent,command/command_argvnull for perplexity/generic,header,env_var, oauth fields with redaction); the codexcommandcarries 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 soclaudeandcodexshare the exec path while opencode rides the writer member;envinjectable 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.xand AWS IMDSv2-over-IPv6fd00:ec2::254) refused as a token-exfil guard while localhost/RFC1918/LAN stay allowed; token redacted from all error output.src/core/connect-probe.tsis the raw-bearer MCP smoke probe backing--install: connects the official MCP SDKClientoverStreamableHTTPClientTransportwith a STATICAuthorizationheader (no OAuth/discovery — distinct frommcp-client.ts:callRemoteToolwhich is OAuth-only andremote-mcp-probe.ts:smokeTestMcpwhich only sendsinitialize), runs the fullinitializehandshake viaclient.connect(), then callsget_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_000shared withconnect.ts.serve-http.tsadds exported pureskillPublishStatus(publishSkills)for the startup bannerSkills: published / not publishedline + a one-linegbrain config set mcp.publish_skills truestderr 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 bytest/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→/tokenmint→get_brain_identity, client registered inbeforeAllbefore serve takes the PGLite single-writer lock; drives realclaude+codexbinaries throughconnect --installwith sandboxedHOME/CODEX_HOME, asserts registration + token never in Codex config, skips when a binary is absent) +test/serve-stdio-roundtrip.test.ts(spawns realgbrain servestdio against a freshinit --pglitebrain, drives the SDK client throughinitialize→tools/list→tools/call, asserts the advertised core-tool set includingcapture, 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-runis 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 startof gbrain's own container viadocker-postgres.ts); rewrite tier under--yes --apply-rewritesonly (config-filedatabase_urlrewrites — 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-rewriteswithout--yesis 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--forcebypass 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--jsonenvelope, validates the record's postgres:// scheme before restoring, and is itself reversible (the outgoing URL becomes the new undo record); anO_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-planeengine/database_urlrows; the schema probe treats a ZERO-ROWpg_extensionresult aspgvector_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). InjectableDbRepairDepsprober/executor seam for tests;defaultDeps.probeAccessis also reused by the init ladder (one prober, one contract). Pinned bytest/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-linedatabase_errorenvelope leading with the report keys (reason= diagnosis reason, fix = the tier's next step:--yesfor auto,--yes --apply-rewriteswith consentcredentialsfor rewrite, none for manual); pre-probe refusals keep their stderr line and add an envelope (unknown_flag/invalid_paramsexit 2,requires_local_engine,config_error,lock_busy,not_found,no_brain). Healthy success shape:test/e2e/cli-json-commands-postgres.test.ts.