Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(connectors): stop on a challenge on any status and on sustained 429s (#7482); never echo a header value (#7483)
garrytane670a32809a7
diff --git a/docs/guides/chat-connectors.md b/docs/guides/chat-connectors.mdindex e8ea6746bb..980f356971 100644--- a/docs/guides/chat-connectors.md+++ b/docs/guides/chat-connectors.md@@ -240,9 +240,13 @@ Env override for a credential (incident escape hatch):`chatgpt.com` / `claude.ai` sit behind bot-management that fingerprints theTLS/HTTP2 handshake, and `cf_clearance` is bound to a real browser. A server-side-`fetch` with a valid cookie may still draw a 403 challenge. When that happens the-connector reports `forbidden` and points you at the official export lane; it never-loop-retries. If server-side fetch is reliably blocked in your environment, prefer+`fetch` with a valid cookie may still draw a challenge, on a 403 or on any other status+(the `cf-mitigated: challenge` header, a challenge page, or a redirect to one). When that+happens the connector reports `forbidden` and points you at the official export lane; it+never loop-retries. Sustained rate limiting ends the run as `rate_limited` instead of+working through the rest of the history, and five conversation fetches in a row that fail+with a server error or no response stop it as `partial` (`stopReason:+consecutive_fetch_failures`). If server-side fetch is reliably blocked in your environment, preferthe export-file lane (`conversation-archive`) — it always works.## Troubleshooting@@ -252,6 +256,8 @@ the export-file lane (`conversation-archive`) — it always works.| Symptom | Cause | Fix | Who acts | Consent | Verify ||---|---|---|---|---|---|| `forbidden` | Cloudflare/bot challenge on server-side fetch | Use the official export + `gbrain transcripts ingest` | user (downloads the export); agent ingests it | none | `gbrain connectors status --json` |+| `rate_limited` | the provider kept answering 429 after four retries, or asked for a wait over two minutes | Wait, then re-run; the next sync resumes where this one stopped. Don't loop it | agent | `credentials` | `gbrain connectors status --json` |+| `auth_required` with "cannot carry" in the hint | the saved cookie or token holds a line break, control or non-ASCII character (`invalid_header_value`); nothing was sent | Re-copy the Cookie header on one line, `gbrain connectors auth` | user (copies the cookie) | `credentials` | `gbrain connectors status --json` || `auth_required` | cookie expired/invalid | Re-copy a fresh Cookie header, `gbrain connectors auth` | user (copies a fresh Cookie header) | `credentials` | `gbrain connectors status --json` || `connectors auth` exits 1 with an `[AGENT]` cookie checklist | no credential and nobody at the terminal ([headless lane](#headless-lane-an-agent-without-a-terminal)) | Relay the `[SHOW USER]` checklist; the user pipes the cookie into `gbrain connectors auth <provider> --cookie -` | user (copies the cookie) | `credentials` | `gbrain connectors status --json` || `partial` | a conversation failed to fetch or import, the conversation list failed, or `--limit` capped the run | Re-run. A failed conversation is retried and holds the watermark until it imports. One that failed three times at the same update time is quarantined instead: it no longer holds the watermark and later syncs retry it on a backoff until it imports | agent | `credentials` (fetches from the provider again with the saved session) | `gbrain connectors status --json` |diff --git a/scripts/agent-contract-baselines/legacy-advice-key.tsv b/scripts/agent-contract-baselines/legacy-advice-key.tsvindex 85fac2ceee..01e1c2f8a9 100644--- a/scripts/agent-contract-baselines/legacy-advice-key.tsv+++ b/scripts/agent-contract-baselines/legacy-advice-key.tsv@@ -36,7 +36,7 @@ src/core/ai/recipes/lmstudio.ts 2src/core/backup/coverage.ts 11src/core/backup/repository.ts 1src/core/brainstorm/error-classify.ts 1-src/core/connectors/sync.ts 8+src/core/connectors/sync.ts 7src/core/context/hook-heartbeat.ts 2src/core/cycle/patterns.ts 1src/core/cycle/synthesize.ts 1diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex ec83bdc3d2..62717011c7 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1237,6 +1237,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.433.0', text: 'Hermes transcript import keeps the answers a user gave in a `clarify` form (answered responses of a submitted form, or the answers a timed-out form had already locked) as user turns, each after its question as the assistant\'s turn. A Hermes session imported before re-renders on its next import scan when it holds such answers, which can run fact extraction for that page again (#7396).' },{ since: '0.60.433.0', text: 'Fact subject inference links more facts and fewer wrong ones: a currency code next to an amount (`CHF 80`) and a record label opening a sentence (`Invoice ...`, `Work session ...`) no longer block a fact that names one person or company, and an entity introduced only as an example (`including X notes`, `for example, X`) is never chosen as the subject. A page named like the code or label still competes. A sentence that opens with `For example, X ...` no longer takes X as its subject (#7405).' },{ since: '0.60.433.0', text: '`gbrain think` gives reasoning models from gpt-5 on 16,000 output tokens behind any provider or router prefix, as it already did for gpt-5 and the o-series on their own provider; gpt-6 ids get it too. Before, those got 4,000 and long answers came back truncated (`LLM_OUTPUT_TRUNCATED`). Providers bill the tokens used, not the cap (#7421).' },+ // GBRA-190 connectors wave. `since` is stamped at the merge slot.+ { since: 'TBD', text: 'Chat-connector syncs stop instead of retrying through a block: a bot challenge on any status (the `cf-mitigated: challenge` header, a challenge page on a 5xx, a redirect to a Cloudflare challenge) now ends the run as `forbidden`; a 429 that outlasts its four retries, or asks for a `Retry-After` over two minutes, ends it as the new status `rate_limited` without fetching the remaining conversations; and five conversation fetches in a row failing with a server error or no response stop it as `partial` with `stopReason: consecutive_fetch_failures`. The next sync resumes from the same place (#7482).' },+ { since: 'TBD', text: 'A chat-connector cookie or token holding a line break, NUL, another control character or a non-ASCII character is refused before any request (`invalid_header_value`): `connectors auth` reports it and `connectors sync` returns `auth_required` with that hint and stamps the auth error. A request that fails before a response is reported by its error code (`ECONNREFUSED`, `TypeError`), never by the runtime\'s message, so a header value can never be echoed into probe output, sync hints or logs (#7483).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/connectors/classify.ts b/src/core/connectors/classify.tsindex 3114e48b10..8211d0d90b 100644--- a/src/core/connectors/classify.ts+++ b/src/core/connectors/classify.ts@@ -56,6 +56,20 @@ function looksLikeCloudflareChallenge(body: string): boolean {return CLOUDFLARE_MARKERS.some((m) => head.includes(m));}+/**+ * #7482: markers only an interactive challenge carries. Bare "cloudflare" is left out: Cloudflare's own 5xx error+ * pages name it, and a transient origin error must stay retryable.+ */+const CHALLENGE_ONLY_MARKERS = ['just a moment', 'cf-browser-verification', 'cf-chl', 'challenge-platform', 'attention required'];++/** A challenge served on a non-2xx status other than 403: a redirect to one, or a challenge page. */+function challengeOnOtherStatus(res: ClassifiableResponse, bodyText: string): boolean {+ const location = res.headers.get('location')?.toLowerCase() ?? '';+ if (res.status >= 300 && res.status < 400 && (location.includes('/cdn-cgi/') || location.includes('__cf_chl'))) return true;+ const head = bodyText.slice(0, 2048).toLowerCase();+ return looksLikeHtml(res.headers.get('content-type'), bodyText) && CHALLENGE_ONLY_MARKERS.some((m) => head.includes(m));+}+/*** Classify a response given its status, headers, and the body text already* read. `nowMs` is injectable so Retry-After HTTP-date parsing is deterministic@@ -68,6 +82,14 @@ export function classifyResponse(): Classification {const { status } = res;+ // Cloudflare sets `cf-mitigated: challenge` on every challenge response, whatever its status.+ if (res.headers.get('cf-mitigated')?.trim().toLowerCase() === 'challenge') {+ return { kind: 'forbidden_fingerprint', detail: `HTTP ${status} with cf-mitigated: challenge — server-side fetch blocked` };+ }+ if (status !== 403 && (status < 200 || status >= 300) && challengeOnOtherStatus(res, bodyText)) {+ return { kind: 'forbidden_fingerprint', detail: `HTTP ${status} with a bot challenge — server-side fetch blocked` };+ }+if (status === 429) {const retryAfterMs = parseRetryAfterMs(res.headers.get('retry-after'), nowMs) ?? undefined;return { kind: 'rate_limited', retryAfterMs, detail: 'HTTP 429 rate limited' };diff --git a/src/core/connectors/client.ts b/src/core/connectors/client.tsindex 0e0a455fec..a4f0a99b5d 100644--- a/src/core/connectors/client.ts+++ b/src/core/connectors/client.ts@@ -36,6 +36,52 @@ export class ConnectorForbiddenError extends Error {}}+/** Raised on a 429 that outlasts its retries, or asks for a wait over MAX_RETRY_AFTER_MS: the run stops. */+export class ConnectorRateLimitedError extends Error {+ readonly code = 'rate_limited';+ constructor(message: string) {+ super(message);+ this.name = 'ConnectorRateLimitedError';+ }+}++/**+ * #7483: an auth header value no HTTP header can carry (CR, LF, NUL, other control or non-ASCII characters). The+ * message names the header, never its value.+ */+export class ConnectorCredentialFormatError extends Error {+ readonly code = 'invalid_header_value';+ constructor(header: string) {+ super(+ `connector: the ${header} credential holds a character an HTTP header cannot carry (a line break, control or ` ++ 'non-ASCII character); copy it again and re-run `gbrain connectors auth`',+ );+ this.name = 'ConnectorCredentialFormatError';+ }+}++/** #7483: a request that failed before any response. The message carries the error's code, never the runtime's text. */+export class ConnectorNetworkError extends Error {+ readonly code = 'network';+ constructor(pathOrUrl: string, cause: unknown) {+ const c = cause as { code?: unknown; name?: unknown };+ const reason = typeof c?.code === 'string' && /^[A-Z][A-Z0-9_]*$/.test(c.code) ? c.code : typeof c?.name === 'string' ? c.name : 'Error';+ super(`connector: request to ${pathOrUrl} failed (${reason})`);+ this.name = 'ConnectorNetworkError';+ }+}++/** A response that stayed non-OK after the client's bounded retries. `status` tells a provider outage (5xx) from an item error (4xx). */+export class ConnectorHttpError extends Error {+ constructor(message: string, readonly status: number) {+ super(message);+ this.name = 'ConnectorHttpError';+ }+}++/** Printable ASCII only: a cookie or token never needs more, and Bun's fetch throws on anything else. */+const HEADER_VALUE_RE = /^[\x20-\x7e]*$/;+/** A desktop-browser UA so the request doesn't self-identify as a bot. */const DEFAULT_USER_AGENT ='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 ' +@@ -60,6 +106,8 @@ export interface ConnectorClientOpts {}const MAX_RATE_RETRIES = 4;+/** #7482: a Retry-After longer than this stops the run instead of holding it. */+export const MAX_RETRY_AFTER_MS = 120_000;function defaultSleep(ms: number, signal?: AbortSignal): Promise<void> {return new Promise<void>((resolve, reject) => {@@ -133,12 +181,22 @@ export class ConnectorClient {let rateRetries = 0;for (;;) {+ const auth = await this.headers();+ for (const [name, value] of Object.entries(auth)) {+ if (!HEADER_VALUE_RE.test(value)) throw new ConnectorCredentialFormatError(name);+ }await this.pace(opts.signal);- const res = await this.fetchImpl(url, {- headers: { 'user-agent': DEFAULT_USER_AGENT, accept: 'application/json', ...(await this.headers()) },- signal: opts.signal,- redirect: 'manual',- });+ let res: Response;+ try {+ res = await this.fetchImpl(url, {+ headers: { 'user-agent': DEFAULT_USER_AGENT, accept: 'application/json', ...auth },+ signal: opts.signal,+ redirect: 'manual',+ });+ } catch (e) {+ if (opts.signal?.aborted || (e as { name?: unknown })?.name === 'AbortError') throw e;+ throw new ConnectorNetworkError(pathOrUrl, e);+ }const bodyText = await res.text();const c = classifyResponse(res, bodyText, this.now());@@ -165,14 +223,19 @@ export class ConnectorClient {}if (c.kind === 'rate_limited') {+ const waitMs = c.retryAfterMs ?? 60_000;+ if (waitMs > MAX_RETRY_AFTER_MS) {+ throw new ConnectorRateLimitedError(+ `connector: rate limited on ${pathOrUrl}; the provider asked for a ${Math.round(waitMs / 1000)}s wait, over the ${MAX_RETRY_AFTER_MS / 1000}s cap`,+ );+ }if (rateRetries < MAX_RATE_RETRIES) {rateRetries++;- const waitMs = c.retryAfterMs ?? 60_000;this.log(`[connector] ${c.detail}; retry ${rateRetries}/${MAX_RATE_RETRIES} in ${Math.round(waitMs / 1000)}s`);await this.sleep(waitMs, opts.signal);continue;}- throw new Error(`connector: rate limited on ${pathOrUrl} after ${MAX_RATE_RETRIES} retries`);+ throw new ConnectorRateLimitedError(`connector: rate limited on ${pathOrUrl} after ${MAX_RATE_RETRIES} retries`);}// server_error or drift: one bounded retry for transient 5xx, else throw.@@ -181,7 +244,7 @@ export class ConnectorClient {await this.sleep(1000 * rateRetries, opts.signal);continue;}- throw new Error(`connector: ${c.detail} on ${pathOrUrl}`);+ throw new ConnectorHttpError(`connector: ${c.detail} on ${pathOrUrl}`, res.status);}}}diff --git a/src/core/connectors/providers/chatgpt.ts b/src/core/connectors/providers/chatgpt.tsindex 9992e68225..18ff0c69e6 100644--- a/src/core/connectors/providers/chatgpt.ts+++ b/src/core/connectors/providers/chatgpt.ts@@ -213,6 +213,8 @@ export const chatgptProvider: ChatHistoryProvider = {const msg = e instanceof Error ? e.message : String(e);if (name === 'ConnectorAuthError') return { ok: false, kind: 'unauthorized', detail: msg };if (name === 'ConnectorForbiddenError') return { ok: false, kind: 'forbidden_fingerprint', detail: msg };+ if (name === 'ConnectorRateLimitedError') return { ok: false, kind: 'rate_limited', detail: msg };+ if (name === 'ConnectorCredentialFormatError') return { ok: false, kind: 'invalid_credential', detail: msg };return { ok: false, kind: 'network', detail: msg };}},diff --git a/src/core/connectors/providers/claude.ts b/src/core/connectors/providers/claude.tsindex bb4af5b0a2..fb36bdea5a 100644--- a/src/core/connectors/providers/claude.ts+++ b/src/core/connectors/providers/claude.ts@@ -139,6 +139,8 @@ export const claudeProvider: ChatHistoryProvider = {const msg = e instanceof Error ? e.message : String(e);if (name === 'ConnectorAuthError') return { ok: false, kind: 'unauthorized', detail: msg };if (name === 'ConnectorForbiddenError') return { ok: false, kind: 'forbidden_fingerprint', detail: msg };+ if (name === 'ConnectorRateLimitedError') return { ok: false, kind: 'rate_limited', detail: msg };+ if (name === 'ConnectorCredentialFormatError') return { ok: false, kind: 'invalid_credential', detail: msg };return { ok: false, kind: 'network', detail: msg };}},diff --git a/src/core/connectors/sync.ts b/src/core/connectors/sync.tsindex e403cbe662..6d89798ff9 100644--- a/src/core/connectors/sync.ts+++ b/src/core/connectors/sync.ts@@ -36,12 +36,20 @@ import { runTranscriptsIngest } from '../transcripts/ingest.ts';import type { TranscriptsIngestResult } from '../transcripts/ingest.ts';import { submitEmbedBackfill } from '../embed-backfill-submit.ts';import { runEmbedCore } from '../../commands/embed.ts';-import { ConnectorAuthError, ConnectorClient, ConnectorForbiddenError } from './client.ts';+import {+ ConnectorAuthError,+ ConnectorClient,+ ConnectorCredentialFormatError,+ ConnectorForbiddenError,+ ConnectorHttpError,+ ConnectorNetworkError,+ ConnectorRateLimitedError,+} from './client.ts';import type { ConnectorFetch } from './client.ts';import { getConnectorProvider } from './registry.ts';import { resolveCredential } from './credentials.ts';import { CONNECTOR_SPOOL_BATCH, pruneSpool, removeSpool, writeSpool } from './spool.ts';-import type { ChatHistoryProvider, ConnectorProviderName, ConversationStub } from './types.ts';+import type { ChatHistoryProvider, ConnectorProviderName, ConversationStub, ProbeResult } from './types.ts';import { QUARANTINE_ATTEMPTS, fullSyncArgv, planConnectorFetch, readFailedLedger, recordFailedAttempt } from './failed-ledger.ts';import {authErrorAtKey,@@ -61,6 +69,7 @@ export type ConnectorSyncStatus =| 'partial'| 'auth_required'| 'forbidden'+ | 'rate_limited'| 'dry_run'| 'not_supported';@@ -104,9 +113,40 @@ export interface ConnectorSyncResult {gone: string[];spoolPaths: string[];embedKickoff: EmbedKickoffOutcome;+ /** #7482: set when the run stopped fetching early because CONSECUTIVE_FETCH_FAILURE_LIMIT fetches failed in a row. */+ stopReason?: 'consecutive_fetch_failures';hint?: string;}+/**+ * #7482: this many conversation fetches failing in a row on a provider-wide error (a 5xx or no response, each after+ * its own bounded retries) stop the run. An item error such as a 404 says the provider is answering, so it resets the run.+ */+export const CONSECUTIVE_FETCH_FAILURE_LIMIT = 5;++type TerminalStatus = 'auth_required' | 'forbidden' | 'rate_limited';++/** Probe failures that end the run before listing; drift and network fall through to `partial`. */+const PROBE_TERMINAL: Partial<Record<Exclude<ProbeResult, { ok: true }>['kind'], TerminalStatus>> = {+ unauthorized: 'auth_required',+ invalid_credential: 'auth_required',+ forbidden_fingerprint: 'forbidden',+ rate_limited: 'rate_limited',+};++/** What the user does about a run that ended on a terminal status. */+function terminalHint(term: TerminalStatus, provider: ChatHistoryProvider): string {+ if (term === 'rate_limited') {+ return 'The provider is rate limiting this account; the sync stopped instead of retrying. Wait before the next ' ++ 'sync (an automatic schedule picks up where this run stopped).';+ }+ if (term === 'forbidden') {+ return 'The provider blocked this request (bot/challenge). Use the cookie-capture lane or ' ++ 'the official export + `gbrain transcripts ingest`.';+ }+ return provider.sessionInstructions();+}+export interface ConnectorSyncDeps {/** Pre-built client (tests). When absent, one is built from the credential. */client?: ConnectorClient;@@ -219,19 +259,9 @@ export async function runConnectorSync(// Probe first: a dead credential must not burn a full list+fetch.const probe = await provider.probe(client, opts.signal);if (!probe.ok) {- if (probe.kind === 'unauthorized') {- await stampAuthError(engine, opts.provider, now);- return { ...base, status: 'auth_required', hint: provider.sessionInstructions() };- }- if (probe.kind === 'forbidden_fingerprint') {- return {- ...base,- status: 'forbidden',- hint:- 'The provider blocked this request (bot/challenge). Use the cookie-capture lane or ' +- 'the official export + `gbrain transcripts ingest`.',- };- }+ const term = PROBE_TERMINAL[probe.kind];+ if (term === 'auth_required') await stampAuthError(engine, opts.provider, now);+ if (term) return { ...base, status: term, hint: probe.kind === 'invalid_credential' ? probe.detail : terminalHint(term, provider) };// drift / network → surface as forbidden-ish partial with the detail.return { ...base, status: 'partial', hint: `probe failed: ${probe.detail}` };}@@ -263,7 +293,7 @@ export async function runConnectorSync(const term = classifyThrow(e);if (term) {if (term === 'auth_required') await stampAuthError(engine, opts.provider, now);- return { ...base, status: term, hint: provider.sessionInstructions() };+ return { ...base, status: term, hint: terminalHint(term, provider) };}log(`[connector] list error: ${e instanceof Error ? e.message : String(e)}`);}@@ -316,10 +346,11 @@ export async function runConnectorSync(let allBatchesClean = true;let anyDrift = false;let aborted = false;+ let consecutiveFetchFailures = 0;const spoolFormat = provider.spoolFormat; // capture: nested closures lose narrowingconst batches = chunk(toFetch, CONNECTOR_SPOOL_BATCH);- for (let bi = 0; bi < batches.length && !aborted; bi++) {+ for (let bi = 0; bi < batches.length && !aborted && !base.stopReason; bi++) {const batch = batches[bi];const convs: Array<Record<string, unknown>> = [];const convStubs: ConversationStub[] = [];@@ -329,26 +360,28 @@ export async function runConnectorSync(convs.push(await provider.fetchConversation(client, stub.id, { signal: opts.signal, orgId: stub.orgId }));convStubs.push(stub);fetched++;+ consecutiveFetchFailures = 0;opts.onProgress?.({ phase: 'fetch', listed: stubs.length, fetched, imported: importedTotal });} catch (e) {// A cancelled run says nothing about the conversation: no strike.if (opts.signal?.aborted) { aborted = true; break; }const term = classifyThrow(e);- if (term === 'auth_required') {- await stampAuthError(engine, opts.provider, now);+ if (term) {+ if (term === 'auth_required') await stampAuthError(engine, opts.provider, now);// Ingest whatever we already collected this batch before returning.if (convs.length) await ingestBatch();await saveLedgers();- return { ...base, status: 'auth_required', listed: stubs.length, fetched, fetchErrors, spoolPaths, hint: provider.sessionInstructions() };- }- if (term === 'forbidden') {- if (convs.length) await ingestBatch();- await saveLedgers();- return { ...base, status: 'forbidden', listed: stubs.length, fetched, fetchErrors, spoolPaths };+ return { ...base, status: term, listed: stubs.length, fetched, fetchErrors, spoolPaths, hint: terminalHint(term, provider) };}fetchErrors++;const attempts = recordFailure(stub, null);log(`[connector] fetch error for ${stub.id} (attempt ${attempts}): ${e instanceof Error ? e.message : String(e)}`);+ const providerWide = e instanceof ConnectorNetworkError || (e instanceof ConnectorHttpError && e.status >= 500);+ consecutiveFetchFailures = providerWide ? consecutiveFetchFailures + 1 : 0;+ if (consecutiveFetchFailures >= CONSECUTIVE_FETCH_FAILURE_LIMIT) {+ base.stopReason = 'consecutive_fetch_failures';+ break;+ }}}if (convs.length) await ingestBatch();@@ -428,7 +461,7 @@ export async function runConnectorSync(base.quarantined = quarantined;// Quarantined conversations no longer hold the watermark back.- const clean = !listErrored && blockingFailures === 0 && !capped && !opts.signal?.aborted;+ const clean = !listErrored && blockingFailures === 0 && !capped && !opts.signal?.aborted && !base.stopReason;// Advance the watermark ONLY on a clean run.if (clean && maxUpdatedAt && maxUpdatedAt !== watermark) {@@ -468,7 +501,7 @@ export async function runConnectorSync(base.unresolved = Object.keys(failed).length;base.hint = unresolvedHint(base, opts.provider, sourceId) ?? base.hint;base.status =- fetchErrors > 0 || capped || !allBatchesClean || listErrored || aborted || base.unresolved > 0 || base.pending.length > 0+ fetchErrors > 0 || capped || !allBatchesClean || listErrored || aborted || base.stopReason || base.unresolved > 0 || base.pending.length > 0? 'partial': importedTotal === 0? 'nothing_new'@@ -479,6 +512,10 @@ export async function runConnectorSync(/** What the run left unarchived (failed or still publishing) and the command that shows it. */function unresolvedHint(base: ConnectorSyncResult, provider: ConnectorProviderName, sourceId: string): string | undefined {const parts: string[] = [];+ if (base.stopReason) {+ parts.push(`Stopped after ${CONSECUTIVE_FETCH_FAILURE_LIMIT} conversation fetches failed in a row; the provider may be ` ++ 'throttling or down. The next sync resumes from the same place.');+ }if (base.unresolved > 0) {parts.push(`${base.unresolved} conversation(s) not archived yet; sync retries them automatically ` +@@ -559,9 +596,10 @@ async function stampAuthError(engine: BrainEngine, provider: ConnectorProviderNa}/** Map a thrown client error to a terminal sync status, or null if non-terminal. */-function classifyThrow(e: unknown): 'auth_required' | 'forbidden' | null {- if (e instanceof ConnectorAuthError) return 'auth_required';+function classifyThrow(e: unknown): TerminalStatus | null {+ if (e instanceof ConnectorAuthError || e instanceof ConnectorCredentialFormatError) return 'auth_required';if (e instanceof ConnectorForbiddenError) return 'forbidden';+ if (e instanceof ConnectorRateLimitedError) return 'rate_limited';return null;}diff --git a/src/core/connectors/types.ts b/src/core/connectors/types.tsindex af1335485d..174529d188 100644--- a/src/core/connectors/types.ts+++ b/src/core/connectors/types.ts@@ -82,7 +82,7 @@ export type ProbeResult =| { ok: true }| {ok: false;- kind: 'unauthorized' | 'forbidden_fingerprint' | 'network' | 'drift';+ kind: 'unauthorized' | 'forbidden_fingerprint' | 'rate_limited' | 'invalid_credential' | 'network' | 'drift';detail: string;};diff --git a/test/connectors-challenge-ratelimit-7482.test.ts b/test/connectors-challenge-ratelimit-7482.test.tsnew file mode 100644index 0000000000..bf592b4028--- /dev/null+++ b/test/connectors-challenge-ratelimit-7482.test.ts@@ -0,0 +1,181 @@+/**+ * #7482: a bot challenge on any status, and sustained rate limiting, stop the connector sync instead of retrying.+ *+ * 1. Protects: cf-mitigated: challenge (any status), a challenge page on a 5xx, and a redirect to a challenge all+ * classify as forbidden; a 429 that outlasts its retries, or asks for a Retry-After over the cap, ends the run as+ * rate_limited at once; CONSECUTIVE_FETCH_FAILURE_LIMIT failed fetches in a row stop the run as partial with+ * stopReason consecutive_fetch_failures when each failure is provider-wide (5xx or no response), and no later+ * conversation is requested; 404s and other item errors never trip it.+ * 2. Fails when: any of those shapes falls back to the generic retry path, or the sync keeps fetching after them.+ * 3. A Cloudflare 5xx error page (it names "cloudflare" but is no challenge) stays a retryable server_error.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';+import { classifyResponse } from '../src/core/connectors/classify.ts';+import { ConnectorClient, ConnectorRateLimitedError, MAX_RETRY_AFTER_MS, type ConnectorFetch } from '../src/core/connectors/client.ts';+import { CONSECUTIVE_FETCH_FAILURE_LIMIT, runConnectorSync } from '../src/core/connectors/sync.ts';+import { saveCredential } from '../src/core/connectors/credentials.ts';+import { watermarkKey } from '../src/core/connectors/config-keys.ts';+import { CHATGPT_BASE_URL } from '../src/core/connectors/providers/chatgpt.ts';+import { chatgptHandler, newFixtureState, startFixture, type FixtureConversation, type FixtureState } from './fixtures/connectors/fixture-server.ts';++function res(status: number, headers: Record<string, string> = {}) {+ const h = new Headers(headers);+ return { status, headers: { get: (n: string) => h.get(n) } };+}++const CHALLENGE_HTML = '<!DOCTYPE html><html><head><title>Just a moment...</title></head><body>cf-chl</body></html>';++describe('#7482 classifyResponse: a challenge on any status is forbidden', () => {+ for (const status of [200, 401, 403, 429, 503]) {+ test(`HTTP ${status} + cf-mitigated: challenge → forbidden_fingerprint`, () => {+ expect(classifyResponse(res(status, { 'cf-mitigated': 'challenge', 'content-type': 'application/json' }), '{}').kind).toBe('forbidden_fingerprint');+ });+ }+ test('503 serving a challenge page → forbidden_fingerprint', () => {+ expect(classifyResponse(res(503, { 'content-type': 'text/html' }), CHALLENGE_HTML).kind).toBe('forbidden_fingerprint');+ });+ test('302 to a Cloudflare challenge path → forbidden_fingerprint', () => {+ expect(classifyResponse(res(302, { location: '/cdn-cgi/challenge-platform/h/b/orchestrate' }), '').kind).toBe('forbidden_fingerprint');+ });+ test('a Cloudflare 502 error page (no challenge) stays a retryable server_error', () => {+ const body = '<!DOCTYPE html><html><title>502 Bad gateway | example.com | Cloudflare</title></html>';+ expect(classifyResponse(res(502, { 'content-type': 'text/html' }), body).kind).toBe('server_error');+ });+ test('a 302 to a login page with a code_challenge is not mistaken for a bot challenge', () => {+ expect(classifyResponse(res(302, { location: '/auth/login?code_challenge=abc' }), '').kind).toBe('server_error');+ });+});++describe('#7482 ConnectorClient rate limiting is bounded', () => {+ const json429 = (retryAfter?: string) => new Response('{"error":"slow down"}', { status: 429, headers: { 'content-type': 'application/json', ...(retryAfter ? { 'retry-after': retryAfter } : {}) } });++ test('a Retry-After over the cap stops at once: no wait, no retry', async () => {+ const sleeps: number[] = [];+ let calls = 0;+ const client = new ConnectorClient({+ baseUrl: 'https://chatgpt.com', headers: async () => ({}), minDelayMs: 0,+ sleep: async (ms) => { sleeps.push(ms); },+ fetchImpl: async () => { calls++; return json429(String(MAX_RETRY_AFTER_MS / 1000 + 1)); },+ });+ const e = await client.fetchJSON('/x').then(() => null, (err: unknown) => err);+ expect(e).toBeInstanceOf(ConnectorRateLimitedError);+ expect((e as ConnectorRateLimitedError).code).toBe('rate_limited');+ expect(calls).toBe(1);+ expect(sleeps).toEqual([]);+ });++ test('sustained 429s: the existing 4 retries, then ConnectorRateLimitedError', async () => {+ const sleeps: number[] = [];+ let calls = 0;+ const client = new ConnectorClient({+ baseUrl: 'https://chatgpt.com', headers: async () => ({}), minDelayMs: 0,+ sleep: async (ms) => { sleeps.push(ms); },+ fetchImpl: async () => { calls++; return json429('2'); },+ });+ await expect(client.fetchJSON('/x')).rejects.toBeInstanceOf(ConnectorRateLimitedError);+ expect(calls).toBe(5);+ expect(sleeps).toEqual([2000, 2000, 2000, 2000]);+ });+});++let engine: PGLiteEngine;+let home: string;+const T0 = 1_786_000_000;+const NOW_MS = (T0 + 100_000) * 1000;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => {+ await resetPgliteState(engine);+ if (home) rmSync(home, { recursive: true, force: true });+ home = mkdtempSync(join(tmpdir(), 'gbrain-connector-7482-'));+});++function conversations(n: number): FixtureConversation[] {+ return Array.from({ length: n }, (_, i) => ({+ id: `c-${i}`, title: `Topic ${i}`, createTime: T0 + i - 100, updateTime: T0 + i,+ turns: [{ role: 'user' as const, text: `q${i}` }, { role: 'assistant' as const, text: `a${i}` }],+ }));+}++/** Detail requests per conversation id, read from the fixture's hit counters. */+function detailHits(state: FixtureState): number {+ return state.hits.detail ?? 0;+}++async function sync(state: FixtureState) {+ const srv = startFixture(chatgptHandler(state));+ const fetchImpl: ConnectorFetch = (url, init) => fetch(url.replace(CHATGPT_BASE_URL, srv.baseUrl), init);+ try {+ return await withEnv({ GBRAIN_HOME: home, GBRAIN_CONNECTOR_CHATGPT_COOKIE: undefined, GBRAIN_CONNECTOR_CHATGPT_TOKEN: undefined }, async () => {+ saveCredential({ provider: 'chatgpt', strategy: 'browser-session', cookie: 'sessionKey=fixture', savedAt: new Date(0).toISOString() });+ return runConnectorSync(engine, { provider: 'chatgpt', sourceId: 'default', deps: { fetchImpl, now: () => NOW_MS, sleep: () => Promise.resolve() } });+ });+ } finally {+ srv.stop();+ }+}++describe('#7482 runConnectorSync stops instead of retrying', () => {+ test('a 503 challenge midway through the fetch phase → forbidden; no later conversation is requested', async () => {+ const state = newFixtureState(conversations(8));+ state.script.push({ pathIncludes: '/backend-api/conversation/', status: 503, body: CHALLENGE_HTML, contentType: 'text/html', onCall: 3 });+ const r = await sync(state);+ expect(r.status).toBe('forbidden');+ expect(r.fetched).toBe(2);+ expect(detailHits(state)).toBe(2);+ expect(state.hits['forced:/backend-api/conversation/:503']).toBe(3);+ });++ test('sustained 429s on conversation detail → rate_limited after the first conversation\'s retries', async () => {+ const state = newFixtureState(conversations(8));+ state.script.push({ pathIncludes: '/backend-api/conversation/', status: 429, body: { error: 'slow down' }, headers: { 'retry-after': '1' } });+ const r = await sync(state);+ expect(r.status).toBe('rate_limited');+ expect(r.hint).toMatch(/rate limit/i);+ expect(state.hits['forced:/backend-api/conversation/:429']).toBe(5);+ expect(r.fetchErrors).toBe(0);+ expect(await engine.getConfig(watermarkKey('chatgpt', 'default'))).toBeNull();+ });++ test('a 429 while listing → rate_limited, and no conversation detail is fetched', async () => {+ const state = newFixtureState(conversations(8));+ state.script.push({ pathIncludes: 'limit=28', status: 429, body: { error: 'slow down' }, headers: { 'retry-after': '1' } });+ const r = await sync(state);+ expect(r.status).toBe('rate_limited');+ expect(state.hits['forced:limit=28:429']).toBe(5);+ expect(state.hits['forced:/backend-api/conversation/:429'] ?? 0).toBe(0);+ expect(detailHits(state)).toBe(0);+ });++ test(`${CONSECUTIVE_FETCH_FAILURE_LIMIT} failed fetches in a row stop the run (partial, consecutive_fetch_failures)`, async () => {+ const state = newFixtureState(conversations(12));+ state.script.push({ pathIncludes: '/backend-api/conversation/', status: 500, body: { error: 'boom' } });+ const r = await sync(state);+ expect(r.status).toBe('partial');+ expect(r.stopReason).toBe('consecutive_fetch_failures');+ expect(r.fetchErrors).toBe(CONSECUTIVE_FETCH_FAILURE_LIMIT);+ expect(state.hits['forced:/backend-api/conversation/:500']).toBe(CONSECUTIVE_FETCH_FAILURE_LIMIT * 5);+ expect(r.hint).toContain('in a row');+ expect(await engine.getConfig(watermarkKey('chatgpt', 'default'))).toBeNull();+ });++ test('item errors (404s) do not trip the breaker: the provider is answering', async () => {+ const state = newFixtureState(conversations(12));+ state.script.push({ pathIncludes: '/backend-api/conversation/', status: 404, body: { error: 'gone' } });+ const r = await sync(state);+ expect(r.status).toBe('partial');+ expect(r.stopReason).toBeUndefined();+ expect(r.fetchErrors).toBe(12);+ });+});diff --git a/test/connectors-header-redaction-7483.test.ts b/test/connectors-header-redaction-7483.test.tsnew file mode 100644index 0000000000..14d5ed5815--- /dev/null+++ b/test/connectors-header-redaction-7483.test.ts@@ -0,0 +1,140 @@+/**+ * #7483: a connector credential value never reaches probe detail, sync hints or logs.+ *+ * 1. Protects: a Cookie/Authorization value holding CR, LF, NUL or a non-ASCII character is refused before any+ * request with the fixed code invalid_header_value, and a fetch layer whose error text echoes header values+ * (Node's undici does: "Headers.append: \"<value>\" is an invalid header value.") never has that text copied out.+ * 2. Fails when: the client sends an unvalidated header value, or a provider probe / the sync orchestrator copies a+ * raw fetch error message into ProbeResult.detail, ConnectorSyncResult.hint or the log.+ * 3. Dummy values only; no live provider is called.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';+import { ConnectorClient, ConnectorCredentialFormatError, type ConnectorFetch } from '../src/core/connectors/client.ts';+import { chatgptProvider, CHATGPT_BASE_URL } from '../src/core/connectors/providers/chatgpt.ts';+import { claudeProvider, CLAUDE_BASE_URL } from '../src/core/connectors/providers/claude.ts';+import { runConnectorSync } from '../src/core/connectors/sync.ts';+import { saveCredential } from '../src/core/connectors/credentials.ts';+import { authErrorAtKey } from '../src/core/connectors/config-keys.ts';++const SECRET = 'DUMMY-SECRET-7483';+const MALFORMED: Record<string, string> = {+ lf: `sessionKey=${SECRET}\nX`,+ crlf: `sessionKey=${SECRET}\r\nX`,+ nul: `sessionKey=${SECRET}\u0000X`,+ non_ascii: `sessionKey=${SECRET}\u20acX`,+};++/** The undici shape: a header-validation TypeError whose message quotes the value. */+const echoingFetch = (calls: { n: number }): ConnectorFetch => async (_url, init) => {+ calls.n++;+ const value = Object.values(init.headers as Record<string, string>).find(v => v.includes(SECRET)) ?? '';+ throw new TypeError(`Headers.append: "${value}" is an invalid header value.`);+};++let engine: PGLiteEngine;+let home: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => {+ await resetPgliteState(engine);+ if (home) rmSync(home, { recursive: true, force: true });+ home = mkdtempSync(join(tmpdir(), 'gbrain-connector-7483-'));+});++function env<T>(fn: () => Promise<T>): Promise<T> {+ return withEnv({+ GBRAIN_HOME: home,+ GBRAIN_CONNECTOR_CHATGPT_COOKIE: undefined, GBRAIN_CONNECTOR_CHATGPT_TOKEN: undefined,+ GBRAIN_CONNECTOR_CLAUDE_COOKIE: undefined, GBRAIN_CONNECTOR_CLAUDE_TOKEN: undefined,+ }, fn);+}++describe('#7483 malformed header values are refused before any request', () => {+ for (const [shape, cookie] of Object.entries(MALFORMED)) {+ for (const [provider, base] of [[chatgptProvider, CHATGPT_BASE_URL], [claudeProvider, CLAUDE_BASE_URL]] as const) {+ test(`${provider.name} probe, ${shape}: invalid_credential, value absent, no request`, async () => {+ const calls = { n: 0 };+ const client = new ConnectorClient({+ baseUrl: base,+ headers: () => provider.authHeaders({ provider: provider.name, strategy: 'browser-session', cookie, savedAt: new Date(0).toISOString() }),+ fetchImpl: echoingFetch(calls),+ sleep: () => Promise.resolve(),+ });+ const r = await provider.probe(client);+ expect(r).toMatchObject({ ok: false, kind: 'invalid_credential' });+ expect(JSON.stringify(r)).not.toContain(SECRET);+ expect(calls.n).toBe(0);+ });+ }+ }++ test('the real runtime fetch is never reached with the value (the client throws its own fixed error)', async () => {+ const client = new ConnectorClient({ baseUrl: 'http://127.0.0.1:9', headers: async () => ({ authorization: `Bearer ${SECRET}\nX` }), sleep: () => Promise.resolve() });+ const e = await client.fetchJSON('/x').then(() => null, (err: unknown) => err);+ expect(e).toBeInstanceOf(ConnectorCredentialFormatError);+ expect((e as ConnectorCredentialFormatError).code).toBe('invalid_header_value');+ expect((e as Error).message).toContain('authorization');+ expect((e as Error).message).not.toContain(SECRET);+ });++ test('sync with a stored malformed cookie: auth_required, auth_error_at stamped, hint and log free of the value', async () => {+ await env(async () => {+ saveCredential({ provider: 'chatgpt', strategy: 'browser-session', cookie: MALFORMED.crlf, savedAt: new Date(0).toISOString() });+ const calls = { n: 0 };+ const logs: string[] = [];+ const r = await runConnectorSync(engine, {+ provider: 'chatgpt',+ deps: { fetchImpl: echoingFetch(calls), sleep: () => Promise.resolve(), log: m => logs.push(m) },+ });+ expect(r.status).toBe('auth_required');+ expect(r.hint).toContain('cannot carry');+ expect(JSON.stringify(r)).not.toContain(SECRET);+ expect(logs.join('\n')).not.toContain(SECRET);+ expect(calls.n).toBe(0);+ expect(await engine.getConfig(authErrorAtKey('chatgpt'))).toBeTruthy();+ });+ });+});++describe('#7483 a fetch error that echoes a header value is never copied out', () => {+ test('probe detail carries the error code, not the runtime text', async () => {+ const calls = { n: 0 };+ const client = new ConnectorClient({+ baseUrl: CHATGPT_BASE_URL,+ headers: async () => ({ cookie: `sessionKey=${SECRET}` }),+ fetchImpl: echoingFetch(calls),+ sleep: () => Promise.resolve(),+ });+ const r = await chatgptProvider.probe(client);+ expect(r).toMatchObject({ ok: false, kind: 'network' });+ expect(JSON.stringify(r)).not.toContain(SECRET);+ expect(JSON.stringify(r)).toContain('TypeError');+ expect(calls.n).toBe(1);+ });++ test('sync: the probe hint (printed by --json, stored by a background job) is free of the value', async () => {+ await env(async () => {+ saveCredential({ provider: 'claude', strategy: 'browser-session', cookie: `sessionKey=${SECRET}`, savedAt: new Date(0).toISOString() });+ const logs: string[] = [];+ const r = await runConnectorSync(engine, {+ provider: 'claude',+ deps: { fetchImpl: echoingFetch({ n: 0 }), sleep: () => Promise.resolve(), log: m => logs.push(m) },+ });+ expect(r.status).toBe('partial');+ expect(r.hint).toContain('probe failed');+ expect(JSON.stringify(r)).not.toContain(SECRET);+ expect(logs.join('\n')).not.toContain(SECRET);+ });+ });+});