From e4e2c5a7050dd28482934678325aae01f20ee131 Mon Sep 17 00:00:00 2001 From: Sergei Solo Date: Sun, 4 Oct 2026 06:57:00 +0000 Subject: [PATCH 1/6] fix: retry overloaded responses and honour Retry-After Only 429 was retried, after a fixed 1s/2s pause. An overloaded (529) response went straight back to the caller, and a 429's Retry-After was ignored: a short one was retried too early, and a usage-limit one that resets in hours was retried twice for nothing. Retry 429 and 529 up to twice, waiting as long as Retry-After asks (exponential backoff when it is absent). A wait longer than 10s is not absorbed inside the request: the response is returned at once, so opencode's own retry loop - which shows the wait and can be cancelled - takes over. The wait ends early when the request is aborted, and the failed response body is released before the retry. 429 keeps its token refresh. --- src/index.test.ts | 139 ++++++++++++++++++++++++++++++++++++++++++++++ src/index.ts | 40 +++++++++---- src/retry.ts | 65 ++++++++++++++++++++++ 3 files changed, 234 insertions(+), 10 deletions(-) create mode 100644 src/retry.ts diff --git a/src/index.test.ts b/src/index.test.ts index 3f3bf61..f6aa078 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -9,6 +9,9 @@ import { describe, it } from "node:test"; import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { translateToolArgsJsonString, @@ -42,6 +45,12 @@ import { } from "./index.js"; import { createSseProcessor, parseSseEvent, buildSseEvent } from "./stream.js"; import { BETA_FLAGS, OAUTH_BETA_FLAG } from "./constants.js"; +import { + MAX_RETRY_DELAY_MS, + getResponseRetryDelayMs, + parseRetryAfterMs, + waitForRetry, +} from "./retry.js"; describe("Anthropic beta headers", () => { it("preserves SDK beta flags alongside the bridge requirements", () => { @@ -2177,3 +2186,133 @@ describe("selectClaudeCredentials", () => { assert.equal(selectClaudeCredentials([null, real]), real); }); }); + +describe("retry policy", () => { + const now = Date.parse("2026-10-04T12:00:00Z"); + + it("reads Retry-After as delay seconds or as an HTTP date", () => { + assert.equal(parseRetryAfterMs("3", now), 3000); + assert.equal(parseRetryAfterMs("Sun, 04 Oct 2026 12:00:05 GMT", now), 5000); + assert.equal(parseRetryAfterMs("Sun, 04 Oct 2026 11:59:00 GMT", now), 0); + assert.equal(parseRetryAfterMs(null, now), null); + assert.equal(parseRetryAfterMs("", now), null); + assert.equal(parseRetryAfterMs("-1", now), null); + assert.equal(parseRetryAfterMs("soon", now), null); + }); + + it("waits as long as Retry-After asks, else backs off", () => { + assert.equal(getResponseRetryDelayMs(new Headers({ "retry-after": "4" }), 0, now), 4000); + assert.equal(getResponseRetryDelayMs(new Headers(), 0, now), 2000); + assert.equal(getResponseRetryDelayMs(new Headers(), 1, now), 4000); + }); + + it("refuses a wait longer than the bridge absorbs", () => { + const seconds = String(MAX_RETRY_DELAY_MS / 1000 + 1); + assert.equal(getResponseRetryDelayMs(new Headers({ "retry-after": seconds }), 0, now), null); + assert.equal(getResponseRetryDelayMs(new Headers({ "retry-after": "18000" }), 0, now), null); + }); + + it("ends a retry wait early when the request is aborted", async () => { + const controller = new AbortController(); + const reason = new Error("aborted by caller"); + const started = Date.now(); + const wait = waitForRetry(5000, controller.signal); + controller.abort(reason); + await assert.rejects(wait, (err) => err === reason); + assert.ok(Date.now() - started < 1000); + await assert.rejects(waitForRetry(10, controller.signal), (err) => err === reason); + }); +}); + +describe("API request retry", () => { + type Reply = { status: number; retryAfter?: string }; + + // Drives the plugin's real fetch wrapper against a stubbed network. Auth is a + // valid stored token, so no refresh (and no real token request) can happen; + // 429 cases only use waits the bridge refuses, which return before refreshing. + // HOME and XDG_DATA_HOME point at a scratch dir so the developer's own Claude + // CLI credentials and opencode log dir are never touched. + async function sendThroughBridge(replies: Reply[], signal?: AbortSignal) { + const originalFetch = globalThis.fetch; + const originalEnv = { + ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY, + HOME: process.env.HOME, + XDG_DATA_HOME: process.env.XDG_DATA_HOME, + }; + const scratchDir = mkdtempSync(join(tmpdir(), "bridge-retry-test-")); + process.env.HOME = scratchDir; + process.env.XDG_DATA_HOME = join(scratchDir, "data"); + const messageCalls: string[] = []; + globalThis.fetch = (async (input: string | URL | Request) => { + const url = input instanceof Request ? input.url : String(input); + if (!url.includes("/v1/messages")) return new Response("{}", { status: 404 }); + messageCalls.push(url); + const reply = replies[Math.min(messageCalls.length - 1, replies.length - 1)]; + return new Response(JSON.stringify({ type: reply.status === 200 ? "message" : "error" }), { + status: reply.status, + headers: reply.retryAfter === undefined ? {} : { "retry-after": reply.retryAfter }, + }); + }) as typeof fetch; + + try { + const hooks = await pluginModule.server({ client: { auth: { set: async () => {} } } }); + const loaded = await hooks.auth.loader( + async () => ({ + type: "oauth", + access: "test-access", + refresh: "test-refresh", + expires: Date.now() + 3_600_000, + }), + { models: {} }, + ) as { fetch: (input: string, init?: RequestInit) => Promise }; + const response = await loaded.fetch("https://api.anthropic.com/v1/messages", { + method: "POST", + body: JSON.stringify({ + model: "claude-haiku-4-5", + max_tokens: 16, + messages: [{ role: "user", content: "hi" }], + }), + signal, + }); + return { status: response.status, calls: messageCalls.length }; + } finally { + globalThis.fetch = originalFetch; + for (const [name, value] of Object.entries(originalEnv)) { + if (value === undefined) delete process.env[name]; + else process.env[name] = value; + } + rmSync(scratchDir, { recursive: true, force: true }); + } + } + + it("retries an overloaded response and returns the recovered one", async () => { + const result = await sendThroughBridge([{ status: 529, retryAfter: "0" }, { status: 200 }]); + assert.deepEqual(result, { status: 200, calls: 2 }); + }); + + it("stops after two retries and returns the last overloaded response", async () => { + const result = await sendThroughBridge([{ status: 529, retryAfter: "0" }]); + assert.deepEqual(result, { status: 529, calls: 3 }); + }); + + it("returns a long Retry-After at once instead of waiting inside the request", async () => { + const started = Date.now(); + const result = await sendThroughBridge([{ status: 429, retryAfter: "18000" }]); + assert.deepEqual(result, { status: 429, calls: 1 }); + assert.ok(Date.now() - started < 1000); + }); + + it("does not retry other errors", async () => { + const result = await sendThroughBridge([{ status: 500 }]); + assert.deepEqual(result, { status: 500, calls: 1 }); + }); + + it("gives up the retry wait when the request is aborted", async () => { + const controller = new AbortController(); + setTimeout(() => controller.abort(new Error("cancelled")), 20); + await assert.rejects( + sendThroughBridge([{ status: 529, retryAfter: "5" }], controller.signal), + /cancelled/, + ); + }); +}); diff --git a/src/index.ts b/src/index.ts index 9d1ef0b..9797ef7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -12,6 +12,12 @@ import { type OAuthTokens, } from "./oauth.js"; import { getClaudeTokens, readClaudeCredentials } from "./keychain.js"; +import { + MAX_RESPONSE_RETRIES, + RETRYABLE_STATUSES, + getResponseRetryDelayMs, + waitForRetry, +} from "./retry.js"; import { BETA_FLAGS, CLI_VERSION, @@ -1102,7 +1108,7 @@ const OpenCodeClaudeBridge = async ({ client }: { client: PluginClient }) => { : input.url, ); - // ── Request (with 429 auto-refresh retry) ── + // ── Request (with 429/529 retry) ── const outHeaders: Record = {}; headers.forEach((v, k) => { outHeaders[k] = v; }); @@ -1115,11 +1121,22 @@ const OpenCodeClaudeBridge = async ({ client }: { client: PluginClient }) => { let response = await doFetch(); - // 429 auto-refresh: rate limits are per-access-token, so refreshing - // the token gives us a fresh rate limit bucket. Try up to 2 retries. - if (response.status === 429) { - for (let retry = 0; retry < 2; retry++) { - console.error(`[opencode-claude-bridge] 429 rate limited (attempt ${retry + 1}/2), refreshing token...`); + // Retry rate-limited (429) and overloaded (529) responses, waiting + // as long as Retry-After asks. A longer wait than the bridge absorbs + // returns the response as-is so opencode's own retry takes over. + for ( + let retry = 0; + retry < MAX_RESPONSE_RETRIES && RETRYABLE_STATUSES.has(response.status); + retry++ + ) { + const delayMs = getResponseRetryDelayMs(response.headers, retry); + if (delayMs === null) break; + const attempt = `attempt ${retry + 1}/${MAX_RESPONSE_RETRIES}`; + + if (response.status === 429) { + // 429 auto-refresh: rate limits are per-access-token, so + // refreshing the token gives us a fresh rate limit bucket. + console.error(`[opencode-claude-bridge] 429 rate limited (${attempt}), refreshing token...`); let freshToken: string | null = null; try { freshToken = await refreshAuth(auth, client); @@ -1133,11 +1150,14 @@ const OpenCodeClaudeBridge = async ({ client }: { client: PluginClient }) => { break; } outHeaders["authorization"] = `Bearer ${freshToken}`; - // Back off briefly: 1s first retry, 2s second - await new Promise((r) => setTimeout(r, 1000 * (retry + 1))); - response = await doFetch(); - if (response.status !== 429) break; + } else { + console.error(`[opencode-claude-bridge] ${response.status} overloaded (${attempt}), retrying in ${Math.ceil(delayMs / 1000)}s...`); } + + // Release the failed response's connection before reusing it. + await response.body?.cancel().catch(() => {}); + await waitForRetry(delayMs, init?.signal); + response = await doFetch(); } // ── Map Claude-style tool names and arguments back to OpenCode ── diff --git a/src/retry.ts b/src/retry.ts new file mode 100644 index 0000000..0076ee5 --- /dev/null +++ b/src/retry.ts @@ -0,0 +1,65 @@ +/** + * Retry policy for the Messages API wrapper. Pure apart from the timer in + * waitForRetry, so it can be tested without a network. + */ + +/** Statuses the bridge retries itself: rate limited, and overloaded. */ +export const RETRYABLE_STATUSES = new Set([429, 529]); + +/** Retries per request; opencode's own retry loop takes over after these. */ +export const MAX_RESPONSE_RETRIES = 2; + +/** + * Longest wait the bridge sits through before retrying. A longer requested + * wait (a usage limit that resets in hours) is handed straight back to the + * caller: opencode's retry loop shows the wait and can be cancelled, while a + * wait inside fetch looks like a hung request. + */ +export const MAX_RETRY_DELAY_MS = 10_000; + +function getOverloadedBackoffMs(attempt: number): number { + return Math.min(2000 * 2 ** attempt, 8000); +} + +/** Parse a Retry-After value (delay seconds or an HTTP date) into milliseconds. */ +export function parseRetryAfterMs(value: string | null, now = Date.now()): number | null { + if (!value?.trim()) return null; + const seconds = Number(value); + if (Number.isFinite(seconds)) return seconds >= 0 ? seconds * 1000 : null; + const date = Date.parse(value); + if (Number.isFinite(date)) return Math.max(date - now, 0); + return null; +} + +/** + * Delay before retry `attempt` (0-based) of a retryable response, or null + * when the server asked for a longer wait than the bridge should absorb. + */ +export function getResponseRetryDelayMs( + headers: Headers, + attempt: number, + now = Date.now(), +): number | null { + const delayMs = parseRetryAfterMs(headers.get("retry-after"), now) + ?? getOverloadedBackoffMs(attempt); + return delayMs > MAX_RETRY_DELAY_MS ? null : delayMs; +} + +/** Wait before a retry, ending early (with the abort reason) when the request is aborted. */ +export function waitForRetry(ms: number, signal?: AbortSignal | null): Promise { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(signal.reason); + return; + } + const onAbort = () => { + clearTimeout(timer); + reject(signal?.reason); + }; + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, ms); + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} From 6f0d4e25243675d33404ab6ff865e8e0963020e2 Mon Sep 17 00:00:00 2001 From: Sergei Solo Date: Sun, 4 Oct 2026 06:58:09 +0000 Subject: [PATCH 2/6] fix: retry the token endpoint when it is overloaded The token request retried only 429. An overloaded (529) answer failed the refresh at once, and when 429 retries ran out the caller got a made-up "Rate limited" response instead of what the endpoint actually said. Retry 529 as well, wait as long as the body's retry_after asks, and return the endpoint's real last answer. The request blocks the process while it sleeps, so a requested wait over 10s is not absorbed: the answer is returned straight away. --- src/index.test.ts | 79 ++++++++++++++++++++++++++++++++++++++++++++++- src/oauth.ts | 20 +++++++----- src/retry.ts | 34 ++++++++++++++++++-- 3 files changed, 123 insertions(+), 10 deletions(-) diff --git a/src/index.test.ts b/src/index.test.ts index f6aa078..056be18 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -9,7 +9,7 @@ import { describe, it } from "node:test"; import assert from "node:assert/strict"; -import { mkdtempSync, rmSync } from "node:fs"; +import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -23,6 +23,7 @@ import { import { extractOAuthErrorDetail, parseOAuthRedirect, + refreshTokens, startOAuthCallbackServer, type OAuthTokens, } from "./oauth.js"; @@ -48,6 +49,7 @@ import { BETA_FLAGS, OAUTH_BETA_FLAG } from "./constants.js"; import { MAX_RETRY_DELAY_MS, getResponseRetryDelayMs, + getTokenRetryDelayMs, parseRetryAfterMs, waitForRetry, } from "./retry.js"; @@ -2212,6 +2214,18 @@ describe("retry policy", () => { assert.equal(getResponseRetryDelayMs(new Headers({ "retry-after": "18000" }), 0, now), null); }); + it("reads the token endpoint's retry_after from the body", () => { + assert.equal(getTokenRetryDelayMs(529, '{"retry_after":2}', 0), 2000); + assert.equal(getTokenRetryDelayMs(429, '{"error":{"retry_after":"3"}}', 0), 3000); + assert.equal(getTokenRetryDelayMs(529, '{"retry_after":600}', 0), null); + }); + + it("backs off the token endpoint when the body has no retry_after", () => { + assert.equal(getTokenRetryDelayMs(529, "not json", 0), 2000); + assert.equal(getTokenRetryDelayMs(529, "{}", 3), 8000); + assert.equal(getTokenRetryDelayMs(429, "{}", 1, 0.5), 2500); + }); + it("ends a retry wait early when the request is aborted", async () => { const controller = new AbortController(); const reason = new Error("aborted by caller"); @@ -2316,3 +2330,66 @@ describe("API request retry", () => { ); }); }); + +describe("token endpoint retry", () => { + type Reply = { status: number; body: string }; + + // Runs refreshTokens against a stand-in `curl` placed first on PATH, so the + // real retry loop executes without a network. POSIX-only (shebang script). + function refreshWithReplies(replies: Reply[]): { result: unknown; calls: number } { + const dir = mkdtempSync(join(tmpdir(), "bridge-token-test-")); + const originalPath = process.env.PATH; + writeFileSync(join(dir, "replies.json"), JSON.stringify(replies)); + writeFileSync(join(dir, "curl"), `#!${process.execPath} +const fs = require("node:fs"); +const dir = ${JSON.stringify(dir)}; +const countFile = dir + "/count"; +const count = fs.existsSync(countFile) ? Number(fs.readFileSync(countFile, "utf8")) : 0; +fs.writeFileSync(countFile, String(count + 1)); +const replies = JSON.parse(fs.readFileSync(dir + "/replies.json", "utf8")); +const reply = replies[Math.min(count, replies.length - 1)]; +process.stdout.write(reply.body + "\\n__HTTP_STATUS__" + reply.status); +`); + chmodSync(join(dir, "curl"), 0o755); + process.env.PATH = `${dir}:${originalPath}`; + try { + let result: unknown; + try { + result = refreshTokens("test-refresh-token"); + } catch (err) { + result = err instanceof Error ? err.message : err; + } + return { result, calls: Number(readFileSync(join(dir, "count"), "utf8")) }; + } finally { + process.env.PATH = originalPath; + rmSync(dir, { recursive: true, force: true }); + } + } + + const ok = { + status: 200, + body: JSON.stringify({ access_token: "new-access", refresh_token: "new-refresh", expires_in: 3600 }), + }; + const overloaded = (retryAfter: number) => ({ + status: 529, + body: JSON.stringify({ error: { type: "overloaded_error", message: "Overloaded" }, retry_after: retryAfter }), + }); + + it("retries an overloaded token endpoint", { skip: process.platform === "win32" }, () => { + const { result, calls } = refreshWithReplies([overloaded(0), ok]); + assert.equal(calls, 2); + assert.equal((result as { access: string }).access, "new-access"); + }); + + it("reports the endpoint's real last answer once retries run out", { skip: process.platform === "win32" }, () => { + const { result, calls } = refreshWithReplies([overloaded(0)]); + assert.equal(calls, 3); + assert.match(String(result), /failed \(529\): Overloaded/); + }); + + it("does not sit through a long requested wait", { skip: process.platform === "win32" }, () => { + const { result, calls } = refreshWithReplies([overloaded(600), ok]); + assert.equal(calls, 1); + assert.match(String(result), /failed \(529\)/); + }); +}); diff --git a/src/oauth.ts b/src/oauth.ts index 8de4c82..7957c54 100644 --- a/src/oauth.ts +++ b/src/oauth.ts @@ -9,6 +9,7 @@ import { SCOPES, USER_AGENT, } from "./constants.js"; +import { RETRYABLE_STATUSES, getTokenRetryDelayMs } from "./retry.js"; export interface OAuthTokens { access: string; @@ -114,6 +115,7 @@ function curlPost( const payload = JSON.stringify(body); for (let attempt = 0; attempt < retries; attempt++) { + let retryDelayMs: number; try { const result = execFileSync( "curl", @@ -129,23 +131,27 @@ function curlPost( const status = parseInt(parts[parts.length - 1], 10); const responseBody = parts.slice(0, -1).join("\n__HTTP_STATUS__"); - if (status !== 429 || attempt === retries - 1) { + if (!RETRYABLE_STATUSES.has(status) || attempt === retries - 1) { return { status, body: responseBody }; } + // Null when the endpoint asks for a longer wait than this blocking call + // should sit through: hand its real answer back instead. + const delayMs = getTokenRetryDelayMs(status, responseBody, attempt); + if (delayMs === null) return { status, body: responseBody }; + retryDelayMs = delayMs; console.error( - `[opencode-oauth] Token endpoint 429 (attempt ${attempt + 1}/${retries}), retrying...`, + `[opencode-oauth] Token endpoint ${status} (attempt ${attempt + 1}/${retries}), retrying...`, ); } catch (err) { if (attempt === retries - 1) throw err; + retryDelayMs = 1000 * Math.pow(2, attempt) + Math.random() * 1000; } - sleep(1000 * Math.pow(2, attempt) + Math.random() * 1000); + sleep(retryDelayMs); } - return { - status: 429, - body: '{"error":{"type":"rate_limit_error","message":"Rate limited"}}', - }; + // Unreachable: the last attempt always returns or throws. + throw new Error("Token endpoint request was not attempted"); } export function extractOAuthErrorDetail(body: string): string { diff --git a/src/retry.ts b/src/retry.ts index 0076ee5..d8906d7 100644 --- a/src/retry.ts +++ b/src/retry.ts @@ -1,6 +1,7 @@ /** - * Retry policy for the Messages API wrapper. Pure apart from the timer in - * waitForRetry, so it can be tested without a network. + * Retry policy shared by the Messages API wrapper and the OAuth token + * endpoint. Pure apart from the timer in waitForRetry, so it can be tested + * without a network. */ /** Statuses the bridge retries itself: rate limited, and overloaded. */ @@ -45,6 +46,35 @@ export function getResponseRetryDelayMs( return delayMs > MAX_RETRY_DELAY_MS ? null : delayMs; } +/** + * Delay before retry `attempt` (0-based) of the token endpoint, which reports + * its requested wait as `retry_after` seconds in the JSON body. Null when that + * wait is longer than the bridge should absorb — the token request is a + * blocking call, so a long sleep would stall opencode entirely. + */ +export function getTokenRetryDelayMs( + status: number, + body: string, + attempt: number, + random = Math.random(), +): number | null { + let requestedMs: number | null = null; + try { + const parsed = JSON.parse(body) as { + retry_after?: number | string; + error?: { retry_after?: number | string }; + }; + const seconds = Number(parsed.retry_after ?? parsed.error?.retry_after); + if (Number.isFinite(seconds) && seconds >= 0) requestedMs = seconds * 1000; + } catch {} + + const delayMs = requestedMs + ?? (status === 529 + ? getOverloadedBackoffMs(attempt) + : 1000 * 2 ** attempt + random * 1000); + return delayMs > MAX_RETRY_DELAY_MS ? null : delayMs; +} + /** Wait before a retry, ending early (with the abort reason) when the request is aborted. */ export function waitForRetry(ms: number, signal?: AbortSignal | null): Promise { return new Promise((resolve, reject) => { From 50c20a8a53b04c87acd0dc75cce0ecfafc4a846c Mon Sep 17 00:00:00 2001 From: Sergei Solo Date: Sun, 4 Oct 2026 06:59:03 +0000 Subject: [PATCH 3/6] fix: accept a plain-string system prompt The Messages API takes `system` either as a string or as text blocks, but the request rewrite assumed blocks. A string made it throw before the billing header was added; the error was swallowed and the request went out unrewritten, so the subscription endpoint rejected it. Wrap a string prompt in a single text block before rewriting. --- src/index.test.ts | 67 +++++++++++++++++++++++++++++++++++------------ src/index.ts | 12 ++++++++- 2 files changed, 61 insertions(+), 18 deletions(-) diff --git a/src/index.test.ts b/src/index.test.ts index 056be18..ede4fc0 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -42,6 +42,7 @@ import { stripAssistantPrefillForClaude, stripMessageCacheControlPreservingTail, stripSystemCacheControl, + toSystemBlocks, type V2PluginContext, } from "./index.js"; import { createSseProcessor, parseSseEvent, buildSseEvent } from "./stream.js"; @@ -2238,7 +2239,7 @@ describe("retry policy", () => { }); }); -describe("API request retry", () => { +describe("bridge fetch wrapper", () => { type Reply = { status: number; retryAfter?: string }; // Drives the plugin's real fetch wrapper against a stubbed network. Auth is a @@ -2246,7 +2247,15 @@ describe("API request retry", () => { // 429 cases only use waits the bridge refuses, which return before refreshing. // HOME and XDG_DATA_HOME point at a scratch dir so the developer's own Claude // CLI credentials and opencode log dir are never touched. - async function sendThroughBridge(replies: Reply[], signal?: AbortSignal) { + async function sendThroughBridge( + replies: Reply[], + signal?: AbortSignal, + requestBody: Record = { + model: "claude-haiku-4-5", + max_tokens: 16, + messages: [{ role: "user", content: "hi" }], + }, + ) { const originalFetch = globalThis.fetch; const originalEnv = { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY, @@ -2257,10 +2266,12 @@ describe("API request retry", () => { process.env.HOME = scratchDir; process.env.XDG_DATA_HOME = join(scratchDir, "data"); const messageCalls: string[] = []; - globalThis.fetch = (async (input: string | URL | Request) => { + const sentBodies: string[] = []; + globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => { const url = input instanceof Request ? input.url : String(input); if (!url.includes("/v1/messages")) return new Response("{}", { status: 404 }); messageCalls.push(url); + sentBodies.push(String(init?.body)); const reply = replies[Math.min(messageCalls.length - 1, replies.length - 1)]; return new Response(JSON.stringify({ type: reply.status === 200 ? "message" : "error" }), { status: reply.status, @@ -2281,14 +2292,10 @@ describe("API request retry", () => { ) as { fetch: (input: string, init?: RequestInit) => Promise }; const response = await loaded.fetch("https://api.anthropic.com/v1/messages", { method: "POST", - body: JSON.stringify({ - model: "claude-haiku-4-5", - max_tokens: 16, - messages: [{ role: "user", content: "hi" }], - }), + body: JSON.stringify(requestBody), signal, }); - return { status: response.status, calls: messageCalls.length }; + return { status: response.status, calls: messageCalls.length, sentBodies }; } finally { globalThis.fetch = originalFetch; for (const [name, value] of Object.entries(originalEnv)) { @@ -2300,25 +2307,38 @@ describe("API request retry", () => { } it("retries an overloaded response and returns the recovered one", async () => { - const result = await sendThroughBridge([{ status: 529, retryAfter: "0" }, { status: 200 }]); - assert.deepEqual(result, { status: 200, calls: 2 }); + const { status, calls } = await sendThroughBridge([{ status: 529, retryAfter: "0" }, { status: 200 }]); + assert.deepEqual({ status, calls }, { status: 200, calls: 2 }); }); it("stops after two retries and returns the last overloaded response", async () => { - const result = await sendThroughBridge([{ status: 529, retryAfter: "0" }]); - assert.deepEqual(result, { status: 529, calls: 3 }); + const { status, calls } = await sendThroughBridge([{ status: 529, retryAfter: "0" }]); + assert.deepEqual({ status, calls }, { status: 529, calls: 3 }); }); it("returns a long Retry-After at once instead of waiting inside the request", async () => { const started = Date.now(); - const result = await sendThroughBridge([{ status: 429, retryAfter: "18000" }]); - assert.deepEqual(result, { status: 429, calls: 1 }); + const { status, calls } = await sendThroughBridge([{ status: 429, retryAfter: "18000" }]); + assert.deepEqual({ status, calls }, { status: 429, calls: 1 }); assert.ok(Date.now() - started < 1000); }); it("does not retry other errors", async () => { - const result = await sendThroughBridge([{ status: 500 }]); - assert.deepEqual(result, { status: 500, calls: 1 }); + const { status, calls } = await sendThroughBridge([{ status: 500 }]); + assert.deepEqual({ status, calls }, { status: 500, calls: 1 }); + }); + + it("rewrites a request whose system prompt is a plain string", async () => { + const { status, sentBodies } = await sendThroughBridge([{ status: 200 }], undefined, { + model: "claude-haiku-4-5", + max_tokens: 16, + system: "Be brief.", + messages: [{ role: "user", content: "hi" }], + }); + assert.equal(status, 200); + const system = JSON.parse(sentBodies[0]).system; + assert.ok(Array.isArray(system), "system must be sent as blocks"); + assert.match(system[0].text, /^x-anthropic-billing-header:/); }); it("gives up the retry wait when the request is aborted", async () => { @@ -2393,3 +2413,16 @@ process.stdout.write(reply.body + "\\n__HTTP_STATUS__" + reply.status); assert.match(String(result), /failed \(529\)/); }); }); + +describe("plain-string system prompt", () => { + it("wraps a string in a single text block", () => { + assert.deepEqual(toSystemBlocks("Be brief."), [{ type: "text", text: "Be brief." }]); + }); + + it("passes blocks through and turns an absent prompt into no blocks", () => { + const blocks = [{ type: "text", text: "x" }]; + assert.equal(toSystemBlocks(blocks), blocks); + assert.deepEqual(toSystemBlocks(undefined), []); + assert.deepEqual(toSystemBlocks(""), []); + }); +}); diff --git a/src/index.ts b/src/index.ts index 9797ef7..fe5a547 100644 --- a/src/index.ts +++ b/src/index.ts @@ -224,6 +224,16 @@ export function rewriteSystemBlocksForModel( }); } +/** + * The Messages API takes `system` as a plain string or as text blocks; the + * request rewrite (billing header, prompt shaping) works on blocks only. + */ +export function toSystemBlocks(system: unknown): unknown { + if (!system) return []; + if (typeof system === "string") return [{ type: "text", text: system }]; + return system; +} + export function stripSystemCacheControl( system: Array<{ type?: string; text?: string; cache_control?: unknown }>, ): Array<{ type?: string; text?: string }> { @@ -777,7 +787,7 @@ async function transformClaudeRequestBody( parsed.temperature = 1; } - if (!parsed.system) parsed.system = []; + parsed.system = toSystemBlocks(parsed.system); if (Array.isArray(parsed.messages)) { parsed.messages = stripAssistantPrefillForClaude(parsed.messages); } From 4c4c875413d89bdc1248ffbd6d4a67c8bf8b01ce Mon Sep 17 00:00:00 2001 From: Sergei Solo Date: Sun, 4 Oct 2026 07:01:01 +0000 Subject: [PATCH 4/6] feat: log failed API responses When a request fails, opencode shows a one-line summary and the error body and request id are gone, which is exactly what is needed to tell a rejected request shape from a rate limit or an outage. Write each failed response that is handed back to opencode (after any retries) to stderr and append it, with its request id, to opencode/log/claude-bridge-api-errors.log under XDG_DATA_HOME (~/.local/share by default), next to opencode's own logs. --- src/index.test.ts | 30 +++++++++++++++++++++++------ src/index.ts | 48 ++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 69 insertions(+), 9 deletions(-) diff --git a/src/index.test.ts b/src/index.test.ts index ede4fc0..bbbe474 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -9,7 +9,7 @@ import { describe, it } from "node:test"; import assert from "node:assert/strict"; -import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -2273,10 +2273,12 @@ describe("bridge fetch wrapper", () => { messageCalls.push(url); sentBodies.push(String(init?.body)); const reply = replies[Math.min(messageCalls.length - 1, replies.length - 1)]; - return new Response(JSON.stringify({ type: reply.status === 200 ? "message" : "error" }), { - status: reply.status, - headers: reply.retryAfter === undefined ? {} : { "retry-after": reply.retryAfter }, - }); + const body = reply.status === 200 + ? { type: "message" } + : { type: "error", error: { type: "api_error", message: `failure ${reply.status}` } }; + const headers: Record = { "request-id": `req_${messageCalls.length}` }; + if (reply.retryAfter !== undefined) headers["retry-after"] = reply.retryAfter; + return new Response(JSON.stringify(body), { status: reply.status, headers }); }) as typeof fetch; try { @@ -2295,7 +2297,9 @@ describe("bridge fetch wrapper", () => { body: JSON.stringify(requestBody), signal, }); - return { status: response.status, calls: messageCalls.length, sentBodies }; + const errorLogPath = join(scratchDir, "data", "opencode", "log", "claude-bridge-api-errors.log"); + const errorLog = existsSync(errorLogPath) ? readFileSync(errorLogPath, "utf8") : ""; + return { status: response.status, calls: messageCalls.length, sentBodies, errorLog }; } finally { globalThis.fetch = originalFetch; for (const [name, value] of Object.entries(originalEnv)) { @@ -2328,6 +2332,20 @@ describe("bridge fetch wrapper", () => { assert.deepEqual({ status, calls }, { status: 500, calls: 1 }); }); + it("records the final failed response in the API error log", async () => { + const { status, errorLog } = await sendThroughBridge([{ status: 529, retryAfter: "0" }, { status: 500 }]); + assert.equal(status, 500); + // Only the response returned to opencode is logged, not the retried ones. + assert.match(errorLog, /status=500 url=https:\/\/api\.anthropic\.com\/v1\/messages\S* request-id=req_2/); + assert.match(errorLog, /response: .*failure 500/); + assert.doesNotMatch(errorLog, /status=529/); + }); + + it("logs nothing for a successful response", async () => { + const { errorLog } = await sendThroughBridge([{ status: 200 }]); + assert.equal(errorLog, ""); + }); + it("rewrites a request whose system prompt is a plain string", async () => { const { status, sentBodies } = await sendThroughBridge([{ status: 200 }], undefined, { model: "claude-haiku-4-5", diff --git a/src/index.ts b/src/index.ts index fe5a547..631f496 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,7 +1,7 @@ import { createHash, randomUUID } from "node:crypto"; -import { readFileSync } from "node:fs"; -import { hostname, userInfo } from "node:os"; -import { join } from "node:path"; +import { appendFileSync, mkdirSync, readFileSync } from "node:fs"; +import { homedir, hostname, userInfo } from "node:os"; +import { dirname, join } from "node:path"; import { createAuthorizationRequest, exchangeCodeForTokens, @@ -359,6 +359,46 @@ const oauthProfileCache = new Map>(); const SYSTEM_PROMPT_CACHE_PATH = process.env.ANTHROPIC_SYSTEM_PROMPT_PATH || join(process.env.HOME || "", ".cache", "opencode-claude-bridge", "claude-system-prompt.json"); +/** + * Where failed API responses are recorded, next to opencode's own logs. + * opencode only surfaces a one-line summary of a failed request; the full + * error body and request id are what a bug report needs. + */ +function getApiErrorLogPath(): string { + const dataHome = process.env.XDG_DATA_HOME || join(homedir(), ".local", "share"); + return join(dataHome, "opencode", "log", "claude-bridge-api-errors.log"); +} + +/** Record a failed API response on stderr and in the error log; never throws. */ +async function logApiErrorResponse(response: Response, requestUrl: string): Promise { + try { + const requestId = response.headers.get("request-id") || response.headers.get("x-request-id"); + const responseBody = await response.clone().text(); + const statusLine = `[opencode-claude-bridge] API error status=${response.status} url=${requestUrl}` + + (requestId ? ` request-id=${requestId}` : ""); + + console.error(statusLine); + if (responseBody) { + console.error(`[opencode-claude-bridge] API error response: ${responseBody.slice(0, 8000)}`); + } + + try { + const logPath = getApiErrorLogPath(); + mkdirSync(dirname(logPath), { recursive: true }); + const entry = [ + `time=${new Date().toISOString()}`, + statusLine, + responseBody ? `response: ${responseBody}` : "", + ].filter(Boolean).join("\n"); + appendFileSync(logPath, `${entry}\n\n`, "utf8"); + } catch (err) { + console.error(`[opencode-claude-bridge] Failed to write the API error log: ${err}`); + } + } catch (err) { + console.error(`[opencode-claude-bridge] Failed to read the API error response: ${err}`); + } +} + function buildAuthFailureResponse(detail: string): Response { const message = [ "Claude OAuth credentials are no longer valid.", @@ -1170,6 +1210,8 @@ const OpenCodeClaudeBridge = async ({ client }: { client: PluginClient }) => { response = await doFetch(); } + if (!response.ok) await logApiErrorResponse(response, finalUrl); + // ── Map Claude-style tool names and arguments back to OpenCode ── return wrapAnthropicResponseWithSse(response, inboundToolNameMap); }, From 075714df7268bf2bf9c99deda94a7ecf619b3092 Mon Sep 17 00:00:00 2001 From: Sergei Solo Date: Sun, 4 Oct 2026 07:01:01 +0000 Subject: [PATCH 5/6] docs: describe retries and the API error log --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index 136ca20..e58c69c 100644 --- a/README.md +++ b/README.md @@ -167,6 +167,12 @@ SHA256(salt + message[4] + message[7] + message[20] + CLI_VERSION).slice(0, 3) The salt is hardcoded in Claude Code's source. This changes per conversation because the user's message text changes. +### Retries and error log + +On OpenCode v1, rate-limited (429) and overloaded (529) responses are retried up to twice, waiting as long as `Retry-After` asks. A requested wait longer than 10 seconds is not absorbed inside the request: the response goes straight back to OpenCode, whose own retry loop shows the wait and can be cancelled. On OpenCode v2, OpenCode's native retry loop handles API response backoff; the OAuth token endpoint is retried on 429/529 across both v1 and v2. + +Every failed OAuth API response handed back to OpenCode is written to stderr and appended, with its request id, to `~/.local/share/opencode/log/claude-bridge-api-errors.log` (under `$XDG_DATA_HOME` when set). + ## OpenCode v2 compatibility OpenCode 2.0 loads plugins through a new contract (`id` + `setup()`), and V1 @@ -286,6 +292,7 @@ src/ constants.ts — Version strings, URLs, env overrides, header values (117 lines) keychain.ts — macOS Keychain access for OAuth tokens oauth.ts — OAuth PKCE flow with local callback server + retry.ts — Retry policy for API responses and the token endpoint scripts/ validate-opencode-oauth.js — Side-by-side wire comparison tool From 15b94fcf1c553fe0321a5a791ed16e09bc231b1e Mon Sep 17 00:00:00 2001 From: Cody Moore Date: Thu, 19 Nov 2026 15:28:01 -0500 Subject: [PATCH 6/6] feat: log failed OAuth API responses in v2 http.response and tighten log mode --- README.md | 18 ++++++++++-------- src/index.test.ts | 48 +++++++++++++++++++++++++++++++++++++++++++++++ src/index.ts | 9 ++++++--- 3 files changed, 64 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index e58c69c..1acb5ec 100644 --- a/README.md +++ b/README.md @@ -285,14 +285,16 @@ Key things that have changed across versions: ``` src/ - index.ts — Main plugin entry point: tool replacement, request/response - transformation, bidirectional parameter translation (~886 lines) - claude-tools.ts — 24 Claude Code tool definitions, fingerprint computation, - parameter translation maps (~757 lines) - constants.ts — Version strings, URLs, env overrides, header values (117 lines) - keychain.ts — macOS Keychain access for OAuth tokens - oauth.ts — OAuth PKCE flow with local callback server - retry.ts — Retry policy for API responses and the token endpoint + index.ts — Main plugin entry point (dual v1 server() + v2 setup()): + OAuth integration, request/response rewriting, system prompt + shaping, and API error logging + claude-tools.ts — Claude Code tool definitions, fingerprint computation, + and bidirectional parameter translation maps + stream.ts — Stateful SSE frame processor for inbound tool_use translation + retry.ts — Retry policy for 429/529 API and token-endpoint responses + constants.ts — Version strings, URLs, env overrides, header values + keychain.ts — macOS Keychain & ~/.claude/.credentials.json token lookup + oauth.ts — OAuth PKCE flow with CSRF-protected local callback server scripts/ validate-opencode-oauth.js — Side-by-side wire comparison tool diff --git a/src/index.test.ts b/src/index.test.ts index bbbe474..601b663 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -1928,6 +1928,54 @@ describe("OpenCode v2 plugin (setup)", () => { assert.equal(apiKeyEvent.system[0].text, "Clean prompt"); }); + it("logs failed OAuth responses in http.response without touching API-key failures", async () => { + const tmpData = mkdtempSync(join(tmpdir(), "bridge-v2-errlog-")); + const prevXdg = process.env.XDG_DATA_HOME; + process.env.XDG_DATA_HOME = tmpData; + try { + const mock = createMockV2Context({ + activeConnection: { type: "credential", id: "cred_1", method: "oauth" }, + resolvedCredential: { type: "oauth", methodID: "oauth", ...validTokens }, + }); + const setup = createOpenCodeClaudeBridgeV2({ + getClaudeTokens: () => validTokens, + readCachedClaudePromptCache: () => null, + fetchOAuthProfile: async () => null, + }); + await setup(mock.ctx); + + const reqEvent = { + request: new Request("https://api.anthropic.com/v1/messages", { + method: "POST", + headers: { authorization: `Bearer ${validTokens.access}` }, + body: JSON.stringify({ model: "claude-sonnet-4-6", messages: [{ role: "user", content: "hi" }] }), + }), + }; + await mock.triggerHook("http.request", reqEvent); + + const resEvent = { + request: reqEvent.request, + response: new Response('{"error":{"type":"overloaded_error","message":"Overloaded"}}', { + status: 529, + headers: { "request-id": "req_v2_529" }, + }), + }; + await mock.triggerHook("http.response", resEvent); + // Body remains readable downstream after logging + assert.ok((await resEvent.response.text()).includes("overloaded_error")); + + const logPath = join(tmpData, "opencode", "log", "claude-bridge-api-errors.log"); + assert.equal(existsSync(logPath), true); + const logged = readFileSync(logPath, "utf8"); + assert.ok(logged.includes("status=529")); + assert.ok(logged.includes("request-id=req_v2_529")); + } finally { + if (prevXdg === undefined) delete process.env.XDG_DATA_HOME; + else process.env.XDG_DATA_HOME = prevXdg; + rmSync(tmpData, { recursive: true, force: true }); + } + }); + it("interactive authorize supports mode:auto with submit paste and code fallback", async () => { const mock = createMockV2Context(); let closed = false; diff --git a/src/index.ts b/src/index.ts index 631f496..ccf1360 100644 --- a/src/index.ts +++ b/src/index.ts @@ -390,7 +390,7 @@ async function logApiErrorResponse(response: Response, requestUrl: string): Prom statusLine, responseBody ? `response: ${responseBody}` : "", ].filter(Boolean).join("\n"); - appendFileSync(logPath, `${entry}\n\n`, "utf8"); + appendFileSync(logPath, `${entry}\n\n`, { encoding: "utf8", mode: 0o600 }); } catch (err) { console.error(`[opencode-claude-bridge] Failed to write the API error log: ${err}`); } @@ -1910,13 +1910,16 @@ export function createOpenCodeClaudeBridgeV2(deps: V2BridgeDeps = {}) { ), ); - // ── SSE tool-name/argument translation (response phase) ── + // ── SSE tool-name/argument translation & error logging (response phase) ── track( await ctx.session.hook( "http.response", - (event: { request: Request; response: Response }) => { + async (event: { request: Request; response: Response }) => { const inboundToolNameMap = inboundMaps.get(event.request); if (!inboundToolNameMap) return; // Not OAuth-rewritten — passthrough + if (!event.response.ok) { + await logApiErrorResponse(event.response, event.request.url); + } try { event.response = wrapAnthropicResponseWithSse(event.response, inboundToolNameMap); } catch (err) {