Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(connect): say where an installed bearer token lives and how to replace it (#5775)

garrytan31f50fcdfd81
diff --git a/docs/architecture/key-files/google-and-loops.md b/docs/architecture/key-files/google-and-loops.md
index c1edd7c7b7..24656df619 100644
--- a/docs/architecture/key-files/google-and-loops.md
+++ b/docs/architecture/key-files/google-and-loops.md
@@ -41,7 +41,7 @@ Historical Gmail repair selects explicit nested MIME metadata fields, excluding
- `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`. The resource preserves the exact seven-tool surface; source, operation, scope, fence and server-gate restrictions remain enforced at dispatch. No worker probe or per-tool database query during discovery. 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.
-- `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. 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.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) 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 <path> is not a system install, so gbrain will not run it with sudo. If you trust that binary, sign in yourself (this runs it as root): `sudo <path> set --operator=$USER && sudo <path> up`, then re-run: <rerun>" — the command is `tailscaleManualLoginCommand(binary)`, naming the discovered path shell-quoted, because a binary outside sudo's `secure_path` is exactly this case — and never spawns `sudo`; macOS `tailscale up`; bounded wait via `GBRAIN_TAILSCALE_LOGIN_TIMEOUT_MS`), `tailscale.identity` (MagicDNS name → `public_url`; pre-checks so `tailscale serve`/`funnel` — which wait interactively instead of failing when a feature is off — are never started blind: empty `CertDomains` → `pending` / exit 2 / `tailscale_https_not_enabled` with `TAILSCALE_ADMIN_DNS_URL`; `--funnel` with `funnelCapable === false` → `tailscale_funnel_not_enabled` with the ACL admin + Funnel KB URLs; `funnelCapable === null` proceeds), `tailscale.publish` (reads the serve config through `readServeView`, which FAILS CLOSED — it returns `{ view: ServeStatusView | null, stderr, status }` with `view: null` when `tailscale serve status --json` exits non-zero / is killed (`status: null`) or when stdout is not a JSON object per `parseServeStatusStrict`; an empty document / `{}` / `null` from exit 0 is the legitimately empty view — a null view before `--bg` is described once by `describeServeReadFailure` (`{ kind, detail, fix }` from one `classifyTailscaleError` call), records `tailscale.publish` = fail and returns exit 1 with reason `tailscale_<kind>` without publishing; a null view after `--bg` is `tailscale_publish_unconfirmed` naming the read failure; refuses a `/` handler proxying a different port, a foreground session or a raw TCP forward without `--force` as `foreign_serve_config` — `next_actions` says `tailscale serve status`, only `message` explains `--force`; `PUBLISH_TIMEOUT_MS` (60s) bounds `--bg`, `SERVE_OFF_TIMEOUT_MS` (30s) every `--https=443 --set-path=/ off` and `STATUS_READ_TIMEOUT_MS` (15s) both status reads; a `status: null` timeout is `unknown` with a run-by-hand hint; stderr classified by `classifyTailscaleError` as the second line of defense; switching our own handler's shape pre-clears ONLY in the funnel → tailnet direction (`funnel --https=443 --set-path=/ off` before `serve --bg`, because `serve --bg` over a Funnel mount keeps `AllowFunnel`; tailnet → funnel is one atomic `funnel --bg`), and when that pre-off was followed by a failed publish (non-zero, timeout, or unconfirmed) `restorePrevious` best-effort re-publishes the previous shape with `tailscaleServeArgv(port, { funnel: true })`, re-reads the view, and appends to the `tailscale.publish` detail whether "the previous funnel handler was restored" or "could NOT be restored"; the existing receipt is never touched on those paths), `admin_token` (ensure the 0600 token file, never printed), `service` (launchd / systemd user unit / `manual` fallback with the exact foreground and `nohup` commands; a `--no-service` re-run carries the existing receipt's service block unchanged and does not rewrite the wrapper; `service_install_failed` still writes the receipt with `service.state: 'stopped'` before exit 1 so `--status`/`--remove` can clean up the published handler; the receipt is ALSO written right after a successful service step — service state as probed at that moment — before verify runs, so a kill during verify always leaves `--status`/`--remove` something to find), `verify.local` (wall-clock `/health` polling up to 20s, timeout → `warn`, exit 2, `verify.tailnet` skipped), `verify.tailnet` (up to 30s, `pending` is exit 2 — EXCEPT when the last probe's rejection was a name-resolution failure per `mcp-expose-probe.ts`: Bun's `fetch` rejects an unresolvable host and a refused connection with the same "Unable to connect. Is the computer able to access the url?" / `ConnectionRefused`, so after a rejected fetch the URL's hostname (never an IP literal or `localhost`) is handed to `deps.lookup` — default `dns.promises.lookup`, bounded by the probe timeout — and a rejection with code `ENOTFOUND` / `EAI_AGAIN` / `EAI_NONAME` / `EAI_NODATA` / `DNS_ENOTFOUND` (or a message naming one) is the verdict, the fetch-message regex staying a secondary hint; a name that resolves but does not answer stays `pending`: then the check is `warn` with `unresolvedDetail(dnsName)` — "this host cannot resolve <name> (MagicDNS may be off here: `tailscale set --accept-dns=true`); devices that do resolve it may already reach the server" — and the run exits 0, since this host's resolver says nothing about the server), `receipt` (rewrites the early receipt with the settled state — the supervisor is re-probed once verify.local ran — keeping `created_at`). The admin-token, service and verify steps run inside one try: a THROW there after this run's `--bg` succeeded but BEFORE the early receipt is rolled back by `rollbackAfterThrow(d, s, opts, published, error, receiptWritten)` — the fresh handler is turned off again with `tailscaleServeOffArgv({ funnel })` only when no `/` handler for our port existed before the run (a pre-existing one is left in place), a `rollback` check records what happened — "turned off again" is claimed only when a re-read of the serve view after an exit-0 `off` no longer shows our port; an exit-0 `off` whose re-read still shows it is a `warn` "NOT turned off (… the handler is still present)", an unreadable re-read is a `warn` "state unknown", and an `off` that exits non-zero or throws is a `warn` whose message says the handler was NOT turned off — no receipt is written, and the error is re-thrown so the outer catch reports `mcp_expose_failed` with a message naming the handler state; once the early receipt is on disk (`receiptWritten`, checked first) a throw tears nothing down (`rollback` = skipped pointing at `--status` / `--remove --yes`), because the receipt makes everything findable (the non-throwing `service_install_failed` path keeps its partial receipt). Success banner and `next_actions` gate the local-agent line on the engine: Postgres → `gbrain bootstrap harness --yes --port N`; PGLite → pre-mint (`gbrain auth create … --scopes read,write` before the service runs) + `--token`, or the scoped `mcp grant … --url http://127.0.0.1:N/mcp --admin-token-file …` + `gbrain connect … --install` path, and "host-side commands fail with `live_serve` — administer through the running server". `--json` emits one stdout document `{ status, receipt, checks[], next_actions, reason?, message? }` with prose on stderr; every `inherit` subprocess redirects its stdout to stderr under `--json`. `--status` and `--remove` read the receipt through `readExposeReceipt`'s shape guard (a partial receipt is `not_exposed` / "nothing to remove", never a crash) and execute the tailscale binary from `resolveReceiptBinary`: the receipt's recorded path is honored only when it still exists AND is either what `findTailscaleBinary` finds now or one of `TAILSCALE_BINARY_CANDIDATES`, otherwise discovery wins — a path in a receipt is data, never a licence to run it. the probes — `probeHealth` (`res.ok`), `probeOccupied` (any response, or an accepted TCP connect), the bounded never-throwing `tryFetch` → `FetchOutcome { res, unresolved }`, `pollHealth` → `{ ok, unresolved }` with the LAST probe's resolution verdict, `unresolvedDetail`, `defaultTcpProbe`, `defaultLookup` — live in `src/commands/mcp-expose-probe.ts` and take the narrow `ProbeDeps` slice of the resolved deps (`fetch`, `tcpProbe`, `lookup`, `now`, `sleep`, `healthIntervalMs`); `defaultTcpProbe` is re-exported here so its import site never moved; `isLiveService(state)` is the one definition of "the supervisor reports our service" (`running` or `loaded`) used by the lock-holder exemption, the service check, `--status` and both `--remove` paths; `serviceLabel` builds on `serviceKindLabel` (`launchd <label>` / `systemd (user) <unit>`). `--status` runs its four independent probes (serve config, supervisor state, local and tailnet `/health`) concurrently with `Promise.all` and still reports the checks in the fixed order `receipt`, `tailscale.publish`, `service`, `verify.local`, `verify.tailnet`; an unreadable serve config (null view) is a FAILED `tailscale.publish` check / exit 1, never "handler present"; a tailnet `/health` rejected for name resolution is `verify.tailnet` = warn (same `unresolvedDetail`), not `pending`, and does not by itself make the exit non-zero. `--status` with NO receipt is `runStatusWithoutReceipt`: it runs the read-only `probeLeftovers(d, opts.port)` (`--port` is honored) and, when the wrapper, the plist / unit or a live service, or a `/` handler on `:443` proxying the port is found, emits one `warn` check per artifact (`receipt`, `service`, `tailscale.publish`, `files`), pushes `recoveryCommand(port, force)` (`gbrain mcp expose --remove --yes`, `--force` only when a handler stands alone with no wrapper / service corroborating it, `--port N` when non-default) to `next_actions`, and finishes `error` / exit 1 / `leftovers_without_receipt` (also under `--json`); an unreadable serve status alone is a caveat warn, not a leftover; nothing found keeps the `not_exposed` answer (exit 0, `--json` exit 2). `--remove` (consent; decline is `pending` / exit 2) probes the supervisor and removes a service that exists even when the receipt says skipped — `recordServiceUninstall` prints the uninstall notes, and when `launchdBootoutFailed(result)` (a `launchctl bootout failed: …` / `unload failed: …` note, i.e. a non-"not loaded" failure) the `service` check is `warn` pointing at `launchctl print gui/$(id -u)/com.gbrain.serve` and "the launchd job (bootout failed)" is added to "Left in place"; it returns the one-line service summary quoted below — then clears only gbrain's own serve/funnel handler through `turnOffOurHandler` (Funnel off first; every `off` is `--https=443 --set-path=/ off`, scoped to our `/` mount; the serve config is re-read only after an `off` command ran, otherwise the view already read is reused; a failed re-read is reported as `unknown` — a warn, never "gone"; a foreign port on `:443` gets "nothing to turn off"). `--remove` never reports success while our handler survives: when `turnOffOurHandler` returns `remaining` as a handler (`tailscale.publish` = fail) or `'unknown'` (= warn), `finishHandlerNotRemoved` keeps the receipt AND the wrapper (mirroring the unreadable-status branch), records `receipt` = skipped "kept: …", pushes `tailscale serve status` + the re-run to `next_actions`, says which service outcome already happened, and exits 1 with reason `handler_not_removed`; `--remove` never runs `tailscale serve reset`, never uninstalls or logs out, keeps the admin token unless `--force` (deleted through the same `unlinkQuietly` as the wrapper and receipt), and unlinks the wrapper / receipt / token ONLY when the path's directory is the serve directory — a receipt path elsewhere is left untouched and named in "Left in place" (also in the plan). The receipt's recorded `plist_path` / `unit_path` are data, never a licence: `uninstallServeService` is always handed the computed `d.plistPath` / `d.unitPath` (home + the fixed label / unit name), and a recorded path that differs is not touched and is named in "Left in place" as "recorded in the receipt but not the expected location". A null serve view during `--remove` fails closed: `tailscale.publish` = fail "could not read tailscale serve status; handler left as is", reason `tailscale_serve_status_unreadable`, exit 1, and the receipt AND wrapper are kept so a re-run finishes the job. With NO receipt, `runRemoveWithoutReceipt` recovers from what is on disk through the same `probeLeftovers` `--status` uses (`wrapperPath(serveDir)`, the launchd plist / systemd unit or a `running`/`loaded` service, a `/` handler on `:443` proxying `opts.port` — `--port` may accompany `--remove`, default 3131); inside it the supervisor chain (`probeServiceTarget` → `serveServiceState`) and the `readServeView` read run concurrently under `Promise.all` (the binary is resolved synchronously first) and the plan / checks are emitted in the fixed order afterwards; the re-run hints come from `recoveryCommand`. The handler is turned off only with corroborating gbrain evidence — the wrapper present, our unit/plist present, or the supervisor reporting our service live — or with `--force`, because another tool may proxy `:443` to the same port: a handler standing alone is reported (`tailscale.publish` = warn naming the proxy target and `--force`, next action `gbrain mcp expose --remove --yes --force`) and left in place on the "not exposed — nothing to remove" exit-0 path; with `--force` the plan line says so. Otherwise it prints a "Recovering without a receipt" plan (`receipt` check = warn), takes consent as usual, removes exactly those artifacts (service via the supervisor — the same `recordServiceUninstall` bootout-failure warn applies — wrapper, the handler — funnel off first when `AllowFunnel` lists the host), leaves the admin token file, and finishes `removed` with reason `recovered_without_receipt`; a handler that survives the `off` is `handler_not_removed` / exit 1 here too, with the wrapper deliberately KEPT as the corroboration the re-run needs (`files` = skipped "kept: the wrapper"; the re-run hint carries `--force` when no wrapper is left); an unreadable serve status on this path (gbrain evidence present, `serveUnreadable` set) fails closed exactly like the receipt path — the service, when found, is still uninstalled, the plan says the handler cannot be checked and the wrapper is kept, `tailscale.publish` = fail "…; handler state unknown", `files` = skipped "kept: the wrapper" (or "nothing (no wrapper was found)"), `next_actions` = `tailscale serve status --json` + the recovery command (`--force` when no wrapper is left), exit 1 with reason `tailscale_serve_status_unreadable` and message "could not read tailscale serve status; handler state unknown"; when nothing of ours is found the answer stays "not exposed — nothing to remove", exit 0 (an unreadable serve status is then only the caveat warn — there is nothing to keep and a handler alone would not be touched anyway). Every filesystem/exec effect goes through injectable deps so tests run against a fake runner in a tmpdir. Success guidance separates owner login, native OAuth registration, and machine grant/install. It uses the expose-managed owner file only when installing or keeping that service; publication with `--no-service` and no managed service instead requires the existing server's independently configured owner credential. Publishing receipts and health checks do not certify client authorization or native activation.
[Continue this subsystem](google-and-loops-continued.md).
diff --git a/docs/guides/hosted-harness-access.md b/docs/guides/hosted-harness-access.md
index d7f061899a..450b29d93f 100644
--- a/docs/guides/hosted-harness-access.md
+++ b/docs/guides/hosted-harness-access.md
@@ -134,7 +134,7 @@ gbrain connect https://your-machine.your-tailnet.ts.net/mcp --harness codex \
For Grok Bot, Muse, or another supported thin CLI adapter, also supply `--root /absolute/verified/persistent-root`. Grok Bot's recommended root is `/workspace/gbrain`. Discover and verify Muse's durable location before choosing a root. Use the generated **absolute launcher** for every later GBrain call; it pins routing and isolates inherited configuration.
-The installer preserves unrelated configuration and refuses an unowned or edited connection. Codex, Claude Code, and opencode receive private managed configuration. Generic adapters supply endpoint/authentication guidance; there is no universal configuration file. [Adapter reference](harness-adapters.md) lists supported mechanisms and reload steps.
+The installer preserves unrelated configuration and refuses an unowned or edited connection. Codex, Claude Code, and opencode receive private managed configuration (mode 0600) with the bearer token stored **inline** in that file: `~/.codex/config.toml`, Claude Code's user MCP config, or opencode's global config. The receipt names it with `token_storage: "inline"` and `config_path`, gives the `renew_command` that writes a fresh token, and lists `if_exposed`: preview and apply `gbrain mcp admin invalidate-tokens <client_id>` on the brain host ([invalidate tokens](../mcp/ADMIN.md#invalidate-tokens-revoke-or-delete)), run the renew command, then reload the harness. Neither the receipt nor the output prints the token. Treat that config file as a secret: when it sits in a Git working tree that does not ignore it, the receipt adds `token_warning`; add the file to the repository's `.gitignore` or move it, and follow `if_exposed` if it was already committed. Rotating the client secret does not invalidate issued access tokens. Generic adapters supply endpoint/authentication guidance; there is no universal configuration file. [Adapter reference](harness-adapters.md) lists supported mechanisms and reload steps.
A configured server is only one step. Follow the adapter's reload instructions and enable the GBrain standing instruction through the harness's actual controls. Thin CLI installations write that instruction to `<ROOT>/GBRAIN-INSTRUCTIONS.md`. Grok Bot/Muse native skill activation remains a separate, visible step until observed in that harness. Generated files alone do not activate a skill.
diff --git a/docs/mcp/CODEX.md b/docs/mcp/CODEX.md
index d3ff7f82f4..c1c86599c0 100644
--- a/docs/mcp/CODEX.md
+++ b/docs/mcp/CODEX.md
@@ -89,12 +89,26 @@ binary the launcher resolves.
Recent versions of the Codex CLI (`@openai/codex`) support remote
streamable-HTTP MCP servers with a bearer token read from an environment
-variable. On THIS page's `gbrain connect` path the token lives in your shell
-env, not in Codex's config file. The exception is `gbrain bootstrap harness`
-(local agent-framework boxes): framework-spawned codex inherits no shell
-profile, so that lane writes the token INLINE into a managed, 0600
-`[mcp_servers.gbrain]` block in the codex config — stated in its consent
-block, removable with `gbrain bootstrap harness --remove`.
+variable. Where the token lives depends on the path:
+
+| Path | Where the bearer token lives |
+| --- | --- |
+| `gbrain connect <url> --token <token> --agent codex [--install]` (this page) | Your shell environment (`GBRAIN_REMOTE_TOKEN`); Codex's config stores only the variable name. |
+| `gbrain connect <url> --harness codex --credentials-file <handoff> --install` (the [machine handoff](../guides/hosted-harness-access.md)) | **Inline** in a managed, 0600 `[mcp_servers.<name>]` block in `~/.codex/config.toml`. |
+| `gbrain bootstrap harness` (local agent-framework boxes) | **Inline** in the same managed block; stated in its consent block, removable with `gbrain bootstrap harness --remove`. |
+
+The inline paths exist because framework-spawned Codex inherits no shell
+profile. Anything that reads or prints that config file (support bundles,
+config diffs, agents inspecting MCP entries) can see a live token. The
+`--harness codex --install` receipt says so: `token_storage: "inline"`,
+`config_path`, the `renew_command` that writes a fresh token, and `if_exposed`,
+which lists the [token invalidation](ADMIN.md#invalidate-tokens-revoke-or-delete)
+preview and apply commands for the brain host, then the renew command and the
+Codex reload. When the config file sits in a Git working tree that does not
+ignore it, the receipt adds `token_warning`: add the file to that repository's
+`.gitignore` or move the config, and follow `if_exposed` if it was already
+committed. Rotating a client secret does not invalidate access tokens already
+issued, so it is not the fix for an exposed token.
## Fastest path: `gbrain connect`
diff --git a/llms-full.txt b/llms-full.txt
index 5529f172c4..d6b93f103e 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -1428,7 +1428,7 @@ gbrain connect https://your-machine.your-tailnet.ts.net/mcp --harness codex \
For Grok Bot, Muse, or another supported thin CLI adapter, also supply `--root /absolute/verified/persistent-root`. Grok Bot's recommended root is `/workspace/gbrain`. Discover and verify Muse's durable location before choosing a root. Use the generated **absolute launcher** for every later GBrain call; it pins routing and isolates inherited configuration.
-The installer preserves unrelated configuration and refuses an unowned or edited connection. Codex, Claude Code, and opencode receive private managed configuration. Generic adapters supply endpoint/authentication guidance; there is no universal configuration file. [Adapter reference](harness-adapters.md) lists supported mechanisms and reload steps.
+The installer preserves unrelated configuration and refuses an unowned or edited connection. Codex, Claude Code, and opencode receive private managed configuration (mode 0600) with the bearer token stored **inline** in that file: `~/.codex/config.toml`, Claude Code's user MCP config, or opencode's global config. The receipt names it with `token_storage: "inline"` and `config_path`, gives the `renew_command` that writes a fresh token, and lists `if_exposed`: preview and apply `gbrain mcp admin invalidate-tokens <client_id>` on the brain host ([invalidate tokens](../mcp/ADMIN.md#invalidate-tokens-revoke-or-delete)), run the renew command, then reload the harness. Neither the receipt nor the output prints the token. Treat that config file as a secret: when it sits in a Git working tree that does not ignore it, the receipt adds `token_warning`; add the file to the repository's `.gitignore` or move it, and follow `if_exposed` if it was already committed. Rotating the client secret does not invalidate issued access tokens. Generic adapters supply endpoint/authentication guidance; there is no universal configuration file. [Adapter reference](harness-adapters.md) lists supported mechanisms and reload steps.
A configured server is only one step. Follow the adapter's reload instructions and enable the GBrain standing instruction through the harness's actual controls. Thin CLI installations write that instruction to `<ROOT>/GBRAIN-INSTRUCTIONS.md`. Grok Bot/Muse native skill activation remains a separate, visible step until observed in that harness. Generated files alone do not activate a skill.
diff --git a/src/commands/harness-connect.ts b/src/commands/harness-connect.ts
index 126a04baa7..22bf6b7b36 100644
--- a/src/commands/harness-connect.ts
+++ b/src/commands/harness-connect.ts
@@ -1,7 +1,7 @@
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
import { readCredentials, credentialReceipt } from '../core/harness/credentials.ts';
import { harnessAdapter } from '../core/harness/registry.ts';
-import { installHarnessConnection } from '../core/harness/install.ts';
+import { installHarnessConnection, type inlineTokenReceipt } from '../core/harness/install.ts';
import { normalizeMcpUrl } from '../core/mcp-registration.ts';
import { validateHarnessArguments } from '../core/harness/arguments.ts';
import { readHarnessConnectionStatus } from '../core/harness/status.ts';
@@ -27,9 +27,15 @@ export async function runHarnessConnect(args: string[]): Promise<void> {
const endpoint = normalizeMcpUrl(args[0] ?? '');
if (!endpoint.ok || endpoint.url !== c.mcp_url) throw new Error('Endpoint does not match the private credential handoff');
const result = args.includes('--install') || args.includes('--remove')
- ? await installHarnessConnection(c, { harness: harness.id, name: value('--name'), root: value('--root'), remove: args.includes('--remove') })
+ ? await installHarnessConnection(c, { harness: harness.id, name: value('--name'), root: value('--root'), remove: args.includes('--remove'), credentialsFile: path })
: { ...credentialReceipt(c), status: 'prepared', harness: harness.id, documentation: harness.guide, next_action: 'Run this command with --install inside the intended harness environment. Keep the credential file private.' };
console.log(JSON.stringify(result, null, args.includes('--json') ? undefined : 2));
+ const token = result as Partial<ReturnType<typeof inlineTokenReceipt>>;
+ if (!args.includes('--json') && token.token_storage === 'inline' && token.if_exposed) {
+ console.error(`The bearer token is stored inline in ${token.config_path}; this output never prints it. Renew it with: ${token.renew_command}`);
+ console.error(`If it was exposed: ${token.if_exposed.steps.join(' Then: ')} See ${token.if_exposed.docs_url}.`);
+ if (token.token_warning) console.error(`WARNING: ${token.token_warning}`);
+ }
if (result.status === 'pending' || 'remote_membership_pending' in result && result.remote_membership_pending) setCliExitVerdict(2);
} catch (error) {
console.log(JSON.stringify({ status: 'error', reason: 'connection_setup_failed', message: error instanceof Error ? error.message : 'Connection setup failed' }));
diff --git a/src/core/harness/install.ts b/src/core/harness/install.ts
index d9b025d59d..3d22e22f45 100644
--- a/src/core/harness/install.ts
+++ b/src/core/harness/install.ts
@@ -1,6 +1,7 @@
import { createHash } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
import { existsSync, readFileSync, mkdirSync, lstatSync, unlinkSync, readdirSync } from 'node:fs';
-import { dirname, join } from 'node:path';
+import { dirname, join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';
import { acquireBootstrapLock } from '../bootstrap/lock.ts';
@@ -11,6 +12,7 @@ import { renderAgentLauncher } from '../agent-install/launcher.ts';
import { isValidName, shellQuote } from '../mcp-registration.ts';
import { GBRAIN_MCP_INSTRUCTIONS } from '../../mcp/instructions.ts';
import { harnessAdapter } from './registry.ts';
+import { GIT_ENV } from '../git-remote.ts';
import { credentialAccessToken, credentialReceipt, type HarnessCredentials } from './credentials.ts';
import { assertNoSymlinks, checkedRoot, confinedPath, sha256, privateWrite } from '../agent-install/state.ts';
import { installSharedSkillsConnection } from './shared-skills.ts';
@@ -18,7 +20,7 @@ import type { SharedSkillsToolCaller } from '../shared-skills/adapter.ts';
import { harnessSharedSkillsRoot } from './status.ts';
export interface InstallOptions { harness: string; name?: string; root?: string; configPath?: string; remove?: boolean;
- sharedSkills?: HarnessCredentials['shared_skills']; toolCaller?: SharedSkillsToolCaller; nativeSkillsDir?: string }
+ sharedSkills?: HarnessCredentials['shared_skills']; toolCaller?: SharedSkillsToolCaller; nativeSkillsDir?: string; credentialsFile?: string }
const hash = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
const readJson = (path: string): Record<string, any> => {
assertNoSymlinks(path);
@@ -41,6 +43,33 @@ function nativeEntry(path: string, format: string, name: string): unknown {
return entries?.[name];
}
+/** The Git working tree whose next commit would include `path`, or null when it is ignored or outside every tree. */
+function committingGitTree(path: string): string | null {
+ const git = (args: string[]) => execFileSync('git', ['-C', dirname(path), ...args],
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: { ...process.env, ...GIT_ENV } }).trim();
+ let tree: string;
+ try { tree = git(['rev-parse', '--show-toplevel']); } catch { return null; }
+ try { git(['check-ignore', '-q', '--', path]); return null; } catch { return tree; }
+}
+
+/** Where an installed bearer token lives and how to replace it, never the token itself (#5775). */
+export function inlineTokenReceipt(c: HarnessCredentials, harness: string, name: string, configPath: string, reload: string, credentialsFile?: string) {
+ const renew = ['gbrain connect', shellQuote(c.mcp_url), '--harness', shellQuote(harness), '--credentials-file',
+ credentialsFile ? shellQuote(credentialsFile) : '<private-handoff-file>', ...(name === 'gbrain' ? [] : ['--name', shellQuote(name)]), '--install'].join(' ');
+ const invalidate = (apply: string) => `gbrain mcp admin invalidate-tokens ${shellQuote(c.client_id)}${apply} --url ${shellQuote(c.mcp_url)} --admin-token-file <owner-admin-token-file> --json`;
+ const tree = committingGitTree(configPath);
+ return {
+ token_storage: 'inline' as const, config_path: configPath, renew_command: renew,
+ if_exposed: {
+ steps: [`On the brain host, preview: ${invalidate('')}`, `Apply with the previewed revision: ${invalidate(' --yes --if-version <revision>')}`,
+ `Write a fresh token here: ${renew}`, reload],
+ docs_url: 'docs/mcp/ADMIN.md#invalidate-tokens-revoke-or-delete',
+ },
+ ...(tree ? { token_warning: `${configPath} is inside the Git working tree ${tree}, so committing there would publish this bearer token. `
+ + `Add ${relative(tree, configPath).split('\\').join('/')} to that repository's .gitignore or move the configuration; if it was already committed, follow if_exposed.` } : {}),
+ };
+}
+
function assertEntryOwned(entry: unknown, prior: Record<string, any>) {
if (entry !== undefined && (!prior.client_id || ![prior.entry_hash, prior.pending_entry_hash].includes(hash(entry)))) throw new Error('configuration_conflict: refusing to replace an unowned or edited MCP entry');
}
@@ -116,7 +145,8 @@ export async function installHarnessConnection(c: HarnessCredentials, opts: Inst
next_action: pending ? 'Local configuration and unchanged owned skills were removed. Remote membership deactivation remains pending; retry when host authority is available.'
: 'The client configuration was removed. Revoke the grant on the brain host if access should end.' };
}
- const nextReceipt = { ...common, entry_hash: hash(nativeEntry(configPath, adapter.connection, name)), status: 'installed', config_path: configPath };
+ const nextReceipt = { ...common, entry_hash: hash(nativeEntry(configPath, adapter.connection, name)), status: 'installed',
+ ...inlineTokenReceipt(c, adapter.id, name, configPath, adapter.reload, opts.credentialsFile) };
atomicWriteTextFile(receiptPath, `${JSON.stringify(nextReceipt, null, 2)}\n`, { forceMode: 0o600 });
const shared_skills = deactivated ?? await installSharedSkillsConnection(c, { ...opts, root: join(dirname(configPath), `.gbrain-${adapter.id}-${name}`) });
return { ...nextReceipt, shared_skills, remote_membership_pending: 'remote_membership_pending' in shared_skills && shared_skills.remote_membership_pending === true };
diff --git a/test/harness-token-receipt.test.ts b/test/harness-token-receipt.test.ts
new file mode 100644
index 0000000000..3cca9c283c
--- /dev/null
+++ b/test/harness-token-receipt.test.ts
@@ -0,0 +1,73 @@
+/** #5775: an inline-token install names where the token lives and how to replace it, never the token. */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { installHarnessConnection } from '../src/core/harness/install.ts';
+import { writeCredentials, type HarnessCredentials } from '../src/core/harness/credentials.ts';
+
+const REPO_ROOT = resolve(import.meta.dir, '..');
+const roots: string[] = [];
+const temp = () => { const p = mkdtempSync(join(tmpdir(), 'gbrain-token-receipt-')); roots.push(p); return p; };
+afterEach(() => { for (const p of roots.splice(0)) rmSync(p, { recursive: true, force: true }); });
+const TOKEN = 'fixture-access-private-value';
+const creds = (): HarnessCredentials => ({ version: 1, mcp_url: 'https://brain.example.com/mcp', issuer_url: 'https://brain.example.com', client_id: 'gbrain_cl_fixture',
+ access_token: TOKEN, client_secret: 'fixture-client-private-value', profile: 'memory-writer', source_id: 'default', expires_at: Date.now() / 1000 + 3600 });
+const CONFIG = { codex: 'config.toml', 'claude-code': 'claude.json', opencode: 'opencode.jsonc' } as const;
+const RELOAD = { codex: 'Start a new Codex session and inspect /mcp.', 'claude-code': 'Restart Claude Code and inspect /mcp.', opencode: 'Restart opencode and inspect its MCP connections.' } as const;
+
+describe('inline bearer token receipt (#5775)', () => {
+ for (const harness of ['codex', 'claude-code', 'opencode'] as const) test(`${harness} receipt names storage, renewal and exposure recovery without the token`, async () => {
+ const dir = temp(), configPath = join(dir, CONFIG[harness]), handoff = join(dir, 'handoff.json');
+ const receipt = await installHarnessConnection(creds(), { harness, configPath, credentialsFile: handoff, name: 'example-brain' }) as Record<string, any>;
+ const renew = `gbrain connect https://brain.example.com/mcp --harness ${harness} --credentials-file ${handoff} --name example-brain --install`;
+ expect(receipt).toMatchObject({ status: 'installed', token_storage: 'inline', config_path: configPath, renew_command: renew });
+ expect(receipt.if_exposed).toEqual({
+ steps: [
+ 'On the brain host, preview: gbrain mcp admin invalidate-tokens gbrain_cl_fixture --url https://brain.example.com/mcp --admin-token-file <owner-admin-token-file> --json',
+ 'Apply with the previewed revision: gbrain mcp admin invalidate-tokens gbrain_cl_fixture --yes --if-version <revision> --url https://brain.example.com/mcp --admin-token-file <owner-admin-token-file> --json',
+ `Write a fresh token here: ${renew}`,
+ RELOAD[harness],
+ ],
+ docs_url: 'docs/mcp/ADMIN.md#invalidate-tokens-revoke-or-delete',
+ });
+ expect(receipt.token_warning).toBeUndefined();
+ expect(readFileSync(configPath, 'utf8')).toContain(TOKEN);
+ expect(JSON.stringify(receipt)).not.toContain(TOKEN);
+ expect(readFileSync(join(dir, `.gbrain-connection-${harness}-example-brain.json`), 'utf8')).not.toContain(TOKEN);
+ });
+
+ test('a configuration inside a Git working tree warns with the fix until it is ignored', async () => {
+ const repo = temp(), configPath = join(repo, '.codex', 'config.toml');
+ execFileSync('git', ['init', '--quiet', repo]);
+ mkdirSync(join(repo, '.codex'));
+ const first = await installHarnessConnection(creds(), { harness: 'codex', configPath }) as Record<string, any>;
+ expect(first.renew_command).toBe('gbrain connect https://brain.example.com/mcp --harness codex --credentials-file <private-handoff-file> --install');
+ expect(first.token_warning).toBe(`${configPath} is inside the Git working tree ${execFileSync('git', ['-C', repo, 'rev-parse', '--show-toplevel'], { encoding: 'utf8' }).trim()}, `
+ + "so committing there would publish this bearer token. Add .codex/config.toml to that repository's .gitignore or move the configuration; if it was already committed, follow if_exposed.");
+ writeFileSync(join(repo, '.gitignore'), '.codex/config.toml\n');
+ const ignored = await installHarnessConnection(creds(), { harness: 'codex', configPath }) as Record<string, any>;
+ expect(ignored.token_warning).toBeUndefined();
+ });
+
+ test('connect --install human output says where the token lives and never prints it', async () => {
+ const dir = temp(), handoff = join(dir, 'handoff.json');
+ writeCredentials(handoff, { ...creds(), harness: 'codex' });
+ const env: Record<string, string> = {};
+ for (const [key, value] of Object.entries(process.env)) if (value !== undefined) env[key] = value;
+ for (const key of ['DATABASE_URL', 'GBRAIN_DATABASE_URL']) delete env[key];
+ Object.assign(env, { HOME: dir, GBRAIN_HOME: dir, CODEX_HOME: join(dir, '.codex'), GBRAIN_SELF_UPGRADE_MODE: 'off', GBRAIN_SKIP_STARTUP_HOOKS: '1' });
+ const proc = Bun.spawn(['bun', 'run', join(REPO_ROOT, 'src', 'cli.ts'), 'connect', 'https://brain.example.com/mcp', '--harness', 'codex', '--credentials-file', handoff, '--install'],
+ { cwd: dir, env, stdout: 'pipe', stderr: 'pipe' });
+ const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ expect(code).toBe(0);
+ const configPath = join(dir, '.codex', 'config.toml');
+ expect(JSON.parse(stdout)).toMatchObject({ status: 'installed', token_storage: 'inline', config_path: configPath });
+ expect(stderr).toContain(`The bearer token is stored inline in ${configPath}; this output never prints it. Renew it with: gbrain connect https://brain.example.com/mcp --harness codex --credentials-file ${handoff} --install`);
+ expect(stderr).toContain('If it was exposed: On the brain host, preview: gbrain mcp admin invalidate-tokens gbrain_cl_fixture');
+ expect(stderr).toContain('docs/mcp/ADMIN.md#invalidate-tokens-revoke-or-delete');
+ expect(stdout + stderr).not.toContain(TOKEN);
+ expect(readFileSync(configPath, 'utf8')).toContain(TOKEN);
+ }, 60_000);
+});