Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
ACP: build the permission card from the call's earlier tool_call updates
RGB-loop6e082e4cb0f0
diff --git a/server/drivers/acp/acp.test.ts b/server/drivers/acp/acp.test.tsindex 8ee4504542..0881e9fb34 100644--- a/server/drivers/acp/acp.test.ts+++ b/server/drivers/acp/acp.test.ts@@ -311,6 +311,7 @@ describe("ACP turns (fake CLI)", () => {delete process.env.FAKE_ACP_ALLOW_ALWAYS;delete process.env.FAKE_ACP_PERMISSION_ANSWER;delete process.env.FAKE_ACP_PERMISSION_TOOL_CALL;+ delete process.env.FAKE_ACP_PERMISSION_PRIOR_UPDATES;delete process.env.FAKE_ACP_PERMISSION_OPTIONS;delete process.env.FAKE_ACP_QUESTION_OPTIONS;delete process.env.FAKE_ACP_ASK_METHOD;@@ -1674,6 +1675,65 @@ describe("ACP turns (fake CLI)", () => {await recorder.until((event) => event.type === "turn.completed");});+ const touch = { sessionUpdate: "tool_call", toolCallId: "call_1", title: "bash: touch marker", kind: "execute", status: "pending", rawInput: { command: "touch marker" } };+ const permissionCard = async (threadId: string, prior: unknown[], toolCall: unknown) => {+ process.env.FAKE_ACP_PERMISSION_PRIOR_UPDATES = JSON.stringify(prior);+ process.env.FAKE_ACP_PERMISSION_TOOL_CALL = JSON.stringify(toolCall);+ await create(GrokAgentDriver, "permission");+ const { turnId } = await instance.adapter.sendTurn({ threadId, text: "go", cwd: scratch });+ const opened = await recorder.until((event) => event.type === "request.opened" && event.turnId === turnId);+ await instance.adapter.respondToRequest(threadId, opened.requestId!, { behavior: "deny" });+ await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);+ return { turnId, opened };+ };++ it("shows the earlier tool_call on a permission request that names the call only by toolCallId", async () => {+ const { opened } = await permissionCard("t-acp-card-id-only", [touch], { toolCallId: "call_1" });+ expect(opened).toMatchObject({ requestType: "permission", tool: "shell", summary: "touch marker" });+ expect(opened).toHaveProperty("command", undefined);+ expect(opened).toHaveProperty("requiresExplicitApproval", undefined);+ });++ it("merges tool_call_update into the card, a null field keeping the earlier value", async () => {+ const { opened } = await permissionCard("t-acp-card-update", [+ { sessionUpdate: "tool_call", toolCallId: "call_1", title: "Bash", kind: "execute", status: "pending" },+ { sessionUpdate: "tool_call_update", toolCallId: "call_1", title: null, kind: null, rawInput: { command: "ls -la" } },+ ], { toolCallId: "call_1", title: "Bash" });+ expect(opened).toMatchObject({ tool: "shell", summary: "ls -la" });+ });++ it("lets the permission request's own fields win over the earlier tool_call", async () => {+ const { opened } = await permissionCard("t-acp-card-own-fields", [touch], { toolCallId: "call_1", kind: "edit", title: "write notes.md" });+ expect(opened).toMatchObject({ tool: "edit", summary: "touch marker" });+ const own = await permissionCard("t-acp-card-own-command", [touch], { toolCallId: "call_1", kind: "execute", rawInput: { command: "echo hi" } });+ expect(own.opened).toMatchObject({ tool: "shell", summary: "echo hi", command: { command: "echo hi", cwd: realpathSync(scratch) } });+ });++ it("leaves a permission request for an unknown toolCallId as it was", async () => {+ const { opened } = await permissionCard("t-acp-card-unknown", [touch], { toolCallId: "call_2" });+ expect(opened).toMatchObject({ tool: "tool", summary: "tool" });+ });++ it("never takes an MCP name or a command grant from an earlier tool_call", async () => {+ const mcp = { sessionUpdate: "tool_call", toolCallId: "call_1", title: "mcp__composio__gmail_send_email", kind: "other", status: "pending", rawInput: {} };+ const { opened } = await permissionCard("t-acp-card-mcp", [mcp], { toolCallId: "call_1" });+ expect(opened.type === "request.opened" && opened.tool.startsWith("mcp__")).toBe(false);+ const sandbox = { ...touch, rawInput: { command: "touch marker", sandbox_permissions: "require_escalated" } };+ const shell = await permissionCard("t-acp-card-sandbox", [sandbox], { toolCallId: "call_1", kind: "execute" });+ expect(shell.opened).toHaveProperty("command", undefined);+ expect(shell.opened).toHaveProperty("requiresExplicitApproval", undefined);+ });++ it("forgets a turn's tool calls when the next turn asks about the same toolCallId", async () => {+ const first = await permissionCard("t-acp-card-turns", [touch], { toolCallId: "call_1" });+ expect(first.opened).toMatchObject({ tool: "shell", summary: "touch marker" });+ const { turnId } = await instance.adapter.sendTurn({ threadId: "t-acp-card-turns", text: "again", cwd: scratch });+ const second = await recorder.until((event) => event.type === "request.opened" && event.turnId === turnId);+ expect(second).toMatchObject({ tool: "tool", summary: "tool" });+ await instance.adapter.respondToRequest("t-acp-card-turns", second.requestId!, { behavior: "deny" });+ await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);+ });+it.each([{ toolCallId: "call-1", justification: "Reason ".repeat(60), requestType: "permission" },{ toolCallId: "call-1", justification: 42, requestType: "permission" },diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.tsindex fd5f96424d..f52cfac2b5 100644--- a/server/drivers/acp/core.ts+++ b/server/drivers/acp/core.ts@@ -65,7 +65,7 @@ import { commandSummary, toolDetailPreview } from "../../tool-summary.ts";import { acpToolEndEvents } from "./tool-items.ts";import { AcpHost } from "./host.ts"; import { LiveSwitchRefused, SignInRequests, type AcpDriverHooks } from "./driver-hooks.ts";import { exitBeforeResult } from "./exit-report.ts"; import { readNodeVersion } from "./node-version.ts";-import { decodeAcpConfig } from "./config-decode.ts";+import { decodeAcpConfig } from "./config-decode.ts"; import { ToolCallDetails } from "./tool-call-details.ts";import { endTurn, receiveText, trackAssistantImage, trackAssistantWords, trackThoughtAfterTool, trackRunningTool, trackToolEndShown, type AcpAskFinish, type AcpSession, type AcpTurn } from "./turn-state.ts";import { recoveryPromptFor } from "../../resume-recovery.ts";import { noticeFailure } from "../../chat-notices.ts";@@ -589,7 +589,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>if (!allow) missing("allow");return send({ jsonrpc: "2.0", id: msg.id, result: allow ? { outcome: { outcome: "selected", optionId: allow } } : cancelled });}- const kind = String(toolCall.kind ?? "");+ const kind = String(toolCall.kind ?? ""), shown = current.toolDetails.merged(toolCall), shownKind = String(shown.kind ?? "");const operationKey = isQuestion || current.controlsHost ? null : acpSessionOperationKey(toolCall);if (operationKey && acpAnswersAlone(toolCall.rawInput) && sessionAllows.get(threadId)?.has(operationKey)) {const allow = optionFor("allow");@@ -598,10 +598,10 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>}}const mcpTitle = !isQuestion && !/^(?:execute|edit|delete|move)$/.test(kind) && typeof toolCall.title === "string" && /^mcp__[\w-]+__[\w.-]+$/.test(toolCall.title) ? toolCall.title : undefined; // an MCP call keeps its name, so a saved grant finds it- const tool = mcpTitle ?? (kind === "execute" ? "shell" : kind === "edit" ? "edit" : kind || "tool");+ const tool = mcpTitle ?? (shownKind === "execute" ? "shell" : shownKind === "edit" ? "edit" : shownKind || "tool");const isShellCommand = !isQuestion && kind === "execute" && !/^mcp(?:__|[.:])/i.test(String(toolCall.title ?? ""));- const rawSummary = String(toolCall.rawInput?.command ?? toolCall.title ?? tool);- const summary = rawSummary.slice(0, isQuestion ? MAX_QUESTION_TEXT : 200) + (!isQuestion && typeof toolCall.rawInput?.justification === "string" ? `\nReason: ${toolCall.rawInput.justification.slice(0, 300)}` : "");+ const rawSummary = String(shown.rawInput?.command ?? shown.title ?? tool);+ const summary = rawSummary.slice(0, isQuestion ? MAX_QUESTION_TEXT : 200) + (!isQuestion && typeof shown.rawInput?.justification === "string" ? `\nReason: ${shown.rawInput.justification.slice(0, 300)}` : "");const questionChoices = isQuestion? options.flatMap((option) => typeof option.name === "string" && option.name.trim() ? [option.name.trim()] : []): [];@@ -750,7 +750,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>}case "tool_call": {current.flushAssistantText();- trackRunningTool(current, u, "pending");+ trackRunningTool(current, u, "pending"); current.toolDetails.record(u);// ACP can send a tool_call already marked completed or failed (e.g. on a denied permission) with no// tool_call_update after it.const itemId = (typeof u.toolCallId === "string" && u.toolCallId) ? u.toolCallId@@ -768,7 +768,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>break;}case "tool_call_update": {- trackRunningTool(current, u);+ trackRunningTool(current, u); current.toolDetails.record(u);if (finished) toolEnded((typeof u.toolCallId === "string" && u.toolCallId) ? u.toolCallId : current.unkeyedToolIds.shift());break;}@@ -1020,7 +1020,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>asks,runningTools: new Set(),unkeyedToolIds: [],- endedToolIds: new Set(),+ endedToolIds: new Set(), toolDetails: new ToolCallDetails(),interruptTimer: null,stopQuietWatch: null,flushAssistantText,diff --git a/server/drivers/acp/tool-call-details.test.ts b/server/drivers/acp/tool-call-details.test.tsnew file mode 100644index 0000000000..554949af23--- /dev/null+++ b/server/drivers/acp/tool-call-details.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it } from "vitest";+import { ToolCallDetails } from "./tool-call-details.ts";++describe("ToolCallDetails", () => {+ it("keeps a field an update leaves out or sends as null, and replaces content", () => {+ const details = new ToolCallDetails();+ details.record({ toolCallId: "a", title: "Bash", kind: "execute", content: [{ type: "content", content: { type: "text", text: "one" } }] });+ details.record({ toolCallId: "a", title: null, rawInput: { command: "ls" }, content: [] });+ expect(details.merged({ toolCallId: "a" })).toEqual({ title: "Bash", kind: "execute", rawInput: { command: "ls" }, content: [] });+ });++ it("puts the request's own fields over what was recorded and ignores calls it does not name", () => {+ const details = new ToolCallDetails();+ details.record({ toolCallId: "a", title: "Bash", kind: "execute" });+ expect(details.merged({ toolCallId: "a", title: "Run ls", kind: null })).toEqual({ title: "Run ls", kind: "execute" });+ expect(details.merged({ toolCallId: "b", title: "Edit" })).toEqual({ title: "Edit" });+ expect(details.merged({ title: "Edit" })).toEqual({ title: "Edit" });+ });++ it("drops the oldest call past its limit", () => {+ const details = new ToolCallDetails();+ for (let i = 0; i <= 256; i++) details.record({ toolCallId: `c${i}`, title: `t${i}` });+ expect(details.merged({ toolCallId: "c0" })).toEqual({});+ expect(details.merged({ toolCallId: "c1" })).toEqual({ title: "t1" });+ expect(details.merged({ toolCallId: "c256" })).toEqual({ title: "t256" });+ });+});diff --git a/server/drivers/acp/tool-call-details.ts b/server/drivers/acp/tool-call-details.tsnew file mode 100644index 0000000000..75e814317e--- /dev/null+++ b/server/drivers/acp/tool-call-details.ts@@ -0,0 +1,32 @@+// ACP's session/request_permission carries a ToolCallUpdate: every field but toolCallId is optional and only changed+// fields are sent (Mistral Vibe 3.1.2 sends the toolCallId alone; Kimi Code 2.4.1 drops kind and rawInput). What the call+// is lives in its earlier tool_call and tool_call_update notifications.+// https://agentclientprotocol.com/protocol/tool-calls+const FIELDS = ["title", "kind", "rawInput", "locations", "content"] as const;+const MAX_CALLS = 256;++export type ToolCallFields = { [field in (typeof FIELDS)[number]]?: any };++/** One turn's tool calls by toolCallId, as their notifications left them. */+export class ToolCallDetails {+ private readonly calls = new Map<string, ToolCallFields>();++ /** A field left out or null keeps its earlier value. */+ record(update: Record<string, any>): void {+ const id = update.toolCallId;+ if (typeof id !== "string" || !id) return;+ const known = this.calls.get(id) ?? {};+ this.calls.delete(id);+ for (const field of FIELDS) if (update[field] !== undefined && update[field] !== null) known[field] = update[field];+ this.calls.set(id, known);+ if (this.calls.size > MAX_CALLS) this.calls.delete(this.calls.keys().next().value!);+ }++ /** The call as known so far, with the request's own fields over it. */+ merged(toolCall: Record<string, any>): ToolCallFields {+ const known = typeof toolCall.toolCallId === "string" ? this.calls.get(toolCall.toolCallId) : undefined;+ const merged: ToolCallFields = { ...known };+ for (const field of FIELDS) if (toolCall[field] !== undefined && toolCall[field] !== null) merged[field] = toolCall[field];+ return merged;+ }+}diff --git a/server/drivers/acp/turn-state.ts b/server/drivers/acp/turn-state.tsindex 1670755a03..314d4293b9 100644--- a/server/drivers/acp/turn-state.ts+++ b/server/drivers/acp/turn-state.ts@@ -8,6 +8,7 @@ import type { AcpConfig } from "./core.ts";import type { AcpDriverHooks } from "./driver-hooks.ts";import type { AcpHost, AcpLink } from "./host.ts"; import type { AppliedConfig } from "./applied-config.ts";import type { AcpTurnSteering } from "./steer.ts";+import type { ToolCallDetails } from "./tool-call-details.ts";export type AcpAskFinish = (behavior: string,@@ -41,6 +42,8 @@ export interface AcpTurn {runningTools: Set<string>;unkeyedToolIds: string[];endedToolIds: Set<string>;+ /** What this turn's tool call notifications said, for a permission request that names only the call. */+ toolDetails: ToolCallDetails;interruptTimer: ReturnType<typeof setTimeout> | null;stopQuietWatch: (() => void) | null;flushAssistantText: () => void;diff --git a/server/testing/fake-acp-cli.ts b/server/testing/fake-acp-cli.tsindex 98b75b0f02..7606c26964 100755--- a/server/testing/fake-acp-cli.ts+++ b/server/testing/fake-acp-cli.ts@@ -43,6 +43,8 @@// FAKE_ACP_CAPABILITIES_META JSON initialize advertises as agentCapabilities._meta// FAKE_ACP_MCP_HOLD=1 every session connects its MCP servers at once and keeps the stdio ones running, as Grok does// FAKE_ACP_PERMISSION_OPTIONS JSON options override in permission mode+// FAKE_ACP_PERMISSION_PRIOR_UPDATES JSON array of tool_call/tool_call_update updates sent before the process's first+// permission request only, as Mistral Vibe does before a request that names the call by toolCallId alone// FAKE_ACP_DUMP path for {argv, env}; with FAKE_ACP_MODES or FAKE_ACP_MODELS also <dump>.prompts.jsonl// and <dump>.initialize.json for the initialize params// FAKE_ACP_LAUNCH_COUNT_FILE process counter incremented at startup@@ -582,6 +584,7 @@ const recordMethod = (method: string, sessionId?: unknown, meta?: unknown) => {const configCalls: Array<{ method: string; params: unknown }> = [];let pendingPermissionId: number | null = null;+let permissionPriorSent = false;let onPermissionAnswered: ((allowed: boolean) => void) | null = null;let lastPermissionCancelled = false;let pendingAskQuestionId: number | null = null;@@ -1894,6 +1897,9 @@ function handle(msg: any) {}if (mode === "permission") {pendingPermissionId = 9001;+ const priorUpdates = process.env.FAKE_ACP_PERMISSION_PRIOR_UPDATES && !permissionPriorSent ? JSON.parse(process.env.FAKE_ACP_PERMISSION_PRIOR_UPDATES) : [];+ permissionPriorSent = true;+ for (const update of priorUpdates) out({ jsonrpc: "2.0", method: "session/update", params: { update } });onPermissionAnswered = () => {out({ jsonrpc: "2.0", method: "session/update", params: { update: { sessionUpdate: "agent_message_chunk", content: { text: "handled the permission decision" } } } });complete();