Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(acp): read a short 429 in an error reply as a rate limit, not a usage limit
plotarmordev54f960e46126
diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 8fa105823c..7bf3a695df 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -905,12 +905,6 @@ and the person hears it once for that stretch of the limit, as a notification:"Codex reached its limit until 14:00, so Kai is using Claude meanwhile." Withno AI to carry on, it says the bot waits instead. Nobody is asked.-An engine that posts the provider's raw error as its whole reply instead of-failing the turn (omp's ACP mode sends `429 {"type":"error",…} retry-after-ms=…`-that way) has that turn count as failed, not as a reply: the person reads it-in plain words, and a 429 that names its wait is a usage limit held until-then. A reply that only quotes such an error among other words stays a reply.-- **Which AI.** For one model's own limit, the same AI's default model first;then the backups chosen for the bot or in Automatic recovery; then the AI anew bot would get. Only an AI that can run a turn now (installed, signed in,@@ -933,6 +927,14 @@ then. A reply that only quotes such an error among other words stays a reply.a sleep the Cloud was stopped for keeps them. A conversation that moved goesback once its AI's limit has reset, with one line saying so.+An engine that posts the provider's raw error as its whole reply instead of+failing the turn (omp's ACP mode sends `429 {"type":"error",…} retry-after-ms=…`+that way) has that turn count as failed, not as a reply, and the person reads+it in plain words. It is a usage limit when its words say so, or when it is a+429 whose wait runs past two minutes, and is then held until that wait ends;+a shorter wait is a rate limit to try again after. A reply that only quotes+such an error among other words stays a reply.+This is on by default. Start the server with `OMB_QUOTA_SWITCH=0` to switch itoff: then only the backups Automatic recovery names take over, and thenotification says the bot waits. Any other value, or none, leaves it on. Itdiff --git a/scripts/testing/file-size-ratchet.test.ts b/scripts/testing/file-size-ratchet.test.tsindex 8cc0a4e511..b53526368b 100644--- a/scripts/testing/file-size-ratchet.test.ts+++ b/scripts/testing/file-size-ratchet.test.ts@@ -22,7 +22,7 @@ const LINES: Record<string, number> = {"server/store.ts": 2323,"src/components/Sidebar.tsx": 1745,"server/drivers/claude.ts": 2122,- "server/drivers/acp/core.ts": 1755,+ "server/drivers/acp/core.ts": 1744,"server/drivers/codex.ts": 1813,"server/routines.ts": 1570,"src/components/ComputerPanel.tsx": 1821,diff --git a/server/drivers/acp/quiet-status.ts b/server/drivers/acp/quiet-status.tsindex 6d84f6e90b..df97f84b77 100644--- a/server/drivers/acp/quiet-status.ts+++ b/server/drivers/acp/quiet-status.ts@@ -318,6 +318,10 @@ export const LIMIT_WORDS = /\b429\b|rate.?limit|too many requests|usage limit|quexport const DEFAULT_LIMIT_QUIET_MS = 2 * 60_000;export const limitQuietMs = (): number => knob("OMB_ACP_LIMIT_QUIET_MS", DEFAULT_LIMIT_QUIET_MS);+/** A 429 whose wait is longer than any engine retries on its own is a usage limit, not a short rate limit. */+export const usageLimitWait = (status: number | null | undefined, waitMs: number | null | undefined): boolean =>+ status === 429 && (waitMs ?? 0) > limitQuietMs();+/** No open request, no CPU and nothing logged, this long: the engine is stuck, and the turn is stopped* (OMB_ACP_NO_SIGNS_STOP_MS overrides). */export const DEFAULT_NO_SIGNS_STOP_MS = 5 * 60_000;@@ -327,7 +331,7 @@ export const noSignsStopMs = (): number => knob("OMB_ACP_NO_SIGNS_STOP_MS", DEFAexport function waitingOutLimit(signal: LogSignal | null): boolean {if (!signal) return false;if (signal.kind === "provider-error") return LIMIT_WORDS.test(signal.message);- return signal.kind === "retry" && signal.status === 429 && (signal.delayMs ?? 0) > limitQuietMs();+ return signal.kind === "retry" && usageLimitWait(signal.status, signal.delayMs);}/** A quiet turn after it is classified: no sign of life reads as "between requests" until `stuckAfterMs`, and the turndiff --git a/server/drivers/acp/turn-state.test.ts b/server/drivers/acp/turn-state.test.tsnew file mode 100644index 0000000000..4ab8219eb0--- /dev/null+++ b/server/drivers/acp/turn-state.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from "vitest";++import { endTurn, type AcpTurn } from "./turn-state.ts";++const ERROR_BODY = '403 {"type":"error","error":{"type":"permission_error","message":"OAuth authentication is currently not allowed for this organization."}}';++/** A turn whose buffered text is `text`, flushed as core.ts does: a non-blank text becomes a reply. */+function turnWith(text: string, state: { stopped?: boolean; replied?: string } = {}) {+ const replies: string[] = [];+ const current = {+ state: { text: state.replied ?? "", stopped: false, producedItem: false, repliedText: false },+ flushAssistantText() {+ const said = current.state.text;+ current.state.text = "";+ if (!said.trim()) return;+ current.state.producedItem = true;+ current.state.repliedText = true;+ replies.push(said);+ },+ };+ if (state.replied) current.flushAssistantText();+ current.state.text = text;+ current.state.stopped = state.stopped ?? false;+ return { current: current as unknown as AcpTurn, replies };+}++describe("endTurn on a reply that is a provider's error body", () => {+ it("after the person's Stop, ends the turn as stopped and keeps what was said", () => {+ const { current, replies } = turnWith(ERROR_BODY, { stopped: true });+ expect(endTurn(current, true, null, "omp")).toEqual({ ok: true, stopReason: "cancelled" });+ expect(replies).toEqual([ERROR_BODY]);+ });++ it("keeps the body a reply when the turn already replied in words before it", () => {+ const { current, replies } = turnWith(ERROR_BODY, { replied: "Let me check the deploy." });+ expect(endTurn(current, true, null, "omp")).toEqual({ ok: true, stopReason: null });+ expect(replies).toEqual(["Let me check the deploy.", ERROR_BODY]);+ });+});diff --git a/server/drivers/acp/turn-state.ts b/server/drivers/acp/turn-state.tsindex 4a2df9413e..a49461819e 100644--- a/server/drivers/acp/turn-state.ts+++ b/server/drivers/acp/turn-state.ts@@ -84,8 +84,7 @@ export interface AcpTurnEnd {export function endTurn(current: AcpTurn, ok: boolean, stopReason: string | null, ai: string): AcpTurnEnd {const ended = ok && stopReason === null;const errorReply = ended && !current.state.stopped && !current.state.repliedText ? errorReplyFailure(ai, current.state.text) : null;- if (errorReply) current.state.text = "";- current.flushAssistantText();+ if (!errorReply) current.flushAssistantText();if (ended && current.state.stopped) return { ok, stopReason: "cancelled" };if (errorReply) {const { stopReason: failed, ...error } = errorReply;diff --git a/server/drivers/engine-errors.test.ts b/server/drivers/engine-errors.test.tsindex 596a20d47b..be5cbc703e 100644--- a/server/drivers/engine-errors.test.ts+++ b/server/drivers/engine-errors.test.ts@@ -130,6 +130,30 @@ describe("errorReplyFailure", () => {.toEqual({ message: "omp is overloaded right now (HTTP 529). This is usually temporary, so try again in a few minutes.", stopReason: "rpc_error" });});+ it("keeps a 429 whose wait an engine retries on its own a rate limit, and reads a longer one as a usage limit", () => {+ const perMinute = anthropic(429, "rate_limit_error", "This request would exceed your organization's rate limit of 30,000 input tokens per minute.");+ const rateLimit = { message: `omp hit a rate limit (HTTP 429; omp says: "This request would exceed your organization's rate limit of 30,000 input tokens per minute"). Wait a minute, then run it again.`, stopReason: "rpc_error" };+ expect(errorReplyFailure("omp", `${perMinute} retry-after-ms=20000`, NOW)).toEqual(rateLimit);+ expect(errorReplyFailure("omp", `${perMinute} retry-after-ms=120000`, NOW)).toEqual(rateLimit);+ expect(errorReplyFailure("omp", `${perMinute} retry-after-ms=120001`, NOW)).toMatchObject({ stopReason: "quota", limit: "engine", limitResetsAt: NOW + 120_001 });+ });++ it("never reads another status's wait as a usage limit", () => {+ expect(errorReplyFailure("omp", `${anthropic(529, "overloaded_error", "Overloaded")} retry-after-ms=300000`, NOW))+ .toEqual({ message: "omp is overloaded right now (HTTP 529). This is usually temporary, so try again in a few minutes.", stopReason: "rpc_error" });+ });++ it("asks for the person's setup on an account out of credits, as the same failure thrown does, whatever its wait", () => {+ const outOfCredits = {+ message: 'Your omp account is out of credits (omp says: "Your credit balance is too low to access the Anthropic API"). Add credits with omp, then run it again.',+ stopReason: "auth_required",+ setup: true,+ };+ expect(errorReplyFailure("omp", anthropic(402, "billing_error", "Your credit balance is too low to access the Anthropic API."), NOW)).toEqual(outOfCredits);+ expect(errorReplyFailure("omp", `${anthropic(429, "billing_error", "Your credit balance is too low to access the Anthropic API.")} retry-after-ms=300000`, NOW))+ .toEqual(outOfCredits);+ });+it("leaves any other text a reply: an error quoted in words, a success status, a body that is no error", () => {for (const text of [`Here is what came back: ${anthropic(403, "permission_error", "OAuth authentication is currently not allowed for this organization.")}`,diff --git a/server/drivers/engine-errors.ts b/server/drivers/engine-errors.tsindex abbd6d6800..b4cac81b24 100644--- a/server/drivers/engine-errors.ts+++ b/server/drivers/engine-errors.ts@@ -5,6 +5,7 @@ import { redactSecretsInText } from "../redact.ts";import { hostTimeZone } from "../turn-clock.ts";import { toolCountLimitFromError } from "../tool-count-limit.ts";import { USAGE_LIMIT } from "./retry.ts";+import { usageLimitWait } from "./acp/quiet-status.ts";export type EngineFailureKind = "credits" | "usage_limit" | "rate_limit" | "overloaded" | "server" | "tool_schema" | "tool_count" | "refused";@@ -138,23 +139,27 @@ function isErrorBody(body: string): boolean {export interface ErrorReplyFailure {message: string;- stopReason: "quota" | "rpc_error";+ stopReason: "quota" | "auth_required" | "rpc_error";+ setup?: true;limit?: "engine";limitResetsAt?: number;}-/** A reply that is only a provider's error body, as the failed turn it is; null for any other text. A 429 that names- * its wait is a usage limit until then. */+/** A reply that is only a provider's error body, as the failed turn it is; null for any other text. It reads by its+ * words, as the same failure thrown would, and an account out of credits needs the person's setup. A 429 whose wait is+ * longer than an engine retries on its own is a usage limit too, and the wait names its reset. */export function errorReplyFailure(provider: string, text: string, now = Date.now(), timeZone?: string): ErrorReplyFailure | null {const match = ERROR_REPLY.exec(text.trim());- if (!match || !isErrorBody(match[2]!)) return null;+ const body = match?.[2];+ if (!match || !body || !isErrorBody(body)) return null;const status = Number(match[1]);- const body = match[2]!;- const retryAfterMs = Number(match[3] ?? 0);- const resetsAt = status === 429 && retryAfterMs > 0 ? now + retryAfterMs : undefined;- const kind = resetsAt ? "usage_limit" : engineFailureKind(body, status);+ const waitMs = Number(match[3] ?? 0);+ const said = engineFailureKind(body, status);+ const kind = said !== "credits" && usageLimitWait(status, waitMs) ? "usage_limit" : said;+ const resetsAt = kind === "usage_limit" && waitMs > 0 ? now + waitMs : undefined;const message = engineFailureMessage(provider, body, { kind, status, resetsAt, timeZone })!;- if (kind !== "usage_limit") return { message, stopReason: kind === "credits" ? "quota" : "rpc_error" };+ if (kind === "credits") return { message, stopReason: "auth_required", setup: true };+ if (kind !== "usage_limit") return { message, stopReason: "rpc_error" };return { message, stopReason: "quota", limit: "engine", ...(resetsAt ? { limitResetsAt: resetsAt } : {}) };}