Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
25.8 KB
Raw Blame

Google connector + open-loop engine (more)

Subsystem index · Previous entries.

  • src/core/harness/oauth-setup.ts + client-setup.ts — explicit client metadata projection, flow selection, native OAuth setup/private-file validation, and live-row-locked secret delivery recovery. Public PKCE needs no journal; confidential exports validate the retained secret against current registration, and machine exports discard cached tokens. Unknown/mixed flows refuse until an explicit supported flow is selected.
  • src/core/harness/capabilities.ts + src/mcp/capabilities.ts — Shared effective-grant orientation for OAuth whoami and authenticated gbrain://capabilities. A stored client token lifetime outside 60 to 7,776,000 seconds (AuthInfo.tokenTtlSeconds) reports token_ttl_invalid, and the delegation repair template then includes a --token-ttl <APPROVED_TTL_SECONDS> choice, since every grant write validates the merged lifetime. The resource preserves the exact seven-tool surface; source, operation, scope, fence and server-gate restrictions remain enforced at dispatch. grant_diagnosis (shared with doctor grant_new_ops_available through grantOperationGaps, grantAge and grantRescopeArgvs) counts the operations the grant's scopes allow but its operation snapshot, its client pin or the server ceiling block, names none of them, keeps inferred grant age apart (intent_unknown without catalog provenance), and builds host commands only from the verifier's principal. No worker probe or per-tool database query during discovery (one audit read for provenance when a snapshot excludes operations). Shared administration guidance explains separate owner authority, links the MCP admin runbook, and exposes an admin URL only for a configured credential-free HTTP MCP endpoint. Stdio never infers an HTTP address. D4 in band: grantBlockedNotice(diagnosis, {refused}) builds the grant_blocked_operations notice (blocker counts, grant age apart, missing scope only when refused; a client narrowed on purpose — grant age provenance_recorded, nothing predating, every blocker an operation snapshot — gets it only on a refused call) and grantRepairAction the host-owned repair (preview argv, then apply, verify = doctor grant_new_ops_available or whoami; server ceiling alone → the read-only doctor check). Dispatch (grantBlockedNotices) delivers it once per (principal, session) or, stateless, per (principal, grant revision).
  • src/commands/mcp.ts + mcp-provision.ts + harness-connect.ts — Host-side grant/preview/CAS and recoverable private delivery, followed by installation inside the intended harness. Codex, Claude Code and opencode installs (src/core/harness/install.ts) store the bearer token inline in the harness config; inlineTokenReceipt adds token_storage, config_path, renew_command, if_exposed (invalidate-tokens preview/apply, renew, reload; renew_command carries --fresh-token for renewable handoffs so it always exchanges a new token) and a token_warning when a Git working tree would commit the file, and harness-connect.ts repeats them on stderr in human mode without printing the token (#5775; test/harness-token-receipt.test.ts). Running PGLite hosts are administered through their authenticated API, never by opening a second database process. CLI status uses the delivery-aware exit verdict. mcp-admin.ts and mcp-admin-http.ts provide engine-free owner commands with explicit-file/env credential precedence, in-memory sessions, private native exports, versioned lifecycle previews, and safe stage/outcome/remedy receipts. Unknown mutation outcomes require inspection instead of automatic repetition. runMcp also dispatches gbrain mcp expose to runMcpExpose (dynamic import of ./mcp-expose.ts; HELP carries the expose lines so the flag registry harvests them) and sets the CLI exit verdict from its returned code. mcpNeedsEngine(args) is true only for grant without an owner credential (--admin-token-file or GBRAIN_ADMIN_BOOTSTRAP_TOKEN) and outside help; admin, expose, and verify never open the database.
  • src/commands/mcp-expose.ts — gbrain mcp expose [--port N] [--funnel] [--surface] [--enable-dcr] [--no-tailscale] [--no-service] [--no-install] [--force] [--dry-run] [--yes] [--json] / --status / --remove: publishes gbrain serve --http on the user's Tailscale tailnet (Serve by default, Funnel only with the explicit flag) and keeps it running as a user service. runMcpExpose(args, deps?) returns the exit code (0 done, 1 failed, 2 needs --yes, the prompt was declined, or a step is pending — a tailnet feature to enable, Tailscale login, tailnet certificate). Arg validation via validateHarnessArguments (exclusive pairs --status/--remove, --funnel/--no-tailscale, --dry-run/--status); the help text names every flag and the verify.local / verify.tailnet checks. Ordered named checks — plan (platform, execution environment, engine kind from loadConfig(); thin clients are refused with "run on the brain host"; engine === 'unknown' — no config or an unreadable one — without --no-service is refused as no_brain_config / exit 1 with next action gbrain init BEFORE consent, because a service around a missing brain only crash-loops, while --dry-run still prints the plan with the refusal marked and exits 0; on a PGLite engine deps.pgliteHolder (default probeLivePgliteHolder from src/core/bootstrap/uninstall.ts, a read-only lock-file probe) is consulted with cfg.database_path, and a live holder that is not our own managed service — receipt present with service.state running/loaded — adds a Lock plan line plus a pglite_lock check with status warn (never a stop); --no-tailscale over an existing receipt whose tailscale.dns_name is set (a live Serve/Funnel mapping) is refused BEFORE consent as tailscale_receipt_present / exit 1 with next actions gbrain mcp expose --remove --yes and the re-run without the flag — --dry-run marks it WOULD BE REFUSED; then probes 127.0.0.1:<port> with probeOccupied(d, port, url) — occupied when EITHER the injectable deps.tcpProbe (default defaultTcpProbe, one node:net connect, socket destroyed on every outcome; true on connect, false on refusal / timeout / throw) accepts a TCP connect OR the /health fetch RESOLVES with ANY status (2xx, 404, 500), so a non-HTTP listener counts too; only both rejecting is free — and refuses a foreign listener with no receipt claiming that port as foreign_listener BEFORE anything is published unless --no-service; the message names the interrupted-run escape hatch gbrain mcp expose --remove --yes; probeHealth (res.ok) stays the bar for verify.local / verify.tailnet / --status), consent (shared confirmOrFinish for publish and --remove: one stderr y/N prompt on a TTY; declining is pending / exit 2 / declined with "Nothing changed. Re-run with --yes to confirm."; non-interactive without --yes prints the plan and exits 2 / confirmation_required; every re-run hint is rendered by rerunCommand(opts) — the user's publish flags + --yes), tailscale.binary (install plan: brew cask on macOS — then open -a Tailscale and a bounded poll of tailscale status --json, up to 20 attempts 1s apart, breaking as soon as the app's daemon answers and otherwise falling through to the login step's daemon-not-running handling — official installer on Linux, --no-install → exit 1), tailscale.login (Linux sudo tailscale set --operator=<user> non-fatal then flagless sudo tailscale up — sudo is put in front of the binary ONLY when isSystemTailscaleBinary(binary) holds (one of TAILSCALE_BINARY_CANDIDATES, literally or via realpathSync); a user-writable tailscale found on PATH stops the step as pending / exit 2 / tailscale_login_manual with the message "tailscale at
  • src/core/connector-install-links.ts — pure builders for one-click client links: cursorInstallLink(mcpUrl, name='gbrain') (Cursor's documented cursor://anysphere.cursor-deeplink/mcp/install?name=…&config=…, config = base64 of JSON.stringify({ url }), then encodeURIComponent), claudeConnectorLink(mcpUrl, name='GBrain') (Anthropic's documented custom connector install link, https://claude.ai/customize/connectors?modal=add-custom-connector&connectorName=…&connectorUrl=…), connectorInstallLinks(mcpUrl, isPublic) (Claude only when isPublic, since claude.ai connects from Anthropic's cloud) installLinkLines(links, isPublic) (the two-column human lines) and printInstallLinks(mcpUrl, isPublic, say) (builds, prints, returns the links for --json). Every builder returns null unless the URL parses as absolute https: with a hostname and no userinfo, so a link never carries a credential. test/connector-install-links.test.ts pins the docs' gbrain.io links to these builders.
  • src/commands/mcp-expose-probe.ts — the health / occupancy probes mcp-expose.ts runs, peeled out behind a narrow ProbeDeps (fetch, tcpProbe, lookup, now, sleep, healthIntervalMs) rather than the whole resolved-deps bag: tryFetch(d, url, timeoutMs) (one bounded fetch, redirect: 'manual', never throws → FetchOutcome { res, unresolved }), probeHealth (res.ok — the verify.* / --status bar), probeOccupied (an accepted TCP connect OR any HTTP answer — the foreign-listener bar), pollHealth (wall-clock budget from d.now(), per-probe timeout min(1500, remaining), attempt cap ceil(budget / healthIntervalMs) as the frozen-clock backstop, unresolved = the LAST probe's verdict), unresolvedDetail(dnsName), defaultTcpProbe (one node:net connect, socket destroyed on every outcome) and defaultLookup (local RFC 6761 .invalid rejection, otherwise dns.promises.lookup). The name-resolution verdict is the reason the module exists: Bun's fetch rejects an unresolvable host with the SAME error as a refused connection ("Unable to connect. Is the computer able to access the url?", code ConnectionRefused), so a message match alone never fires in production. After a rejection nameUnresolved takes new URL(url).hostname, skips IP literals (isIP) and localhost, and otherwise awaits d.lookup(host) raced against the probe's timeoutMs (a lookup that does not answer in time proves nothing; the race keeps a late rejection handled); isUnresolvedLookupError classifies the lookup rejection by code — ENOTFOUND, EAI_AGAIN, EAI_NONAME, EAI_NODATA, DNS_ENOTFOUND (a resolver outage counts: the verdict is about THIS host) — or by those tokens in its message, and the fetch-message regex (ENOTFOUND|getaddrinfo|EAI_AGAIN|failed to resolve|Unable to connect.*resolve) is OR-ed in afterwards as the secondary hint. Tests inject a fake fetch, TCP probe and resolver (test/mcp-expose.test.ts; the fixture's default lookup resolves every name, reserved-name and label-boundary cases do not query external DNS, and the real defaultLookup resolves localhost). statusOnlyHealthDetail(port) reads this host's live status-only marker for the port so verify.local reads "status-only ()" instead of a timeout or "no answer".