Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(thin-client): report a rate-limited /token mint as rate-limited, not "OAuth discovery failed"

garrytane659c0fa5ec7
diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.md
index 86446d2bd1..bc1202a22b 100644
--- a/docs/architecture/key-files/runtime.md
+++ b/docs/architecture/key-files/runtime.md
@@ -19,7 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/console-prefix.ts` — `AsyncLocalStorage<string>`-backed per-source line-prefix helper. Exports `withSourcePrefix(id, fn)` (runs `fn` with `id` as active prefix; nested wraps replace then restore), `getSourcePrefix()` (read-only accessor; test seam), `slog(...)` / `serr(...)` (prefix-aware `console.log`/`console.error`), and `withHumanLogsToStderr(fn)` (runs `fn` with every `slog` line, prefixed or not, routed to stderr; `runSync` wraps its body in it under `--json` so stdout carries only the ONE JSON envelope (the cost-gate status object rides inside it as `cost_gate`, #4684) while `serr` and direct `console.log(JSON.stringify(..))` sites are unaffected; scoped via its own `AsyncLocalStorage`, never a process-wide console rebind). Embedded-newline-safe: a multi-line string under prefix `[foo]` emits `[foo] line1\n[foo] line2`. Outside a wrap, `slog`/`serr` fall through to bare `console.log`/`console.error` so single-source callers see identical output (back-compat invariant). Use `src.id` (slug-validated by `sources add`) NOT `src.name` (free-form) to defeat log-injection through newline/control-character names. Coverage: `src/commands/sync.ts` performSync + callees, `src/commands/embed.ts` runEmbedCore + helpers, `src/core/progress.ts` emitHumanLine, `src/commands/import.ts` runImport's human-only lines (`info()` + the end-of-run `Import complete` summary — so the first-sync full import under `sync --json` lands on stderr too).
-- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout, and `buildMcpRequestOptions` forwards `timeoutMs` as the SDK request deadline (otherwise its own 60s default wins); an SDK `RequestTimeout` classifies as `network`/`timeout`, never unreachable. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). `extractToolErrorCode` parses the operation `{error: string, message}` shape as well as legacy envelopes. Mutation arguments retain one request UUID before the first transport attempt, across OAuth refresh and caller retries. Mutation errors retain that UUID and distinguish unknown delivery from requests never submitted; the shared CLI renderer emits same-ID retry guidance without fabricating a receipt. Received pending or terminal error receipts and frozen verb metadata survive deadlines during client cleanup, including the refreshed attempt. Only the locked SDK’s typed `StreamableHTTPError` with numeric code 401 triggers one refresh and reconstructed client; application error text never causes authentication replay. The outer abort signal reaches discovery, minting, initialization, fetch and tool calls, with per-request limits retained and clients closed after failed initialization or abort. `unpackToolResult<T>(res)` parses tool-call JSON content. `ignoredRemoteParams(res)` lists params the host reported ignoring (`_meta.warnings` `unknown_param` entries plus the warning text blocks after `content[0]`); the CLI fails when a sent scope param (`source_id`, `all_sources`) is among them and warns for other ignored params the op declares. `_clearMcpClientTokenCache()` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`. Agent contract v1: a tool_error body is `content[0]` alone; `extractToolErrorDetail` keeps `code` (legacy `error`) plus `canonical_code`, `reason`, `why`, `fix`, `notices`, `contract_version`; `RemoteMcpError.toJSON` adds `code` (derived via `canonicalCodeFor` for old servers) and those fields when present; `extractNotices(res)` reads `_meta.gbrain_notices` or prefixed blocks. Skew pinned by `test/thin-client-contract-skew.test.ts` with a frozen v0.60.37.0 parser.
+- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout, and `buildMcpRequestOptions` forwards `timeoutMs` as the SDK request deadline (otherwise its own 60s default wins); an SDK `RequestTimeout` classifies as `network`/`timeout`, never unreachable. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). A /token 429 is `rate_limited` with `RemoteMcpErrorDetail.retry_after_s` parsed from Retry-After (`parseRetryAfterSeconds` in `remote-mcp-probe.ts`); any other non-auth /token failure is `token`, never `discovery`. `extractToolErrorCode` parses the operation `{error: string, message}` shape as well as legacy envelopes. Mutation arguments retain one request UUID before the first transport attempt, across OAuth refresh and caller retries. Mutation errors retain that UUID and distinguish unknown delivery from requests never submitted; the shared CLI renderer emits same-ID retry guidance without fabricating a receipt. Received pending or terminal error receipts and frozen verb metadata survive deadlines during client cleanup, including the refreshed attempt. Only the locked SDK’s typed `StreamableHTTPError` with numeric code 401 triggers one refresh and reconstructed client; application error text never causes authentication replay. The outer abort signal reaches discovery, minting, initialization, fetch and tool calls, with per-request limits retained and clients closed after failed initialization or abort. `unpackToolResult<T>(res)` parses tool-call JSON content. `ignoredRemoteParams(res)` lists params the host reported ignoring (`_meta.warnings` `unknown_param` entries plus the warning text blocks after `content[0]`); the CLI fails when a sent scope param (`source_id`, `all_sources`) is among them and warns for other ignored params the op declares. `_clearMcpClientTokenCache()` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`. Agent contract v1: a tool_error body is `content[0]` alone; `extractToolErrorDetail` keeps `code` (legacy `error`) plus `canonical_code`, `reason`, `why`, `fix`, `notices`, `contract_version`; `RemoteMcpError.toJSON` adds `code` (derived via `canonicalCodeFor` for old servers) and those fields when present; `extractNotices(res)` reads `_meta.gbrain_notices` or prefixed blocks. Skew pinned by `test/thin-client-contract-skew.test.ts` with a frozen v0.60.37.0 parser.
- `src/core/op-checkpoint.ts` — DB-backed checkpoint primitive for long-running ops. Migration v67 introduces `op_checkpoints (op TEXT, fingerprint TEXT, completed_keys JSONB, updated_at TIMESTAMPTZ, PK(op, fingerprint))`. Per-op fingerprint helpers (`embedFingerprint`, `extractFingerprint`, `reindexFingerprint`, `integrityFingerprint`, `purgeFingerprint`) compute `sha8(canonical-JSON(relevant-params))` so re-running with the same params resumes from `completed_keys` and re-running with different params (e.g. `--limit 100` vs `--limit 200`) starts fresh. Cross-worker safe on Postgres (DB row, no file-lock race); PGLite degrades gracefully. The 7-day TTL GC runs in the cycle's `purge` phase. All writes (`recordCompleted`, `clearOpCheckpoint`) route through `engine.executeRawDirect` + `withRetry(BULK_RETRY_OPTS)` so they survive Supavisor pool exhaustion, and `recordCompleted` returns `boolean` (banked vs failed-after-retries) — the 9 non-sync consumers keep its REPLACE-into-`completed_keys` semantics. Resumable sync uses the additive `appendCompleted(key, deltaKeys)` / `appendCompletedOnce` (the latter no-retry for the SIGTERM path) which INSERT a delta into the `op_checkpoint_paths` child table (migration v115: `(op, fingerprint, path)` PK, FK to `op_checkpoints` ON DELETE CASCADE) via a single writable-CTE `unnest($3::text[])` write — O(delta), never an O(N²) full-set rewrite. `loadOpCheckpoint` returns the `UNION ALL` of legacy `completed_keys` + child-table paths (deduped in JS), so an in-flight upgrade loses nothing. The legacy arm is gated on `jsonb_typeof(completed_keys) = 'array'` so a non-array (scalar) parent row can't make `jsonb_array_elements_text` throw "cannot extract elements from a scalar" and take down the whole union (which would discard the valid child rows and lose all banked progress for the key); a third union arm flags the corruption so the loader logs it once and keeps the child rows. Migration v119 adds the `op_checkpoints_completed_keys_array` CHECK (`jsonb_typeof(completed_keys) = 'array'`) — a DB-enforced, always-on guard that makes the scalar-corruption class structurally impossible going forward; the migration repairs any pre-existing scalar to `'[]'` under `LOCK TABLE ... IN SHARE ROW EXCLUSIVE MODE` and `src/core/schema-embedded.generated.ts` + `src/core/pglite-schema.ts` ship the same CHECK on fresh installs (a loader hit implies schema drift, a disabled constraint, or an out-of-band writer). `recordCompleted` binds its array through `$3::text::jsonb` (NOT a bare `$3::jsonb`) so postgres.js `.unsafe()` doesn't double-encode `JSON.stringify(sorted)` into the scalar string that CHECK rejects (PGLite parses it silently, so only real Postgres surfaces the bug). A DATABASE_URL-gated `test/e2e/op-checkpoint-jsonb-parity.test.ts` (its own CI job) asserts the array shape on real Postgres. `syncFingerprint({sourceId, lastCommit})` keys the sync rows. Pinned by `test/op-checkpoint.test.ts` (incl. delta-append, union read, cascade clear, durable-write boolean, and the scalar-parent guard). `import-checkpoint.ts` stays a separate file-backed checkpoint — both systems coexist without conflict (unifying them would mean async-propagating the four sync call sites in `src/commands/import.ts`; deferred). TTL cleanup preserves unresolved managed cursors, their manifests and failure observations; a completed full cursor does not hide a different failed incremental cursor. Unfinished `managed-atoms` and `managed-atoms-generation` checkpoints survive ordinary seven-day GC so accepted output/retry state is not silently forgotten.
- `src/core/persistence/preview-approval.ts` — preview-bound approval shared by `jobs authorize-legacy --select`, `jobs cancel --select`, `repair stale-atoms` and `repair extractor-facts` (fix wave 5, ENG-O1). `previewHash(parts)` is SHA-256 over key-sorted JSON, byte-identical to `authorityDigest`; `saveApprovedSet` / `loadApprovedSet` / `clearApprovedSet` keep the approved items in `op_checkpoints` (`op='repair-approval'`, fingerprint `<command>:<hash>`). A missing, foreign, malformed or older-than-`APPROVAL_MAX_AGE_DAYS` (7, the purge TTL) set refuses whole with `preview_changed`. Tests: `test/preview-approval.test.ts` (PGLite; Postgres via `test/e2e/preview-approval-postgres.test.ts`).
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index bcb69c4cd9..4c7bf1673d 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -25,7 +25,7 @@ src/core/postgres-engine.ts 2914 ratchet +1 System One v1 evals: search arms cla
src/core/search/hybrid.ts 1584 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key
src/core/types.ts 2123 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes)
src/core/minions/queue.ts 2522 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys
-src/commands/init.ts 1932 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init
+src/commands/init.ts 1933 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; +1 --mcp-only pre-flight: rate-limit hint and retry_after_s for a /token 429
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
src/core/minions/handlers/subagent.ts 1918 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch
src/commands/bootstrap.ts 2142 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags)
diff --git a/src/cli.ts b/src/cli.ts
index 5061e94c47..a803149783 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -821,6 +821,14 @@ async function runThinClientRouted(
console.error('OAuth auth failed after token refresh. Credentials may have been revoked.');
console.error('Run `gbrain remote doctor` to confirm.');
break;
+ case 'rate_limited':
+ console.error(`OAuth /token is rate-limited by the server (HTTP 429)${e.detail?.retry_after_s !== undefined ? `; retry in ${e.detail.retry_after_s}s` : ''}.`);
+ console.error('This is the host\'s token-mint budget, not a connectivity problem; the host operator can raise GBRAIN_OAUTH_TOKEN_RATE_LIMIT_MAX.');
+ break;
+ case 'token':
+ console.error(`${e.message} (issuer ${cfg.remote_mcp!.issuer_url}).`);
+ console.error('Run `gbrain remote doctor` for details.');
+ break;
case 'network':
if (e.detail?.kind === 'timeout') {
const hint = cliOpts.timeoutMs ? '' : ` (default ${defaultTimeoutMs}ms; pass --timeout=Ns to override)`;
diff --git a/src/commands/init.ts b/src/commands/init.ts
index f835e31770..6a55034bf2 100644
--- a/src/commands/init.ts
+++ b/src/commands/init.ts
@@ -924,9 +924,10 @@ async function initRemoteMcp(opts: {
if (!tokenRes.ok) {
fail(
`token_${tokenRes.reason}`,
- `Pre-flight failed: OAuth /token — ${tokenRes.message}\n` +
- `Hint: the host operator can run \`gbrain auth register-client <name> --grant-types client_credentials --scopes read,write,admin\` to mint fresh credentials.`,
- { detail: tokenRes.message, ...(tokenRes.status ? { status: tokenRes.status } : {}) },
+ `Pre-flight failed: OAuth /token — ${tokenRes.message}\n` + (tokenRes.reason === 'rate_limited'
+ ? `Hint: the host's /token mint budget is spent; rerun after the wait, or the host operator can raise GBRAIN_OAUTH_TOKEN_RATE_LIMIT_MAX.`
+ : `Hint: the host operator can run \`gbrain auth register-client <name> --grant-types client_credentials --scopes read,write,admin\` to mint fresh credentials.`),
+ { detail: tokenRes.message, ...(tokenRes.status ? { status: tokenRes.status } : {}), ...(tokenRes.retry_after_s !== undefined ? { retry_after_s: tokenRes.retry_after_s } : {}) },
);
}
if (!jsonOutput) console.log(` ✓ OAuth /token (${tokenRes.token.token_type ?? 'bearer'}, scope=${tokenRes.token.scope ?? 'unspecified'})`);
diff --git a/src/core/doctor-remote.ts b/src/core/doctor-remote.ts
index ad89153407..3d15e36b93 100644
--- a/src/core/doctor-remote.ts
+++ b/src/core/doctor-remote.ts
@@ -174,7 +174,10 @@ export async function collectRemoteDoctorReport(
name: 'oauth_token',
status: 'fail',
message: tokenRes.message,
- detail: { reason: tokenRes.reason, ...(tokenRes.status ? { status: tokenRes.status } : {}) },
+ detail: {
+ reason: tokenRes.reason, ...(tokenRes.status ? { status: tokenRes.status } : {}),
+ ...(tokenRes.retry_after_s !== undefined ? { retry_after_s: tokenRes.retry_after_s } : {}),
+ },
});
return finalize(remote, checks);
}
diff --git a/src/core/mcp-client.ts b/src/core/mcp-client.ts
index 67ec1d63b8..ab97968fd3 100644
--- a/src/core/mcp-client.ts
+++ b/src/core/mcp-client.ts
@@ -64,6 +64,10 @@ export type RemoteMcpErrorReason =
| 'discovery'
| 'auth'
| 'auth_after_refresh'
+ /** OAuth /token answered 429; `detail.retry_after_s` carries its Retry-After. */
+ | 'rate_limited'
+ /** OAuth /token failed after discovery succeeded (non-auth HTTP status or bad body). */
+ | 'token'
| 'network'
| 'tool_error'
| 'parse';
@@ -75,6 +79,8 @@ export interface RemoteMcpErrorDetail {
kind?: 'timeout' | 'aborted' | 'unreachable';
/** v0.31.1: server-supplied error code on tool_error (e.g. 'missing_scope'). */
code?: string;
+ /** Seconds the server asked us to wait before minting again (rate_limited). */
+ retry_after_s?: number;
/** An accepted mutation's receipt survives the transport's tool-error wrapper. */
write_request?: WriteReceipt;
write_error?: WriteErrorCode;
@@ -287,10 +293,14 @@ async function getAccessToken(config: GBrainConfig, force = false, signal?: Abor
const tokenRes = await mintClientCredentialsToken(disco.metadata.token_endpoint, remote.oauth_client_id, secret, { signal });
signal?.throwIfAborted();
if (!tokenRes.ok) {
+ // Discovery already succeeded, so a /token failure is never 'discovery'.
throw new RemoteMcpError(
- tokenRes.reason === 'auth' ? 'auth' : tokenRes.reason === 'network' ? 'network' : 'discovery',
+ tokenRes.reason === 'http' || tokenRes.reason === 'parse' ? 'token' : tokenRes.reason,
`OAuth /token failed: ${tokenRes.message}`,
- { ...(tokenRes.status ? { status: tokenRes.status } : {}), ...(tokenRes.kind ? { kind: tokenRes.kind } : {}), mcp_url: remote.mcp_url },
+ {
+ ...(tokenRes.status ? { status: tokenRes.status } : {}), ...(tokenRes.kind ? { kind: tokenRes.kind } : {}),
+ ...(tokenRes.retry_after_s !== undefined ? { retry_after_s: tokenRes.retry_after_s } : {}), mcp_url: remote.mcp_url,
+ },
);
}
diff --git a/src/core/remote-mcp-probe.ts b/src/core/remote-mcp-probe.ts
index 8cb48306aa..f873e9cf97 100644
--- a/src/core/remote-mcp-probe.ts
+++ b/src/core/remote-mcp-probe.ts
@@ -11,7 +11,8 @@
* Each function returns a discriminated `{ok: true, ...}` / `{ok: false, error}`
* so callers can render the error reason consistently. Network errors surface
* as `network` reason; HTTP non-2xx surfaces as `http` with status. Auth
- * errors get their own `auth` reason for clean rendering.
+ * errors get their own `auth` reason for clean rendering, and a /token 429
+ * gets `rate_limited` with the server's Retry-After.
*/
import { anySignal } from './abort-check.ts';
@@ -21,9 +22,26 @@ type ProbeFailure<Reason extends string> = {
reason: Reason;
status?: number;
kind?: 'timeout' | 'aborted';
+ /** Seconds the server asked the caller to wait (Retry-After), when it said. */
+ retry_after_s?: number;
message: string;
};
+/** Longest Retry-After honoured; a larger value is clamped to it. */
+const MAX_RETRY_AFTER_S = 24 * 60 * 60;
+
+/**
+ * Parse a Retry-After header (delta-seconds or HTTP-date, RFC 9110 §10.2.3)
+ * into whole seconds, clamped to [0, MAX_RETRY_AFTER_S]. Unparseable → undefined.
+ */
+export function parseRetryAfterSeconds(value: string | null, now = Date.now()): number | undefined {
+ const trimmed = value?.trim();
+ if (!trimmed) return undefined;
+ const seconds = /^\d+$/.test(trimmed) ? Number(trimmed) : Math.ceil((Date.parse(trimmed) - now) / 1000);
+ if (Number.isNaN(seconds)) return undefined;
+ return Math.min(Math.max(seconds, 0), MAX_RETRY_AFTER_S);
+}
+
function networkFailure(label: string, error: unknown, signal: AbortSignal): ProbeFailure<'network'> {
if (signal.aborted) {
const kind = signal.reason instanceof Error && signal.reason.name === 'TimeoutError'
@@ -90,8 +108,9 @@ export async function discoverOAuth(
/**
* POST <token_endpoint> with grant_type=client_credentials. Returns the
- * access_token + expires_in on success. 401 → reason=auth; other non-2xx
- * → reason=http; network → reason=network.
+ * access_token + expires_in on success. 401 → reason=auth; 429 →
+ * reason=rate_limited (+ retry_after_s); other non-2xx → reason=http;
+ * network → reason=network.
*/
export interface TokenResponse {
access_token: string;
@@ -105,7 +124,7 @@ export async function mintClientCredentialsToken(
clientId: string,
clientSecret: string,
opts: { scope?: string; timeoutMs?: number; signal?: AbortSignal } = {},
-): Promise<{ ok: true; token: TokenResponse } | ProbeFailure<'network' | 'http' | 'auth' | 'parse' | 'config'>> {
+): Promise<{ ok: true; token: TokenResponse } | ProbeFailure<'network' | 'http' | 'auth' | 'rate_limited' | 'parse' | 'config'>> {
if (!clientId) return { ok: false, reason: 'config', message: 'client_id is required' };
if (!clientSecret) return { ok: false, reason: 'config', message: 'client_secret is required' };
@@ -129,6 +148,17 @@ export async function mintClientCredentialsToken(
await res.body?.cancel().catch(() => {});
return { ok: false, reason: 'auth', status: res.status, message: `OAuth /token returned ${res.status} — check client_id and client_secret` };
}
+ if (res.status === 429) {
+ // The host's /token limiter spent this caller's mint budget. Discovery
+ // already answered, so this is neither a discovery nor a network fault.
+ await res.body?.cancel().catch(() => {});
+ const retryAfter = parseRetryAfterSeconds(res.headers.get('retry-after'));
+ return {
+ ok: false, reason: 'rate_limited', status: 429,
+ ...(retryAfter !== undefined ? { retry_after_s: retryAfter } : {}),
+ message: `OAuth /token returned 429 (rate-limited by the server${retryAfter !== undefined ? `; retry in ${retryAfter}s` : ''})`,
+ };
+ }
if (!res.ok) {
await res.body?.cancel().catch(() => {});
return { ok: false, reason: 'http', status: res.status, message: `OAuth /token returned ${res.status}` };
diff --git a/test/doctor-remote.serial.test.ts b/test/doctor-remote.serial.test.ts
index e2d309361d..b027fc665a 100644
--- a/test/doctor-remote.serial.test.ts
+++ b/test/doctor-remote.serial.test.ts
@@ -56,6 +56,7 @@ beforeAll(async () => {
if (req.url === '/token') {
res.statusCode = tokenStatus;
res.setHeader('Content-Type', 'application/json');
+ if (tokenStatus === 429) res.setHeader('Retry-After', '900');
res.end(JSON.stringify(tokenBody ?? {
access_token: 'test-token-' + Date.now(),
token_type: 'bearer',
@@ -190,6 +191,17 @@ describe('collectRemoteDoctorReport', () => {
expect(report.checks.find(c => c.name === 'mcp_smoke')).toBeUndefined();
});
+ test('token 429 — fails with reason=rate_limited and the server\'s Retry-After', async () => {
+ reset();
+ tokenStatus = 429;
+ tokenBody = { error: 'too_many_requests' };
+ const report = await collectRemoteDoctorReport(makeConfig(), SKIP_PROBE_OPTS);
+ const token = report.checks.find(c => c.name === 'oauth_token')!;
+ expect(token.status).toBe('fail');
+ expect(token.detail).toEqual({ reason: 'rate_limited', status: 429, retry_after_s: 900 });
+ expect(token.message).toContain('retry in 900s');
+ });
+
test('mcp 401 — bearer rejected; fails with reason=auth', async () => {
reset();
mcpStatus = 401;
diff --git a/test/e2e/thin-client.test.ts b/test/e2e/thin-client.test.ts
index c1bdedc715..67b4addaac 100644
--- a/test/e2e/thin-client.test.ts
+++ b/test/e2e/thin-client.test.ts
@@ -415,18 +415,17 @@ describeWhen('thin-client end-to-end (requires DATABASE_URL)', () => {
// GBRAIN_REMOTE_CLIENT_SECRET overrides the config-file secret
// (mcp-client resolveSecret), so this exercises the exact wire path a
// revoked/rotated credential takes: the host's /token endpoint answers
- // 400 invalid_grant (RFC 6749 §5.2) for bad AND revoked clients alike.
+ // 401 invalid_client (RFC 6749 §5.2) for bad AND revoked clients alike.
const r = await spawn(['search', G3_MARKER, '--json'], clientHome, {
GBRAIN_REMOTE_CLIENT_SECRET: 'gbrain_cs_definitely_not_the_real_secret',
});
expect(r.exitCode, cliDiagnostic("thin-client CLI", r)).toBe(1);
// No fabricated results — stdout stays empty on the error path.
expect(r.stdout.trim()).toBe('');
- // Canonical RemoteMcpError surface. mcp-client maps the non-401 /token
- // HTTP failure to reason 'discovery' today ("OAuth discovery failed at
- // <issuer>."); allow the 'auth' spelling too so a future 401
- // reclassification on the host doesn't false-fail the guard.
- expect(r.stderr).toMatch(/OAuth (discovery|auth) failed/);
+ // Canonical RemoteMcpError surface: reason 'auth' ("OAuth auth failed.");
+ // any other /token status renders as reason 'token' ("OAuth /token
+ // failed: ..."), never as a discovery failure.
+ expect(r.stderr).toMatch(/OAuth (auth|\/token) failed/);
});
test('stopped host: routed verbs fail fast with the canonical unreachable error, not a hang', async () => {
diff --git a/test/init-mcp-only.test.ts b/test/init-mcp-only.test.ts
index a772a711ae..bbba4f50ad 100644
--- a/test/init-mcp-only.test.ts
+++ b/test/init-mcp-only.test.ts
@@ -44,6 +44,7 @@ beforeAll(async () => {
if (req.url === '/token') {
res.statusCode = tokenStatus;
res.setHeader('Content-Type', 'application/json');
+ if (tokenStatus === 429) res.setHeader('Retry-After', '900');
res.end(JSON.stringify({
access_token: 'token-' + Date.now(),
token_type: 'bearer',
@@ -264,6 +265,23 @@ describe('gbrain init --mcp-only — pre-flight smoke failures', () => {
expect(parsed.reason).toBe('token_auth');
});
+ test('token 429 → exits 1 with token_rate_limited, the wait, and a rate-limit hint', async () => {
+ tokenStatus = 429;
+ const r = await run([
+ 'init', '--mcp-only', '--json',
+ '--issuer-url', `http://127.0.0.1:${port}`,
+ '--mcp-url', `http://127.0.0.1:${port}/mcp`,
+ '--oauth-client-id', 'cid',
+ '--oauth-client-secret', 'csecret',
+ ]);
+ expect(r.exitCode).toBe(1);
+ expect(existsSync(configPath())).toBe(false);
+ const parsed = JSON.parse(r.stdout.trim().split('\n').pop()!);
+ expect(parsed).toMatchObject({ reason: 'token_rate_limited', status: 429, retry_after_s: 900 });
+ expect(parsed.message).toContain('GBRAIN_OAUTH_TOKEN_RATE_LIMIT_MAX');
+ expect(parsed.message).not.toContain('register-client');
+ });
+
test('mcp smoke 500 → exits 1 with mcp_smoke_http reason', async () => {
mcpStatus = 500;
const r = await run([
diff --git a/test/thin-client-token-rate-limit.test.ts b/test/thin-client-token-rate-limit.test.ts
new file mode 100644
index 0000000000..15a66008e5
--- /dev/null
+++ b/test/thin-client-token-rate-limit.test.ts
@@ -0,0 +1,141 @@
+/**
+ * A /token 429 is the host's mint budget running out, not a discovery or
+ * connectivity fault. The probe, the MCP client and the thin-client CLI must
+ * all name it and carry the server's Retry-After (express-rate-limit sends it
+ * on every 429), and any other /token failure must not read as "discovery".
+ *
+ * Loopback OAuth fixture only: no datastore, no keys, no outside network.
+ */
+
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { callRemoteTool, _clearMcpClientTokenCache } from '../src/core/mcp-client.ts';
+import { mintClientCredentialsToken } from '../src/core/remote-mcp-probe.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+
+let server: ReturnType<typeof Bun.serve>;
+let base: string;
+let tokenResponse: () => Response;
+const roots: string[] = [];
+
+/** The 429 the host's /token limiter sends (express-rate-limit, standardHeaders). */
+function rateLimited(retryAfter: string | null): () => Response {
+ return () => Response.json(
+ { error: 'too_many_requests', error_description: 'Rate limit exceeded. Try again later.' },
+ { status: 429, headers: {
+ 'RateLimit-Limit': '50', 'RateLimit-Remaining': '0',
+ ...(retryAfter === null ? {} : { 'Retry-After': retryAfter }),
+ } },
+ );
+}
+
+beforeAll(() => {
+ server = Bun.serve({ hostname: '127.0.0.1', port: 0, fetch(req) {
+ const path = new URL(req.url).pathname;
+ if (path === '/.well-known/oauth-authorization-server') return Response.json({ issuer: base, token_endpoint: `${base}/token` });
+ if (path === '/token') return tokenResponse();
+ return new Response(null, { status: 404 });
+ } });
+ base = `http://127.0.0.1:${server.port}`;
+});
+
+afterAll(async () => { await server.stop(true); });
+
+afterEach(() => {
+ _clearMcpClientTokenCache();
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
+});
+
+function config(): GBrainConfig {
+ return { engine: 'pglite', remote_mcp: {
+ issuer_url: base, mcp_url: `${base}/mcp`, oauth_client_id: 'fixture', oauth_client_secret: 'fixture',
+ } };
+}
+
+describe('mintClientCredentialsToken on a 429', () => {
+ test('classifies it as rate_limited with the Retry-After seconds', async () => {
+ tokenResponse = rateLimited('900');
+ const res = await mintClientCredentialsToken(`${base}/token`, 'fixture', 'fixture');
+ expect(res).toMatchObject({ ok: false, reason: 'rate_limited', status: 429, retry_after_s: 900 });
+ expect(res.ok ? '' : res.message).toContain('retry in 900s');
+ });
+
+ test('reads an HTTP-date Retry-After as seconds from now', async () => {
+ tokenResponse = rateLimited(new Date(Date.now() + 120_000).toUTCString());
+ const res = await mintClientCredentialsToken(`${base}/token`, 'fixture', 'fixture');
+ expect(res).toMatchObject({ ok: false, reason: 'rate_limited' });
+ const wait = res.ok ? undefined : res.retry_after_s;
+ expect(wait).toBeGreaterThanOrEqual(118);
+ expect(wait).toBeLessThanOrEqual(120);
+ });
+
+ test('clamps an absurd Retry-After to one day', async () => {
+ tokenResponse = rateLimited('31536000');
+ expect(await mintClientCredentialsToken(`${base}/token`, 'fixture', 'fixture'))
+ .toMatchObject({ ok: false, reason: 'rate_limited', retry_after_s: 86_400 });
+ });
+
+ for (const header of [null, 'soon']) {
+ test(`stays rate_limited without a usable Retry-After (${header ?? 'absent'})`, async () => {
+ tokenResponse = rateLimited(header);
+ const res = await mintClientCredentialsToken(`${base}/token`, 'fixture', 'fixture');
+ expect(res).toMatchObject({ ok: false, reason: 'rate_limited', status: 429 });
+ expect(res.ok ? 'ok' : res.retry_after_s).toBeUndefined();
+ });
+ }
+});
+
+describe('callRemoteTool when /token fails after discovery succeeded', () => {
+ test('a 429 surfaces as rate_limited, not discovery', async () => {
+ tokenResponse = rateLimited('900');
+ await expect(callRemoteTool(config(), 'get_brain_identity')).rejects.toMatchObject({
+ reason: 'rate_limited', detail: { status: 429, retry_after_s: 900 },
+ });
+ });
+
+ test('a 500 surfaces as a /token failure with its status, not discovery', async () => {
+ tokenResponse = () => new Response('boom', { status: 500 });
+ await expect(callRemoteTool(config(), 'get_brain_identity')).rejects.toMatchObject({
+ reason: 'token', detail: { status: 500 },
+ });
+ });
+});
+
+async function runCli(args: string[]): Promise<{ code: number; stdout: string; stderr: string }> {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-token-429-'));
+ roots.push(root);
+ mkdirSync(join(root, '.gbrain'));
+ writeFileSync(join(root, '.gbrain', 'config.json'), JSON.stringify(config()));
+ const env: Record<string, string | undefined> = { ...process.env, GBRAIN_HOME: root, GBRAIN_NO_BANNER: '1', GBRAIN_BACKUP_CHECK: '0' };
+ for (const name of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_SOURCE', 'GBRAIN_REMOTE_CLIENT_SECRET']) delete env[name];
+ const child = Bun.spawn([process.execPath, join(import.meta.dir, '../src/cli.ts'), ...args], {
+ cwd: root, env, stdout: 'pipe', stderr: 'pipe',
+ });
+ const watchdog = setTimeout(() => child.kill('SIGKILL'), 20_000);
+ try {
+ const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
+ return { code, stdout, stderr };
+ } finally { clearTimeout(watchdog); }
+}
+
+describe('thin-client CLI rendering', () => {
+ test('a rate-limited mint names the limit, the wait and the host knob', async () => {
+ tokenResponse = rateLimited('900');
+ const r = await runCli(['search', 'anything']);
+ expect(r.code).toBe(1);
+ expect(r.stdout).toBe('');
+ expect(r.stderr).toContain('OAuth /token is rate-limited by the server (HTTP 429); retry in 900s.');
+ expect(r.stderr).toContain('GBRAIN_OAUTH_TOKEN_RATE_LIMIT_MAX');
+ expect(r.stderr).not.toContain('OAuth discovery failed');
+ }, 30_000);
+
+ test('another /token failure keeps its status instead of blaming discovery', async () => {
+ tokenResponse = () => new Response('boom', { status: 503 });
+ const r = await runCli(['search', 'anything']);
+ expect(r.code).toBe(1);
+ expect(r.stderr).toContain(`OAuth /token failed: OAuth /token returned 503 (issuer ${base}).`);
+ expect(r.stderr).not.toContain('OAuth discovery failed');
+ }, 30_000);
+});