Skip to content

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

fix(grok): ignore updates trailing our own turn, end the process when work cannot be closed, harden the config write

Krishna Dobhal95b425c9383c
diff --git a/docs/verification/grok-steering.md b/docs/verification/grok-steering.md
index 569e19ad13..8a91adaa32 100644
--- a/docs/verification/grok-steering.md
+++ b/docs/verification/grok-steering.md
@@ -24,8 +24,15 @@ OpenMausBot adds the line itself, for a signed-in Grok, when a turn starts. A
the real CLI needs a server started by hand. Use a temporary data directory and a copy
of the sign-in, never `~/.grok`:
-1. Make a data directory `$D` with `$D/grokhome/` holding a copy of `~/.grok/auth.json`
- and an empty `$D/tmp/`.
+1. Make a private data directory, export it so the start script below can read it, and copy
+ the sign-in into it:
+
+ ```sh
+ export D="$(mktemp -d)" # mode 0700 on Linux and macOS
+ mkdir -p "$D/grokhome" "$D/tmp"
+ cp ~/.grok/auth.json "$D/grokhome/auth.json"
+ ```
+
2. Write `$D/config.json` (the server reads `config.json` from `OMB_DATA_DIR`):
```json
@@ -57,6 +64,8 @@ of the sign-in, never `~/.grok`:
```
4. Open `http://127.0.0.1:19975` and create the first bot; it uses the Grok instance.
+5. When done, stop the server (Ctrl-C) and delete the directory, which holds the copied
+ sign-in: `rm -rf "$D"`.
Grok's shell tool needs a shell the isolated environment can find, so use its file tools
for the check below.
@@ -94,13 +103,19 @@ turn pays a `session/load`.
When it cannot end the work:
-- **No `sessionCapabilities.close`.** An agent that does not advertise it gets no
- `session/close`, and the driver leaves its background work as it was: it can still wake a
- turn nobody prompted, and that turn runs unseen.
+- **No `sessionCapabilities.close`.** An agent that does not advertise it cannot have its
+ work ended that way, so the driver ends the session's process instead (the same step it
+ takes for a session that ignores `session/cancel`). For such an agent that happens at every
+ Stop and every wake.
- **The close fails or times out.** The driver tries it once more. If that fails too, it ends
- the session's process (the same step it takes for a session that ignores `session/cancel`),
- which also stops the work; the thread's next turn loads its history in a new process. If
- even that fails, the work can keep running.
+ the session's process the same way. The thread's next turn loads its history in a new
+ process, and does not start until the old one has ended. If even that fails, the work can
+ keep running.
+
+A turn of ours can settle before its last updates arrive (a cancel timeout, a stuck turn, a
+failed prompt). An update in the first 2 seconds after one of our turns settles is taken for
+that turn's tail, not a wake. A woken turn keeps streaming past that, so it is still caught; a
+woken turn shorter than that window would be missed.
Recorded on the real CLI (2026-11-19): a subagent launched in the background
finished after the turn and Grok then ran a turn that confirmed its file; with
diff --git a/server/drivers/acp/background-work.test.ts b/server/drivers/acp/background-work.test.ts
index ff5c38debe..f7fd37f2e3 100644
--- a/server/drivers/acp/background-work.test.ts
+++ b/server/drivers/acp/background-work.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { closeEndsBackgroundWork } from "./background-work.ts";
+import { closeEndsBackgroundWork, WAKE_GRACE_MS } from "./background-work.ts";
const capable = { agentCapabilities: { sessionCapabilities: { close: {} } } };
@@ -15,6 +15,14 @@ describe("close-ends background work", () => {
expect(work.wakes(undefined)).toBe(false);
});
+ it("takes an update that trails a turn of ours as that turn's tail, not a wake", () => {
+ const work = closeEndsBackgroundWork();
+ expect(work.wakes({ sessionUpdate: "tool_call_update" }, 0)).toBe(false);
+ expect(work.wakes({ sessionUpdate: "agent_message_chunk" }, WAKE_GRACE_MS - 1)).toBe(false);
+ expect(work.wakes({ sessionUpdate: "agent_message_chunk" }, WAKE_GRACE_MS)).toBe(true);
+ expect(work.wakes({ sessionUpdate: "agent_message_chunk" })).toBe(true);
+ });
+
it("closes the session, forgets its live id, and resumes the same id", async () => {
const work = closeEndsBackgroundWork();
const calls: string[] = [];
@@ -28,11 +36,11 @@ describe("close-ends background work", () => {
expect(work.resumeCursor(undefined, null, {})).toBeNull();
});
- it("does nothing when the agent cannot close sessions, and keeps the session when the close fails", async () => {
+ it("reports it could not end the work when the agent cannot close sessions, and keeps the session when the close fails", async () => {
const work = closeEndsBackgroundWork();
const calls: string[] = [];
const noClose = { sessionId: "s1" as string | null, cwd: "/w", initResult: { agentCapabilities: { sessionCapabilities: {} } } };
- await work.end(noClose, async (method: string) => { calls.push(method); return {}; });
+ expect(await work.end(noClose, async (method: string) => { calls.push(method); return {}; })).toBe(false);
expect(calls).toEqual([]);
expect(noClose.sessionId).toBe("s1");
diff --git a/server/drivers/acp/background-work.ts b/server/drivers/acp/background-work.ts
index 34f6822c1d..f1fd42107e 100644
--- a/server/drivers/acp/background-work.ts
+++ b/server/drivers/acp/background-work.ts
@@ -3,8 +3,9 @@ type Request = (method: string, params: unknown, timeoutMs?: number) => Promise<
/** Work an agent goes on with after its turn (a background subagent or shell command) and whose finish wakes a turn no
* `session/prompt` asked for. The driver ends it when the person stops a turn, and when such a turn wakes between ours. */
export interface AcpBackgroundWork {
- /** Whether a session/update that arrives while no turn of ours runs is the agent working on its own. */
- wakes(update: Record<string, any> | undefined): boolean;
+ /** Whether a session/update that arrives while no turn of ours runs is the agent working on its own. `sinceSettledMs` is how
+ * long ago a turn of ours last settled; an update of that turn can still trail it. */
+ wakes(update: Record<string, any> | undefined, sinceSettledMs?: number): boolean;
/** The session a turn resumes: its stored cursor, or with none whatever ending the work left behind for this live session. */
resumeCursor(cursor: unknown, live: string | null, session?: object): string | null;
/** Ends the session's background work and any turn it woke, keeping its history. Never throws. Resolves false when the work
@@ -15,19 +16,25 @@ export interface AcpBackgroundWork {
/** The session/update kinds a turn streams; titles, usage, compaction and command lists are not one. */
export const TURN_UPDATES: ReadonlySet<string> = new Set(["agent_message_chunk", "agent_thought_chunk", "tool_call", "tool_call_update", "plan"]);
+/** A turn of ours can settle before its last updates arrive (a cancel timeout, a stuck turn, a failed prompt); an update this
+ * soon after it is taken for that turn's tail, not a wake. A woken turn streams on past it. */
+export const WAKE_GRACE_MS = 2_000;
+
const CLOSE_WAIT_MS = 10_000;
/** For an agent whose `session/close` ends the session's background work and whose `session/load` of the same id brings its
- * history back (grok 1.0.89): the session is closed and the thread's next turn loads it again, under the same id. */
+ * history back (grok 1.0.89): the session is closed and the thread's next turn loads it again, under the same id. An agent
+ * that does not advertise `session/close` cannot end the work that way, so `end` reports it could not. */
export function closeEndsBackgroundWork(): AcpBackgroundWork {
const closed = new WeakMap<object, string>();
return {
- wakes: (update) => TURN_UPDATES.has(update?.sessionUpdate),
+ wakes: (update, sinceSettledMs = Infinity) => TURN_UPDATES.has(update?.sessionUpdate) && sinceSettledMs >= WAKE_GRACE_MS,
resumeCursor: (cursor, live, session) =>
typeof cursor === "string" ? cursor : live === null && session ? closed.get(session) ?? null : null,
end: async (session, request) => {
const sessionId = session.sessionId;
- if (!sessionId || !session.initResult?.agentCapabilities?.sessionCapabilities?.close) return;
+ if (!sessionId) return;
+ if (!session.initResult?.agentCapabilities?.sessionCapabilities?.close) return false;
for (let attempt = 0; attempt < 2; attempt++) {
try {
await request("session/close", { sessionId }, CLOSE_WAIT_MS);
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.ts
index 4bf6dd95ee..a2c695de90 100644
--- a/server/drivers/acp/core.ts
+++ b/server/drivers/acp/core.ts
@@ -407,7 +407,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
const sessionIdle = sessionIdlePolicy("ACP");
const backgroundEnds = new Map<string, Promise<void>>(), endBackground = (threadId: string, session: AcpSession) => support.backgroundWork && !backgroundEnds.has(threadId) && session.child.exitCode === null
- && backgroundEnds.set(threadId, support.backgroundWork.end(session, (m, p, t) => session.host.request(null, m, p, t)).then((ended) => { if (ended === false) void endUncancelled(threadId, session); }).finally(() => backgroundEnds.delete(threadId)));
+ && backgroundEnds.set(threadId, support.backgroundWork.end(session, (m, p, t) => session.host.request(null, m, p, t)).then(async (ended) => { if (ended === false) await endUncancelled(threadId, session); }).finally(() => backgroundEnds.delete(threadId)));
const closeSession = (threadId: string, why: string) => {
const session = sessions.get(threadId);
if (!session || session.closing) return;
@@ -574,7 +574,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
for (const finish of current.asks.values()) finish("cancel", "system");
session.acp.failAll(new Error("turn settled"));
// Detach before the final events: a listener may start the next turn synchronously.
- session.current = null;
+ session.current = null; session.settledAt = Date.now();
active.delete(threadId); if (current.state.stopped) endBackground(threadId, session);
const end = endTurn(current, ok, stopReason, support.displayName);
if (end.error) emit({ ...base(threadId, current.turnId), type: "runtime.error", ...end.error });
@@ -816,7 +816,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
if (current && ["agent_message_chunk", "agent_thought_chunk", "tool_call", "tool_call_update", "plan"].includes(p.update?.sessionUpdate)) {
current.state.startupActivity = true; if (current.state.promptSent) current.acknowledge();
}
- if (!current || !current.state.promptSent) return void (!current && support.backgroundWork?.wakes(p.update) && endBackground(threadId, session));
+ if (!current || !current.state.promptSent) return void (!current && support.backgroundWork?.wakes(p.update, Date.now() - (session.settledAt ?? 0)) && endBackground(threadId, session));
const u = filterUpdate ? filterUpdate(p.update ?? {}) : p.update ?? {};
if (!u || (u.sessionUpdate === "agent_message_chunk" && typeof u.content?.text === "string" && current.steering?.swallow(u.content.text))) return;
const finished = u.status === "completed" || u.status === "failed";
diff --git a/server/drivers/acp/grok-background.test.ts b/server/drivers/acp/grok-background.test.ts
index b6b79d5713..c7e0b684e8 100644
--- a/server/drivers/acp/grok-background.test.ts
+++ b/server/drivers/acp/grok-background.test.ts
@@ -107,6 +107,45 @@ describe("Grok background work", () => {
}
});
+ it("takes an update that trails our finished turn as its tail, not a wake, and keeps the session open", async () => {
+ const { instance, recorder, calls, ask } = await start("grok-background-late", { FAKE_ACP_LATE_UPDATE: "1", FAKE_ACP_WAKE_MS: "60000" });
+ const threadId = "t-grok-background-late";
+ try {
+ expect(await ask(threadId, "build it")).toMatchObject({ ok: true });
+ const session = promptedSession(calls)!;
+ await pause(600);
+ expect(calls().filter((call) => call.method === "session/close")).toEqual([]);
+ expect(await ask(threadId, "and now?")).toMatchObject({ ok: true });
+ expect(promptedSession(calls)).toBe(session);
+ expect(calls().filter((call) => call.method === "session/load")).toEqual([]);
+ } finally {
+ recorder.stop();
+ await instance.dispose();
+ }
+ });
+
+ it("ends the session's process when the agent cannot close sessions, so no turn wakes unseen", async () => {
+ const { instance, recorder, calls, steps, ask } = await start("grok-background-no-close", { FAKE_ACP_NO_CLOSE: "1" });
+ const threadId = "t-grok-background-no-close";
+ try {
+ expect(await ask(threadId, "build it")).toMatchObject({ ok: true });
+ await until(() => steps() > 0);
+ let last = -1;
+ for (let i = 0; steps() !== last; i++) {
+ if (i > 40) throw new Error("the woken turn never stopped");
+ last = steps();
+ await pause(300);
+ }
+ expect(calls().filter((call) => call.method === "session/close")).toEqual([]);
+ expect(JSON.stringify(recorder.events)).not.toContain("WOKEN");
+ expect(await ask(threadId, "and now?")).toMatchObject({ ok: true });
+ expect(JSON.stringify(recorder.events)).not.toContain("WOKEN");
+ } finally {
+ recorder.stop();
+ await instance.dispose();
+ }
+ });
+
it("ends the session's background work when the person stops the turn, before it can wake a turn", async () => {
const { instance, recorder, calls, steps, ask } = await start("grok-background-stop", { FAKE_ACP_WAKE_MS: String(STOP_WAKE_MS) });
const threadId = "t-grok-background-stop";
diff --git a/server/drivers/acp/grok-follow-up.test.ts b/server/drivers/acp/grok-follow-up.test.ts
index 6ab9fc2b33..1dc46eb35d 100644
--- a/server/drivers/acp/grok-follow-up.test.ts
+++ b/server/drivers/acp/grok-follow-up.test.ts
@@ -43,8 +43,17 @@ describe("Grok's ui.follow_up_behavior in config.toml", () => {
expect(read("x = 1\n").insertAt).toBeUndefined();
});
+ it("counts any other definition of ui, so no [ui] table is added after it", () => {
+ for (const text of ["ui = []\n", 'ui = "minimal"\n', "[[ui]]\nx = 1\n"]) {
+ expect(read(text), text).toMatchObject({ uiElsewhere: true, present: false });
+ expect(read(text).insertAt, text).toBeUndefined();
+ }
+ });
+
it("steps over multi-line arrays and tables, and reports what it cannot place", () => {
expect(read('args = [\n "a",\n "[ui]",\n]\n[ui]\nfollow_up_behavior = "steer"\n')).toMatchObject({ value: "steer", unclear: false });
+ expect(read('args = [ # arguments\n "a", # one\n]\n[ui]\nfollow_up_behavior = "queue"\n')).toMatchObject({ value: "queue", unclear: false });
+ expect(read('args = ["a#b"]\n[ui]\nfollow_up_behavior = "steer" # on\n')).toMatchObject({ value: "steer" });
expect(read('note = """\n[ui]\n"""\n')).toMatchObject({ unclear: true });
expect(read("this is not toml\n")).toMatchObject({ unclear: true });
});
diff --git a/server/drivers/acp/grok-follow-up.ts b/server/drivers/acp/grok-follow-up.ts
index a944b2f6a8..bb8d64a781 100644
--- a/server/drivers/acp/grok-follow-up.ts
+++ b/server/drivers/acp/grok-follow-up.ts
@@ -43,12 +43,25 @@ function stringValue(text: string): string | undefined {
return end > 0 ? unescape(text.slice(1, end)) : undefined;
}
-/** How many brackets and braces a value leaves open, ignoring strings and a trailing comment. */
+/** `text` without a trailing `#` comment; a `#` inside a string is kept. */
+function withoutComment(text: string): string {
+ for (let i = 0; i < text.length; i++) {
+ const c = text[i];
+ if (c === "#") return text.slice(0, i);
+ if (c === '"' || c === "'") {
+ const close = c === '"' ? basicStringEnd(text, i) : text.indexOf("'", i + 1);
+ if (close < 0) return text;
+ i = close;
+ }
+ }
+ return text;
+}
+
+/** How many brackets and braces a value without comments leaves open, ignoring strings. */
function openDepth(text: string): number {
let depth = 0;
for (let i = 0; i < text.length; i++) {
const c = text[i];
- if (c === "#") break;
if (c === '"' || c === "'") {
const close = c === '"' ? basicStringEnd(text, i) : text.indexOf("'", i + 1);
if (close < 0) return depth;
@@ -71,24 +84,26 @@ export function readGrokFollowUp(text: string): GrokFollowUp {
if (/^\s*(#.*)?$/.test(line)) continue;
const header = HEADER.exec(line);
if (header) {
- table = header[1] === "[[" ? null : keyPath(header[2]);
+ const path = keyPath(header[2]);
+ table = header[1] === "[[" ? null : path;
+ if (header[1] === "[[" && same(path, ["ui"])) result.uiElsewhere = true;
if (table && same(table, ["ui"]) && result.insertAt === undefined) result.insertAt = ends[i];
continue;
}
const assign = ASSIGN.exec(line);
if (!assign) { result.unclear = true; return result; }
- let rest = assign[2].trim();
+ let rest = withoutComment(assign[2]).trim();
if (rest.startsWith('"""') || rest.startsWith("'''")) { result.unclear = true; return result; }
- while (openDepth(rest) > 0 && i + 1 < lines.length) rest += " " + lines[++i].replace(/\r$/, "").trim();
+ while (openDepth(rest) > 0 && i + 1 < lines.length) rest += " " + withoutComment(lines[++i].replace(/\r$/, "")).trim();
if (table === null) continue;
const path = [...table, ...keyPath(assign[1])];
if (same(path, ["ui", "follow_up_behavior"])) {
result.present = true;
result.value = stringValue(rest);
if (table.length === 0) result.uiElsewhere = true;
- } else if (same(path, ["ui"]) && rest.startsWith("{")) {
+ } else if (same(path, ["ui"])) {
result.uiElsewhere = true;
- const inner = INLINE_KEY.exec(rest);
+ const inner = rest.startsWith("{") ? INLINE_KEY.exec(rest) : null;
if (inner) { result.present = true; result.value = stringValue(inner[1].trim()); }
} else if (path[0] === "ui" && table.length === 0 && path.length > 1) {
result.uiElsewhere = true;
diff --git a/server/drivers/acp/grok-steer.test.ts b/server/drivers/acp/grok-steer.test.ts
index 64ee9b14c8..b33b0e3444 100644
--- a/server/drivers/acp/grok-steer.test.ts
+++ b/server/drivers/acp/grok-steer.test.ts
@@ -180,7 +180,7 @@ describe("ensureGrokSteer", () => {
it("writes nothing when ui is defined another way, or the file cannot be read with confidence", () => {
signedIn();
- for (const text of ['ui.screen_mode = "minimal"\n', 'ui = { screen_mode = "minimal" }\n', 'note = """\n[ui]\n"""\n']) {
+ for (const text of ['ui.screen_mode = "minimal"\n', 'ui = { screen_mode = "minimal" }\n', 'note = """\n[ui]\n"""\n', "ui = []\n", "[[ui]]\nx = 1\n"]) {
writeFileSync(config(), text);
ensureGrokSteer(env());
expect(readFileSync(config(), "utf8"), text).toBe(text);
diff --git a/server/drivers/acp/grok.ts b/server/drivers/acp/grok.ts
index 2c8053e03c..38a6505807 100644
--- a/server/drivers/acp/grok.ts
+++ b/server/drivers/acp/grok.ts
@@ -1,6 +1,6 @@
// Grok Build: the official `grok` CLI over ACP stdio (`grok … agent stdio`) on the grok.com
// subscription login (~/.grok/auth.json), not the xAI API key. Verified against grok 1.0.0.
-import { existsSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
+import { existsSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { parse as parseYaml } from "yaml";
@@ -377,11 +377,13 @@ export function ensureGrokSteer(env: Record<string, string | undefined> = proces
const next = found.insertAt !== undefined
? text.slice(0, found.insertAt) + (text.slice(0, found.insertAt).endsWith("\n") ? "" : eol) + line + text.slice(found.insertAt)
: `${text}${text && !text.endsWith("\n") ? eol : ""}${text ? eol : ""}[ui]${eol}${line}`;
+ // config.toml can hold `api_key` values (ensureGrokInjectSlug writes them), so the staged copy is private from its first byte.
+ const staged = `${path}.omb-${process.pid}.tmp`;
try {
- const staged = `${path}.omb-${process.pid}.tmp`;
- writeFileSync(staged, next);
+ writeFileSync(staged, next, { mode: 0o600, flag: "wx" });
renameSync(staged, path);
} catch {
+ rmSync(staged, { force: true });
// Grok then keeps queueing mid-turn messages, its default.
}
}
diff --git a/server/drivers/acp/turn-state.ts b/server/drivers/acp/turn-state.ts
index ad1a87b379..bd9001146f 100644
--- a/server/drivers/acp/turn-state.ts
+++ b/server/drivers/acp/turn-state.ts
@@ -63,6 +63,8 @@ export interface AcpSession {
dead: boolean;
readonly stderr: string;
current: AcpTurn | null;
+ /** When a turn of ours last settled on this session. */
+ settledAt?: number;
/** The slash commands the agent last advertised for this session. */
commands?: ReadonlySet<string>;
fallbackNotice?: string;
diff --git a/server/testing/fake-acp-cli.ts b/server/testing/fake-acp-cli.ts
index e5f6982292..e11de882b9 100755
--- a/server/testing/fake-acp-cli.ts
+++ b/server/testing/fake-acp-cli.ts
@@ -30,8 +30,9 @@
// STOP_ME in it waits for session/cancel; FAKE_ACP_WAKE_MS (300) later that shell's finish wakes a turn no prompt
// asked for, one step every FAKE_ACP_STEP_MS (50), each appended to FAKE_ACP_WOKEN_FILE, until session/close or
// session/delete interrupts it; only session/delete ends the job. session/fork answers <id>-fork; a closed or
-// deleted session refuses session/prompt until loaded. Advertises close, delete and, unless FAKE_ACP_NO_FORK=1, fork; FAKE_ACP_CLOSE_ENDS_JOBS=1: session/close
-// ends the job too, as grok 1.0.89's does)
+// deleted session refuses session/prompt until loaded. Advertises close (unless FAKE_ACP_NO_CLOSE=1), delete and, unless
+// FAKE_ACP_NO_FORK=1, fork; FAKE_ACP_CLOSE_ENDS_JOBS=1: session/close ends the job too, as grok 1.0.89's does;
+// FAKE_ACP_LATE_UPDATE=1: a tool_call_update of the finished prompt arrives 50 ms after its answer)
// FAKE_ACP_GROK_NATIVE_MCP _x.ai/mcp/list reports these comma-separated native servers after the session's accepted ones
// FAKE_ACP_MCP_TRANSPORTS remote MCP transports advertised in initialize, e.g. "http,sse"
// FAKE_ACP_PERMISSION_OPTIONS JSON options override in permission mode
@@ -927,7 +928,8 @@ function handle(msg: any) {
...(agentName ? { loadSession: true, sessionCapabilities: { resume: true }, auth: { logout: true } } : {}),
...(closesSessions || deletesSessions
? { sessionCapabilities: { ...(closesSessions ? { close: {} } : {}), ...(deletesSessions ? { delete: {} } : {}),
- ...(mode === "background-wake" ? { close: {}, ...(process.env.FAKE_ACP_NO_FORK === "1" ? {} : { fork: {} }) } : {}) } }
+ ...(mode === "background-wake" ? { ...(process.env.FAKE_ACP_NO_CLOSE === "1" ? {} : { close: {} }),
+ ...(process.env.FAKE_ACP_NO_FORK === "1" ? {} : { fork: {} }) } : {}) } }
: {}),
...(acceptsImages ? { promptCapabilities: { image: true } } : {}),
...(mcpTransports.length ? { mcpCapabilities: { http: mcpTransports.includes("http"), sse: mcpTransports.includes("sse") } } : {}),
@@ -989,15 +991,19 @@ function handle(msg: any) {
break;
}
case "session/close":
- if (process.env.FAKE_ACP_SESSION_CLOSE !== "error") endWokenStep(msg.params?.sessionId);
+ // A failed close leaves the session, its woken steps and its jobs exactly as they were.
+ if (process.env.FAKE_ACP_SESSION_CLOSE === "error") {
+ out({ jsonrpc: "2.0", id: msg.id, error: { code: -32603, message: "close failed" } });
+ break;
+ }
+ endWokenStep(msg.params?.sessionId);
if (process.env.FAKE_ACP_CLOSE_ENDS_JOBS === "1") {
const job = backgroundJobs.get(String(msg.params?.sessionId))?.job;
if (job) clearTimeout(job);
backgroundJobs.delete(String(msg.params?.sessionId));
}
if (mode === "background-wake") detachedSessions.add(String(msg.params?.sessionId));
- if (process.env.FAKE_ACP_SESSION_CLOSE === "error") out({ jsonrpc: "2.0", id: msg.id, error: { code: -32603, message: "close failed" } });
- else if (process.env.FAKE_ACP_SESSION_CLOSE_MS) setTimeout(() => result(msg.id, {}), Number(process.env.FAKE_ACP_SESSION_CLOSE_MS));
+ if (process.env.FAKE_ACP_SESSION_CLOSE_MS) setTimeout(() => result(msg.id, {}), Number(process.env.FAKE_ACP_SESSION_CLOSE_MS));
else result(msg.id, {});
break;
case "session/delete": {
@@ -1372,6 +1378,9 @@ function handle(msg: any) {
return;
}
complete();
+ if (process.env.FAKE_ACP_LATE_UPDATE === "1") {
+ setTimeout(() => update({ sessionUpdate: "tool_call_update", toolCallId: "tc-build", status: "completed" }), 50);
+ }
return;
}
if (mode === "finished-tools") {