Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(cursor): a model call Cursor reports as its reply fails the turn
Absterrg0b1beeb3486d4
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.tsindex 2f06ef5935..43f6926b45 100644--- a/server/drivers/acp/core.ts+++ b/server/drivers/acp/core.ts@@ -17,8 +17,7 @@ import { acpModelCatalog } from "./model-catalog.ts";import { decodeInjectId } from "../local-inject.ts";import { DeviceAuthController, deviceAuthInstanceSurface, type DeviceSignIn } from "../device-auth.ts";import { AcpBrowserAuth, acpBrowserAuthInstanceSurface, type AcpBrowserSignInSpec } from "./browser-auth.ts";-import { deletePromptSplitReceipt, promptHalves, readPromptSplitReceipt, splitSessionPrompt, writePromptSplitReceipt } from "../prompt-split.ts";-import type { PromptSplitReceipt } from "../prompt-split.ts";+import { commitPromptSplitReceipt, deletePromptSplitReceipt, promptHalves, readPromptSplitReceipt, splitSessionPrompt, type PendingPromptSplitReceipt } from "../prompt-split.ts";import { boxAudienceKey, describeSpawnFailure, execCli, killCliTree, sharedBoxScope, spawnCli } from "../../procs.ts"; import { stopEngineTree, stopEngineTrees } from "../../engine-stop.ts";import { runAcpOneShot } from "./background-text.ts"; import type { AcpBackgroundWork } from "./background-work.ts";import { acpCapabilities } from "./capabilities.ts"; import { readAcpMediaLinks } from "./media-links.ts";@@ -67,7 +66,7 @@ import { commandSummary, toolDetailPreview } from "../../tool-summary.ts";import { acpToolEndEvents } from "./tool-items.ts";import { AcpHost } from "./host.ts"; import { SignInRequests, type AcpDriverHooks } from "./driver-hooks.ts";import { exitBeforeResult } from "./exit-report.ts"; import { readNodeVersion } from "./node-version.ts";-import { endTurn, trackRunningTool, type AcpAskFinish, type AcpSession, type AcpTurn } from "./turn-state.ts";+import { dropFailedChunk, endTurn, replyFailureOf, trackRunningTool, type AcpAskFinish, type AcpSession, type AcpTurn } from "./turn-state.ts";import { recoveryPromptFor } from "../../resume-recovery.ts";import { noticeFailure } from "../../chat-notices.ts";import { armIdleClose, engineIdleMs, sessionIdlePolicy, stopIdleClose } from "../session-idle.ts";@@ -844,6 +843,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>&& isHermesReasoningReplay(delta, current.state.text)) break;current.state.textMessageId = messageId;current.state.text += delta;+ current.state.lastText = delta;const trimmed = current.state.text.trimStart();if (!trimmed.startsWith("<SYSTEM_MESSAGE") &&!trimmed.startsWith("The following is a <SYSTEM_MESSAGE") &&@@ -1081,7 +1081,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>): Promise<any> =>signIn.refused(session.host) ?? session.acp.request(method, params, timeoutMs, receive, idleMs, idleMessage);- 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 };+ 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, lastText: "", cancelling: false };let acknowledge = () => {};let rejectStartup = (_error: TurnNotStartedError) => {};const startupAck = turn.startupRecovery ? new Promise<{ turnId: string }>((resolve, reject) => {@@ -1155,7 +1155,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>session.current = current;(async () => {- let pendingSplitReceipt: { key: string; receipt: PromptSplitReceipt; previous: PromptSplitReceipt | null } | null = null;+ let pendingSplitReceipt: PendingPromptSplitReceipt | null = null;try {const handshake = async (): Promise<boolean> => {for (const child of retiring.get(threadId) ?? []) {@@ -1412,26 +1412,9 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>);const steersOut = current.steering?.promptAnswered();if (steersOut && !state.stopped) { current.flushAssistantText(); await steersOut; }- if (pendingSplitReceipt) {- // session/prompt resolving is the acceptance boundary: a rejected prompt leaves no receipt.- if (state.usageCompacted) {- deletePromptSplitReceipt(DRIVER_KIND, pendingSplitReceipt.key);- } else {- const previousLastUsed = typeof pendingSplitReceipt.previous?.lastUsed === "number"- ? pendingSplitReceipt.previous.lastUsed- : undefined;- const lastUsed = state.usageLast ?? previousLastUsed;- writePromptSplitReceipt(- DRIVER_KIND,- pendingSplitReceipt.key,- {- ...pendingSplitReceipt.receipt,- ...(lastUsed === undefined ? {} : { lastUsed }),- ...(state.usagePeak === null ? {} : { peakUsed: state.usagePeak }),- },- );- }- }+ const failure = replyFailureOf(current, support.replyFailure);+ // session/prompt resolving is the acceptance boundary: a rejected or reported-failed prompt leaves no receipt.+ if (pendingSplitReceipt && !failure) commitPromptSplitReceipt(DRIVER_KIND, pendingSplitReceipt, { compacted: state.usageCompacted, last: state.usageLast, peak: state.usagePeak });const answers = turnAnswers(support.steer, result, current.steering?.replies);if (current.steering?.failure !== undefined && !state.stopped) throw current.steering.failure;const runOf = (answer: unknown) => support.steer && "run" in support.steer ? support.steer.run?.(answer) : undefined;@@ -1443,6 +1426,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>}const final = answers.at(-1);const reason = final?.stopReason, reported = await promptOutcome?.(final); if (reported) throw reported;+ if (failure && reason === "end_turn") throw dropFailedChunk(current, failure);if (reason === "end_turn") settle(threadId, session, true, null);else if (reason === "cancelled" || state.stopped) settle(threadId, session, true, "cancelled");else {diff --git a/server/drivers/acp/cursor.test.ts b/server/drivers/acp/cursor.test.tsindex eb5c986e6b..1133af5895 100644--- a/server/drivers/acp/cursor.test.ts+++ b/server/drivers/acp/cursor.test.ts@@ -1,4 +1,5 @@-import { chmodSync, existsSync, mkdtempSync, readFileSync } from "node:fs";+import { randomUUID } from "node:crypto";+import { chmodSync, existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { dirname, join } from "node:path";import { fileURLToPath } from "node:url";@@ -8,10 +9,12 @@ import type { RuntimeEvent } from "../../contracts.ts";import { ensureDirs } from "../../config.ts";import { recordEvents } from "../../testing/events.ts";import { removeTempDir } from "../../testing/cleanup.ts";+import { classifyRoutineFailure } from "../../routine-recovery.ts";import {classifyCursorError,createCursorAgentDriver,cursorCatalogFromSession,+ cursorReplyFailure,CursorAgentDriver,decodeCursorAuthStatus,decodeCursorAuthText,@@ -133,6 +136,21 @@ describe("classifyCursorError", () => {});});+describe("cursorReplyFailure", () => {+ it("reads the chunk Cursor sends for a failed model call", () => {+ expect(cursorReplyFailure("\n\nError: RetriableError: [unavailable] HTTP 503")).toBe("[unavailable] HTTP 503");+ expect(cursorReplyFailure("\n\nError: NonRetriableError: model not available\n")).toBe("model not available");+ expect(cursorReplyFailure("\n\nError: [unauthenticated] Backend rejected authentication.")).toBe("[unauthenticated] Backend rejected authentication.");+ });++ it("leaves a chunk that carries the model's own words", () => {+ expect(cursorReplyFailure("The log ended with:\n\nError: RetriableError: [unavailable] HTTP 503")).toBeNull();+ expect(cursorReplyFailure("Error: RetriableError: [unavailable] HTTP 503")).toBeNull();+ expect(cursorReplyFailure("\n\nError: RetriableError: [unavailable] HTTP 503\n\nIt recovered.")).toBeNull();+ expect(cursorReplyFailure("\n\nError: ")).toBeNull();+ });+});+describe("CursorAgentDriver", () => {const scratchDirs: string[] = [];// The fake answers --version the way cursor-agent does: another answer is another program behind the CLI path.@@ -628,6 +646,101 @@ describe("CursorAgentDriver", () => {});});+ // cursor-agent 2026.10.22's session/prompt catches a failed model call, sends `\n\nError: ${String(error)}` as one+ // message chunk and still answers end_turn.+ describe("a failed model call Cursor sends as its last chunk", () => {+ const turn = async (threadId: string, last: string, before: string[] = []) => {+ ensureDirs();+ chmodSync(FAKE_CLI, 0o755);+ const scratch = mkdtempSync(join(tmpdir(), "omb-cursor-reply-failure-"));+ scratchDirs.push(scratch);+ process.env.FAKE_ACP_UPDATES_FILE = join(scratch, "updates.json");+ writeFileSync(process.env.FAKE_ACP_UPDATES_FILE, JSON.stringify(before.map((text) => ({+ update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } },+ }))));+ process.env.FAKE_ACP_TEXT_REPLY = last;+ const instance = await CursorAgentDriver.create({+ instanceId: "cursor-reply-failure", displayName: "Cursor", environment: {}, enabled: true, config: { cli: FAKE_CLI, fullAuto: false },+ });+ const recorder = recordEvents(instance.adapter);+ try {+ await instance.adapter.sendTurn({ threadId, text: "go" });+ const done = await recorder.until((e) => e.type === "turn.completed");+ const replies = recorder.events.flatMap((e) => e.type === "item.completed" && e.itemType === "assistant_text" ? [e.text] : []);+ const errors = recorder.events.flatMap((e) => e.type === "runtime.error" ? [e] : []);+ return { done, replies, errors };+ } finally {+ recorder.stop();+ await instance.dispose();+ delete process.env.FAKE_ACP_TEXT_REPLY;+ delete process.env.FAKE_ACP_UPDATES_FILE;+ }+ };++ it("fails the turn on a 503, so a routine run is retried as a temporary AI error", async () => {+ const { done, replies, errors } = await turn("t-cursor-503", "\n\nError: RetriableError: [unavailable] HTTP 503");+ expect(done).toMatchObject({ ok: false, stopReason: "rpc_error" });+ expect(replies).toEqual([]);+ expect(errors).toHaveLength(1);+ expect(errors[0]!.message).toMatch(/^Cursor had a temporary server problem \(HTTP 503/);+ expect(classifyRoutineFailure(errors[0]!.message, { stopReason: "rpc_error" })).toEqual({ kind: "retry", cause: "provider" });+ });++ it("fails the turn on a dropped stream and keeps what was said before it", async () => {+ const dropped = "Stream ended without turnEnded — connection likely dropped mid-stream";+ const { done, replies, errors } = await turn("t-cursor-dropped", `\n\nError: RetriableError: ${dropped}`, ["Checking the queue now."]);+ expect(done).toMatchObject({ ok: false, stopReason: "rpc_error" });+ expect(replies).toEqual(["Checking the queue now."]);+ expect(errors).toEqual([expect.objectContaining({ message: dropped })]);+ expect(classifyRoutineFailure(errors[0]!.message, { stopReason: "rpc_error" }).kind).toBe("retry");+ });++ it("asks for Cursor's sign-in when the backend rejected its authentication", async () => {+ const { done, errors } = await turn("t-cursor-unauthenticated", "\n\nError: [unauthenticated] Backend rejected authentication.");+ expect(done).toMatchObject({ ok: false, stopReason: "auth_required" });+ expect(errors).toEqual([expect.objectContaining({ setup: true })]);+ });++ it("sends the stable instructions again on the next turn, as the failed call may not be in Cursor's history", async () => {+ ensureDirs();+ chmodSync(FAKE_CLI, 0o755);+ const scratch = mkdtempSync(join(tmpdir(), "omb-cursor-reply-receipt-"));+ scratchDirs.push(scratch);+ const updates = join(scratch, "updates.json");+ const dump = join(scratch, "dump.json");+ Object.assign(process.env, { FAKE_ACP_UPDATES_FILE: updates, FAKE_ACP_DUMP: dump, FAKE_ACP_DUMP_PROMPT: "1" });+ writeFileSync(updates, JSON.stringify([{ update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "\n\nError: RetriableError: [unavailable] HTTP 503" } } }]));+ const instance = await CursorAgentDriver.create({+ instanceId: "cursor-reply-receipt", displayName: "Cursor", environment: {}, enabled: true, config: { cli: FAKE_CLI, fullAuto: false },+ });+ const recorder = recordEvents(instance.adapter);+ const input = { threadId: `t-cursor-reply-receipt-${randomUUID()}`, text: "go", system: "STABLE RULES\n\ntoday", systemStable: "STABLE RULES", systemVolatile: "today" };+ const sentPrompt = () => JSON.stringify(JSON.parse(readFileSync(`${dump}.prompt.json`, "utf8")));+ try {+ const first = await instance.adapter.sendTurn(input);+ expect(await recorder.until((e) => e.type === "turn.completed" && e.turnId === first.turnId)).toMatchObject({ ok: false });+ expect(sentPrompt()).toContain("STABLE RULES");+ writeFileSync(updates, "[]");+ const second = await instance.adapter.sendTurn(input);+ expect(await recorder.until((e) => e.type === "turn.completed" && e.turnId === second.turnId)).toMatchObject({ ok: true });+ expect(sentPrompt()).toContain("STABLE RULES");+ } finally {+ recorder.stop();+ await instance.dispose();+ delete process.env.FAKE_ACP_UPDATES_FILE;+ delete process.env.FAKE_ACP_DUMP_PROMPT;+ }+ });++ it("keeps a reply whose own words end by quoting such a line", async () => {+ const quoted = "The log ended with:\n\nError: RetriableError: [unavailable] HTTP 503";+ const { done, replies, errors } = await turn("t-cursor-quoted", quoted);+ expect(done).toMatchObject({ ok: true, stopReason: null });+ expect(replies).toEqual([quoted]);+ expect(errors).toEqual([]);+ });+ });+it("keeps going when session/set_model is missing and argv already pinned the model", async () => {ensureDirs();chmodSync(FAKE_CLI, 0o755);diff --git a/server/drivers/acp/cursor.ts b/server/drivers/acp/cursor.tsindex e5a52eb8b8..fc60d73298 100644--- a/server/drivers/acp/cursor.ts+++ b/server/drivers/acp/cursor.ts@@ -396,6 +396,14 @@ export function classifyCursorError(error: unknown): ProviderErrorCode | undefinreturn undefined;}+/** cursor-agent 2026.10.22's session/prompt catches any failed model call, sends `\n\nError: ${String(error)}` as one+ * message chunk and answers end_turn. Its own errors are named RetriableError and NonRetriableError. */+const CURSOR_REPLY_FAILURE = /^\n\nError: (?:(?:Non)?RetriableError: )?([^\n]+)$/;++export function cursorReplyFailure(chunk: string): string | null {+ return CURSOR_REPLY_FAILURE.exec(chunk.trimEnd())?.[1]?.trim() || null;+}+/** Cursor's AskQuestion blocks on `cursor/ask_question` (cursor.com/docs/cli/acp; cursor-agent 2026.10.01, no sessionId).* Cursor answers by option id only, so a reply with any own words goes back whole as `skipped` with the answers as the* reason, which Cursor hands the model verbatim: a typed answer is never forced onto an option. */@@ -514,6 +522,7 @@ const support = (run: typeof execCli): AcpSupport => ({authFailure: "continue",isAuthenticated: (env, config) => probeCursorAuth(config.cli || "cursor-agent", env, run),classifyError: classifyCursorError,+ replyFailure: cursorReplyFailure,clientCapabilitiesMeta: CURSOR_CLIENT_META,diff --git a/server/drivers/acp/driver-hooks.ts b/server/drivers/acp/driver-hooks.tsindex fa19a4183e..bb405c4b52 100644--- a/server/drivers/acp/driver-hooks.ts+++ b/server/drivers/acp/driver-hooks.ts@@ -29,6 +29,10 @@ export interface AcpDriverHooks {/** The failure a turn's thrown error stands for, in the person's words (a usage limit with its reset), or undefined to* keep the error as it is. Must not throw. */reportedFailure?(error: unknown): Error | undefined;+ /** Gets the last text chunk of a prompt the agent answered with end_turn. When the agent sent a failed model call as+ * that chunk instead of failing the prompt, returns the failure in its words, which fails the turn as a thrown one+ * does; the text before the chunk stays the reply. Null for any other chunk. */+ replyFailure?(chunk: string): string | null;}const MAX_LINE_CHARS = 64 * 1024;diff --git a/server/drivers/acp/turn-state.ts b/server/drivers/acp/turn-state.tsindex bd9001146f..f381329f54 100644--- a/server/drivers/acp/turn-state.ts+++ b/server/drivers/acp/turn-state.ts@@ -5,6 +5,7 @@ import type { spawnCli } from "../../procs.ts";import { noticeFailure } from "../../chat-notices.ts";import { errorReplyFailure, type ErrorReplyFailure } from "../engine-errors.ts";import type { AcpConfig } from "./core.ts";+import type { AcpDriverHooks } from "./driver-hooks.ts";import type { AcpHost, AcpLink } from "./host.ts";import type { AcpTurnSteering } from "./steer.ts";@@ -25,6 +26,8 @@ export interface AcpTurn {usagePeak: number | null;usageLast: number | null;usageCompacted: boolean;+ /** The last text chunk received; it may since have been sent with `text`. */+ lastText: string;/** Stop went unanswered: only the cancel timeout settles the turn, once its session is closed or its process gone. */cancelling: boolean;};@@ -79,6 +82,19 @@ export function trackRunningTool(current: AcpTurn, update: { toolCallId?: unknowelse if (status === "pending" || status === "in_progress") current.runningTools.add(update.toolCallId);}+/** The failure `read` finds in the turn's last text chunk while that chunk still ends the unsent reply; null otherwise. */+export function replyFailureOf(current: AcpTurn, read: AcpDriverHooks["replyFailure"]): string | null {+ const { text, lastText } = current.state;+ return lastText && text.endsWith(lastText) ? read?.(lastText) ?? null : null;+}++/** Sends the reply before the failed chunk, never the chunk itself, and gives the error that fails the turn. */+export function dropFailedChunk(current: AcpTurn, failure: string): Error {+ current.state.text = current.state.text.slice(0, -current.state.lastText.length);+ current.flushAssistantText();+ return new Error(failure);+}+export interface AcpTurnEnd {ok: boolean;stopReason: string | null;diff --git a/server/drivers/prompt-split.ts b/server/drivers/prompt-split.tsindex e5bbb7c83b..55deeebe04 100644--- a/server/drivers/prompt-split.ts+++ b/server/drivers/prompt-split.ts@@ -88,6 +88,24 @@ export function deletePromptSplitReceipt(scope: string, key: string): void {} catch {}}+export interface PendingPromptSplitReceipt { key: string; receipt: PromptSplitReceipt; previous: PromptSplitReceipt | null }++/** Records a prompt the agent accepted, with the context use its turn last reported; after a compaction nothing is+ * recorded, so the next turn sends the whole prompt again. */+export function commitPromptSplitReceipt(+ scope: string,+ pending: PendingPromptSplitReceipt,+ usage: { compacted: boolean; last: number | null; peak: number | null },+): void {+ if (usage.compacted) return deletePromptSplitReceipt(scope, pending.key);+ const lastUsed = usage.last ?? (typeof pending.previous?.lastUsed === "number" ? pending.previous.lastUsed : undefined);+ writePromptSplitReceipt(scope, pending.key, {+ ...pending.receipt,+ ...(lastUsed === undefined ? {} : { lastUsed }),+ ...(usage.peak === null ? {} : { peakUsed: usage.peak }),+ });+}+/** reAnchorAfterTurns re-sends the full prompt after that many bare turns, for history rewrites no event reports. */export function splitSessionPrompt(stable: string,diff --git a/server/testing/fake-acp-cli.ts b/server/testing/fake-acp-cli.tsindex ea6285a25c..c35b93c581 100755--- a/server/testing/fake-acp-cli.ts+++ b/server/testing/fake-acp-cli.ts@@ -7,7 +7,7 @@// FAKE_ACP_CACHED_LIVE_LOAD a live session/load is acknowledged but keeps the old MCP credentials, like Qwen// FAKE_ACP_COPY_LIVE_LOAD=1 a session/load of a session still open adds a second copy, and each open copy streams// FAKE_ACP_TEXT_REPLY again, like mistral-vibe 3.1.2; session/close ends every copy-// FAKE_ACP_TEXT_REPLY answer every session/prompt with only this text+// FAKE_ACP_TEXT_REPLY answer every session/prompt with FAKE_ACP_UPDATES_FILE's updates, then only this text// FAKE_STREAM_SCRIPT, FAKE_STREAM_CADENCE a scripted reply chosen by a marker in the prompt (stream-script.ts)// FAKE_ACP_MODE happy (default) | image | empty-reply | reasoning-only | exit-early | fail-after-text | crash-in-prompt// | abort-in-prompt (a sign-in link, then a TCMalloc CHECK line on stderr, then exit 134 as bubblewrap reports SIGABRT) | hang@@ -1216,6 +1216,7 @@ function handle(msg: any) {return;}if (process.env.FAKE_ACP_TEXT_REPLY !== undefined) {+ emitSessionReports();for (let copy = openCopies.get(String(msg.params?.sessionId)) ?? 1; copy > 0; copy -= 1) {out({ jsonrpc: "2.0", method: "session/update", params: { sessionId: msg.params?.sessionId, update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: process.env.FAKE_ACP_TEXT_REPLY } } } });}