Skip to content

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

fix(acp): fail a turn whose whole reply is a provider error body

plotarmordeve0964ccbcf2c
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 6f10ba32df..8fa105823c 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -905,6 +905,12 @@ 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." With
no 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 a
new bot would get. Only an AI that can run a turn now (installed, signed in,
diff --git a/server/drivers/acp/acp.test.ts b/server/drivers/acp/acp.test.ts
index ce3bad2d6c..f9ad9f74e6 100644
--- a/server/drivers/acp/acp.test.ts
+++ b/server/drivers/acp/acp.test.ts
@@ -11,6 +11,7 @@ import type { ProviderInstance } from "../../contracts.ts";
import { TurnNotStartedError } from "../../contracts.ts";
import { recordEvents, type EventRecorder } from "../../testing/events.ts";
import { promptSplitFingerprints, writePromptSplitReceipt } from "../prompt-split.ts";
+import { classifyError } from "../retry.ts";
import { createAcpDriver, skipSubscriptionAuthForLocalInject, type AcpSupport } from "./core.ts";
import { DEFAULT_ACP_PROMPT_IDLE_MS } from "./quiet-status.ts";
import { GrokAgentDriver, grokAcceptsUnadvertisedImages } from "./grok.ts";
@@ -247,6 +248,7 @@ describe("ACP turns (fake CLI)", () => {
delete process.env.FAKE_ACP_ASK_TIMING;
delete process.env.FAKE_ACP_HOLD_ON_CANCELLED;
delete process.env.FAKE_ACP_CANCEL_STOP_REASON;
+ delete process.env.FAKE_ACP_TEXT_REPLY;
delete process.env.XAI_API_KEY;
delete process.env.OPENCODE_API_KEY;
delete process.env.CLINE_API_KEY;
@@ -2227,6 +2229,56 @@ describe("ACP turns (fake CLI)", () => {
expect(message).not.toContain("grokAgent");
});
+ // omp 18.12's ACP mode sends a provider's refusal as the reply's text and ends the turn with end_turn.
+ describe("a reply that is only a provider's error body", () => {
+ const OAUTH_REFUSED = '403 {"type":"error","error":{"type":"permission_error","message":"OAuth authentication is currently not allowed for this organization.","details":{"error_code":"oauth_not_allowed_for_organization"}},"request_id":"req_011CgY35mSFzqEa1NBU5nq8i"}';
+ const WEEKLY_LIMIT = '429 {"type":"error","error":{"type":"rate_limit_error","code":"1310","message":"[1310][Weekly/Monthly Limit Exhausted. Your limit will reset at 2026-10-23 09:13:38][20261022010620e41a1d021c2d4ce4]"},"request_id":"20261022010620e41a1d021c2d4ce4"} retry-after-ms=115636000';
+ const turn = async (threadId: string, reply: string) => {
+ process.env.FAKE_ACP_TEXT_REPLY = reply;
+ await create(GrokAgentDriver);
+ await instance.adapter.sendTurn({ threadId, text: "go" });
+ const done = await recorder.until((e) => e.type === "turn.completed");
+ const replies = recorder.events.filter((e) => e.type === "item.completed" && e.itemType === "assistant_text");
+ const errors = recorder.events.flatMap((e) => e.type === "runtime.error" ? [e] : []);
+ return { done, replies, errors };
+ };
+
+ it("fails the turn on a 403 and says the refusal in plain words, never the JSON", async () => {
+ const { done, replies, errors } = await turn("t-error-403", OAUTH_REFUSED);
+ expect(done).toMatchObject({ ok: false, stopReason: "rpc_error" });
+ expect(replies).toEqual([]);
+ expect(errors).toEqual([expect.objectContaining({
+ message: 'Grok stopped with an error (HTTP 403; Grok says: "OAuth authentication is currently not allowed for this organization").',
+ })]);
+ expect(errors[0]).not.toHaveProperty("limit");
+ expect(classifyError({ text: errors[0]!.message }).reason).toBe("auth");
+ });
+
+ it("fails the turn on a 429 that names its wait as a usage limit held until then", async () => {
+ const before = Date.now();
+ const { done, replies, errors } = await turn("t-error-429", WEEKLY_LIMIT);
+ const after = Date.now();
+ expect(done).toMatchObject({ ok: false, stopReason: "quota" });
+ expect(replies).toEqual([]);
+ expect(errors).toHaveLength(1);
+ const error = errors[0]!;
+ expect(error.limit).toBe("engine");
+ expect(error.limitResetsAt).toBeGreaterThanOrEqual(before + 115_636_000);
+ expect(error.limitResetsAt).toBeLessThanOrEqual(after + 115_636_000);
+ expect(error.message).toMatch(/^This Grok account has reached its usage limit \(Grok says: "\[1310\]\[Weekly\/Monthly Limit Exhausted"\), which resets .+\. Until then, switch this bot to another AI\.$/);
+ expect(error.message).not.toMatch(/rate_limit_error|retry-after-ms|request_id/);
+ expect(classifyError({ text: error.message }).reason).toBe("quota");
+ });
+
+ it("keeps a reply that quotes such an error among its own words", async () => {
+ const quoted = `The deploy failed with this response:\n\n${OAUTH_REFUSED}\n\nI'll retry with the API key.`;
+ const { done, replies, errors } = await turn("t-error-quoted", quoted);
+ expect(done).toMatchObject({ ok: true, stopReason: null });
+ expect(replies).toEqual([expect.objectContaining({ text: quoted })]);
+ expect(errors).toEqual([]);
+ });
+ });
+
it("names the AI, never its internal id, when it exits before answering", async () => {
await create(GrokAgentDriver, "exit-early");
await instance.adapter.sendTurn({ threadId: "t-exit-name", text: "go" });
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.ts
index b3b6c40077..175247c7fa 100644
--- a/server/drivers/acp/core.ts
+++ b/server/drivers/acp/core.ts
@@ -58,7 +58,7 @@ import { openQuestionRequest, questionRequestFor, type AcpQuestionRequest } from
import { commandSummary, toolDetailPreview } from "../../tool-summary.ts";
import { acpToolEndEvents } from "./tool-items.ts";
import { AcpHost } from "./host.ts";
-import { trackRunningTool, type AcpAskFinish, type AcpSession, type AcpTurn } from "./turn-state.ts";
+import { endTurn, trackRunningTool, type AcpAskFinish, type AcpSession, type AcpTurn } from "./turn-state.ts";
import { recoveryPromptFor } from "../../resume-recovery.ts";
import { engineIdleMs, sessionIdlePolicy } from "../session-idle.ts";
import { classifyError } from "../retry.ts";
@@ -606,21 +606,9 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
// Detach before the final events: a listener may start the next turn synchronously.
session.current = null;
active.delete(threadId);
- current.flushAssistantText();
- let finalOk = ok;
- let finalStopReason = stopReason;
- // A Stop the agent answers with end_turn (OpenCode does) is the person's stop. Otherwise `end_turn` with
- // nothing to show is a lost turn: a provider may cut a reasoning-only stream and still answer end_turn.
- if (finalOk && finalStopReason === null && current.state.stopped) finalStopReason = "cancelled";
- else if (finalOk && finalStopReason === null && !current.state.producedItem) {
- finalOk = false; finalStopReason = "empty_turn";
- emit({
- ...base(threadId, current.turnId),
- type: "runtime.error",
- message: `${support.displayName} finished without replying.`,
- });
- }
- emit({ ...base(threadId, current.turnId), type: "turn.completed", ok: finalOk, stopReason: finalStopReason, cost: null });
+ const end = endTurn(current, ok, stopReason, support.displayName);
+ if (end.error) emit({ ...base(threadId, current.turnId), type: "runtime.error", ...end.error });
+ emit({ ...base(threadId, current.turnId), type: "turn.completed", ok: end.ok, stopReason: end.stopReason, cost: null });
if (session.child.exitCode === null && !session.closing && !session.dead) {
armIdle(threadId);
recycleWhenIdle(session.host);
@@ -1153,7 +1141,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
): Promise<any> =>
session.acp.request(method, params, timeoutMs, receive, idleMs, idleMessage);
- const state: AcpTurn["state"] = { settled: false, promptSent: false, text: "", textMessageId: null, producedItem: false, startupActivity: false, stopped: false, usagePeak: null, usageLast: null, usageCompacted: false, cancelling: false };
+ const state: AcpTurn["state"] = { settled: false, promptSent: false, text: "", textMessageId: null, producedItem: false, repliedText: false, startupActivity: false, stopped: false, usagePeak: null, usageLast: null, usageCompacted: false, cancelling: false };
let acknowledge = () => {};
let rejectStartup = (_error: TurnNotStartedError) => {};
const startupAck = turn.startupRecovery ? new Promise<{ turnId: string }>((resolve, reject) => {
@@ -1181,6 +1169,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
const text = stripLeakedSystemHarnessMessages(raw);
if (!text.trim()) return;
state.producedItem = true;
+ state.repliedText = true;
emit({ ...base(threadId, turnId), type: "item.completed", itemType: "assistant_text", text });
};
const current: AcpTurn = {
diff --git a/server/drivers/acp/turn-state.ts b/server/drivers/acp/turn-state.ts
index 128e1846ff..4a2df9413e 100644
--- a/server/drivers/acp/turn-state.ts
+++ b/server/drivers/acp/turn-state.ts
@@ -2,6 +2,7 @@
// sessions) and the turn running in it.
import type { RequestOutcome, SendTurnInput } from "../../contracts.ts";
import type { spawnCli } from "../../procs.ts";
+import { errorReplyFailure, type ErrorReplyFailure } from "../engine-errors.ts";
import type { AcpConfig } from "./core.ts";
import type { AcpHost, AcpLink } from "./host.ts";
@@ -18,7 +19,7 @@ export interface AcpTurn {
turnConfig: AcpConfig;
controlsHost: boolean;
state: {
- settled: boolean; promptSent: boolean; text: string; textMessageId: string | null; producedItem: boolean; startupActivity: boolean; stopped: boolean;
+ settled: boolean; promptSent: boolean; text: string; textMessageId: string | null; producedItem: boolean; repliedText: boolean; startupActivity: boolean; stopped: boolean;
usagePeak: number | null;
usageLast: number | null;
usageCompacted: boolean;
@@ -70,3 +71,26 @@ export function trackRunningTool(current: AcpTurn, update: { toolCallId?: unknow
if (status === "completed" || status === "failed") current.runningTools.delete(update.toolCallId);
else if (status === "pending" || status === "in_progress") current.runningTools.add(update.toolCallId);
}
+
+export interface AcpTurnEnd {
+ ok: boolean;
+ stopReason: string | null;
+ error?: Omit<ErrorReplyFailure, "stopReason">;
+}
+
+/** How a settling turn ends, once its last text is out. A Stop the agent answers with end_turn (OpenCode does) is the
+ * person's stop. A reply that is only a provider's error body fails the turn in plain words. Otherwise `end_turn` with
+ * nothing to show is a lost turn: a provider may cut a reasoning-only stream and still answer end_turn. */
+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 (ended && current.state.stopped) return { ok, stopReason: "cancelled" };
+ if (errorReply) {
+ const { stopReason: failed, ...error } = errorReply;
+ return { ok: false, stopReason: failed, error };
+ }
+ if (ended && !current.state.producedItem) return { ok: false, stopReason: "empty_turn", error: { message: `${ai} finished without replying.` } };
+ return { ok, stopReason };
+}
diff --git a/server/drivers/claude-limits.ts b/server/drivers/claude-limits.ts
index 8c6c4e09b7..a4e9e82b83 100644
--- a/server/drivers/claude-limits.ts
+++ b/server/drivers/claude-limits.ts
@@ -1,5 +1,5 @@
import { hostTimeZone } from "../turn-clock.ts";
-import { engineFailureMessage, type EngineFailureKind } from "./engine-errors.ts";
+import { engineFailureMessage, limitResetTime, type EngineFailureKind } from "./engine-errors.ts";
import { USAGE_LIMIT } from "./retry.ts";
export interface ClaudeLimit {
@@ -73,13 +73,7 @@ export function claudeLimitMessage(limit: ClaudeLimit | null, said?: string, now
const name = limit?.window && Object.hasOwn(CLAUDE_LIMIT_NAMES, limit.window) ? CLAUDE_LIMIT_NAMES[limit.window] : "usage limit";
const meanwhile = modelWindow(limit?.window) ? "choose another model for this bot" : "switch this bot to another AI or Claude account";
if (limit?.resetsAt && limit.resetsAt * 1000 > now) {
- let resets: string;
- try {
- resets = `${new Date(limit.resetsAt * 1000).toLocaleString("en-US", { month: "short", day: "numeric", hour: "numeric", minute: "2-digit", timeZone })} (${timeZone})`;
- } catch {
- resets = `${new Date(limit.resetsAt * 1000).toISOString().slice(0, 16).replace("T", " ")} UTC`;
- }
- return `This Claude account has reached its ${name}, which resets ${resets}. Until then, ${meanwhile}.`;
+ return `This Claude account has reached its ${name}, which resets ${limitResetTime(limit.resetsAt * 1000, timeZone)}. Until then, ${meanwhile}.`;
}
const words = said?.trim().replace(/[.\s]+$/, "");
return `This Claude account has reached its ${name}${words ? ` (Claude says: "${words}")` : ""}. For now, ${meanwhile}.`;
diff --git a/server/drivers/engine-errors.test.ts b/server/drivers/engine-errors.test.ts
index 6496d2abe6..596a20d47b 100644
--- a/server/drivers/engine-errors.test.ts
+++ b/server/drivers/engine-errors.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { engineFailureKind, engineFailureMessage, httpStatusOf, plainFailureMessage, providerReason, stopCause } from "./engine-errors.ts";
+import { engineFailureKind, engineFailureMessage, errorReplyFailure, httpStatusOf, plainFailureMessage, providerReason, stopCause } from "./engine-errors.ts";
import { classifyError } from "./retry.ts";
const reason = (text: string) => classifyError({ text }).reason;
@@ -105,6 +105,44 @@ describe("a provider refusing a tool's schema", () => {
});
});
+describe("errorReplyFailure", () => {
+ const NOW = Date.parse("2026-10-27T06:12:46Z");
+ const anthropic = (status: number, type: string, message: string) =>
+ `${status} {"type":"error","error":{"type":"${type}","message":"${message}"},"request_id":"req_011CgY35mSFzqEa1NBU5nq8i"}`;
+
+ it("names a usage limit and its reset from a 429's retry-after, in the zone given", () => {
+ const reply = `${anthropic(429, "rate_limit_error", "[1308][Usage limit reached for 5 hour. Your limit will reset at 2026-10-27 15:22:19][2026]")} retry-after-ms=4171000`;
+ expect(errorReplyFailure("omp", reply, NOW, "UTC")).toEqual({
+ message: 'This omp account has reached its usage limit (omp says: "[1308][Usage limit reached for 5 hour"), which resets Oct 27, 7:22 AM (UTC). Until then, switch this bot to another AI.',
+ stopReason: "quota",
+ limit: "engine",
+ limitResetsAt: NOW + 4_171_000,
+ });
+ });
+
+ it("reads a 429 without a wait by its words, and an OpenAI-style body too", () => {
+ const limit = errorReplyFailure("omp", anthropic(429, "rate_limit_error", "You've reached your 5-hour usage limit."), NOW);
+ expect(limit).toMatchObject({ stopReason: "quota", limit: "engine" });
+ expect(limit).not.toHaveProperty("limitResetsAt");
+ expect(errorReplyFailure("omp", '429 {"error":{"message":"Rate limit reached for requests","type":"requests","code":"rate_limit_exceeded"}}'))
+ .toEqual({ message: 'omp hit a rate limit (HTTP 429; omp says: "Rate limit reached for requests"). Wait a minute, then run it again.', stopReason: "rpc_error" });
+ expect(errorReplyFailure("omp", ' 529 {"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}\n'))
+ .toEqual({ message: "omp is overloaded right now (HTTP 529). This is usually temporary, so try again in a few minutes.", stopReason: "rpc_error" });
+ });
+
+ 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.")}`,
+ `${anthropic(403, "permission_error", "refused")} and then I stopped`,
+ '200 {"type":"error","error":{"type":"x","message":"y"}}',
+ '403 {"type":"message","content":[]}',
+ '403 {"error":"refused"}',
+ "403 {not json}",
+ `${anthropic(429, "rate_limit_error", "slow down")} retry-after-ms=soon`,
+ ]) expect(errorReplyFailure("omp", text), text).toBeNull();
+ });
+});
+
describe("stopCause", () => {
it("never lets a bare stop token stand alone as the cause, and keeps the token so its class still reads", () => {
for (const token of ["stop_sequence", "api_error", "rpc_error", "error"]) {
diff --git a/server/drivers/engine-errors.ts b/server/drivers/engine-errors.ts
index 80e0aa6dec..abbd6d6800 100644
--- a/server/drivers/engine-errors.ts
+++ b/server/drivers/engine-errors.ts
@@ -2,6 +2,7 @@
// overloaded or failing service, or any other HTTP refusal names the provider and keeps its own short reason. Each
// sentence keeps the words classifyError (retry.ts) reads, so retries, account switching and health codes are unchanged.
import { redactSecretsInText } from "../redact.ts";
+import { hostTimeZone } from "../turn-clock.ts";
import { toolCountLimitFromError } from "../tool-count-limit.ts";
import { USAGE_LIMIT } from "./retry.ts";
@@ -83,7 +84,7 @@ export function engineFailureKind(text: string, status = httpStatusOf(text)): En
export function engineFailureMessage(
provider: string,
text: string,
- { kind, status }: { kind?: EngineFailureKind | null; status?: number | null } = {},
+ { kind, status, resetsAt, timeZone }: { kind?: EngineFailureKind | null; status?: number | null; resetsAt?: number; timeZone?: string } = {},
): string | null {
const http = status === undefined ? httpStatusOf(text) : status;
const what = kind ?? engineFailureKind(text, http);
@@ -94,7 +95,9 @@ export function engineFailureMessage(
const code = http ? `HTTP ${http}` : null;
switch (what) {
case "credits": return `Your ${provider} account is out of credits${detail(says)}. Add credits with ${provider}, then run it again.`;
- case "usage_limit": return `This ${provider} account has reached its usage limit${detail(says)}. Wait for it to reset, or switch this bot to another AI.`;
+ case "usage_limit": return resetsAt
+ ? `This ${provider} account has reached its usage limit${detail(says)}, which resets ${limitResetTime(resetsAt, timeZone)}. Until then, switch this bot to another AI.`
+ : `This ${provider} account has reached its usage limit${detail(says)}. Wait for it to reset, or switch this bot to another AI.`;
case "rate_limit": return `${provider} hit a rate limit${detail(code, says)}. Wait a minute, then run it again.`;
case "overloaded": return `${provider} is overloaded right now${detail(code, says)}. This is usually temporary, so try again in a few minutes.`;
case "server": return `${provider} had a temporary server problem${detail(code, says)}. Try again in a few minutes.`;
@@ -110,6 +113,51 @@ export function engineFailureMessage(
}
}
+/** When a usage limit resets, in `timeZone` with its name, or in UTC when the zone is unknown. */
+export function limitResetTime(epochMs: number, timeZone = hostTimeZone()): string {
+ try {
+ return `${new Date(epochMs).toLocaleString("en-US", { month: "short", day: "numeric", hour: "numeric", minute: "2-digit", timeZone })} (${timeZone})`;
+ } catch {
+ return `${new Date(epochMs).toISOString().slice(0, 16).replace("T", " ")} UTC`;
+ }
+}
+
+/** A provider's HTTP error an engine posted as its whole reply instead of failing the turn (omp 18.12's ACP mode sends
+ * it as message text and ends with end_turn): the status, an Anthropic `{"type":"error",…}` or OpenAI `{"error":{…}}`
+ * body, and omp's ` retry-after-ms=<n>` when the provider named a wait. */
+const ERROR_REPLY = /^([45]\d\d) (\{[\s\S]*\})(?: retry-after-ms=(\d+))?$/;
+
+function isErrorBody(body: string): boolean {
+ try {
+ const value = JSON.parse(body);
+ return value?.type === "error" || (typeof value?.error === "object" && value.error !== null);
+ } catch {
+ return false;
+ }
+}
+
+export interface ErrorReplyFailure {
+ message: string;
+ stopReason: "quota" | "rpc_error";
+ 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. */
+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 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 message = engineFailureMessage(provider, body, { kind, status, resetsAt, timeZone })!;
+ if (kind !== "usage_limit") return { message, stopReason: kind === "credits" ? "quota" : "rpc_error" };
+ return { message, stopReason: "quota", limit: "engine", ...(resetsAt ? { limitResetsAt: resetsAt } : {}) };
+}
+
/** Only an out-of-credits failure or a refused tool schema or tool count in plain words; any other text stays as it is. */
export function plainFailureMessage(provider: string, text: string): string {
const kind = engineFailureKind(text);