Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(acp): hold Cursor's failure line back from the reply as it arrives
Absterrg03d68e3a2f9c5
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.tsindex 43f6926b45..5849949e48 100644--- a/server/drivers/acp/core.ts+++ b/server/drivers/acp/core.ts@@ -66,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 { dropFailedChunk, endTurn, replyFailureOf, trackRunningTool, type AcpAskFinish, type AcpSession, type AcpTurn } from "./turn-state.ts";+import { endTurn, receiveText, 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";@@ -842,8 +842,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>if (support.resendsReasoningReply && messageId && messageId === current.state.textMessageId&& isHermesReasoningReplay(delta, current.state.text)) break;current.state.textMessageId = messageId;- current.state.text += delta;- current.state.lastText = delta;+ receiveText(current.state, delta, support.replyFailure);const trimmed = current.state.text.trimStart();if (!trimmed.startsWith("<SYSTEM_MESSAGE") &&!trimmed.startsWith("The following is a <SYSTEM_MESSAGE") &&@@ -1081,7 +1080,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, lastText: "", 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, failedChunk: null, cancelling: false };let acknowledge = () => {};let rejectStartup = (_error: TurnNotStartedError) => {};const startupAck = turn.startupRecovery ? new Promise<{ turnId: string }>((resolve, reject) => {@@ -1412,7 +1411,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>);const steersOut = current.steering?.promptAnswered();if (steersOut && !state.stopped) { current.flushAssistantText(); await steersOut; }- const failure = replyFailureOf(current, support.replyFailure);+ const failure = state.failedChunk?.failure;// 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);@@ -1426,7 +1425,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 (failure && reason === "end_turn") { flushAssistantText(); throw new Error(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 1133af5895..6d5d1bf9e6 100644--- a/server/drivers/acp/cursor.test.ts+++ b/server/drivers/acp/cursor.test.ts@@ -732,6 +732,50 @@ describe("CursorAgentDriver", () => {}});+ // Cursor's prompt handler waits on backgrounded shells after the failure line, shown as a "Watching: …" tool call.+ const scripted = async (threadId: string, updates: Array<Record<string, unknown>>) => {+ ensureDirs();+ chmodSync(FAKE_CLI, 0o755);+ const scratch = mkdtempSync(join(tmpdir(), "omb-cursor-reply-held-"));+ scratchDirs.push(scratch);+ process.env.FAKE_ACP_UPDATES_FILE = join(scratch, "updates.json");+ writeFileSync(process.env.FAKE_ACP_UPDATES_FILE, JSON.stringify(updates.map((update) => ({ update }))));+ const instance = await CursorAgentDriver.create({+ instanceId: "cursor-reply-held", 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] : []);+ return { done, replies, errors: recorder.events.filter((e) => e.type === "runtime.error") };+ } finally {+ recorder.stop();+ await instance.dispose();+ delete process.env.FAKE_ACP_UPDATES_FILE;+ }+ };+ const text = (chunk: string) => ({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: chunk } });+ const watching = [+ { sessionUpdate: "tool_call", toolCallId: "watch-1", title: "Watching: wait until 06:15", kind: "other" },+ { sessionUpdate: "tool_call_update", toolCallId: "watch-1", status: "completed" },+ ];++ it("fails the turn when a tool call follows the failure line, and never sends the line as a reply", async () => {+ const { done, replies, errors } = await scripted("t-cursor-503-watching", [text("\n\nError: RetriableError: [unavailable] HTTP 503"), ...watching]);+ expect(done).toMatchObject({ ok: false, stopReason: "rpc_error" });+ expect(replies.some((reply) => reply.includes("RetriableError"))).toBe(false);+ expect(errors).toEqual([expect.objectContaining({ message: expect.stringMatching(/^Cursor had a temporary server problem \(HTTP 503/) })]);+ });++ it("puts the line back in the reply when the agent goes on writing after it", async () => {+ const line = "\n\nError: RetriableError: [unavailable] HTTP 503";+ const { done, replies, errors } = await scripted("t-cursor-503-went-on", [text(line), ...watching, text(" Retried, and it went through.")]);+ expect(done).toMatchObject({ ok: true, stopReason: null });+ expect(replies.at(-1)).toBe("Error: RetriableError: [unavailable] HTTP 503 Retried, and it went through.");+ expect(errors).toEqual([]);+ });+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);diff --git a/server/drivers/acp/turn-state.ts b/server/drivers/acp/turn-state.tsindex f381329f54..95026c6323 100644--- a/server/drivers/acp/turn-state.ts+++ b/server/drivers/acp/turn-state.ts@@ -26,8 +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;+ /** A chunk the driver read as a failed model call, kept out of `text` while it is the agent's last words. */+ failedChunk: { chunk: string; failure: string } | null;/** Stop went unanswered: only the cancel timeout settles the turn, once its session is closed or its process gone. */cancelling: boolean;};@@ -82,17 +82,13 @@ 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);+/** Adds a text chunk to the unsent reply. A chunk `read` names a failed model call is held back instead, so no flush+ * sends it; later words return it to the reply, as it was not the agent's last. */+export function receiveText(state: AcpTurn["state"], delta: string, read: AcpDriverHooks["replyFailure"]): void {+ if (state.failedChunk) state.text += state.failedChunk.chunk;+ const failure = read?.(delta) ?? null;+ state.failedChunk = failure === null ? null : { chunk: delta, failure };+ if (failure === null) state.text += delta;}export interface AcpTurnEnd {