Skip to content

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

Grok: learn the process limit from its thread failures, end turns on prompt_complete, map its rate-limit stop

milind-soni7c26e29790ce
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.ts
index db1745539c..1d404f306c 100644
--- a/server/drivers/acp/core.ts
+++ b/server/drivers/acp/core.ts
@@ -597,7 +597,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
const running = sharedHost(hostKey, threadId, cwd);
if (running) return running;
const child = spawnCli(launch.command, argv, { cwd, env, stdio: ["pipe", "pipe", "pipe"], box: { allowEnv: instanceEnvNames(input.environment, env), botThreads: hostKey !== null, ro: launch.ro } }, "bot");
- const host = new AcpHost(child, hostKey, { source: SOURCE, logMessage: nativeLogMessage, unrouted: refuse });
+ const host = new AcpHost(child, hostKey, { source: SOURCE, logMessage: nativeLogMessage, unrouted: refuse, promptCompletion: support.promptCompletion });
hosts.add(host); signIn.watch(host);
child.once("close", () => hosts.delete(host));
child.once("error", () => hosts.delete(host));
@@ -938,7 +938,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
if (current?.state.cancelling) return;
if (current) {
if (!current.state.stopped) emit({ ...base(threadId, current.turnId), type: "runtime.error",
- ...exitBeforeResult(support.displayName, code, signal, session.stderr, support.minNodeVersion, found) });
+ ...exitBeforeResult(support.displayName, code, signal, session.stderr, support.minNodeVersion, found, session.host.startRefused) });
settle(threadId, session, current.state.stopped, current.state.stopped ? "cancelled" : "exit_before_result");
} else if (sessions.get(threadId) === session) {
// The identity check keeps an old child's exit from unlinking its replacement.
@@ -1132,7 +1132,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
const interrupt = () => {
state.stopped = true;
if (session.sessionId) {
- session.acp.send({ jsonrpc: "2.0", method: "session/cancel", params: { sessionId: session.sessionId } });
+ session.acp.send({ jsonrpc: "2.0", method: "session/cancel", params: { sessionId: session.sessionId, ...(support.cancelMeta ? { _meta: support.cancelMeta } : {}) } });
if (current.interruptTimer) clearTimeout(current.interruptTimer);
current.interruptTimer = setTimeout(() => {
state.cancelling = true;
@@ -1164,7 +1164,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
session.initResult = await session.host.once("initialize", () => request(
"initialize",
{
- protocolVersion: 1,
+ protocolVersion: 1, ...(support.initializeMeta ? { _meta: support.initializeMeta } : {}),
clientInfo: support.clientInfo?.(instanceId) ?? { name: "openmausbot", version: "0.0.0" },
clientCapabilities: {
fs: {
diff --git a/server/drivers/acp/driver-hooks.ts b/server/drivers/acp/driver-hooks.ts
index fa19a4183e..65f8d6ee71 100644
--- a/server/drivers/acp/driver-hooks.ts
+++ b/server/drivers/acp/driver-hooks.ts
@@ -29,6 +29,22 @@ 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;
+ /** initialize's own `_meta` (beside clientCapabilities' vendor `_meta`), for an agent that reads who its client is there. */
+ initializeMeta?: Record<string, unknown>;
+ /** session/cancel's `_meta`, for an agent that reads how its turn was stopped there. */
+ cancelMeta?: Record<string, unknown>;
+ /** An agent that also ends each prompt with a notification of its own, which may come before the prompt's reply or
+ * without it. */
+ promptCompletion?: AcpPromptCompletion;
+}
+
+/** How an agent names the end of a prompt outside its session/prompt reply. */
+export interface AcpPromptCompletion {
+ /** `_meta` each session/prompt carries, so the agent names that prompt when it ends. */
+ meta(promptId: string): Record<string, unknown>;
+ /** The prompt a notification ends (its session, and its id or null when it names none) and its answer in a session/prompt
+ * reply's shape; null for any other notification. */
+ read(msg: { method?: unknown; params?: unknown }): { sessionId: string; promptId: string | null; result: { stopReason: string; error?: string } } | null;
}
const MAX_LINE_CHARS = 64 * 1024;
diff --git a/server/drivers/acp/exit-report.ts b/server/drivers/acp/exit-report.ts
index 91ab04141f..26fa6a8888 100644
--- a/server/drivers/acp/exit-report.ts
+++ b/server/drivers/acp/exit-report.ts
@@ -134,9 +134,11 @@ export function exitDetail(code: number | null, signal: NodeJS.Signals | null, t
}
/** Why an engine stopped before its reply: on a Node.js (`found`) older than it needs (`needed`), that, in the
- * person's language; otherwise its exit in words, with its last output. */
+ * person's language; for one that could not start its threads (`startRefused`), the server's own notice for a
+ * spawn it had no room for; otherwise its exit in words, with its last output. */
export function exitBeforeResult(provider: string, code: number | null, signal: NodeJS.Signals | null, tail: string,
- needed?: string, found?: string | null): { message: string; text?: ServerText } {
+ needed?: string, found?: string | null, startRefused = false): { message: string; text?: ServerText } {
if (needed && found && nodeOlderThan(found, needed)) return noticeFailure("chat.notice.acpNodeTooOld", { provider, needed, found });
+ if (startRefused) return noticeFailure("chat.notice.outOfProcesses", { code: "EAGAIN" });
return { message: `${provider} exited ${code ?? signal ?? "unexpectedly"} before the prompt result${exitDetail(code, signal, tail)}` };
}
diff --git a/server/drivers/acp/grok-signals.test.ts b/server/drivers/acp/grok-signals.test.ts
new file mode 100644
index 0000000000..df0f367274
--- /dev/null
+++ b/server/drivers/acp/grok-signals.test.ts
@@ -0,0 +1,163 @@
+// Grok's own ACP signals against the scripted peer: its prompt_complete notification, its rate-limit stop, the client type and
+// stop gesture it reads, and a process that could not start its threads.
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { ensureDirs } from "../../config.ts";
+import type { ProviderInstance, RuntimeEvent } from "../../contracts.ts";
+import { processBudget } from "../../process-room.ts";
+import { outOfProcesses } from "../../process-shortage.ts";
+import { removeTempDir } from "../../testing/cleanup.ts";
+import { recordEvents } from "../../testing/events.ts";
+import { CustomAcpDriver } from "./custom.ts";
+import { GrokAgentDriver } from "./grok.ts";
+
+const FAKE_CLI = join(dirname(fileURLToPath(import.meta.url)), "../../testing/fake-acp-cli.ts");
+const TOKIO = "grok: failed to start tokio runtime: blocking pool pre-warm stalled after 14 of 16 threads";
+
+const scratches: string[] = [];
+const instances: ProviderInstance[] = [];
+afterEach(async () => {
+ for (const instance of instances.splice(0)) await instance.dispose();
+ for (const dir of scratches.splice(0)) await removeTempDir(dir);
+});
+
+type Call = { method: string; sessionId?: string; meta?: Record<string, unknown> };
+
+const start = async (extra: Record<string, string>, driver: "grok" | "custom" = "grok") => {
+ ensureDirs();
+ const scratch = mkdtempSync(join(tmpdir(), "omb-grok-signals-"));
+ scratches.push(scratch);
+ mkdirSync(join(scratch, "grok"), { recursive: true });
+ writeFileSync(join(scratch, "grok", "auth.json"), "{}");
+ const files = { rpc: join(scratch, "rpc.jsonl"), dump: join(scratch, "dump") };
+ const environment = { GROK_HOME: join(scratch, "grok"), FAKE_ACP_RPC_APPEND_FILE: files.rpc, FAKE_ACP_DUMP: files.dump, ...extra };
+ const instance = (driver === "grok"
+ ? await GrokAgentDriver.create({ instanceId: `grok-signals-${scratches.length}`, displayName: "Grok", enabled: true, environment, config: { cli: FAKE_CLI, fullAuto: true } } as never)
+ : await CustomAcpDriver.create({ instanceId: `custom-signals-${scratches.length}`, displayName: "Custom", enabled: true, environment, config: { cli: FAKE_CLI, fullAuto: true } })) as ProviderInstance;
+ instances.push(instance);
+ const recorder = recordEvents(instance.adapter);
+ const calls = (): Call[] => existsSync(files.rpc) ? readFileSync(files.rpc, "utf8").trim().split("\n").map((line) => JSON.parse(line) as Call) : [];
+ const initialize = () => JSON.parse(readFileSync(`${files.dump}.initialize.json`, "utf8")) as Record<string, unknown>;
+ const ask = async (text = "hi") => {
+ const threadId = `t-${scratches.length}`;
+ const { turnId } = await instance.adapter.sendTurn({ threadId, text });
+ await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId, 15_000);
+ return recorder.events.filter((event) => "turnId" in event && event.turnId === turnId);
+ };
+ return { instance, recorder, calls, initialize, ask };
+};
+
+const of = <T extends RuntimeEvent["type"]>(events: RuntimeEvent[], type: T) => events.filter((event) => event.type === type) as Array<Extract<RuntimeEvent, { type: T }>>;
+const replyText = (events: RuntimeEvent[]) => of(events, "item.completed").map((event) => (event as { text?: string }).text ?? "").join("");
+
+describe("Grok's prompt_complete", () => {
+ it("names each prompt by an id of its own, and a reply that follows the notification still ends the turn once, with its usage", async () => {
+ const { calls, ask } = await start({ FAKE_ACP_MODE: "grok-complete" });
+ const events = await ask();
+ expect(of(events, "turn.completed")).toEqual([expect.objectContaining({ ok: true, stopReason: null })]);
+ expect(of(events, "thread.token-usage.updated")).toEqual([expect.objectContaining({ input: 20, output: 7 })]);
+ const prompt = calls().find((call) => call.method === "session/prompt")!;
+ expect(prompt.meta).toEqual({ promptId: expect.stringMatching(/^omb-prompt-\d+$/), requestId: prompt.meta?.promptId });
+ });
+
+ it("ends the turn on the notification alone when no reply comes", async () => {
+ const { ask } = await start({ FAKE_ACP_MODE: "grok-complete", FAKE_ACP_COMPLETE_REPLY: "never" });
+ const events = await ask();
+ expect(of(events, "turn.completed")).toEqual([expect.objectContaining({ ok: true, stopReason: null })]);
+ expect(replyText(events)).toBe("answered");
+ });
+
+ it("takes a notification that names no prompt for its session's one prompt out", async () => {
+ const { ask } = await start({ FAKE_ACP_MODE: "grok-complete", FAKE_ACP_COMPLETE_REPLY: "never", FAKE_ACP_COMPLETE_NAMES: "none" });
+ expect(of(await ask(), "turn.completed")).toEqual([expect.objectContaining({ ok: true })]);
+ });
+
+ it("ignores a background task's end and another session's, and waits for the prompt's own reply", async () => {
+ const { ask } = await start({ FAKE_ACP_MODE: "grok-complete", FAKE_ACP_COMPLETE_REPLY: "late", FAKE_ACP_COMPLETE_NAMES: "task,other-session" });
+ const events = await ask();
+ expect(of(events, "turn.completed")).toEqual([expect.objectContaining({ ok: true })]);
+ expect(replyText(events)).toBe("answered late words");
+ expect(of(events, "thread.token-usage.updated")).toEqual([expect.objectContaining({ input: 20, output: 7 })]);
+ });
+
+ it("says what Grok said when it ended the prompt on an error", async () => {
+ const { ask } = await start({ FAKE_ACP_MODE: "grok-complete", FAKE_ACP_COMPLETE_REPLY: "never", FAKE_ACP_COMPLETE_STOP: "error",
+ FAKE_ACP_COMPLETE_RESULT: "API error (status 400 Bad Request): invalid_request_error: the request was malformed" });
+ const events = await ask();
+ expect(of(events, "turn.completed")).toEqual([expect.objectContaining({ ok: false })]);
+ expect(of(events, "runtime.error").map((event) => event.message).join("\n")).toContain("the request was malformed");
+ });
+});
+
+describe("Grok's rate-limit stop", () => {
+ const usageLimit = (events: RuntimeEvent[]) => {
+ expect(of(events, "turn.completed")).toEqual([expect.objectContaining({ ok: false, stopReason: "quota" })]);
+ const [error] = of(events, "runtime.error");
+ expect(error).toMatchObject({ limit: "engine" });
+ expect(error!.message).toMatch(/^This Grok account has reached its usage limit/);
+ };
+
+ it("is the account's usage limit, so another AI can carry on: from the notification, the error reply or the reply's own stop", async () => {
+ usageLimit(await (await start({ FAKE_ACP_MODE: "grok-complete", FAKE_ACP_COMPLETE_STOP: "rate_limit", FAKE_ACP_COMPLETE_REPLY: "never" })).ask());
+ usageLimit(await (await start({ FAKE_ACP_MODE: "grok-complete", FAKE_ACP_COMPLETE_STOP: "rate_limit", FAKE_ACP_COMPLETE_REPLY: "rate-limit-error" })).ask());
+ usageLimit(await (await start({ FAKE_ACP_MODE: "grok-complete", FAKE_ACP_COMPLETE_STOP: "rate_limit", FAKE_ACP_COMPLETE_REPLY: "after" })).ask());
+ });
+
+ it("keeps its own words when they name another cause, such as the service being down", async () => {
+ const events = await (await start({ FAKE_ACP_MODE: "grok-complete", FAKE_ACP_COMPLETE_STOP: "rate_limit", FAKE_ACP_COMPLETE_REPLY: "never",
+ FAKE_ACP_COMPLETE_RESULT: "API error (status 503 Service Unavailable): capacity" })).ask();
+ expect(of(events, "turn.completed")).toEqual([expect.objectContaining({ ok: false })]);
+ expect(of(events, "turn.completed")[0]!.stopReason).not.toBe("quota");
+ expect(of(events, "runtime.error")[0]).not.toHaveProperty("limit");
+ expect(of(events, "runtime.error")[0]!.message).toMatch(/^Grok had a temporary server problem/);
+ });
+});
+
+describe("what Grok is told at start and at Stop", () => {
+ it("tells Grok it is an extension client, and that a Stop is Ctrl+C", async () => {
+ const { instance, recorder, calls, initialize } = await start({ FAKE_ACP_MODE: "hang" });
+ const { turnId } = await instance.adapter.sendTurn({ threadId: "t-stop", text: "hi" });
+ await expect.poll(() => calls().some((call) => call.method === "session/prompt"), { timeout: 10_000 }).toBe(true);
+ await instance.adapter.interruptTurn("t-stop", turnId);
+ await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);
+ expect(initialize()._meta).toEqual({ clientType: "extension" });
+ expect(calls().find((call) => call.method === "session/cancel")?.meta).toEqual({ cancelTrigger: "ctrl_c" });
+ });
+
+ it("tells no other ACP agent any of it", async () => {
+ const { instance, recorder, calls, initialize } = await start({ FAKE_ACP_MODE: "hang" }, "custom");
+ const { turnId } = await instance.adapter.sendTurn({ threadId: "t-other", text: "hi" });
+ await expect.poll(() => calls().some((call) => call.method === "session/prompt"), { timeout: 10_000 }).toBe(true);
+ await instance.adapter.interruptTurn("t-other", turnId);
+ await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);
+ expect(initialize()).not.toHaveProperty("_meta");
+ expect(calls().find((call) => call.method === "session/prompt")).not.toHaveProperty("meta");
+ expect(calls().find((call) => call.method === "session/cancel")).not.toHaveProperty("meta");
+ });
+});
+
+describe("a Grok that could not start its threads", () => {
+ it("is the server's refused spawn: the budget hears EAGAIN, and the turn says there was no room, never the runtime's words", async () => {
+ const before = processBudget.counts().spawnFailed.EAGAIN;
+ const { ask } = await start({ FAKE_ACP_START_FAILURE: TOKIO });
+ const events = await ask();
+ expect(processBudget.counts().spawnFailed.EAGAIN).toBe(before + 1);
+ expect(of(events, "turn.completed")).toEqual([expect.objectContaining({ ok: false })]);
+ const [error] = of(events, "runtime.error");
+ expect(outOfProcesses(error!.message)).toBe(true);
+ expect(error!.message).toMatch(/^There is no room to start another program \(EAGAIN\)/);
+ expect(JSON.stringify(events)).not.toContain("tokio");
+ });
+
+ it("keeps another early exit's own words", async () => {
+ const before = processBudget.counts().spawnFailed.EAGAIN;
+ const { ask } = await start({ FAKE_ACP_START_FAILURE: "grok: config.toml: unexpected key" });
+ const [error] = of(await ask(), "runtime.error");
+ expect(processBudget.counts().spawnFailed.EAGAIN).toBe(before);
+ expect(error!.message).toContain("unexpected key");
+ });
+});
diff --git a/server/drivers/acp/grok-signals.ts b/server/drivers/acp/grok-signals.ts
new file mode 100644
index 0000000000..1da70d9764
--- /dev/null
+++ b/server/drivers/acp/grok-signals.ts
@@ -0,0 +1,56 @@
+// What Grok reads and says beside ACP itself: who its client is, how a turn was stopped, and how a prompt ended.
+import { engineFailure, engineFailureKind } from "../engine-errors.ts";
+import type { AcpPromptCompletion } from "./driver-hooks.ts";
+import { AcpReportedFailure } from "./failure-words.ts";
+
+/** Grok reads `clientType` from initialize's `_meta` (grok 1.0.25 knows "generic", "extension" and its own clients). For a
+ * "generic" client its Auto mode denies what its classifier refuses without asking; for "extension" it asks with a
+ * permission request. */
+export const GROK_INITIALIZE_META = { clientType: "extension" } as const;
+
+/** Grok reads the stop gesture from session/cancel's `_meta.cancelTrigger` (grok 1.0.25: its own terminal sends "ctrl_c",
+ * "mouse" or "dashboard_stop"). "ctrl_c" also keeps background work from waking a turn before the next prompt. */
+export const GROK_CANCEL_META = { cancelTrigger: "ctrl_c" } as const;
+
+/** Grok's JSON-RPC error code for a session/prompt it ended on a rate limit. */
+const GROK_RATE_LIMITED = -32003;
+
+const PROMPT_COMPLETE = new Set(["_x.ai/session/prompt_complete", "x.ai/session/prompt_complete"]);
+
+const text = (value: unknown): string | null => typeof value === "string" && value.trim() ? value : null;
+
+/** grok 1.0.41 ends each prompt with `_x.ai/session/prompt_complete` {sessionId, promptId, stopReason, agentResult} just
+ * before its session/prompt reply, and names the prompt by the `promptId` that prompt's `_meta` gave it. A background task's
+ * finish ends a prompt of its own, under a `task-completed-…` id no session/prompt of ours has. */
+export const GROK_PROMPT_COMPLETION: AcpPromptCompletion = {
+ meta: (promptId) => ({ promptId, requestId: promptId }),
+ read(msg) {
+ if (typeof msg.method !== "string" || !PROMPT_COMPLETE.has(msg.method)) return null;
+ const params = msg.params as { sessionId?: unknown; promptId?: unknown; stopReason?: unknown; agentResult?: unknown } | null;
+ const sessionId = text(params?.sessionId);
+ if (!sessionId) return null;
+ const stopReason = text(params?.stopReason) ?? "end_turn", error = text(params?.agentResult);
+ return { sessionId, promptId: text(params?.promptId), result: { stopReason, ...(error && stopReason !== "end_turn" ? { error } : {}) } };
+ },
+};
+
+/** A prompt Grok ended for a rate limit, after its own retries: the account's usage limit, unless its words name another
+ * cause (a server error, an overload, no credit), which then keeps its own words. */
+function grokLimitFailure(said: string): AcpReportedFailure | undefined {
+ const kind = engineFailureKind(said);
+ if (kind !== null && kind !== "usage_limit" && kind !== "rate_limit") return undefined;
+ return new AcpReportedFailure(engineFailure("Grok", said, { kind: "usage_limit", status: null })!, true);
+}
+
+/** The prompt's answer, its own or the one its notification gave. */
+export async function grokPromptOutcome(): Promise<(result: unknown) => Promise<Error | undefined>> {
+ return async (result) => {
+ const answer = result as { stopReason?: unknown; error?: unknown } | null;
+ return answer?.stopReason === "rate_limit" ? grokLimitFailure(text(answer.error) ?? "") : undefined;
+ };
+}
+
+export function grokReportedFailure(error: unknown): Error | undefined {
+ if ((error as { code?: unknown } | null)?.code !== GROK_RATE_LIMITED) return undefined;
+ return grokLimitFailure(error instanceof Error ? error.message : "");
+}
diff --git a/server/drivers/acp/grok.ts b/server/drivers/acp/grok.ts
index 38a6505807..5d0a1ef1be 100644
--- a/server/drivers/acp/grok.ts
+++ b/server/drivers/acp/grok.ts
@@ -12,6 +12,7 @@ import { decodeInjectId, hostApiKey, localHost, mergeLocalInject } from "../loca
import { createAcpDriver, type AcpSupport } from "./core.ts";
import { closeEndsBackgroundWork } from "./background-work.ts";
import { readGrokFollowUp } from "./grok-follow-up.ts";
+import { GROK_CANCEL_META, GROK_INITIALIZE_META, GROK_PROMPT_COMPLETION, grokPromptOutcome, grokReportedFailure } from "./grok-signals.ts";
import type { AcpPromptSteer } from "./steer.ts";
import { bundledEngineCatalog } from "../../model-manifest/bundled.ts";
import { currentEngineCatalog } from "../../model-manifest/manifest.ts";
@@ -455,6 +456,11 @@ const support: AcpSupport = {
deviceSignIn: GROK_DEVICE_SIGN_IN,
steer: GROK_STEER,
backgroundWork: GROK_BACKGROUND,
+ initializeMeta: GROK_INITIALIZE_META,
+ cancelMeta: GROK_CANCEL_META,
+ promptCompletion: GROK_PROMPT_COMPLETION,
+ promptOutcome: grokPromptOutcome,
+ reportedFailure: grokReportedFailure,
// With the instance HOME/GROK_HOME: ensureGrokInjectSlug defaults to process.env.
resolveTurnModel: (model, env) => (model ? ensureGrokInjectSlug(model, env) : model),
diff --git a/server/drivers/acp/host.ts b/server/drivers/acp/host.ts
index 730a67bdb7..19a76846ab 100644
--- a/server/drivers/acp/host.ts
+++ b/server/drivers/acp/host.ts
@@ -5,10 +5,19 @@ import type { ChildProcessWithoutNullStreams } from "node:child_process";
import { engineMemory } from "../../engine-memory.ts";
import { engineOwners } from "../../engine-owners.ts";
+import { threadsRefused } from "../../host-fault.ts";
+import { processBudget } from "../../process-room.ts";
import { appendNative } from "../native.ts";
+import type { AcpPromptCompletion } from "./driver-hooks.ts";
import { StderrTail } from "./exit-report.ts";
import { acpRpcError } from "./rpc-error.ts";
+/** How long a prompt the agent's own notification ended still waits for its session/prompt reply, which carries the
+ * prompt's token usage and, in recorded traffic, follows the notification at once. */
+const REPLY_AFTER_END_MS = 2_000;
+/** A stderr line longer than this is not the short line a refused thread start writes. */
+const STDERR_LINE_CHARS = 4096;
+
/** A catalog can contain credential-bearing native configuration, including late replies. */
export function acpNativeIncomingLogMessage(message: any, privateResponses: ReadonlySet<number>): unknown {
if (!privateResponses.has(message?.id)) return message;
@@ -50,6 +59,8 @@ interface Pending {
timer: ReturnType<typeof setTimeout> | null;
idleTimer: ReturnType<typeof setTimeout> | null;
armIdle: () => void;
+ /** A session/prompt: the id its `_meta` gave it and its session. */
+ prompt: { id: string; sessionId: unknown } | null;
}
export interface AcpHostOptions {
@@ -59,6 +70,7 @@ export interface AcpHostOptions {
logMessage(msg: any): unknown;
/** A request for a session no thread holds: it must still be answered or the agent blocks. */
unrouted(msg: any, send: (obj: unknown) => void): void;
+ promptCompletion?: AcpPromptCompletion;
}
export class AcpLink implements AcpConnection {
@@ -112,6 +124,9 @@ export class AcpHost {
authenticated = false;
/** The last stderr lines, masked, for the exit message. */
readonly stderrTail = new StderrTail();
+ /** Before its first message, the agent said it could not start its threads for want of room. */
+ startRefused = false;
+ #spoke = false;
dead = false;
/** Takes no new sessions; it ends when its last one closes. */
draining = false;
@@ -154,22 +169,39 @@ export class AcpHost {
} catch {
continue;
}
+ this.#spoke = true;
this.#receive(msg);
}
});
child.stderr.setEncoding("utf8");
- child.stderr.on("data", (chunk: string) => this.stderrTail.write(chunk));
+ let partial = "";
+ const watch = (lines: string[]) => { if (!this.startRefused && !this.#spoke && lines.some(threadsRefused)) this.#refuseStart(); };
+ child.stderr.on("data", (chunk: string) => {
+ this.stderrTail.write(chunk);
+ const lines = (partial + chunk).split("\n");
+ partial = (lines.pop() ?? "").slice(-STDERR_LINE_CHARS);
+ watch(lines);
+ });
child.on("error", (error) => {
this.dead = true;
for (const link of this.#listening()) link.inbound?.error(error);
});
child.on("close", (code, signal) => {
this.dead = true;
+ watch([partial]);
this.stderrTail.flush();
for (const link of this.#listening()) link.inbound?.exit(code, signal);
});
}
+ /** Counted as the refused spawn it is: the process budget learns the limit and holds new work, and each linked thread's
+ * turn ends as one the server had no room for. */
+ #refuseStart(): void {
+ this.startRefused = true;
+ processBudget.spawnFailed("EAGAIN");
+ for (const link of this.links) engineMemory.spawnRefused("EAGAIN", true, link.threadId);
+ }
+
/** Room for `threadId` in `folder`: alive, not draining, under `limit` sessions open and `lifetime` ever opened, and
* no other thread has had a session in that folder here. */
accepts(limit: number, lifetime: number, threadId: string, folder: string): boolean {
@@ -222,6 +254,9 @@ export class AcpHost {
return new Promise<any>((resolve, reject) => {
const id = this.#nextId++;
if (method === "_x.ai/mcp/list") this.#privateResponses.add(id);
+ const completion = method === "session/prompt" ? this.options.promptCompletion : undefined;
+ const prompt = completion ? { id: `omb-prompt-${id}`, sessionId: (params as { sessionId?: unknown } | null)?.sessionId } : null;
+ if (completion && prompt) params = { ...params as object, _meta: { ...(params as { _meta?: object } | null)?._meta, ...completion.meta(prompt.id) } };
let timer: ReturnType<typeof setTimeout> | null = null;
if (timeoutMs) {
timer = setTimeout(() => {
@@ -253,6 +288,7 @@ export class AcpHost {
timer,
get idleTimer() { return idleTimer; },
armIdle,
+ prompt,
});
this.write({ jsonrpc: "2.0", id, method, params }, link?.threadId ?? null);
});
@@ -285,6 +321,25 @@ export class AcpHost {
return only;
}
+ /** A notification that ends a prompt answers it, unless the prompt's own reply comes within REPLY_AFTER_END_MS. A
+ * notification that names no prompt ends one only when it is its session's one prompt out. */
+ #promptEnded(msg: any): void {
+ const ended = this.options.promptCompletion?.read(msg);
+ if (!ended) return;
+ const prompts = [...this.#pending].filter(([, pending]) => pending.prompt !== null && pending.prompt.sessionId === ended.sessionId
+ && (ended.promptId === null || pending.prompt.id === ended.promptId));
+ if (prompts.length !== 1) return;
+ const [id, pending] = prompts[0]!;
+ const timer = setTimeout(() => {
+ if (this.#pending.get(id) !== pending) return;
+ this.#pending.delete(id);
+ if (pending.timer) clearTimeout(pending.timer);
+ if (pending.idleTimer) clearTimeout(pending.idleTimer);
+ pending.resolve(ended.result);
+ }, REPLY_AFTER_END_MS);
+ timer.unref?.();
+ }
+
#receive(msg: any): void {
const link = this.#route(msg);
if (link) {
@@ -305,8 +360,9 @@ export class AcpHost {
} else if (msg.id !== undefined && msg.method) {
if (link?.inbound && !link.closed) link.inbound.request(msg);
else this.options.unrouted(msg, (obj) => this.write(obj, link?.threadId ?? null));
- } else if (msg.method && link && !link.closed) {
- link.inbound?.notification(msg);
+ } else if (msg.method) {
+ this.#promptEnded(msg);
+ if (link && !link.closed) link.inbound?.notification(msg);
}
}
}
diff --git a/server/engine-memory.ts b/server/engine-memory.ts
index 49b5b2c2df..332be6377e 100644
--- a/server/engine-memory.ts
+++ b/server/engine-memory.ts
@@ -10,7 +10,7 @@ import { newEventId, newId, TurnAuthenticationRefusedError, TurnNotStartedError,
import { readCgroupMemory } from "./process-limits.ts";
import { namesOwnCause, shortageCode, type ShortageCode } from "./process-shortage.ts";
import {
- BROWSER_TASKS, ENGINE_TASKS, gateHost, linuxTreeUse, processBudget, SESSION_TASKS, turnsSetting, turnsUnder, type GateHost, type ProcessBudget, type TreeUse,
+ BROWSER_TASKS, ENGINE_TASKS, engineTasks, gateHost, linuxTreeUse, processBudget, SESSION_TASKS, turnsSetting, turnsUnder, type GateHost, type ProcessBudget, type TreeUse,
type TurnsSetting,
} from "./process-room.ts";
@@ -217,7 +217,7 @@ export class EngineMemory {
private readonly engines = new Map<number, Engine>();
private readonly active = new Set<string>();
/** Threads admitted in the last RESERVE_MS: when, and what they were let in for. */
- private readonly reserved = new Map<string, { at: number; start: "process" | "session"; browser: boolean; browserSince?: number }>();
+ private readonly reserved = new Map<string, { at: number; start: "process" | "session"; tasks: number; browser: boolean; browserSince?: number }>();
private readonly queue: Waiter[] = [];
/** Threads whose engine was stopped for memory: how many tasks ran then, and whether their browser was running. */
private readonly stops = new Map<string, { count: number; browser: boolean }>();
@@ -384,9 +384,10 @@ export class EngineMemory {
expectFrame(threadId: string): void { if (this.enabled) this.expecting.add(threadId); }
/** A spawn the system refused. Every one is a sign of a shortage; an engine's own (`engine`) inside a thread's running
- * turn also fails that turn as one the server had no room for. */
- spawnRefused(code: string | undefined, engine = false): void {
- const threadId = this.context.getStore(), shortage = shortageCode({ code });
+ * turn also fails that turn as one the server had no room for. `threadId` is that turn's, read from the spawn's own
+ * context unless given. */
+ spawnRefused(code: string | undefined, engine = false, threadId = this.context.getStore()): void {
+ const shortage = shortageCode({ code });
if (!this.enabled || shortage === null) return;
this.lastRefusal = { at: this.now(), code: shortage };
if (engine && threadId !== undefined && this.active.has(threadId) && !this.starved.has(threadId)) this.starved.set(threadId, { code: shortage, why: "refused" });
@@ -490,9 +491,9 @@ export class EngineMemory {
/** Resolves once a new engine process, or a session in the running one `joining` names by pid, fits for this thread, or
* for `turn` once the plan's limit has a place for its turn; `notify` tells the person when it has to wait. False when
* aborted. A thread joining a process counts on it at once, so that process is never stopped as idle to make room for its
- * own new session. */
+ * own new session. `tasks`: what a new process of this engine holds against the pids limit. */
async admit(threadId: string, abort: AbortSignal, notify: (text: string) => void, start: "process" | "session" | "turn" = "process",
- joining?: number): Promise<boolean> {
+ joining?: number, tasks = ENGINE_TASKS): Promise<boolean> {
if (!this.enabled) return true;
if (joining !== undefined) this.engines.get(joining)?.threads.add(threadId);
const waiter: Waiter = { wake: () => {}, threadId, since: this.now() };
@@ -505,9 +506,9 @@ export class EngineMemory {
if (this.order()[0] === waiter && this.capped(threadId) === undefined) {
// Counted at once: another waiter woken with this one must see its place taken.
if (start === "turn") { this.active.add(threadId); return true; }
- const room = this.room(start, threadId);
+ const room = this.room(start, threadId, tasks);
if (room === "admit") {
- this.reserved.set(threadId, { at: this.now(), start, browser: this.browserStarts(threadId) });
+ this.reserved.set(threadId, { at: this.now(), start, tasks, browser: this.browserStarts(threadId) });
this.arm();
return true;
}
@@ -644,9 +645,9 @@ export class EngineMemory {
.sort((a, b) => a.startedAt - b.startedAt)[0] ?? null;
}
- private room(start: "process" | "session", threadId: string): "admit" | "wait" | Engine {
+ private room(start: "process" | "session", threadId: string, tasks: number): "admit" | "wait" | Engine {
const memory = this.read();
- if (!memory) return this.crowded(start, threadId, 0, false) ? this.idle() ?? (this.othersBusy(threadId) === 0 ? "admit" : "wait") : "admit";
+ if (!memory) return this.crowded(start, threadId, 0, false, tasks) ? this.idle() ?? (this.othersBusy(threadId) === 0 ? "admit" : "wait") : "admit";
const groups = this.groups(), at = this.now();
const live = [...this.engines.entries()].filter(([, engine]) => !engine.stopping);
const measured = live.filter(([, engine]) => at - engine.startedAt >= SETTLED_MS).map(([pid]) => groups.get(pid)).filter((bytes) => bytes !== undefined);
@@ -658,7 +659,7 @@ export class EngineMemory {
// An engine's processes are all there within seconds of its start, long before its memory settles.
const up = admitted.start === "process" && live.some(([, engine]) => engine.threads.has(threadId) && at - engine.startedAt >= TASKS_SETTLED_MS);
if (at - admitted.at < TASKS_RESERVE_MS && !up) {
- heldTasks += admitted.start === "session" ? SESSION_TASKS : ENGINE_TASKS;
+ heldTasks += admitted.start === "session" ? SESSION_TASKS : admitted.tasks;
heldBrowser ||= admitted.browser && this.browserStarts(threadId);
}
// A browser grows as it starts and loads its first pages: its share is held until it has run SETTLED_MS.
@@ -677,7 +678,7 @@ export class EngineMemory {
}
const newBrowser = this.browserStarts(threadId) && !heldBrowsers.has(this.browsers?.which?.(threadId) ?? threadId);
const need = (start === "session" ? SESSION_BYTES : process) + (newBrowser ? BROWSER_BYTES : 0);
- if (this.free(memory) - this.floor(memory) - held >= need && !this.crowded(start, threadId, heldTasks, heldBrowser)) return "admit";
+ if (this.free(memory) - this.floor(memory) - held >= need && !this.crowded(start, threadId, heldTasks, heldBrowser, tasks)) return "admit";
return this.idle() ?? (this.othersBusy(threadId) === 0 ? "admit" : "wait");
}
@@ -685,10 +686,10 @@ export class EngineMemory {
* call, not with its engine, and itself waits for room before it opens (browser-room.ts): room for one more
* is kept while any start pending may open one, rather than one for every such start, which would let one turn in at a
* time. Browsers already running count in the limit's own count. */
- private crowded(start: "process" | "session", threadId: string, heldTasks: number, heldBrowser: boolean): boolean {
+ private crowded(start: "process" | "session", threadId: string, heldTasks: number, heldBrowser: boolean, tasks: number): boolean {
if (!this.processes) return false;
const browser = heldBrowser || this.browserStarts(threadId) ? BROWSER_TASKS : 0;
- return this.processes.short((start === "session" ? SESSION_TASKS : ENGINE_TASKS) + browser, heldTasks);
+ return this.processes.short((start === "session" ? SESSION_TASKS : tasks) + browser, heldTasks);
}
private browserStarts(threadId: string): boolean { return this.browsers?.starts(threadId) === true; }
@@ -778,6 +779,7 @@ export function withEngineMemory(instance: ProviderInstance, memory: EngineMemor
const adapter = instance.adapter;
const listeners = new Set<RuntimeEventListener>();
const waiting = new Map<string, AbortController>();
+ const tasks = engineTasks(instance.driverKind);
const explained = new Set<string>();
const event = (threadId: string, fields: Record<string, unknown>) =>
({ eventId: newEventId(), provider: instance.driverKind, threadId, createdAt: new Date().toISOString(), ...fields }) as RuntimeEvent;
@@ -818,7 +820,7 @@ export function withEngineMemory(instance: ProviderInstance, memory: EngineMemor
try {
const admitted = await memory.admit(threadId, controller.signal, (message) => {
for (const listener of listeners) listener(event(threadId, { type: "runtime.notice", message }));
- }, start, joining);
+ }, start, joining, tasks);
if (!admitted) throw new TurnNotStartedError(newId(), "stopped while waiting for memory");
} finally {
if (waiting.get(threadId) === controller) waiting.delete(threadId);
diff --git a/server/host-fault.test.ts b/server/host-fault.test.ts
index fd815f6833..58dd6e905d 100644
--- a/server/host-fault.test.ts
+++ b/server/host-fault.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { hostFaultOf, retryCannotFix } from "./host-fault.ts";
+import { hostFaultOf, retryCannotFix, threadsRefused } from "./host-fault.ts";
describe("hostFaultOf", () => {
it.each([
@@ -30,6 +30,11 @@ describe("hostFaultOf", () => {
["unexpected status 401 Unauthorized: Missing bearer or basic authentication in header", "signed_out"],
["API error (status 401 Unauthorized): Invalid API key", "signed_out"],
["Not logged in · Please run /login", "signed_out"],
+ ["Grok exited 1 before the prompt result: Last output: grok: failed to start tokio runtime: blocking pool pre-warm stalled after 14 of 16 threads", "process_start"],
+ ["grok: failed to start tokio runtime: Resource temporarily unavailable (os error 11)", "process_start"],
+ ['thread \'main\' panicked at library/std/src/thread/mod.rs: failed to spawn thread: Os { code: 11, kind: WouldBlock, message: "Resource temporarily unavailable" }', "process_start"],
+ ["runtime/cgo: pthread_create failed: Resource temporarily unavailable", "process_start"],
+ ["runtime: failed to create new OS thread (have 12 already; errno=11)", "process_start"],
] as const)("%s is %s", (failure, fault) => {
expect(hostFaultOf(failure)).toBe(fault);
});
@@ -58,7 +63,19 @@ describe("hostFaultOf", () => {
"Forbidden-words scan: Claude is overloaded right now (HTTP 529).",
"Tool fetch_orders failed: the /orders endpoint returned 403 Forbidden",
"401 Unauthorized",
+ "read: Resource temporarily unavailable",
+ "failed to spawn thread for the git status worker",
+ "grok: failed to start tokio runtime: invalid configuration",
])("%s is not this server's fault", (failure) => {
expect(hostFaultOf(failure)).toBeNull();
});
});
+
+describe("threadsRefused", () => {
+ it("reads an engine's own line for threads it could not start, and only that", () => {
+ expect(threadsRefused("grok: failed to start tokio runtime: blocking pool pre-warm stalled after 14 of 16 threads")).toBe(true);
+ expect(threadsRefused('failed to spawn thread: Os { code: 11, kind: WouldBlock, message: "Resource temporarily unavailable" }')).toBe(true);
+ expect(threadsRefused("Resource temporarily unavailable")).toBe(false);
+ expect(threadsRefused("spawn grok EAGAIN")).toBe(false);
+ });
+});
diff --git a/server/host-fault.ts b/server/host-fault.ts
index 987dbaf098..af30df2b5b 100644
--- a/server/host-fault.ts
+++ b/server/host-fault.ts
@@ -10,10 +10,21 @@
export type HostFault = "process_start" | "out_of_room" | "disk_full" | "tool_server" | "signed_out" | "bot_memory";
const EXHAUSTED = String.raw`(?:EAGAIN|EMFILE|ENFILE)`;
+/** An engine that started but could not start its own threads, which counts against the same pids limit: grok 1.0.x's
+ * "grok: failed to start tokio runtime: blocking pool pre-warm stalled after 14 of 16 threads", Rust's "failed to spawn
+ * thread: Os { code: 11, kind: WouldBlock, … }", glibc's and Go's pthread_create or new-OS-thread failure with EAGAIN. */
+const THREAD_START = new RegExp(
+ String.raw`\bblocking pool pre-warm stalled\b` +
+ String.raw`|\b(?:failed to start tokio runtime|failed to (?:spawn|create) (?:a |new )?(?:OS )?thread|pthread_create)\b[^\n]*` +
+ String.raw`(?:\bresource temporarily unavailable\b|\bos error 11\b|\berrno=11\b|\bEAGAIN\b|\bWouldBlock\b)`, "i");
const PROCESS_START = new RegExp(
String.raw`\b(?:posix_)?spawn(?:Sync)?\b[^\n]*\b${EXHAUSTED}\b|\b${EXHAUSTED}\b[^\n]*\b(?:posix_)?spawn\b` +
String.raw`|\bfork\b[^\n]*\bresource temporarily unavailable\b|\btoo many open files\b` +
- String.raw`|^There is no room to start another program \(${EXHAUSTED}\)`, "i");
+ String.raw`|^There is no room to start another program \(${EXHAUSTED}\)|${THREAD_START.source}`, "i");
+
+/** Whether a line an engine wrote says it could not start its threads for want of room (the pids limit or RLIMIT_NPROC),
+ * as a refused spawn's EAGAIN does. */
+export const threadsRefused = (line: string): boolean => THREAD_START.test(line);
const OUT_OF_ROOM = new RegExp(
String.raw`\bENOMEM\b|\bcannot allocate memory\b|^There is no room to start another program \(ENOMEM\)` +
String.raw`|^Ran out of room, so I (?:closed the browser|stopped this task)\b|\bran out of memory\b|\bout of memory\b|\bOOM[- ]kill` +
diff --git a/server/process-room.test.ts b/server/process-room.test.ts
index 543499e10c..45c8f427a5 100644
--- a/server/process-room.test.ts
+++ b/server/process-room.test.ts
@@ -6,7 +6,7 @@ import { engineFailureKind } from "./drivers/engine-errors.ts";
import { classifyError } from "./drivers/retry.ts";
import { EngineMemory, FIRST_FRAME_MS, readHostMemory, withEngineMemory, type HostMemory } from "./engine-memory.ts";
import { containerLimited, readCgroupMemory, readPids, readProcessLimits } from "./process-limits.ts";
-import { BROWSER_NO_ROOM, BROWSER_TASKS, ENGINE_TASKS, gateHost, linuxTreeUse, margin, ProcessBudget, turnsSetting, turnsUnder, type TreeUse } from "./process-room.ts";
+import { BROWSER_NO_ROOM, BROWSER_TASKS, ENGINE_TASKS, engineTasks, gateHost, linuxTreeUse, margin, ProcessBudget, turnsSetting, turnsUnder, type TreeUse } from "./process-room.ts";
import { outOfProcesses, shortageCode } from "./process-shortage.ts";
import { describeSpawnFailure, linuxGroupOnlyExited } from "./procs.ts";
import { classifyRoutineFailure, recoverRun, ROUTINE_BUSY_WAIT_MS } from "./routine-recovery.ts";
@@ -170,6 +170,30 @@ describe("the pids budget", () => {
});
});
+describe("an engine's own size against the pids limit", () => {
+ it("counts Grok's runtime threads, a pre-warmed pool of 16 and a worker per CPU, beside every other engine's usual size", () => {
+ expect(engineTasks("grokAgent", 4)).toBe(ENGINE_TASKS + 16 + 4);
+ expect(engineTasks("grokAgent", 16)).toBe(ENGINE_TASKS + 32);
+ expect(engineTasks("codex", 16)).toBe(ENGINE_TASKS);
+ });
+
+ it("holds a Grok engine still starting at its own size, so fewer others start beside it", async () => {
+ // pids.max 256 keeps 32 back: 26 running, a Grok engine of 80 and one of 60 promised, and a third of 60 would pass 224.
+ const grok = server({ pids: 256, turns: 100 });
+ expect(await grok.memory.admit("grok", new AbortController().signal, () => {}, "process", undefined, engineTasks("grokAgent", 4))).toBe(true);
+ expect(await grok.memory.admit("a", new AbortController().signal, () => {})).toBe(true);
+ const stop = new AbortController(), notices: string[] = [];
+ const third = grok.memory.admit("b", stop.signal, (text) => notices.push(text));
+ await settle();
+ expect(notices).toHaveLength(1);
+ stop.abort();
+ expect(await third).toBe(false);
+
+ const generic = server({ pids: 256, turns: 100 });
+ for (const thread of ["first", "a", "b"]) expect(await generic.memory.admit(thread, new AbortController().signal, () => {})).toBe(true);
+ });
+});
+
describe("a spawn the system refused is the server's shortage, not the AI's failure", () => {
const refused = (code: string) => Object.assign(new Error(`spawn /usr/local/bin/claude ${code}`), { code });
diff --git a/server/process-room.ts b/server/process-room.ts
index 8dc3d9b207..fa6fd1d4d1 100644
--- a/server/process-room.ts
+++ b/server/process-room.ts
@@ -1,6 +1,7 @@
// A server in a container may hold only so many processes and threads (its cgroup's pids.max); past that every spawn
// fails with EAGAIN. The gate that holds turns for memory (engine-memory.ts) asks here whether one more engine fits.
import { readFileSync } from "node:fs";
+import { availableParallelism } from "node:os";
import { nameBucket, parseReapedChildrenMs, type ProcessRow } from "./perf/process-buckets.ts";
import { linuxProcessList } from "./perf/process-sampler.ts";
import { containerLimited, readPids } from "./process-limits.ts";
@@ -10,6 +11,14 @@ import type { ShortageCode } from "./process-shortage.ts";
* 6 processes with 44 threads (a scripted engine on Node 24, 2026-11-16); a real engine CLI and the commands it runs add
* to that. */
export const ENGINE_TASKS = 60;
+/** Grok's engine is a native binary whose async runtime pre-warms a blocking pool of 16 threads before it answers (the count
+ * grok 1.0.x names when that fails, "blocking pool pre-warm stalled after 14 of 16 threads") and runs a worker thread per
+ * CPU; counted on top of the generic estimate, not measured. */
+const GROK_RUNTIME_THREADS = 16;
+
+/** What one engine of `driverKind` holds against pids.max while it works. */
+export const engineTasks = (driverKind: string, cpus: number = availableParallelism()): number =>
+ driverKind === "grokAgent" ? ENGINE_TASKS + GROK_RUNTIME_THREADS + cpus : ENGINE_TASKS;
/** One more session in an engine process that is already running: its tool servers. */
export const SESSION_TASKS = 40;
/** One bot's browser: 13 processes with 163 threads (agent-browser 0.37.0 and Chromium 156 on one page, 2026-11-16). */
diff --git a/server/testing/fake-acp-cli.ts b/server/testing/fake-acp-cli.ts
index ea6285a25c..7c3fc01e46 100755
--- a/server/testing/fake-acp-cli.ts
+++ b/server/testing/fake-acp-cli.ts
@@ -101,12 +101,25 @@
// during a running one is injected into it and answers {stopReason:"cancelled", _meta:{completionKind:"removedFromQueue"}}
// at once; the running prompt then ends with end_turn and every steer it took.
// FAKE_ACP_STEERING=off the two steer modes above report no steering capability.
+// FAKE_ACP_MODE=grok-complete grok 1.0.41's `_x.ai/session/prompt_complete`: a prompt says "answered", then sends the
+// notification {sessionId, promptId: the prompt's _meta.promptId, stopReason: FAKE_ACP_COMPLETE_STOP (end_turn),
+// agentResult: FAKE_ACP_COMPLETE_RESULT (null)}, then answers per FAKE_ACP_COMPLETE_REPLY: "after" (default) at once
+// with that stopReason and usage, "never", "late" after FAKE_ACP_COMPLETE_REPLY_MS (3500) with "late words" and usage,
+// or "rate-limit-error" (JSON-RPC -32003). FAKE_ACP_COMPLETE_NAMES (own) lists the prompts the notifications name:
+// own, none (no promptId), task (a background task's task-completed-… id), other-session.
+// FAKE_ACP_START_FAILURE this line on stderr at startup, then exit 1 before reading anything, as grok 1.0.x does when it
+// cannot start its threads
import { AsyncLocalStorage } from "node:async_hooks";
import { spawn } from "node:child_process";
-import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
+import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
const mode = process.env.FAKE_ACP_MODE ?? "happy";
+if (process.env.FAKE_ACP_START_FAILURE) {
+ writeSync(2, `${process.env.FAKE_ACP_START_FAILURE}\n`);
+ process.exit(1);
+}
+
// The scripted replies every fake plays (FAKE_STREAM_SCRIPT, FAKE_STREAM_CADENCE); inlined, since tests copy this fake
// out of the repo.
type StreamStep = { say?: string; think?: string; tool?: string; fail?: string };
@@ -495,12 +508,12 @@ const resultAndConfigUpdates = (id: unknown, res: unknown, after: string, sessio
process.stdout.write([{ jsonrpc: "2.0", id, result: res }, ...updates].map((message) => JSON.stringify(message)).join("\n") + "\n");
};
const rpcMethods: string[] = [];
-const recordMethod = (method: string, sessionId?: unknown) => {
+const recordMethod = (method: string, sessionId?: unknown, meta?: unknown) => {
rpcMethods.push(method);
if (process.env.FAKE_ACP_RPC_DUMP) writeFileSync(process.env.FAKE_ACP_RPC_DUMP, JSON.stringify(rpcMethods));
if (process.env.FAKE_ACP_RPC_APPEND_FILE) {
try {
- appendFileSync(process.env.FAKE_ACP_RPC_APPEND_FILE, JSON.stringify({ pid: process.pid, method, cwd: process.cwd(), sessionId }) + "\n");
+ appendFileSync(process.env.FAKE_ACP_RPC_APPEND_FILE, JSON.stringify({ pid: process.pid, method, cwd: process.cwd(), sessionId, ...(meta === undefined ? {} : { meta }) }) + "\n");
} catch {}
}
};
@@ -773,6 +786,26 @@ let gatedTurn: { run: string; steers: string[]; pending: unknown[] } | null = nu
let gatedRuns = 0;
/** A prompt that says "working. " and waits for FAKE_ACP_GATE_FILE. devin-steer: a prompt during it joins the run and is
* answered with the first one, with the same usage and run id, as Devin does. opencode-steer: only `_session/steering` joins it. */
+function grokCompletePrompt(msg: any) {
+ const sessionId = msg.params?.sessionId, own = msg.params?._meta?.promptId, stopReason = process.env.FAKE_ACP_COMPLETE_STOP ?? "end_turn";
+ const say = (text: string) => out({ jsonrpc: "2.0", method: "session/update", params: { sessionId, update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } } } });
+ say("answered");
+ const named: Record<string, { sessionId: unknown; promptId?: unknown }> = {
+ own: { sessionId, promptId: own }, none: { sessionId }, task: { sessionId, promptId: "task-completed-00000000-0000-4000-8000-000000000002" },
+ "other-session": { sessionId: "another-session", promptId: own },
+ };
+ for (const name of (process.env.FAKE_ACP_COMPLETE_NAMES ?? "own").split(",")) {
+ out({ jsonrpc: "2.0", method: "_x.ai/session/prompt_complete", params: { ...named[name], stopReason, agentResult: process.env.FAKE_ACP_COMPLETE_RESULT ?? null } });
+ }
+ const usage = { sessionId, requestId: own, promptId: own, inputTokens: 20, outputTokens: 7 };
+ switch (process.env.FAKE_ACP_COMPLETE_REPLY ?? "after") {
+ case "after": result(msg.id, { stopReason, _meta: usage }); break;
+ case "never": hangKeepAlive = setInterval(() => {}, 1_000); break;
+ case "late": setTimeout(() => { say(" late words"); result(msg.id, { stopReason, _meta: usage }); }, Number(process.env.FAKE_ACP_COMPLETE_REPLY_MS ?? 3_500)); break;
+ case "rate-limit-error": out({ jsonrpc: "2.0", id: msg.id, error: { code: -32003, message: "Rate limited", data: { message: process.env.FAKE_ACP_COMPLETE_RESULT ?? "Rate limited" } } }); break;
+ }
+}
+
function gatedPrompt(msg: any) {
const text = (Array.isArray(msg.params?.prompt) ? msg.params.prompt : []).map((block: any) => block?.text ?? "").join("");
if (gatedTurn && mode === "grok-steer") {
@@ -896,7 +929,7 @@ function handle(msg: any) {
}
if (!msg.method) return;
if (msg.method === "session/prompt" && heldByHoldFile(msg)) return;
- recordMethod(msg.method, msg.params?.sessionId);
+ recordMethod(msg.method, msg.params?.sessionId, msg.params?._meta);
switch (msg.method) {
case "initialize": {
@@ -1199,6 +1232,10 @@ function handle(msg: any) {
gatedPrompt(msg);
return;
}
+ if (mode === "grok-complete") {
+ grokCompletePrompt(msg);
+ return;
+ }
if (process.env.FAKE_ACP_TOOL_LIMIT) {
const limit = Number(process.env.FAKE_ACP_TOOL_LIMIT);
const handshake = process.env.FAKE_ACP_MCP_HANDSHAKE ? JSON.parse(process.env.FAKE_ACP_MCP_HANDSHAKE) : GROK_MCP_HANDSHAKE;