Skip to content

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

fix(drivers): classify HTTP failures by status; never retry liveness notices

Saim Shafique4c4bfb982e8a
diff --git a/server/drivers/engine-errors.test.ts b/server/drivers/engine-errors.test.ts
index 59d887001f..d3beaabe51 100644
--- a/server/drivers/engine-errors.test.ts
+++ b/server/drivers/engine-errors.test.ts
@@ -271,3 +271,19 @@ describe("a model the engine has no route to", () => {
expect(classifyError({ text: "Internal error: OpenCode service failure (session/prompt)" }).reason).toBe("unknown");
});
});
+
+describe("classifyError reads an explicit HTTP status before body text", () => {
+ it.each([
+ ["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" }],
+ ["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" }],
+ ["HTTP 408: request timed out", { transient: true, reason: "timeout" }],
+ ["Upstream returned 401 Unauthorized", { transient: false, reason: "auth" }],
+ ["Upstream returned 402 Payment Required: exceeded your quota", { transient: false, reason: "quota" }],
+ ])("classifies %s", (message, expected) => {
+ expect(classifyError({ text: message })).toEqual(expected);
+ });
+});
diff --git a/server/drivers/openai-chat.test.ts b/server/drivers/openai-chat.test.ts
index b6c19bf1e4..a148129aa4 100644
--- a/server/drivers/openai-chat.test.ts
+++ b/server/drivers/openai-chat.test.ts
@@ -986,6 +986,68 @@ describe("createOpenAIChatRuntime transient retries", () => {
const rateLimited = () => new Response(JSON.stringify({ error: { message: "Rate limit reached", code: "rate_limit_exceeded" } }), { status: 429 });
const answer = () => sse('data: {"choices":[{"index":0,"finish_reason":"stop","delta":{"content":"Hello!"}}]}\n\ndata: [DONE]\n\n');
+ it("does not retry a turn the liveness notice stopped", async () => {
+ // A local server on port 503: the notice names its host, and the bare "503" in it must not
+ // read as a 5xx status. The completions POST hangs until the notice aborts it, like a frozen
+ // server; the /models probe fails so the watcher fires.
+ vi.stubEnv("OPENMAUS_OPENAI_COMPAT_PROBE_MS", "200");
+ let requests = 0;
+ try {
+ vi.stubGlobal("fetch", vi.fn(async (url: string | URL, init?: { signal?: AbortSignal }) => {
+ // The probe and the Ollama check fail at once, so neither waits out its timeout.
+ if (String(url).endsWith("/v1/models") || String(url).endsWith("/api/version")) throw new Error("fetch failed");
+ requests++;
+ return new Promise((_resolve, reject) => {
+ init?.signal?.addEventListener("abort", () => reject(init.signal!.reason ?? new DOMException("aborted", "AbortError")), { once: true });
+ });
+ }));
+ const instance = await OpenAICompatDriver.create({
+ instanceId: "compat-liveness", displayName: "Compat", enabled: true,
+ config: OpenAICompatDriver.decodeConfig({ url: "http://127.0.0.1:503/v1", apiKeyEnv: "K", model: "m" }),
+ environment: { K: "secret" },
+ });
+ const events: RuntimeEvent[] = [];
+ instance.adapter.onEvent((event) => events.push(event));
+ await instance.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 instance.dispose();
+ expect(requests).toBe(1);
+ expect(events.filter((event) => event.type === "turn.retrying")).toHaveLength(0);
+ expect(events.find((event) => event.type === "runtime.error")).toMatchObject({ message: expect.stringContaining("stopped answering") });
+ expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: false });
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ }, 20_000);
+
+ it("does not retry a 409 whose body only looks like a server failure", async () => {
+ let requests = 0;
+ vi.stubGlobal("fetch", vi.fn(async (url: string | URL) => {
+ // Creation fetches /models for the catalog; only the completions POST counts.
+ if (String(url).endsWith("/v1/models")) return new Response("", { status: 404 });
+ requests++;
+ return new Response(JSON.stringify({ error: { message: "max 500 tokens" } }), { status: 409, headers: { "content-type": "application/json" } });
+ }));
+ const instance = await OpenAICompatDriver.create({
+ instanceId: "compat-409", displayName: "Compat", enabled: true,
+ config: OpenAICompatDriver.decodeConfig({ url: "https://api.example.com/v1", apiKeyEnv: "K", model: "m" }),
+ environment: { K: "secret" },
+ });
+ const events: RuntimeEvent[] = [];
+ instance.adapter.onEvent((event) => events.push(event));
+ await instance.adapter.sendTurn({ threadId: "thread", text: "hi" });
+ await vi.waitFor(() => {
+ if (!events.some((event) => event.type === "turn.completed")) throw new Error("turn still running");
+ }, { timeout: 5_000 });
+ expect(requests).toBe(1);
+ expect(events.filter((event) => event.type === "turn.retrying")).toHaveLength(0);
+ expect(events.find((event) => event.type === "runtime.error")).toMatchObject({ message: expect.stringContaining("HTTP 409") });
+ expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: false });
+ await instance.dispose();
+ });
+
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 5cbdf3cf99..7d3f795f61 100644
--- a/server/drivers/openai-chat.ts
+++ b/server/drivers/openai-chat.ts
@@ -716,7 +716,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 || !verdict.transient || attempt >= RETRY_MAX_ATTEMPTS - 1) throw error;
+ error instanceof ChatProtocolError || error instanceof RuntimeNoticeError || !verdict.transient || 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/openrouter-free.test.ts b/server/drivers/openrouter-free.test.ts
index f45f9d2aac..bd8c13aa2b 100644
--- a/server/drivers/openrouter-free.test.ts
+++ b/server/drivers/openrouter-free.test.ts
@@ -288,6 +288,8 @@ describe("OpenRouter failures in plain words", () => {
await recorder.until((event) => event.type === "turn.completed" && event.threadId === "free");
expect(errorFor("paid")).toBe(OPENROUTER_FAILURES.credits);
expect(errorFor("free")).toBe(OPENROUTER_FAILURES.freeLimit);
+ // The 402 is terminal, so the paid model is sent once; the free turn's 429 is a transient
+ // rate limit, so the free model is retried up to the gate's three attempts.
expect(bodies.map((body) => body.model)).toEqual(["deepseek/deepseek-v4.1-flash-1017", PREFERRED, PREFERRED, PREFERRED]);
} finally {
recorder.stop();
diff --git a/server/drivers/retry.ts b/server/drivers/retry.ts
index 0cb5ae9e11..f28a329008 100644
--- a/server/drivers/retry.ts
+++ b/server/drivers/retry.ts
@@ -92,6 +92,24 @@ const messageOf = (err: FailureInput): string => {
return [err.stderr ?? "", ""].join(" ").trim();
};
+/** 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 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 {
+ 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 >= 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 {
@@ -104,6 +122,8 @@ 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);
+ if (statusVerdict) return statusVerdict;
for (const { pattern, reason } of TRANSIENT_PATTERNS) {
if (pattern.test(text)) return { transient: true, reason };
}
@@ -112,6 +132,8 @@ 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);
+ if (statusVerdict) return statusVerdict;
for (const { pattern, reason } of TRANSIENT_PATTERNS) {
if (pattern.test(text)) return { transient: true, reason };
}