Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(claude): show an MCP server's question as an approval card (#4255)
Aditya Umaleb95ff9015a41
diff --git a/server/drivers/claude-cost-history.ts b/server/drivers/claude-cost-history.tsnew file mode 100644index 0000000000..f79dde8887--- /dev/null+++ b/server/drivers/claude-cost-history.ts@@ -0,0 +1,39 @@+// Each Claude session's last few cost snapshots, so a resumed session's running total is split back into turns.+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { DATA_DIR } from "../config.ts";+import { writeFileAtomic } from "../atomic.ts";+import type { ClaudeCostSnapshot } from "./claude.ts";++const COST_HISTORY_FILE = join(DATA_DIR, "claude-cost-history.json");+const COST_HISTORY_SESSIONS = 100;+const COST_HISTORY_STATES = 8;++function isCostSnapshot(value: unknown): value is ClaudeCostSnapshot {+ if (!value || typeof value !== "object") return false;+ const { total, models } = value as { total?: unknown; models?: unknown };+ return typeof total === "number" && !!models && typeof models === "object" &&+ Object.values(models).every((counts) => Array.isArray(counts) && counts.length === 4 && counts.every((n) => typeof n === "number"));+}++export function readCostHistory(): Record<string, ClaudeCostSnapshot[]> {+ try {+ const parsed: unknown = JSON.parse(readFileSync(COST_HISTORY_FILE, "utf8"));+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};+ return Object.fromEntries(Object.entries(parsed).map(([id, states]) => [id, Array.isArray(states) ? states.filter(isCostSnapshot) : []]));+ } catch {+ return {};+ }+}++export function recordCostState(sessionId: string, state: ClaudeCostSnapshot): void {+ const history = readCostHistory();+ const states = [...(history[sessionId] ?? []), state].slice(-COST_HISTORY_STATES);+ delete history[sessionId];+ history[sessionId] = states;+ const ids = Object.keys(history);+ for (const id of ids.slice(0, Math.max(0, ids.length - COST_HISTORY_SESSIONS))) delete history[id];+ try {+ writeFileAtomic(COST_HISTORY_FILE, JSON.stringify(history), { mode: 0o600, durable: false });+ } catch {}+}diff --git a/server/drivers/claude-elicitation.test.ts b/server/drivers/claude-elicitation.test.tsnew file mode 100644index 0000000000..0d89dee539--- /dev/null+++ b/server/drivers/claude-elicitation.test.ts@@ -0,0 +1,132 @@+import { describe, expect, it } from "vitest";+import { claudeElicitations } from "./claude-elicitation.ts";++function harness(delivered = true) {+ const written: any[] = [];+ const events: any[] = [];+ const elicit = claudeElicitations(async (frame) => { written.push(frame); return delivered; }, (event) => events.push(event));+ return { elicit, written, events };+}++const ask = (id: string, request: Record<string, unknown> = {}) => ({+ type: "control_request",+ request_id: id,+ request: { subtype: "elicitation", mcp_server_name: "github", message: "Allow access to your repos?", mode: "form", requested_schema: { type: "object", properties: {} }, ...request },+});+const sent = (id: string, response: unknown) => ({ type: "control_response", response: { subtype: "success", request_id: id, response } });+const done = (id: string, behavior: string, source: string) => ({ type: "request.resolved", requestId: `elicitation:${id}`, behavior, source });++describe("claudeElicitations", () => {+ it("turns a plain confirmation into an approval card and accepts it", async () => {+ const { elicit, written, events } = harness();+ expect(elicit.frame(ask("e1"))).toBe(true);+ expect(written).toEqual([]);+ expect(events).toEqual([{+ type: "request.opened",+ requestId: "elicitation:e1",+ requestType: "permission",+ tool: "mcp__github",+ summary: "github: Allow access to your repos?",+ requiresExplicitApproval: true,+ }]);+ await expect(elicit.answer("elicitation:e1", "allow")).resolves.toBe("sent");+ expect(written).toEqual([sent("e1", { action: "accept", content: {} })]);+ expect(events.at(-1)).toEqual(done("e1", "allow", "user"));+ await expect(elicit.answer("elicitation:e1", "allow")).resolves.toBe(false);+ });++ it("declines when the person declines", async () => {+ const { elicit, written, events } = harness();+ elicit.frame(ask("e2"));+ await expect(elicit.answer("elicitation:e2", "deny")).resolves.toBe("sent");+ expect(written).toEqual([sent("e2", { action: "decline" })]);+ expect(events.at(-1)).toEqual(done("e2", "deny", "user"));+ });++ it("withdraws the card when the CLI cancels the question", async () => {+ const { elicit, written, events } = harness();+ elicit.frame(ask("e3"));+ expect(elicit.frame({ type: "control_cancel_request", request_id: "e3" })).toBe(true);+ expect(events.at(-1)).toEqual(done("e3", "deny", "timeout"));+ await expect(elicit.answer("elicitation:e3", "allow")).resolves.toBe(false);+ expect(written).toEqual([]);+ expect(elicit.frame({ type: "control_cancel_request", request_id: "other" })).toBe(false);+ });++ it("declines a form with fields at once and says why", async () => {+ const { elicit, written, events } = harness();+ expect(elicit.frame(ask("e4", { requested_schema: { type: "object", properties: { token: { type: "string" } } } }))).toBe(true);+ expect(written).toEqual([sent("e4", { action: "decline" })]);+ expect(events).toEqual([{ type: "runtime.notice", message: expect.stringContaining("github asked you to fill in a field") }]);+ });++ it("declines a form whose required fields are not listed as properties", async () => {+ const { elicit, written, events } = harness();+ expect(elicit.frame(ask("e4b", { requested_schema: { type: "object", properties: {}, required: ["token"] } }))).toBe(true);+ expect(written).toEqual([sent("e4b", { action: "decline" })]);+ expect(events).toEqual([{ type: "runtime.notice", message: expect.stringContaining("github asked you to fill in a field") }]);+ });++ it("declines a link request and passes on only a web link", async () => {+ const { elicit, written, events } = harness();+ elicit.frame(ask("e5", { mode: "url", url: "https://example.com/auth" }));+ elicit.frame(ask("e6", { mode: "url", url: "javascript:alert(1)" }));+ elicit.frame(ask("e6b", { mode: "url", url: "http://example.com/auth" }));+ expect(written).toEqual([sent("e5", { action: "decline" }), sent("e6", { action: "decline" }), sent("e6b", { action: "decline" })]);+ expect(events[0].message).toContain(": https://example.com/auth.");+ expect(events[1].message).not.toContain("javascript:");+ expect(events[2].message).not.toContain("http://");+ });++ it("withdraws every open card when the session closes", async () => {+ const { elicit, events } = harness();+ elicit.frame(ask("a"));+ elicit.frame(ask("b"));+ elicit.close();+ expect(events.slice(-2)).toEqual([done("a", "deny", "system"), done("b", "deny", "system")]);+ await expect(elicit.answer("elicitation:a", "allow")).resolves.toBe(false);+ });++ it("withdraws the card instead of showing it approved when the answer can't reach the CLI", async () => {+ const { elicit, written, events } = harness(false);+ elicit.frame(ask("e7"));+ await expect(elicit.answer("elicitation:e7", "allow")).resolves.toBe("failed");+ expect(written).toEqual([sent("e7", { action: "accept", content: {} })]);+ expect(events.at(-1)).toEqual(done("e7", "deny", "system"));+ await expect(elicit.answer("elicitation:e7", "allow")).resolves.toBe(false);+ });++ it("withdraws a card whose answer was still on its way when the session closed", async () => {+ let deliver!: (ok: boolean) => void;+ const events: any[] = [];+ const elicit = claudeElicitations(() => new Promise<boolean>((resolve) => { deliver = resolve; }), (event) => events.push(event));+ elicit.frame(ask("e8"));+ const answered = elicit.answer("elicitation:e8", "allow");+ elicit.close();+ expect(events.filter((e) => e.type === "request.resolved")).toEqual([done("e8", "deny", "system")]);+ deliver(true);+ await expect(answered).resolves.toBe("failed");+ expect(events.filter((e) => e.type === "request.resolved")).toEqual([done("e8", "deny", "system")]);+ });++ it("withdraws a card the CLI cancels while its answer is still on its way", async () => {+ let deliver!: (ok: boolean) => void;+ const events: any[] = [];+ const elicit = claudeElicitations(() => new Promise<boolean>((resolve) => { deliver = resolve; }), (event) => events.push(event));+ elicit.frame(ask("e9"));+ const answered = elicit.answer("elicitation:e9", "allow");+ expect(elicit.frame({ type: "control_cancel_request", request_id: "e9" })).toBe(true);+ expect(events.filter((e) => e.type === "request.resolved")).toEqual([done("e9", "deny", "timeout")]);+ elicit.close();+ deliver(true);+ await expect(answered).resolves.toBe("failed");+ expect(events.filter((e) => e.type === "request.resolved")).toEqual([done("e9", "deny", "timeout")]);+ });++ it("leaves other frames and cards alone", async () => {+ const { elicit } = harness();+ expect(elicit.frame({ type: "control_request", request_id: "x", request: { subtype: "can_use_tool" } })).toBe(false);+ expect(elicit.frame({ type: "assistant" })).toBe(false);+ await expect(elicit.answer("tool-123", "allow")).resolves.toBe(false);+ });+});diff --git a/server/drivers/claude-elicitation.ts b/server/drivers/claude-elicitation.tsnew file mode 100644index 0000000000..d8da6fe1ad--- /dev/null+++ b/server/drivers/claude-elicitation.ts@@ -0,0 +1,105 @@+// MCP elicitation through Claude Code's stream-json control protocol (2.1.317). When an MCP server asks the+// person something during a tool call, the CLI writes {type:"control_request", request:{subtype:"elicitation"}}+// and waits for a control_response on stdin; a control_cancel_request withdraws the question (the server gave up).+// Unanswered, the tool call failed "No response to elicitation prompt within the allowed time". A plain confirmation+// becomes an approval card; a form with fields or a link to open is declined at once with a note in the chat.+import type { RuntimeEvent } from "../../shared/runtime-events.ts";++type Body<T> = T extends unknown ? Omit<T, "threadId" | "turnId" | "provider" | "providerInstanceId" | "createdAt" | "eventId"> : never;+type ElicitationEvent = Body<Extract<RuntimeEvent, { type: "request.opened" | "request.resolved" | "runtime.notice" }>>;++const CARD_PREFIX = "elicitation:";+const text = (value: unknown) => (typeof value === "string" ? value.trim() : "");++/** `write` settles true once the frame reached the CLI's stdin, false when it could not be sent. */+export function claudeElicitations(write: (frame: unknown) => Promise<boolean>, emit: (event: ElicitationEvent) => void) {+ const pending = new Set<string>();+ // Answers still being written to the CLI; true once the card was withdrawn meanwhile.+ const sending = new Map<string, boolean>();+ const reply = (id: string, response: Record<string, unknown>) =>+ write({ type: "control_response", response: { subtype: "success", request_id: id, response } });+ const resolved = (id: string, behavior: "allow" | "deny", source: "user" | "timeout" | "system") =>+ emit({ type: "request.resolved", requestId: CARD_PREFIX + id, behavior, source });+ return {+ /** Consumes an elicitation frame or its withdrawal; false for every other frame. */+ frame(o: any): boolean {+ if (o?.type === "control_cancel_request") {+ if (typeof o.request_id !== "string") return false;+ if (sending.has(o.request_id)) {+ if (!sending.get(o.request_id)) resolved(o.request_id, "deny", "timeout");+ sending.set(o.request_id, true);+ return true;+ }+ if (!pending.delete(o.request_id)) return false;+ resolved(o.request_id, "deny", "timeout");+ return true;+ }+ if (o?.type !== "control_request" || o.request?.subtype !== "elicitation" || typeof o.request_id !== "string") return false;+ const id: string = o.request_id;+ const r = o.request;+ const serverName = text(r.mcp_server_name);+ const server = text(r.display_name) || serverName || "An MCP server";+ const message = text(r.message);+ const properties = r.requested_schema?.properties;+ const required = r.requested_schema?.required;+ // A required name with no declared property still needs a value the card can't collect.+ const fields = new Set([+ ...(properties && typeof properties === "object" ? Object.keys(properties) : []),+ ...(Array.isArray(required) ? required.filter((name: unknown) => typeof name === "string") : []),+ ]).size;+ if (r.mode === "url" || fields > 0) {+ void reply(id, { action: "decline" });+ const url = text(r.url);+ emit({+ type: "runtime.notice",+ message: r.mode === "url"+ ? `${server} asked you to open a link to continue${/^https:\/\//i.test(url) ? `: ${url}` : ""}. OpenMausBot can't open it from here, so the request was declined. Open the link yourself, then ask the bot to try again.`+ : `${server} asked you to fill in ${fields === 1 ? "a field" : `${fields} fields`}${message ? ` ("${message}")` : ""}. OpenMausBot can't show that form yet, so the request was declined.`,+ });+ return true;+ }+ pending.add(id);+ emit({+ type: "request.opened",+ requestId: CARD_PREFIX + id,+ requestType: "permission",+ tool: serverName ? `mcp__${serverName}` : "mcp",+ summary: message ? `${server}: ${message}` : `${server} asks to continue`,+ // The server asks, not a tool: Auto mode and remembered tool grants never answer it.+ requiresExplicitApproval: true,+ });+ return true;+ },+ /**+ * The person's answer to one of these cards: "sent" once the CLI has it, "failed" when it could not be+ * delivered (the card is withdrawn, never shown as approved), false when the card is not an open elicitation.+ */+ async answer(requestId: string, behavior: "allow" | "deny" | "answer"): Promise<"sent" | "failed" | false> {+ const id = requestId.startsWith(CARD_PREFIX) ? requestId.slice(CARD_PREFIX.length) : "";+ if (!pending.delete(id)) return false;+ sending.set(id, false);+ const delivered = await reply(id, behavior === "allow" ? { action: "accept", content: {} } : { action: "decline" });+ const cancelled = sending.get(id);+ sending.delete(id);+ // The card was withdrawn (CLI cancelled, session closed) while the answer was on its way: it never counts.+ if (cancelled) return "failed";+ if (!delivered) {+ resolved(id, "deny", "system");+ return "failed";+ }+ resolved(id, behavior === "allow" ? "allow" : "deny", "user");+ return "sent";+ },+ /** The CLI that asked is gone: every open card is withdrawn. */+ close(): void {+ for (const id of pending) resolved(id, "deny", "system");+ pending.clear();+ // Answers still on their way are withdrawn now too; answer() then reports them as failed.+ for (const [id, withdrawn] of sending) {+ if (withdrawn) continue;+ resolved(id, "deny", "system");+ sending.set(id, true);+ }+ },+ };+}diff --git a/server/drivers/claude.test.ts b/server/drivers/claude.test.tsindex e4c6b8b92a..d33d86e712 100644--- a/server/drivers/claude.test.ts+++ b/server/drivers/claude.test.ts@@ -1100,6 +1100,35 @@ describe("ClaudeDriver turns (fake CLI)", () => {await recorder.until((e) => e.type === "turn.completed");});+ it("shows an MCP server's question as an approval card and answers it on stdin", async () => {+ const log = join(scratch, "control.ndjson");+ await create("hang", {+ FAKE_CLAUDE_ELICIT: JSON.stringify({ mcp_server_name: "github", message: "Allow access to your repos?", mode: "form", requested_schema: { type: "object", properties: {} } }),+ FAKE_CLAUDE_CONTROL_LOG: log,+ });+ await instance.adapter.sendTurn({ threadId: "t-elicit", text: "go" });+ const opened = await recorder.until((e) => e.type === "request.opened");+ expect(opened).toMatchObject({ requestId: "elicitation:elicit-1", requestType: "permission", tool: "mcp__github", summary: "github: Allow access to your repos?", requiresExplicitApproval: true });+ await expect(instance.adapter.respondToRequest("t-elicit", "elicitation:elicit-1", { behavior: "allow" })).resolves.toBe("allowed-once");+ await vi.waitFor(() => expect(existsSync(log)).toBe(true));+ expect(JSON.parse(readFileSync(log, "utf8"))).toEqual({ type: "control_response", response: { subtype: "success", request_id: "elicit-1", response: { action: "accept", content: {} } } });+ await recorder.until((e) => e.type === "request.resolved" && e.requestId === "elicitation:elicit-1");+ await expect(instance.adapter.respondToRequest("t-elicit", "elicitation:elicit-1", { behavior: "allow" })).resolves.toBe("unavailable");+ await instance.adapter.interruptTurn("t-elicit");+ await recorder.until((e) => e.type === "turn.completed");+ });++ it("withdraws an MCP server's open question when the launch that asked it fails and is retried", async () => {+ process.env.FAKE_CLAUDE_TRANSIENTS = "1";+ process.env.FAKE_CLAUDE_STATE = join(scratch, "elicit-launches");+ process.env.FAKE_CLAUDE_RETRY_SCALE = "0.001";+ await create(undefined, { FAKE_CLAUDE_ELICIT: JSON.stringify({ mcp_server_name: "github", message: "Allow access?", mode: "form", requested_schema: { type: "object", properties: {} } }) });+ await instance.adapter.sendTurn({ threadId: "t-elicit-retry", text: "go" });+ await recorder.until((e) => e.type === "turn.completed" && e.ok === true);+ expect(recorder.events.filter((e) => e.type === "request.opened").map((e) => e.requestId)).toEqual(["elicitation:elicit-1"]);+ expect(recorder.events.find((e) => e.type === "request.resolved" && e.requestId === "elicitation:elicit-1")).toMatchObject({ behavior: "deny", source: "system" });+ });+it("sends attached images as native blocks before text without logging their bytes", async () => {await create();const dump = join(scratch, "dump-images.json");diff --git a/server/drivers/claude.ts b/server/drivers/claude.tsindex 4443c71ccd..8c58a11eb7 100644--- a/server/drivers/claude.ts+++ b/server/drivers/claude.ts@@ -8,7 +8,7 @@ import { join, dirname, isAbsolute, normalize } from "node:path";import { DATA_DIR, stripWorkspaceCredentialEnv } from "../config.ts";import { openStartupModelCatalog, unconfirmedModelCatalog, writeStartupModelCache } from "../startup-model-catalog.ts";-import { writeFileAtomic, writeFileAtomicIfChanged } from "../atomic.ts";+import { writeFileAtomicIfChanged } from "../atomic.ts";import { augmentedPath } from "../env-path.ts";import { brokerSocketPath, cliVersionReader, describeSpawnFailure, execCli, killCliTree, spawnCli } from "../procs.ts";import { claudeAuthStatus } from "./claude-auth-status.ts";@@ -18,6 +18,8 @@ import { claudeBilling, claudeCallUsage } from "./claude-billing.ts";import { claudeAuthFailure, claudeAuthRecovery } from "./claude-auth-recovery.ts";import { claudeModelExtras } from "./claude-model-extras.ts";import { claudeToolSearchSetting } from "./claude-tool-search.ts";+import { claudeElicitations } from "./claude-elicitation.ts";+import { readCostHistory, recordCostState } from "./claude-cost-history.ts";import { classifyResumeFailure, mayReplay, rebuiltSessionNotice, recoveryPromptFor } from "../resume-recovery.ts";import { ClaudeLoginController } from "./claude-login-auth.ts";@@ -709,39 +711,6 @@ export function restoredCostBase(return exact ?? inside;}-const COST_HISTORY_FILE = join(DATA_DIR, "claude-cost-history.json");-const COST_HISTORY_SESSIONS = 100;-const COST_HISTORY_STATES = 8;--function isCostSnapshot(value: unknown): value is ClaudeCostSnapshot {- if (!value || typeof value !== "object") return false;- const { total, models } = value as { total?: unknown; models?: unknown };- return typeof total === "number" && !!models && typeof models === "object" &&- Object.values(models).every((counts) => Array.isArray(counts) && counts.length === 4 && counts.every((n) => typeof n === "number"));-}--function readCostHistory(): Record<string, ClaudeCostSnapshot[]> {- try {- const parsed: unknown = JSON.parse(readFileSync(COST_HISTORY_FILE, "utf8"));- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};- return Object.fromEntries(Object.entries(parsed).map(([id, states]) => [id, Array.isArray(states) ? states.filter(isCostSnapshot) : []]));- } catch {- return {};- }-}--function recordCostState(sessionId: string, state: ClaudeCostSnapshot): void {- const history = readCostHistory();- const states = [...(history[sessionId] ?? []), state].slice(-COST_HISTORY_STATES);- delete history[sessionId];- history[sessionId] = states;- const ids = Object.keys(history);- for (const id of ids.slice(0, Math.max(0, ids.length - COST_HISTORY_SESSIONS))) delete history[id];- try {- writeFileAtomic(COST_HISTORY_FILE, JSON.stringify(history), { mode: 0o600, durable: false });- } catch {}-}-type ClaudeImage = NonNullable<SendTurnInput["images"]>[number];type ClaudeUserContent =| { type: "image"; source: { type: "base64"; media_type: ClaudeImage["mime"]; data: string } }@@ -873,6 +842,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {interface Session {child: ReturnType<typeof spawnCli>;broker?: Awaited<ReturnType<typeof createPermissionBroker>>;+ elicit: ReturnType<typeof claudeElicitations>;mcpConfigPath: string | null;systemPromptPath: string | null;argsKey: string;@@ -938,6 +908,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {const broker = s.broker;s.broker = undefined;broker?.close();+ s.elicit.close();appendNative(threadId, { dir: "out", source: "claude.session", msg: { close: why } });// stdin EOF is the CLI's exit signal; give it a moment, then insisttry {@@ -1381,6 +1352,13 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {closed: new Promise<void>((resolve) => { markClosed = resolve; }),child,broker,+ // A CLI that already exited needs no answer: the write is skipped, like writeUser's.+ elicit: claudeElicitations((frame) => new Promise<boolean>((resolve) => {+ const { stdin } = session.child;+ if (!stdin.writable || stdin.destroyed) return resolve(false);+ try { stdin.write(`${JSON.stringify(frame)}\n`, (err) => resolve(!err)); } catch { resolve(false); }+ }),+ (event) => emit({ ...base(threadId, session.turn?.turnId ?? turnId), ...event })),mcpConfigPath,systemPromptPath,argsKey,@@ -1468,6 +1446,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {authRecovery.frame(threadId, o, session.costTotal);// A replayed stdin message carries its images again: keep their bytes out of the log.appendNative(threadId, { dir: "in", source: "claude.sdk.message", msg: o?.type === "user" && o.isReplay === true && o.message ? diagnosticClaudeUserMessage(o) : o });+ if (session.elicit.frame(o)) return;if (session.turn?.continuationSilence && !(o.type === "system" && o.subtype === "init") && !(o.type === "user" && o.isReplay === true)) {clearTimeout(session.turn.continuationSilence);session.turn.continuationSilence = null;@@ -1763,6 +1742,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {session.broker = undefined;failedBroker?.pause();failedBroker?.close();+ session.elicit.close();if (session.mcpConfigPath) {try {rmSync(dirname(session.mcpConfigPath), { recursive: true, force: true });@@ -1842,6 +1822,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {});session.broker?.close();session.broker = undefined;+ session.elicit.close();if (session.mcpConfigPath) {try {rmSync(dirname(session.mcpConfigPath), { recursive: true, force: true });@@ -1883,6 +1864,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {}if (session.idleTimer) clearTimeout(session.idleTimer);session.broker?.close();+ session.elicit.close();if (session.mcpConfigPath) {try {rmSync(dirname(session.mcpConfigPath), { recursive: true, force: true });@@ -2085,6 +2067,9 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {steer,interruptTurn: async (threadId) => active.get(threadId)?.stop(),respondToRequest: async (threadId, requestId, decision) => {+ const elicited = await sessions.get(threadId)?.elicit.answer(requestId, decision.behavior);+ if (elicited === "failed") return "unavailable";+ if (elicited === "sent") return decision.behavior === "allow" ? "allowed-once" : "rejected";const broker = sessions.get(threadId)?.broker ?? active.get(threadId)?.broker;if (!broker) return "unavailable";const behavior = decision.behavior === "answer" ? "answer" : decision.behavior;diff --git a/server/drivers/codex.test.ts b/server/drivers/codex.test.tsindex 9fe548db79..b1161a50db 100644--- a/server/drivers/codex.test.ts+++ b/server/drivers/codex.test.ts@@ -2688,6 +2688,7 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)expect(recorder.events.some((event) => event.type === "request.opened")).toBe(false);expect(JSON.parse(readFileSync(dump, "utf8")).decision).toEqual({ action: "decline" });+ expect(recorder.events.find((event) => event.type === "runtime.notice")?.message).toBe("example asked for input OpenMausBot can't show yet, so the request was declined.");});it("grants Codex additional permissions with their native response shape", async () => {diff --git a/server/drivers/codex.ts b/server/drivers/codex.tsindex 475853cc21..7cd0e82789 100644--- a/server/drivers/codex.ts+++ b/server/drivers/codex.ts@@ -963,11 +963,11 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {const isPermission = legacy || isMcpPermission || isAdditionalPermission ||method === "item/commandExecution/requestApproval" ||method === "item/fileChange/requestApproval";- // An MCP elicitation asks for real input, not permission; unknown server requests fail closed- // instead of being accepted by Full access.+ // An MCP elicitation asks for real input, not permission; unknown server requests fail closed instead of being accepted by Full access.if (!isQuestion && !isPermission) {if (isMcpElicitation) {send({ jsonrpc: "2.0", id: msg.id, result: { action: "decline" } });+ emit({ ...base(threadId, turnId), type: "runtime.notice", message: `${boundedLabel(params.serverName) ?? "An MCP server"} asked for input OpenMausBot can't show yet, so the request was declined.` });} else {send({jsonrpc: "2.0",diff --git a/server/testing/fake-claude-cli.ts b/server/testing/fake-claude-cli.tsindex e0c66be61d..c22687c97e 100755--- a/server/testing/fake-claude-cli.ts+++ b/server/testing/fake-claude-cli.ts@@ -13,6 +13,9 @@// FAKE_CLAUDE_ANSWER_MODEL the `model` of its assistant frames, as when the CLI answers with another model than asked// FAKE_CLAUDE_RELEASE with hang: the turn ends normally once this file exists; a scripted call's `hold` ends then too// FAKE_CLAUDE_DUMP path for the latest turn's {argv, env, cwd, prompt, systemPrompt, mcpConfig}+// FAKE_CLAUDE_ELICIT JSON request body: a "hang" turn (or a failing FAKE_CLAUDE_TRANSIENTS launch) first asks it+// as control_request "elicit-1"+// FAKE_CLAUDE_CONTROL_LOG JSON-lines file every control_response the host writes is appended to// FAKE_CLAUDE_EXIT_AFTER_TURN 1: exit once the turn is answered, so later turns relaunch with --resume// FAKE_CLAUDE_AUTH_AFTER_TURN 1: from the second turn, answer as not-logged-in; FAKE_CLAUDE_AUTH_AFTER_WORK 1: not-logged-in// calls a tool first@@ -897,6 +900,8 @@ const playTurn = (prompt: JsonValue, late = false) => {if (process.env.FAKE_CLAUDE_PARTIAL_FAILS) {out({ type: "stream_event", event: { type: "content_block_delta", delta: { type: "text_delta", text: "half an answer" } } });}+ // an MCP server's question still open when the launch fails+ if (process.env.FAKE_CLAUDE_ELICIT) out({ type: "control_request", request_id: "elicit-1", request: { subtype: "elicitation", ...JSON.parse(process.env.FAKE_CLAUDE_ELICIT) } });process.stderr.write("claude: API error (503): service temporarily unavailable\n");process.exit(5);}@@ -961,6 +966,9 @@ const playTurn = (prompt: JsonValue, late = false) => {if (process.env.FAKE_CLAUDE_USES_CLOUD_COMPUTER === "1") useCloudComputer();if (mode === "hang") {+ if (process.env.FAKE_CLAUDE_ELICIT) {+ out({ type: "control_request", request_id: "elicit-1", request: { subtype: "elicitation", ...JSON.parse(process.env.FAKE_CLAUDE_ELICIT) } });+ }const release = process.env.FAKE_CLAUDE_RELEASE;const finishGate = process.env.FAKE_CLAUDE_FINISH_GATE;const held = setInterval(() => {@@ -1249,6 +1257,10 @@ process.stdin.on("data", (c) => {} catch {continue;}+ if ((prompt as { type?: unknown } | null)?.type === "control_response") {+ if (process.env.FAKE_CLAUDE_CONTROL_LOG) appendFileSync(process.env.FAKE_CLAUDE_CONTROL_LOG, `${line}\n`);+ continue;+ }if (turnRunning || lateTurnWaiting) {if (process.env.FAKE_CLAUDE_LATE_STEER_GATE) lateSteers.push(prompt);else {