Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(drivers): retry opt-out, outer HTTP status, OpenAI 409s

Saim Shafique16fca9255536
diff --git a/server/drivers/engine-errors.test.ts b/server/drivers/engine-errors.test.ts
index d3beaabe51..b8683fb805 100644
--- a/server/drivers/engine-errors.test.ts
+++ b/server/drivers/engine-errors.test.ts
@@ -277,6 +277,9 @@ describe("classifyError reads an explicit HTTP status before body text", () => {
["OpenAI HTTP 409: max 500 tokens", { transient: false, reason: "invalid_request" }],
["(status 409 Conflict): max 500 tokens", { transient: false, reason: "invalid_request" }],
["API Error: 409 Conflict", { transient: false, reason: "invalid_request" }],
+ ["API Error: 503: proxy said HTTP 409 for backend", { transient: true, reason: "server_error" }],
+ ["Internal error: API Error: 503: proxy said HTTP 409 for backend", { transient: true, reason: "server_error" }],
+ ["API Error: 409: backend said HTTP 503 for this call", { transient: false, reason: "invalid_request" }],
["xAI HTTP 429: too many requests", { transient: true, reason: "rate_limited" }],
["(status 503 Service Unavailable)", { transient: true, reason: "server_error" }],
["(status 529) overloaded", { transient: true, reason: "overloaded" }],
@@ -286,4 +289,15 @@ describe("classifyError reads an explicit HTTP status before body text", () => {
])("classifies %s", (message, expected) => {
expect(classifyError({ text: message })).toEqual(expected);
});
+
+ it("retries a 409 from OpenAI and not from any other provider", () => {
+ expect(classifyError({ text: "API Error: 409 Conflict" }, { openAi: true }))
+ .toEqual({ transient: true, reason: "server_error" });
+ expect(classifyError({ text: "OpenAI HTTP 409: conflict with the current resource state" }, { openAi: true }))
+ .toEqual({ transient: true, reason: "server_error" });
+ expect(classifyError({ text: "API Error: 409 Conflict" }))
+ .toEqual({ transient: false, reason: "invalid_request" });
+ expect(classifyError({ text: "OpenAI HTTP 409: max 500 tokens" }))
+ .toEqual({ transient: false, reason: "invalid_request" });
+ });
});
diff --git a/server/drivers/openai-chat.test.ts b/server/drivers/openai-chat.test.ts
index a148129aa4..a9f9d98925 100644
--- a/server/drivers/openai-chat.test.ts
+++ b/server/drivers/openai-chat.test.ts
@@ -10,6 +10,7 @@ import { discardNativeLog, flushNativeLog } from "./native.ts";
import type { RuntimeEvent, SendTurnInput } from "../contracts.ts";
import { GrokDriver } from "./grok.ts";
import { MinimaxDriver } from "./minimax.ts";
+import { createOpenAIChatRuntime } from "./openai-chat.ts";
import { OpenAICompatDriver } from "./openai-compat.ts";
import { MistralDriver } from "./mistral.ts";
import { startFakeHttpMcp } from "../testing/fake-http-mcp-server.ts";
@@ -966,12 +967,12 @@ describe("createOpenAIChatRuntime rejected keys", () => {
describe("createOpenAIChatRuntime transient retries", () => {
// Like runTurn, but the turn waits out the retry backoff before it completes.
- const runRetryTurn = async (respond: () => Response) => {
+ const runRetryTurn = async (respond: () => Response, apiUrl = "https://api.example.com/v1") => {
vi.stubGlobal("fetch", vi.fn(async (url: string | URL) =>
String(url).endsWith("/chat/completions") ? respond() : new Response("", { status: 404 })));
const instance = await OpenAICompatDriver.create({
instanceId: "compat", displayName: "Compat", enabled: true,
- config: OpenAICompatDriver.decodeConfig({ url: "https://api.example.com/v1", apiKeyEnv: "K", model: "m" }),
+ config: OpenAICompatDriver.decodeConfig({ url: apiUrl, apiKeyEnv: "K", model: "m" }),
environment: { K: "secret" },
});
const events: RuntimeEvent[] = [];
@@ -1048,6 +1049,48 @@ describe("createOpenAIChatRuntime transient retries", () => {
await instance.dispose();
});
+ it("retries a 409 from api.openai.com, then answers", async () => {
+ let requests = 0;
+ const conflict = () => new Response(JSON.stringify({ error: { message: "conflict with the current resource state" } }), { status: 409 });
+ const events = await runRetryTurn(() => ++requests === 1 ? conflict() : answer(), "https://api.openai.com/v1");
+ expect(requests).toBe(2);
+ expect(events.find((event) => event.type === "turn.retrying")).toMatchObject({ attempt: 1, reason: "server_error" });
+ expect(events.find((event) => event.type === "item.completed")).toMatchObject({ text: "Hello!" });
+ expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: true });
+ }, 20_000);
+
+ it("does not retry a 429 when the caller opts out", async () => {
+ let requests = 0;
+ vi.stubGlobal("fetch", vi.fn(async (url: string | URL) =>
+ String(url).endsWith("/chat/completions")
+ ? (requests++, rateLimited())
+ : new Response("", { status: 404 })));
+ const runtime = createOpenAIChatRuntime({
+ input: { instanceId: "runtime", displayName: "Runtime", environment: {}, enabled: true, config: {} },
+ driverKind: "test",
+ apiKey: "secret",
+ apiUrl: "https://api.example.com/v1",
+ models: () => ({ default: "m", options: [{ id: "m", label: "m" }] }),
+ requestBody: (model, messages, stream) => ({ model, messages, stream }),
+ httpErrorLabel: "Test",
+ missingKeyError: "missing key",
+ unavailableReason: "missing key",
+ timeoutMs: 10_000,
+ noRetry: true,
+ nativeLog: { source: "test", outgoing: () => ({}), incoming: () => ({}) },
+ });
+ const events: RuntimeEvent[] = [];
+ runtime.adapter.onEvent((event) => events.push(event));
+ await runtime.adapter.sendTurn({ threadId: "thread", text: "hi" });
+ await vi.waitFor(() => {
+ if (!events.some((event) => event.type === "turn.completed")) throw new Error("turn still running");
+ }, { timeout: 10_000 });
+ await runtime.dispose();
+ expect(requests).toBe(1);
+ expect(events.filter((event) => event.type === "turn.retrying")).toHaveLength(0);
+ expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: false });
+ }, 20_000);
+
it("retries a 429 from an endpoint that omits retryScale, then answers", async () => {
let requests = 0;
const events = await runRetryTurn(() => ++requests === 1 ? rateLimited() : answer());
diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.ts
index 7d3f795f61..38a4448244 100644
--- a/server/drivers/openai-chat.ts
+++ b/server/drivers/openai-chat.ts
@@ -24,7 +24,7 @@ import { ChatProtocolError, ChatReasoningDetails, ChatToolCalls, object, type Ch
import { completionError, httpErrorDetail, refusedToolCall, refusedToolCallFailure, rejectsReasoningReplay, rejectsToolsParameter, RejectedToolCallError, UnsupportedChatToolsError, UnsupportedReasoningReplayError, type ProviderBody } from "./openai-chat-refusals.ts";
import { ChatRepeatGuard } from "./chat-repeat-guard.ts";
import { TextCallHoldback, textToolCalls } from "./chat-text-tool-calls.ts";
-import { createModelRoutes, ModelRouteRefused, noRouteLeft, readResponsesStream, responsesRequest, routeRefusal, type ModelRoute, type ResponseItem } from "./openai-responses.ts";
+import { createModelRoutes, isOpenAIAddress, ModelRouteRefused, noRouteLeft, readResponsesStream, responsesRequest, routeRefusal, type ModelRoute, type ResponseItem } from "./openai-responses.ts";
import { appendNative } from "./native.ts";
import { classifyError, computeBackoff, interruptibleDelay, RETRY_MAX_ATTEMPTS } from "./retry.ts";
import { plainFailure } from "./engine-errors.ts";
@@ -113,6 +113,8 @@ interface RuntimeOptions<Config> {
includeUsageInCompleted?: boolean;
noBodyError?: string;
retryScale?: number;
+ /** A caller that must not resend a turn after an ambiguous failure: no retry even for transient errors. */
+ noRetry?: boolean;
tools?: boolean;
computerUse?: boolean;
/** A text-only model keeps the computer and browser tools but never receives a screenshot or attachment. */
@@ -672,7 +674,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
break;
} catch (value) {
const error = asError(value);
- const verdict = classifyError(error);
+ const verdict = classifyError(error, { openAi: isOpenAIAddress(options.apiUrl) });
// A provider refuses a request with too many tools before running anything: learn its limit and list fewer.
const refit = streamed || seenCalls.size || abort.signal.aborted ? undefined : await refitChatTools(tools, error, chatToolLimitKey(options.apiUrl, model), [ASK_USER_TOOL_DEFINITION]);
if (refit) {
@@ -716,7 +718,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
}
// Once a call has been handled, never replay it through a turn retry.
if (abort.signal.aborted || streamed || seenCalls.size ||
- error instanceof ChatProtocolError || error instanceof RuntimeNoticeError || !verdict.transient || attempt >= RETRY_MAX_ATTEMPTS - 1) throw error;
+ error instanceof ChatProtocolError || error instanceof RuntimeNoticeError || !verdict.transient || options.noRetry || attempt >= RETRY_MAX_ATTEMPTS - 1) throw error;
const delayMs = computeBackoff(attempt++);
emit({ ...base(turn.threadId, turnId), type: "turn.retrying", attempt, delayMs, reason: verdict.reason });
await interruptibleDelay(delayMs * (options.retryScale ?? 1), abort.signal).promise;
diff --git a/server/drivers/retry.ts b/server/drivers/retry.ts
index f28a329008..de1a860bd0 100644
--- a/server/drivers/retry.ts
+++ b/server/drivers/retry.ts
@@ -94,25 +94,28 @@ const messageOf = (err: FailureInput): string => {
/** The three status-carrying forms the drivers' errors use (the STATUS pattern in engine-errors.ts):
* Grok Build's "(status 409 …)", the chat drivers' "xAI HTTP 409: …" and Claude Code's "API Error: 409 …".
- * A bare number is not a status. */
-const HTTP_STATUS = /\(status (\d{3})\b[^)]*\)|\bHTTP (\d{3})\b|^API Error:? (\d{3})\b/i;
+ * A bare number is not a status. The API Error form names the response's own status, so it matches wherever
+ * it appears: a status quoted inside the provider's message never wins over it. */
+const HTTP_STATUS = /\(status (\d{3})\b[^)]*\)|\bHTTP (\d{3})\b|\bAPI Error:? (\d{3})\b/i;
/** A failure line that names its HTTP status is decided by the status, not by numbers in its body: a 409
* whose body says "max 500 tokens" is a request the provider will refuse again, not a server failure.
* 429 stays a rate limit and 408 stays a timeout; 5xx stays with the body patterns (so 529 still reads
- * as overloaded). Any other 4xx is terminal. */
-function httpStatusVerdict(text: string): ErrorClassification | undefined {
+ * as overloaded). Any other 4xx is terminal, except a 409 from OpenAI: its SDK retries one by default,
+ * so it reads as a server error when the caller says the endpoint is OpenAI's. */
+function httpStatusVerdict(text: string, provider: { openAi?: boolean }): ErrorClassification | undefined {
const match = HTTP_STATUS.exec(text);
const status = Number(match?.[1] ?? match?.[2] ?? match?.[3]);
if (status === 429) return { transient: true, reason: "rate_limited" };
if (status === 408) return { transient: true, reason: "timeout" };
+ if (status === 409 && provider.openAi) return { transient: true, reason: "server_error" };
if (status >= 400 && status < 500) return { transient: false, reason: "invalid_request" };
return undefined;
}
/** A nonzero exit with no error text is terminal (`terminal_exit`): the CLI already reported its own
* failure. A signal kill (negative code) is never retried. */
-export function classifyError(err: FailureInput): ErrorClassification {
+export function classifyError(err: FailureInput, provider: { openAi?: boolean } = {}): ErrorClassification {
const text = messageOf(err);
// A surrounding HTTP 5xx/429 must not replay a provider safety block.
if (isProviderSafetyBlock(text)) return { transient: false, reason: "provider_safety" };
@@ -122,7 +125,7 @@ export function classifyError(err: FailureInput): ErrorClassification {
for (const { pattern, reason } of TERMINAL_PATTERNS) {
if (pattern.test(text)) return { transient: false, reason };
}
- const statusVerdict = httpStatusVerdict(text);
+ const statusVerdict = httpStatusVerdict(text, provider);
if (statusVerdict) return statusVerdict;
for (const { pattern, reason } of TRANSIENT_PATTERNS) {
if (pattern.test(text)) return { transient: true, reason };
@@ -132,7 +135,7 @@ export function classifyError(err: FailureInput): ErrorClassification {
for (const { pattern, reason } of TERMINAL_PATTERNS) {
if (pattern.test(text)) return { transient: false, reason };
}
- const statusVerdict = httpStatusVerdict(text);
+ const statusVerdict = httpStatusVerdict(text, provider);
if (statusVerdict) return statusVerdict;
for (const { pattern, reason } of TRANSIENT_PATTERNS) {
if (pattern.test(text)) return { transient: true, reason };