From 35be26082883d015312b3a72cf2d4c40078f2e19 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:16:36 -0500 Subject: [PATCH] fix(antigravity): pre-approve direct Threadlines MCP calls and add session approvals Antigravity CLI 1.5 invokes attached HTTP MCP tools directly as kind "other" with "Run mcp__" titles rather than through the legacy call_mcp_tool wrapper, so Threadlines' built-in room, page, command, and device tools still prompted for approval in Auto and Supervised modes. Its ACP server also sends only allow_once and reject_once options on permission requests, so users had no way to allow a tool or command for the session. Recognized direct Threadlines MCP tool calls against the exact registered tool inventory in AntigravityToolCalls (preserving wrapper and conflict checks) so pre-approved Threadlines MCP servers auto-approve once while browser, external, and conflicting calls still prompt. Added client-side in-memory session approval grants in AcpAdapter and AcpSessionApprovals for descriptors with clientSessionApprovals enabled (Antigravity), scoped to exact MCP tools, working-directory-bound commands (with read-only prefix matching only for reviewed git/gh subcommands on POSIX), and symlink-verified workspace edits, with Plan mode pause and security warning propagation. --- apps/server/scripts/antigravity-mock-agent.ts | 116 +++- apps/server/src/provider/acp/AcpAdapter.ts | 114 +++- .../src/provider/acp/AcpProviderDescriptor.ts | 7 + .../src/provider/acp/AcpRuntimeModel.ts | 8 + .../provider/acp/AcpSessionApprovals.test.ts | 396 +++++++++++++ .../src/provider/acp/AcpSessionApprovals.ts | 559 ++++++++++++++++++ .../src/provider/acp/AntigravityAcpSupport.ts | 1 + .../antigravity/AntigravityToolCalls.test.ts | 123 ++++ .../antigravity/AntigravityToolCalls.ts | 228 ++++++- .../antigravity/AntigravityTurns.test.ts | 104 +++- docs/providers/antigravity.md | 20 +- 11 files changed, 1618 insertions(+), 58 deletions(-) create mode 100644 apps/server/src/provider/acp/AcpSessionApprovals.test.ts create mode 100644 apps/server/src/provider/acp/AcpSessionApprovals.ts diff --git a/apps/server/scripts/antigravity-mock-agent.ts b/apps/server/scripts/antigravity-mock-agent.ts index 6ce5064c9..51914e9e8 100644 --- a/apps/server/scripts/antigravity-mock-agent.ts +++ b/apps/server/scripts/antigravity-mock-agent.ts @@ -564,7 +564,7 @@ const program = Effect.gen(function* () { { optionId: "deny", name: "Deny", kind: "reject_once" }, ], }); - // Threadlines room tool: auto-approved once even in Supervised mode. + // Threadlines room tool (legacy call_mcp_tool wrapper): auto-approved once even in Supervised mode. yield* ask({ toolCallId: "call_room", title: "MCP Tool room_ask", @@ -576,7 +576,23 @@ const program = Effect.gen(function* () { Arguments: { agent: "Codex", question: "Ready?" }, }, }); - // Threadlines browser tool: must still ask in Supervised mode. + // Direct HTTP MCP room tool (`agy acp` 1.5 shape): auto-approved once without asking. + yield* ask({ + toolCallId: "call_room_direct", + title: "Run mcp_threadlines_room_room_diff", + kind: "other", + status: "pending", + rawInput: { view: "status", toolSummary: "Check git status" }, + }); + // Direct HTTP MCP browser tool: must still ask in Supervised mode. + yield* ask({ + toolCallId: "call_browser_direct", + title: "Run mcp_threadlines_browser_browser_snapshot", + kind: "other", + status: "pending", + rawInput: { toolSummary: "Read page" }, + }); + // Threadlines browser tool (wrapper): must still ask in Supervised mode. yield* ask({ toolCallId: "call_browser", title: "MCP Tool browser_status", @@ -604,6 +620,102 @@ const program = Effect.gen(function* () { yield* modelCallEnds(sessionId); return { stopReason: "end_turn" as const }; } + if (scenario === "session-approvals") { + const ask = ( + toolCall: AcpSchema.ToolCallUpdate, + warning?: { readonly title: string; readonly message: string }, + ) => + agent.client.requestPermission({ + sessionId, + toolCall, + options: [ + { + optionId: "allow", + name: "Allow", + kind: "allow_once", + ...(warning ? { _meta: { "agy.security.warning": warning } } : {}), + }, + { optionId: "deny", name: "Deny", kind: "reject_once" }, + ], + }); + if (promptsSeen === 1) { + yield* ask( + { + toolCallId: "call_gh_view_1", + title: "gh pr view 101 --json state", + kind: "execute", + status: "pending", + rawInput: { CommandLine: "gh pr view 101 --json state" }, + }, + { title: "Network access", message: "Runs outside the terminal sandbox." }, + ); + // Covered by the `gh pr view` session grant. + yield* ask({ + toolCallId: "call_gh_view_2", + title: "gh pr view 102 --json body", + kind: "execute", + status: "pending", + rawInput: { CommandLine: "gh pr view 102 --json body" }, + }); + // Mutating sibling: must still ask. + yield* ask({ + toolCallId: "call_gh_merge", + title: "gh pr merge 101 --squash", + kind: "execute", + status: "pending", + rawInput: { CommandLine: "gh pr merge 101 --squash" }, + }); + // Two concurrent browser_snapshot calls: granting the first resolves both. + yield* Effect.all( + [ + ask({ + toolCallId: "call_snap_1", + title: "Run mcp_threadlines_browser_browser_snapshot", + kind: "other", + status: "pending", + rawInput: { tabId: "t1" }, + }), + ask({ + toolCallId: "call_snap_2", + title: "Run mcp_threadlines_browser_browser_snapshot", + kind: "other", + status: "pending", + rawInput: { tabId: "t2" }, + }), + ], + { concurrency: "unbounded" }, + ); + // Subsequent browser_snapshot is auto-approved; browser_click still asks. + yield* ask({ + toolCallId: "call_snap_3", + title: "Run mcp_threadlines_browser_browser_snapshot", + kind: "other", + status: "pending", + rawInput: { tabId: "t3" }, + }); + yield* ask({ + toolCallId: "call_click", + title: "Run mcp_threadlines_browser_browser_click", + kind: "other", + status: "pending", + rawInput: { target: "btn" }, + }); + yield* say(sessionId, "Turn 1 done."); + yield* modelCallEnds(sessionId); + return { stopReason: "end_turn" as const }; + } + // Second turn (sent in plan mode): prior `gh pr view` grant must not auto-approve. + yield* ask({ + toolCallId: "call_gh_view_plan", + title: "gh pr view 103 --json state", + kind: "execute", + status: "pending", + rawInput: { CommandLine: "gh pr view 103 --json state" }, + }); + yield* say(sessionId, "Plan turn done."); + yield* modelCallEnds(sessionId); + return { stopReason: "end_turn" as const }; + } if (scenario === "permission-second") { if (promptsSeen === 1) { yield* say(sessionId, "First done."); diff --git a/apps/server/src/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index 74f4ec91f..d999e49fb 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -112,6 +112,7 @@ import { isAcpAuthRequiredError, mapAcpToAdapterError, } from "./AcpAdapterSupport.ts"; +import { acpSessionApprovalGrantKey, isAcpSessionApprovalGranted } from "./AcpSessionApprovals.ts"; import { makeAcpAssistantItemEvent, makeAcpContentDeltaEvent, @@ -277,6 +278,8 @@ export interface AcpAdapterOptions { interface PendingApproval { readonly decision: Deferred.Deferred; readonly kind: string | "unknown"; + /** Re-checks if a client-side session grant added by another approval covers this pending card. */ + readonly grantIfCovered?: () => Effect.Effect; } interface PendingUserInput { @@ -334,6 +337,10 @@ interface AcpSessionContext { readonly acpSessionId: string; /** Attached Threadlines MCP servers pre-approved without asking (room, pages, commands, device). */ readonly preapprovedMcpServers: ReadonlySet; + /** Client-side session approval grants remembered in memory (`descriptor.clientSessionApprovals`). */ + readonly sessionApprovalGrants: Set; + /** Interaction mode of the active prompt (`plan` disables client-side session approval auto-grants). */ + activeInteractionMode: ProviderInteractionMode | undefined; /** What the agent's `initialize` answer says it reads in a prompt. */ readonly promptCapabilities: EffectAcpSchema.PromptCapabilities | null | undefined; /** The subagents this session's tool calls launched (`subagents`), as the thread shows them. */ @@ -2369,13 +2376,32 @@ export function makeAcpAdapter( (option) => !descriptor.isLastingPermissionOption!(option), ) : params.options; + // Require an explicit allow_once option (never a synthetic fallback + // for an empty options list) and no agent-native allow_always. + const hasExplicitAllowOnce = offered.some( + (option) => option.kind === "allow_once" && option.optionId.trim().length > 0, + ); + const clientSessionApprovalEligible = + descriptor.clientSessionApprovals === true && + ownSession && + ctx.activeInteractionMode !== "plan" && + !offered.some((option) => option.kind === "allow_always") && + hasExplicitAllowOnce; + const sessionGranted = + clientSessionApprovalEligible && + isAcpSessionApprovalGranted( + permissionRequest, + ctx.sessionApprovalGrants, + ctx.cwdRoots, + ); // Full access answers each request once: an "always" option // would leave a standing rule behind in the agent's own store. // A request with no "once" to give goes to the user instead. if ( input.runtimeMode === "full-access" || planFileWrite || - preapprovedThreadlinesMcpCall + preapprovedThreadlinesMcpCall || + sessionGranted ) { const once = acpPermissionOptionId("accept", offered); if (once !== undefined) return selected(once); @@ -2387,25 +2413,65 @@ export function makeAcpAdapter( requestId: ApprovalRequestId.make(crypto.randomUUID()), permissionRequest, }; - pendingApprovals.set(card.requestId, { decision, kind: permissionRequest.kind }); + const grantIfCovered = + clientSessionApprovalEligible && ctx !== undefined + ? () => + ctx.activeInteractionMode !== "plan" && + isAcpSessionApprovalGranted( + card.permissionRequest, + ctx.sessionApprovalGrants, + ctx.cwdRoots, + ) + ? Deferred.succeed(decision, "accept").pipe(Effect.asVoid) + : Effect.void + : undefined; + pendingApprovals.set(card.requestId, { + decision, + kind: permissionRequest.kind, + ...(grantIfCovered ? { grantIfCovered } : {}), + }); const warningFor = (kind: EffectAcpSchema.PermissionOption["kind"]) => { const option = offered.find((candidate) => candidate.kind === kind); return option ? descriptor.permissionOptionWarning?.(option) : undefined; }; const acceptForSessionWarning = warningFor("allow_always"); const acceptWarning = warningFor("allow_once"); - const decisionWarnings = - acceptForSessionWarning || acceptWarning - ? { - ...(acceptWarning ? { accept: acceptWarning } : {}), - ...(acceptForSessionWarning - ? { acceptForSession: acceptForSessionWarning } - : {}), - } - : undefined; - const availableDecisions = acpAvailableDecisions(offered); + const baseDecisions = acpAvailableDecisions(offered); + const decisionsForCard = () => { + if ( + !baseDecisions || + !clientSessionApprovalEligible || + baseDecisions.includes("acceptForSession") || + acpSessionApprovalGrantKey(card.permissionRequest, ctx.cwdRoots) === undefined + ) { + return baseDecisions; + } + return [ + ...baseDecisions.filter((candidate) => candidate !== "accept"), + "acceptForSession" as const, + ...(baseDecisions.includes("accept") ? (["accept"] as const) : []), + ]; + }; const openCard = (turnId: TurnId | undefined) => Effect.gen(function* () { + const availableDecisions = decisionsForCard(); + // A synthesized session grant authorizes the same `allow_once` + // option, so it must carry any warning attached to `allow_once`. + const effectiveSessionWarning = + acceptForSessionWarning ?? + (clientSessionApprovalEligible && + availableDecisions?.includes("acceptForSession") + ? acceptWarning + : undefined); + const decisionWarnings = + effectiveSessionWarning || acceptWarning + ? { + ...(acceptWarning ? { accept: acceptWarning } : {}), + ...(effectiveSessionWarning + ? { acceptForSession: effectiveSessionWarning } + : {}), + } + : undefined; yield* offerRuntimeEvent( makeAcpRequestOpenedEvent({ stamp: yield* makeEventStamp(), @@ -2454,7 +2520,11 @@ export function makeAcpAdapter( ); card.requestId = ApprovalRequestId.make(crypto.randomUUID()); card.permissionRequest = next; - pendingApprovals.set(card.requestId, { decision, kind: next.kind }); + pendingApprovals.set(card.requestId, { + decision, + kind: next.kind, + ...(grantIfCovered ? { grantIfCovered } : {}), + }); yield* openCard(turnId); }), }; @@ -2472,6 +2542,21 @@ export function makeAcpAdapter( }), ), ); + if ( + resolved === "acceptForSession" && + clientSessionApprovalEligible && + ctx.activeInteractionMode !== "plan" + ) { + const grantKey = acpSessionApprovalGrantKey(card.permissionRequest, ctx.cwdRoots); + if (grantKey !== undefined) { + ctx.sessionApprovalGrants.add(grantKey); + for (const [otherId, other] of pendingApprovals) { + if (otherId !== card.requestId && other.grantIfCovered) { + yield* other.grantIfCovered(); + } + } + } + } const turnId = yield* Deferred.await(shown); yield* offerRuntimeEvent( makeAcpRequestResolvedEvent({ @@ -2615,6 +2700,8 @@ export function makeAcpAdapter( lastContextUsageKey: undefined, acpSessionId: started.sessionId, preapprovedMcpServers, + sessionApprovalGrants: new Set(), + activeInteractionMode: undefined, promptCapabilities: started.initializeResult.agentCapabilities?.promptCapabilities, subagentRoster: descriptor.subagents === undefined @@ -4106,6 +4193,7 @@ export function makeAcpAdapter( } // The mode and model the message asks for, set before its prompt goes out. const configure = Effect.gen(function* () { + ctx.activeInteractionMode = input.interactionMode; yield* applyRequestedSessionConfiguration({ runtime: ctx.acp, threadId: input.threadId, diff --git a/apps/server/src/provider/acp/AcpProviderDescriptor.ts b/apps/server/src/provider/acp/AcpProviderDescriptor.ts index a4a731aab..9ec43125a 100644 --- a/apps/server/src/provider/acp/AcpProviderDescriptor.ts +++ b/apps/server/src/provider/acp/AcpProviderDescriptor.ts @@ -707,6 +707,13 @@ export interface AcpProviderDescriptor { * chosen; "Accept for session" then appears only for a real session grant. */ readonly isLastingPermissionOption?: (option: EffectAcpSchema.PermissionOption) => boolean; + /** + * Offers "Always allow this session" client-side when a permission request + * includes `allow_once` without `allow_always` (e.g. Antigravity's `agy acp`). + * Grants live in memory on the open session and answer matching subsequent + * requests with `allow_once`, never persisting rules on disk. + */ + readonly clientSessionApprovals?: boolean; /** A risk the agent attached to a permission option, shown with the approval. */ readonly permissionOptionWarning?: ( option: EffectAcpSchema.PermissionOption, diff --git a/apps/server/src/provider/acp/AcpRuntimeModel.ts b/apps/server/src/provider/acp/AcpRuntimeModel.ts index c02f4a5c6..3d9233372 100644 --- a/apps/server/src/provider/acp/AcpRuntimeModel.ts +++ b/apps/server/src/provider/acp/AcpRuntimeModel.ts @@ -40,6 +40,12 @@ export interface AcpToolCallState { * `normalizeToolCall`; absent, the row type follows `kind`. */ readonly itemType?: ToolLifecycleItemType; + /** + * In-memory tag of which MCP wire shape `normalizeToolCall` established + * (`wrapper` vs `direct`), preserved across merges so later updates are only + * validated against that same form. Not written to `data`. + */ + readonly mcpCallMode?: "wrapper" | "direct"; readonly data: Record; } @@ -591,6 +597,7 @@ export function mergeToolCallState( const status = next.status ?? previous?.status; const command = next.command ?? previous?.command; const detail = next.detail ?? previous?.detail; + const mcpCallMode = next.mcpCallMode ?? previous?.mcpCallMode; return { toolCallId: next.toolCallId, ...(kind ? { kind } : {}), @@ -599,6 +606,7 @@ export function mergeToolCallState( ...(status ? { status } : {}), ...(command ? { command } : {}), ...(detail ? { detail } : {}), + ...(mcpCallMode ? { mcpCallMode } : {}), data: mergeToolCallData(previous?.data, next.data, kind, command), }; } diff --git a/apps/server/src/provider/acp/AcpSessionApprovals.test.ts b/apps/server/src/provider/acp/AcpSessionApprovals.test.ts new file mode 100644 index 000000000..36c4c6550 --- /dev/null +++ b/apps/server/src/provider/acp/AcpSessionApprovals.test.ts @@ -0,0 +1,396 @@ +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { describe, expect, it } from "vite-plus/test"; + +import type { AcpPermissionRequest } from "./AcpRuntimeModel.ts"; +import { + acpSessionApprovalGrantKey, + isAcpSessionApprovalGranted, + splitSafeShellChain, +} from "./AcpSessionApprovals.ts"; + +const WORKSPACE = ["/repo/project"] as const; + +const execRequest = (command: string, cwd?: string): AcpPermissionRequest => ({ + kind: "execute", + detail: command, + toolCall: { + toolCallId: "call_cmd", + kind: "execute", + title: command, + command, + data: { + kind: "execute", + command, + rawInput: { CommandLine: command, ...(cwd ? { Cwd: cwd } : {}) }, + ...(cwd ? { item: { command, cwd } } : {}), + }, + }, +}); + +const mcpRequest = ( + server: string, + tool: string, + args: Record = {}, +): AcpPermissionRequest => ({ + kind: "other", + detail: `MCP tool ${server} · ${tool}`, + toolCall: { + toolCallId: "call_mcp", + kind: "other", + itemType: "mcp_tool_call", + title: tool, + detail: `MCP tool ${server} · ${tool}`, + data: { kind: "other", server, tool, arguments: args }, + }, +}); + +const fileRequest = ( + kind: "edit" | "delete" | "move" | "read", + paths: ReadonlyArray, +): AcpPermissionRequest => ({ + kind, + detail: paths.join(", "), + toolCall: { + toolCallId: "call_file", + kind, + title: `File ${paths[0] ?? ""}`, + data: { + kind, + locations: paths.map((path) => ({ path })), + }, + }, +}); + +describe("AcpSessionApprovals", () => { + it("scopes MCP grants to the exact server and tool, with any arguments", () => { + const grants = new Set(); + const snap1 = mcpRequest("threadlines_browser", "browser_snapshot", { tabId: "t1" }); + const snap2 = mcpRequest("threadlines_browser", "browser_snapshot", { tabId: "t2" }); + const click = mcpRequest("threadlines_browser", "browser_click", { target: "btn" }); + + const key = acpSessionApprovalGrantKey(snap1, WORKSPACE, "darwin"); + expect(key).toBeDefined(); + grants.add(key!); + + expect(isAcpSessionApprovalGranted(snap2, grants, WORKSPACE, "darwin")).toBe(true); + expect(isAcpSessionApprovalGranted(click, grants, WORKSPACE, "darwin")).toBe(false); + }); + + it("generalizes only strictly read-only git and gh subcommands, never mutating forms or exec flags", () => { + const grants = new Set(); + grants.add( + acpSessionApprovalGrantKey(execRequest("gh pr view 1073 --json state"), WORKSPACE, "darwin")!, + ); + grants.add(acpSessionApprovalGrantKey(execRequest("git status"), WORKSPACE, "darwin")!); + grants.add(acpSessionApprovalGrantKey(execRequest("git branch --list"), WORKSPACE, "darwin")!); + grants.add( + acpSessionApprovalGrantKey( + execRequest("git push --dry-run origin main"), + WORKSPACE, + "darwin", + )!, + ); + grants.add(acpSessionApprovalGrantKey(execRequest("vp run typecheck"), WORKSPACE, "darwin")!); + + expect( + isAcpSessionApprovalGranted( + execRequest("gh pr view 1074 --json body"), + grants, + WORKSPACE, + "darwin", + ), + ).toBe(true); + expect( + isAcpSessionApprovalGranted( + execRequest("gh pr view 1074 --web"), + grants, + WORKSPACE, + "darwin", + ), + ).toBe(false); + expect( + isAcpSessionApprovalGranted( + execRequest("gh pr merge 1073 --squash"), + grants, + WORKSPACE, + "darwin", + ), + ).toBe(false); + + expect( + isAcpSessionApprovalGranted(execRequest("git status -sb"), grants, WORKSPACE, "darwin"), + ).toBe(true); + expect( + isAcpSessionApprovalGranted( + execRequest("git -c core.pager=evil status"), + grants, + WORKSPACE, + "darwin", + ), + ).toBe(false); + expect( + isAcpSessionApprovalGranted( + execRequest("git status --exec-path=/tmp"), + grants, + WORKSPACE, + "darwin", + ), + ).toBe(false); + expect( + isAcpSessionApprovalGranted( + execRequest("git status --output=/tmp/x"), + grants, + WORKSPACE, + "darwin", + ), + ).toBe(false); + + // Mutating or non-readonly commands require exact matching. + expect( + isAcpSessionApprovalGranted(execRequest("git branch -D main"), grants, WORKSPACE, "darwin"), + ).toBe(false); + expect( + isAcpSessionApprovalGranted(execRequest("git push origin main"), grants, WORKSPACE, "darwin"), + ).toBe(false); + expect( + isAcpSessionApprovalGranted(execRequest("vp run typecheck"), grants, WORKSPACE, "darwin"), + ).toBe(true); + expect( + isAcpSessionApprovalGranted( + execRequest("vp run typecheck --watch"), + grants, + WORKSPACE, + "darwin", + ), + ).toBe(false); + expect( + isAcpSessionApprovalGranted(execRequest("vp run deploy"), grants, WORKSPACE, "darwin"), + ).toBe(false); + }); + + it("binds command grants to cwd and refuses truncated or display-only commands", () => { + const grants = new Set(); + const scratchKey = acpSessionApprovalGrantKey( + execRequest("rm -rf build", "/tmp/scratch"), + WORKSPACE, + "darwin", + ); + expect(scratchKey).toBeDefined(); + grants.add(scratchKey!); + + expect( + isAcpSessionApprovalGranted( + execRequest("rm -rf build", "/tmp/scratch"), + grants, + WORKSPACE, + "darwin", + ), + ).toBe(true); + expect( + isAcpSessionApprovalGranted( + execRequest("rm -rf build", "/repo/project"), + grants, + WORKSPACE, + "darwin", + ), + ).toBe(false); + expect( + isAcpSessionApprovalGranted(execRequest("rm -rf build"), grants, WORKSPACE, "darwin"), + ).toBe(false); + + // Truncated command text cannot uniquely identify a command. + expect( + acpSessionApprovalGrantKey( + execRequest("echo hello\n\n[Command truncated]"), + WORKSPACE, + "darwin", + ), + ).toBeUndefined(); + + // Display-only detail without `toolCall.command` must not create a command grant. + const detailOnly: AcpPermissionRequest = { + kind: "execute", + detail: "git status", + toolCall: { toolCallId: "c1", kind: "execute", title: "git status", data: {} }, + }; + expect(acpSessionApprovalGrantKey(detailOnly, WORKSPACE, "darwin")).toBeUndefined(); + }); + + it("rejects pipelines and Windows shell splitting, and requires every chain segment to match", () => { + const grants = new Set(); + grants.add(acpSessionApprovalGrantKey(execRequest("git status"), WORKSPACE, "darwin")!); + grants.add(acpSessionApprovalGrantKey(execRequest("git diff"), WORKSPACE, "darwin")!); + + expect( + isAcpSessionApprovalGranted( + execRequest("git status && git diff"), + grants, + WORKSPACE, + "darwin", + ), + ).toBe(true); + expect( + isAcpSessionApprovalGranted( + execRequest("git status && rm -rf /"), + grants, + WORKSPACE, + "darwin", + ), + ).toBe(false); + // Pipelines change command semantics and must not be split across grants. + expect( + isAcpSessionApprovalGranted( + execRequest("git status | git diff"), + grants, + WORKSPACE, + "darwin", + ), + ).toBe(false); + expect(splitSafeShellChain("git status | cat", "darwin")).toBeUndefined(); + expect(splitSafeShellChain("git status && git diff", "win32")).toBeUndefined(); + // On Windows, prefix generalization and chain splitting are disabled. + const winGrants = new Set(); + winGrants.add(acpSessionApprovalGrantKey(execRequest("git status"), WORKSPACE, "win32")!); + expect( + isAcpSessionApprovalGranted(execRequest("git status -sb"), winGrants, WORKSPACE, "win32"), + ).toBe(false); + expect( + isAcpSessionApprovalGranted(execRequest("git status"), winGrants, WORKSPACE, "win32"), + ).toBe(true); + // Metacharacters and redirects are rejected from chain matching. + expect( + isAcpSessionApprovalGranted( + execRequest("git status > /tmp/out"), + grants, + WORKSPACE, + "darwin", + ), + ).toBe(false); + expect( + isAcpSessionApprovalGranted( + execRequest('git status "$(whoami)"'), + grants, + WORKSPACE, + "darwin", + ), + ).toBe(false); + }); + + it("verifies realpath workspace containment (blocking symlinks) and preserves path whitespace", () => { + const tempBase = mkdtempSync(join(tmpdir(), "acp-grants-")); + try { + const workspace = join(tempBase, "workspace"); + const outside = join(tempBase, "outside"); + mkdirSync(join(workspace, "src"), { recursive: true }); + mkdirSync(outside, { recursive: true }); + const insideFile = join(workspace, "src", "a.ts"); + const insideNewFile = join(workspace, "src", "nested", "new.ts"); + const escapeLink = join(workspace, "escape"); + writeFileSync(insideFile, "a"); + symlinkSync(outside, escapeLink); + + const grants = new Set(); + const wsKey = acpSessionApprovalGrantKey(fileRequest("edit", [insideFile]), [workspace]); + expect(wsKey).toBe("file:edit:workspace"); + grants.add(wsKey!); + + // Another file inside workspace (including a not-yet-created one) matches. + expect( + isAcpSessionApprovalGranted(fileRequest("edit", [insideNewFile]), grants, [workspace]), + ).toBe(true); + // Delete stays separate from edit. + expect( + isAcpSessionApprovalGranted(fileRequest("delete", [insideFile]), grants, [workspace]), + ).toBe(false); + // Symlink inside workspace pointing outside MUST NOT match the workspace edit grant. + expect( + isAcpSessionApprovalGranted(fileRequest("edit", [join(escapeLink, "secret.txt")]), grants, [ + workspace, + ]), + ).toBe(false); + + // Trailing whitespace in outside file names is preserved (distinct files). + const outsideClean = join(outside, "file.txt"); + const outsidePadded = join(outside, "file.txt "); + grants.add(acpSessionApprovalGrantKey(fileRequest("edit", [outsideClean]), [workspace])!); + expect( + isAcpSessionApprovalGranted(fileRequest("edit", [outsideClean]), grants, [workspace]), + ).toBe(true); + expect( + isAcpSessionApprovalGranted(fileRequest("edit", [outsidePadded]), grants, [workspace]), + ).toBe(false); + } finally { + rmSync(tempBase, { recursive: true, force: true }); + } + }); + + it("suppresses session approval when a revised card has a conflicting kind", () => { + const revisedEditToExec: AcpPermissionRequest = { + kind: "edit", + detail: "rm -rf /", + toolCall: { + toolCallId: "call_rev", + kind: "execute", + title: "rm -rf /", + command: "rm -rf /", + data: { + kind: "execute", + command: "rm -rf /", + locations: [{ path: "/repo/project/src/a.ts" }], + }, + }, + }; + expect(acpSessionApprovalGrantKey(revisedEditToExec, WORKSPACE)).toBeUndefined(); + const grants = new Set(["file:edit:workspace"]); + expect(isAcpSessionApprovalGranted(revisedEditToExec, grants, WORKSPACE)).toBe(false); + }); + + it("scopes web fetches by origin and refuses generic untitled tools", () => { + const grants = new Set(); + const fetch1: AcpPermissionRequest = { + kind: "fetch", + toolCall: { + toolCallId: "f1", + kind: "fetch", + title: "Fetch docs", + data: { + kind: "fetch", + rawInput: { url: "https://antigravity.google/docs/permissions.md" }, + }, + }, + }; + const fetch2: AcpPermissionRequest = { + kind: "fetch", + toolCall: { + toolCallId: "f2", + kind: "fetch", + title: "Fetch settings", + data: { + kind: "fetch", + rawInput: { url: "https://antigravity.google/docs/settings.md" }, + }, + }, + }; + const fetchOther: AcpPermissionRequest = { + kind: "fetch", + toolCall: { + toolCallId: "f3", + kind: "fetch", + title: "Fetch other", + data: { kind: "fetch", rawInput: { url: "https://evil.example/docs" } }, + }, + }; + grants.add(acpSessionApprovalGrantKey(fetch1, WORKSPACE)!); + expect(isAcpSessionApprovalGranted(fetch2, grants, WORKSPACE)).toBe(true); + expect(isAcpSessionApprovalGranted(fetchOther, grants, WORKSPACE)).toBe(false); + + const generic: AcpPermissionRequest = { + kind: "other", + toolCall: { toolCallId: "g1", kind: "other", title: "Tool", data: {} }, + }; + expect(acpSessionApprovalGrantKey(generic, WORKSPACE)).toBeUndefined(); + }); +}); diff --git a/apps/server/src/provider/acp/AcpSessionApprovals.ts b/apps/server/src/provider/acp/AcpSessionApprovals.ts new file mode 100644 index 000000000..d1aaff1df --- /dev/null +++ b/apps/server/src/provider/acp/AcpSessionApprovals.ts @@ -0,0 +1,559 @@ +/** + * Client-side session approval grants for ACP agents whose `request_permission` + * offers only `allow_once` (such as Antigravity's `agy acp`). + * + * Grants live in memory on the open session and die when it stops; nothing is + * persisted to disk or sent to the agent as `allow_always`. + * + * Scoping rules: + * - Command grants are always bound to their resolved working directory (`cwd`) + * and never derived from truncated command text or display labels. + * - Prefix generalization on POSIX applies only to reviewed read-only `git` + * and `gh` subcommands without mutating/output/exec flags; everything else + * (including pipelines, Windows shells, redirects, substitutions, env + * overrides, and mutating subcommands) requires an exact command + cwd match. + * - Workspace edit grants verify realpath containment (walking up to the + * nearest existing ancestor for new files) so symlinks inside the workspace + * cannot escape it, and never trim file paths. + * - Revised cards whose `toolCall.kind` conflicts with `request.kind` never + * create or match a session grant. + * + * @module provider/acp/AcpSessionApprovals + */ +import { realpathSync } from "node:fs"; +import { dirname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path"; + +import type { AcpPermissionRequest, AcpToolCallState } from "./AcpRuntimeModel.ts"; + +const isRecord = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +/** Strictly read-only `git` subcommands safe to generalize by subcommand prefix. */ +const READONLY_GIT_SUBCOMMANDS = new Set([ + "status", + "diff", + "log", + "show", + "rev-parse", + "describe", + "shortlog", + "blame", + "ls-files", + "ls-tree", + "merge-base", + "cat-file", + "rev-list", +]); + +/** Git flags that can execute helpers, redirect output to disk, or target another repo. */ +const DISALLOWED_GIT_FLAGS = new Set([ + "-c", + "--config-env", + "--exec-path", + "--upload-pack", + "--receive-pack", + "--git-dir", + "--work-tree", + "--ext-diff", + "-o", + "--output", +]); + +/** Strictly read-only `gh ` pairs safe to generalize by prefix. */ +const READONLY_GH_VERBS: Readonly>> = { + pr: new Set(["view", "list", "status", "diff", "checks"]), + issue: new Set(["view", "list", "status"]), + repo: new Set(["view", "list"]), + run: new Set(["view", "list", "watch"]), + workflow: new Set(["view", "list"]), + release: new Set(["view", "list"]), + search: new Set(["repos", "issues", "prs", "code", "commits"]), +}; + +/** `gh` flags that open browsers, write files, or alter HTTP methods. */ +const DISALLOWED_GH_FLAGS = new Set(["-w", "--web", "-o", "--output", "-X", "--method"]); + +const ENV_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/u; +const CWD_KEYS = ["cwd", "Cwd", "workingDir", "working_dir", "WorkingDirectory"] as const; +const TRUNCATION_MARKERS = ["\n\n[Command truncated]", "[Earlier output truncated]\n\n"] as const; + +/** + * Splits a POSIX shell command into sequential segments separated by `&&`, + * `||`, or `;` outside quotes. Rejects pipelines (`|`) and any construct that + * can hide execution or alter I/O (newlines, redirects, substitutions, + * subshells, brace expansion, backgrounding, or unterminated quotes). + */ +export function splitSafeShellChain( + command: string, + platform: NodeJS.Platform = process.platform, +): ReadonlyArray | undefined { + // Windows shells (`cmd.exe` / PowerShell) do not share POSIX quoting rules. + if (platform === "win32") return undefined; + const trimmed = command.trim(); + if (trimmed.length === 0 || /[\r\n]/u.test(trimmed)) return undefined; + + const segments: Array = []; + let current = ""; + let quote: "'" | '"' | undefined; + let i = 0; + + while (i < trimmed.length) { + const ch = trimmed[i]!; + const next = trimmed[i + 1]; + + if (quote === "'") { + if (ch === "'") { + quote = undefined; + } + current += ch; + i += 1; + continue; + } + + if (quote === '"') { + if (ch === "\\") { + if (next === undefined) return undefined; + current += ch + next; + i += 2; + continue; + } + if (ch === "`" || (ch === "$" && (next === "(" || next === "{"))) { + return undefined; + } + if (ch === '"') { + quote = undefined; + } + current += ch; + i += 1; + continue; + } + + if (ch === "\\") { + if (next === undefined) return undefined; + current += ch + next; + i += 2; + continue; + } + if (ch === "'" || ch === '"') { + quote = ch; + current += ch; + i += 1; + continue; + } + if ( + ch === "`" || + ch === "<" || + ch === ">" || + ch === "(" || + ch === ")" || + ch === "{" || + ch === "}" || + (ch === "$" && (next === "(" || next === "{")) + ) { + return undefined; + } + if (ch === "&") { + if (next !== "&") return undefined; + const part = current.trim(); + if (part.length === 0) return undefined; + segments.push(part); + current = ""; + i += 2; + continue; + } + if (ch === "|") { + // Only `||` is a sequential separator; single `|` pipes data between commands. + if (next !== "|") return undefined; + const part = current.trim(); + if (part.length === 0) return undefined; + segments.push(part); + current = ""; + i += 2; + continue; + } + if (ch === ";") { + const part = current.trim(); + if (part.length === 0) return undefined; + segments.push(part); + current = ""; + i += 1; + continue; + } + + current += ch; + i += 1; + } + + if (quote !== undefined) return undefined; + const tail = current.trim(); + if (tail.length === 0) return undefined; + segments.push(tail); + return segments; +} + +/** Tokenizes one already-validated simple POSIX shell segment into argv words. */ +function tokenizeSimpleShellSegment(segment: string): ReadonlyArray | undefined { + const tokens: Array = []; + let current = ""; + let inToken = false; + let quote: "'" | '"' | undefined; + let i = 0; + + while (i < segment.length) { + const ch = segment[i]!; + const next = segment[i + 1]; + + if (quote === "'") { + if (ch === "'") { + quote = undefined; + } else { + current += ch; + } + i += 1; + continue; + } + + if (quote === '"') { + if (ch === "\\") { + if (next === undefined) return undefined; + current += next; + i += 2; + continue; + } + if (ch === '"') { + quote = undefined; + } else { + current += ch; + } + i += 1; + continue; + } + + if (ch === " " || ch === "\t") { + if (inToken) { + tokens.push(current); + current = ""; + inToken = false; + } + i += 1; + continue; + } + + inToken = true; + if (ch === "\\") { + if (next === undefined) return undefined; + current += next; + i += 2; + continue; + } + if (ch === "'" || ch === '"') { + quote = ch; + i += 1; + continue; + } + current += ch; + i += 1; + } + + if (quote !== undefined) return undefined; + if (inToken) tokens.push(current); + return tokens.length > 0 ? tokens : undefined; +} + +function hasDisallowedFlag(args: ReadonlyArray, disallowed: ReadonlySet): boolean { + return args.some((arg) => { + const flag = arg.split("=")[0] ?? arg; + return disallowed.has(flag); + }); +} + +/** + * Strictly read-only subcommand prefix key for one simple POSIX command + * segment, bound to `cwd`, or `undefined` when exact command matching is + * required. + */ +function safeReadOnlyCommandPrefixKey(segment: string, cwd: string): string | undefined { + const tokens = tokenizeSimpleShellSegment(segment); + if (!tokens || tokens.length === 0) return undefined; + const [exe, sub1, sub2, ...rest] = tokens; + if (!exe || ENV_ASSIGNMENT.test(exe) || exe.includes("/") || exe.includes("\\")) { + return undefined; + } + + if (exe === "git") { + if (!sub1 || !READONLY_GIT_SUBCOMMANDS.has(sub1)) return undefined; + if (hasDisallowedFlag([sub2 ?? "", ...rest], DISALLOWED_GIT_FLAGS)) return undefined; + return `cmd:prefix:${cwd}\0git\0${sub1}`; + } + + if (exe === "gh") { + const verbs = sub1 ? READONLY_GH_VERBS[sub1] : undefined; + if (!sub1 || !sub2 || !verbs?.has(sub2)) return undefined; + if (hasDisallowedFlag(rest, DISALLOWED_GH_FLAGS)) return undefined; + return `cmd:prefix:${cwd}\0gh\0${sub1}\0${sub2}`; + } + + return undefined; +} + +function isTruncatedText(text: string): boolean { + return TRUNCATION_MARKERS.some((marker) => text.includes(marker)); +} + +/** + * Complete command text from the tool call itself (never from display-only + * `request.detail`, and never from truncated command text). + */ +function commandOf(request: AcpPermissionRequest): string | undefined { + const fromToolCall = request.toolCall?.command?.trim(); + if (!fromToolCall || isTruncatedText(fromToolCall)) return undefined; + return fromToolCall; +} + +function resolveRealOrLexical(filePath: string): string { + try { + return realpathSync(filePath); + } catch { + return normalize(filePath); + } +} + +/** + * Working directory the command runs in, resolved against the session's root + * so identical relative commands in different directories never share a grant. + */ +function commandCwdOf( + toolCall: AcpToolCallState | undefined, + cwdRoots: ReadonlyArray, +): string | undefined { + const item = toolCall && isRecord(toolCall.data.item) ? toolCall.data.item : undefined; + const rawInput = + toolCall && isRecord(toolCall.data.rawInput) ? toolCall.data.rawInput : undefined; + let rawCwd: string | undefined; + if (typeof item?.cwd === "string" && item.cwd.length > 0) { + rawCwd = item.cwd; + } else if (rawInput) { + for (const key of CWD_KEYS) { + const value = rawInput[key]; + if (typeof value === "string" && value.length > 0) { + rawCwd = value; + break; + } + } + } + const base = cwdRoots[0]; + if (rawCwd !== undefined) { + const absolute = isAbsolute(rawCwd) || base === undefined ? rawCwd : resolve(base, rawCwd); + return resolveRealOrLexical(absolute); + } + return base !== undefined ? resolveRealOrLexical(base) : undefined; +} + +/** Preserves exact path bytes (never trimmed: trailing spaces name another file). */ +function pathsFromToolCall(toolCall: AcpToolCallState | undefined): ReadonlyArray { + if (!toolCall) return []; + const raw: Array = []; + const push = (value: unknown) => { + if (typeof value === "string" && value.length > 0) raw.push(value); + }; + const { content, locations, rawInput } = toolCall.data; + if (Array.isArray(content)) { + for (const entry of content) { + if (isRecord(entry)) push(entry.path); + } + } + if (Array.isArray(locations)) { + for (const entry of locations) { + if (isRecord(entry)) push(entry.path); + } + } + if (isRecord(rawInput)) { + push(rawInput.file_path); + push(rawInput.TargetFile); + push(rawInput.AbsolutePath); + push(rawInput.Path); + push(rawInput.path); + } + return raw; +} + +function resolveFilePath(filePath: string, cwdRoots: ReadonlyArray): string { + const base = cwdRoots[0]; + return isAbsolute(filePath) || base === undefined ? normalize(filePath) : resolve(base, filePath); +} + +/** + * Resolves `targetPath` through any symlinks on its existing prefix (including + * the nearest existing parent directory for a not-yet-created file). Returns + * `undefined` if no existing ancestor can be resolved. + */ +function resolveRealPathThroughAncestors(targetPath: string): string | undefined { + const suffix: Array = []; + let cursor = normalize(targetPath); + while (true) { + try { + const real = realpathSync(cursor); + return suffix.length === 0 ? real : join(real, ...suffix.toReversed()); + } catch { + const parent = dirname(cursor); + if (parent === cursor) return undefined; + suffix.push(cursor.slice(parent.length).replace(/^[\\/]+/u, "")); + cursor = parent; + } + } +} + +function isInsideRoot(root: string, candidate: string): boolean { + const rel = relative(root, candidate); + return rel === "" || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`)); +} + +/** + * Whether every resolved path sits inside a real workspace root after symlink + * resolution, so a symlink inside the workspace pointing outside can never + * inherit a workspace edit grant. + */ +function isRealPathInsideWorkspace(filePath: string, cwdRoots: ReadonlyArray): boolean { + const realRoots: Array = []; + for (const root of cwdRoots) { + try { + realRoots.push(realpathSync(root)); + } catch { + // Unresolvable root cannot prove containment. + } + } + if (realRoots.length === 0) return false; + const resolvedTarget = resolveRealPathThroughAncestors(resolveFilePath(filePath, cwdRoots)); + if (resolvedTarget === undefined) return false; + return realRoots.some((root) => isInsideRoot(root, resolvedTarget)); +} + +function urlOriginFromToolCall(toolCall: AcpToolCallState | undefined): string | undefined { + const rawInput = toolCall?.data.rawInput; + if (!isRecord(rawInput)) return undefined; + const candidate = rawInput.url ?? rawInput.Url ?? rawInput.URL; + if (typeof candidate !== "string") return undefined; + try { + const parsed = new URL(candidate.trim()); + return parsed.protocol === "http:" || parsed.protocol === "https:" ? parsed.origin : undefined; + } catch { + return undefined; + } +} + +const GENERIC_TOOL_TITLES = new Set(["tool", "tool call", "terminal"]); + +/** + * Suppresses session approval when a revised (`reask`) tool call's kind or + * command evidence conflicts with the permission request's original kind. + */ +function hasConflictingKind(request: AcpPermissionRequest): boolean { + const toolCall = request.toolCall; + if (!toolCall) return false; + if (toolCall.itemType === "mcp_tool_call") return false; + if (toolCall.kind !== undefined && toolCall.kind !== request.kind) return true; + if (request.kind !== "execute" && toolCall.command !== undefined) return true; + return false; +} + +/** + * The session-scoped grant key recorded when the user chooses "Always allow + * this session" on `request`, or `undefined` when no safe key can be derived. + */ +export function acpSessionApprovalGrantKey( + request: AcpPermissionRequest, + cwdRoots: ReadonlyArray, + platform: NodeJS.Platform = process.platform, +): string | undefined { + if (hasConflictingKind(request)) return undefined; + const toolCall = request.toolCall; + + // Normalized MCP tool calls (e.g. `threadlines_browser · browser_snapshot`). + if ( + toolCall?.itemType === "mcp_tool_call" && + typeof toolCall.data.server === "string" && + typeof toolCall.data.tool === "string" && + toolCall.data.server.length > 0 && + toolCall.data.tool.length > 0 + ) { + return `mcp:${toolCall.data.server}\0${toolCall.data.tool}`; + } + + if (request.kind === "execute") { + const command = commandOf(request); + const cwd = commandCwdOf(toolCall, cwdRoots); + if (!command || !cwd) return undefined; + const segments = splitSafeShellChain(command, platform); + if (segments && segments.length === 1) { + const prefix = safeReadOnlyCommandPrefixKey(segments[0]!, cwd); + if (prefix !== undefined) return prefix; + } + return `cmd:exact:${cwd}\0${command}`; + } + + if (request.kind === "edit" || request.kind === "delete" || request.kind === "move") { + const paths = pathsFromToolCall(toolCall); + if (paths.length === 0) return undefined; + if (paths.every((filePath) => isRealPathInsideWorkspace(filePath, cwdRoots))) { + return `file:${request.kind}:workspace`; + } + const exact = [ + ...new Set(paths.map((filePath) => resolveFilePath(filePath, cwdRoots))), + ].toSorted(); + return `file:${request.kind}:paths:${exact.join("\0")}`; + } + + if (request.kind === "read") { + const paths = pathsFromToolCall(toolCall); + if (paths.length > 0) { + const exact = [ + ...new Set(paths.map((filePath) => resolveFilePath(filePath, cwdRoots))), + ].toSorted(); + return `file:read:paths:${exact.join("\0")}`; + } + } + + if (request.kind === "fetch" || request.kind === "search") { + const origin = urlOriginFromToolCall(toolCall); + if (origin !== undefined) return `web:${request.kind}:${origin}`; + } + + const title = toolCall?.title?.trim(); + if (title && !GENERIC_TOOL_TITLES.has(title.toLowerCase())) { + return `tool:${request.kind}:${title}`; + } + return undefined; +} + +/** + * Whether `request` is covered by the session's remembered grants. For chained + * sequential commands without pipelines, redirects, or substitutions (`A && B`), + * every segment must individually match a remembered grant in the same `cwd`. + */ +export function isAcpSessionApprovalGranted( + request: AcpPermissionRequest, + grants: ReadonlySet, + cwdRoots: ReadonlyArray, + platform: NodeJS.Platform = process.platform, +): boolean { + if (grants.size === 0 || hasConflictingKind(request)) return false; + + const key = acpSessionApprovalGrantKey(request, cwdRoots, platform); + if (key !== undefined && grants.has(key)) return true; + + if (request.kind === "execute") { + const command = commandOf(request); + const cwd = commandCwdOf(request.toolCall, cwdRoots); + if (!command || !cwd) return false; + if (grants.has(`cmd:exact:${cwd}\0${command}`)) return true; + const segments = splitSafeShellChain(command, platform); + if (!segments || segments.length === 0) return false; + return segments.every((segment) => { + if (grants.has(`cmd:exact:${cwd}\0${segment}`)) return true; + const prefix = safeReadOnlyCommandPrefixKey(segment, cwd); + return prefix !== undefined && grants.has(prefix); + }); + } + + return false; +} diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index d49140020..d1ebf1a7e 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -1204,6 +1204,7 @@ export function makeAntigravityDescriptor( classifyPermissionRequest: antigravityQuestion, classifyElicitationForm: extractAntigravityElicitationForm, permissionOptionWarning: antigravityOptionWarning, + clientSessionApprovals: true, onEphemeralSessionClosed: (sessionId) => removeAntigravitySessionFiles(paths.profileDir, sessionId), cancellationNotice: "The request was cancelled by the client.", diff --git a/apps/server/src/provider/antigravity/AntigravityToolCalls.test.ts b/apps/server/src/provider/antigravity/AntigravityToolCalls.test.ts index d151066c3..ee23f85ba 100644 --- a/apps/server/src/provider/antigravity/AntigravityToolCalls.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityToolCalls.test.ts @@ -9,6 +9,7 @@ import { } from "../acp/AcpRuntimeModel.ts"; import { ANTIGRAVITY_TOOL_TEXT_LIMIT, + antigravityDirectMcpTool, antigravityProxiedMcpTool, boundAntigravityCommandLine, boundAntigravityText, @@ -211,6 +212,128 @@ describe("Antigravity call_mcp_tool, exactly", () => { }); }); +describe("Antigravity direct Threadlines MCP tools", () => { + it("recognizes direct Run mcp__ calls, including ask_user_to_run's command parameter", () => { + const roomDiff = { + title: "Run mcp_threadlines_room_room_diff", + kind: "other", + rawInput: { toolSummary: "Check git log", view: "log" }, + } as const; + expect(antigravityDirectMcpTool(roomDiff)).toEqual({ + server: "threadlines_room", + tool: "room_diff", + arguments: { toolSummary: "Check git log", view: "log" }, + }); + + const askToRun = { + title: "Run mcp_threadlines_commands_ask_user_to_run", + kind: "other", + rawInput: { command: "git push", reason: "Needs auth" }, + } as const; + expect(antigravityDirectMcpTool(askToRun)).toEqual({ + server: "threadlines_commands", + tool: "ask_user_to_run", + arguments: { command: "git push", reason: "Needs auth" }, + }); + + // Rejects wrong kind, unknown server, prefix-colliding external server, whitespace, edits, locations, or unexpected command fields. + const rejected = [ + { ...roomDiff, kind: "execute" }, + { ...roomDiff, title: "Run mcp_github_list_issues" }, + { ...roomDiff, title: "Run mcp_threadlines_room_extra_status" }, + { ...roomDiff, title: " Run mcp_threadlines_room_room_diff " }, + { ...roomDiff, title: "Run mcp_threadlines_room_room diff" }, + { ...roomDiff, rawInput: { CommandLine: "rm -rf /" } }, + { ...roomDiff, rawInput: { command: "rm -rf /" } }, + { ...roomDiff, rawInput: { executable: "/bin/sh", args: ["-c", "id"] } }, + { ...askToRun, rawInput: { CommandLine: "rm -rf /" } }, + { ...askToRun, rawInput: { executable: "/bin/sh" } }, + { ...roomDiff, content: [{ type: "diff" }] }, + { ...roomDiff, locations: [{ path: "/a" }] }, + ]; + for (const candidate of rejected) { + expect(antigravityDirectMcpTool(candidate)).toBeUndefined(); + } + }); + + it("keeps direct MCP identity across completion updates and drops it on conflicting updates", () => { + const direct = { + title: "Run mcp_threadlines_commands_ask_user_to_run", + kind: "other" as const, + rawInput: { command: "git push", reason: "Needs auth" }, + }; + const initial = makeToolCallState({ + toolCallId: "call_direct", + title: direct.title, + kind: direct.kind, + status: "pending", + rawInput: direct.rawInput, + })!; + const shown = normalizeAntigravityToolCall(initial, direct); + expect(shown).toMatchObject({ + itemType: "mcp_tool_call", + mcpCallMode: "direct", + title: "ask_user_to_run", + data: { server: "threadlines_commands", tool: "ask_user_to_run" }, + }); + expect(shown.command).toBeUndefined(); + expect(shown.data).not.toHaveProperty("command"); + + // Completion update without kind/rawInput stays an MCP tool call. + const doneUpdate = { + status: "completed" as const, + content: [{ type: "content" as const, content: { type: "text" as const, text: "shown" } }], + }; + const completed = normalizeAntigravityToolCall( + mergeToolCallState(shown, makeToolCallState({ toolCallId: "call_direct", ...doneUpdate })!), + doneUpdate, + ); + expect(completed.itemType).toBe("mcp_tool_call"); + expect(completed.data.server).toBe("threadlines_commands"); + + // A bare `kind: "execute"` update on a direct call must revert it (never fall into wrapper mode). + const bareExec = { kind: "execute" as const }; + const revertedBare = normalizeAntigravityToolCall( + mergeToolCallState(shown, makeToolCallState({ toolCallId: "call_direct", ...bareExec })!), + bareExec, + ); + expect(revertedBare.itemType).toBeUndefined(); + expect(revertedBare.kind).toBe("execute"); + expect(revertedBare.data).not.toHaveProperty("server"); + + // Conflicting execute update with CommandLine reverts it back to a shell command. + const conflict = { kind: "execute" as const, rawInput: { CommandLine: "rm -rf /" } }; + const reverted = normalizeAntigravityToolCall( + mergeToolCallState(shown, makeToolCallState({ toolCallId: "call_direct", ...conflict })!), + conflict, + ); + expect(reverted.itemType).toBeUndefined(); + expect(reverted.kind).toBe("execute"); + expect(reverted.data).not.toHaveProperty("server"); + + // A merged call that already carries a diff cannot be upgraded into a direct MCP call later. + const earlierEdit = makeToolCallState({ + toolCallId: "call_edit", + kind: "edit", + content: [{ type: "diff", path: "/repo/a.ts", oldText: "a", newText: "b" }], + })!; + const roomDirect = { + title: "Run mcp_threadlines_room_room_diff", + kind: "other" as const, + rawInput: { view: "status" }, + }; + const upgraded = normalizeAntigravityToolCall( + mergeToolCallState( + earlierEdit, + makeToolCallState({ toolCallId: "call_edit", ...roomDirect })!, + ), + roomDirect, + ); + expect(upgraded.itemType).toBeUndefined(); + expect(upgraded.data).not.toHaveProperty("server"); + }); +}); + describe("Antigravity tool text, storage", () => { it("drops inline data links, bounds long links and terminal ids, and budgets the command first", () => { const big = "x".repeat(70_000); diff --git a/apps/server/src/provider/antigravity/AntigravityToolCalls.ts b/apps/server/src/provider/antigravity/AntigravityToolCalls.ts index 3b46f8032..c1afaa866 100644 --- a/apps/server/src/provider/antigravity/AntigravityToolCalls.ts +++ b/apps/server/src/provider/antigravity/AntigravityToolCalls.ts @@ -17,9 +17,28 @@ * * @module provider/antigravity/AntigravityToolCalls */ +import { + AGENT_PAGE_PREVIEW_TOOL_NAME, + AGENT_PAGE_SHOW_TOOL_NAME, +} from "@threadlines/shared/agentPages"; import * as Schema from "effect/Schema"; import * as EffectAcpSchema from "effect-acp/schema"; +import { BrowserScreenshotToolkit, BrowserStandardToolkit } from "../../mcp/browserTools.ts"; +import { ASK_USER_TO_RUN_TOOL_NAME, COMMANDS_MCP_SERVER_NAME } from "../../mcp/commandTools.ts"; +import { DEVICE_MCP_SERVER_NAME, DEVICE_TOOLS } from "../../mcp/deviceTools.ts"; +import { BROWSER_MCP_SERVER_NAME } from "../../mcp/McpHttpServer.ts"; +import { PAGES_MCP_SERVER_NAME } from "../../mcp/pageTools.ts"; +import { + ROOM_MCP_SERVER_NAME, + ROOM_TOOL_NAMES, + SCHEDULED_RUN_TOOL_NAME, +} from "../../mcp/roomToolAccess.ts"; +import { + THEME_FIND_VSCODE_TOOL_NAME, + THEME_PREVIEW_TOOL_NAME, + THEME_SHOW_TOOL_NAME, +} from "../../mcp/themeTools.ts"; import { type AcpToolCallState, makeToolCallState } from "../acp/AcpRuntimeModel.ts"; /** The most characters one tool text field keeps, its cut marker included. */ @@ -40,6 +59,7 @@ const COMMAND_LINE_FIELDS = new Set([ "commandLine", "command", "cmd", + "executable", ]); const isRecord = (value: unknown): value is Record => @@ -274,18 +294,80 @@ export interface AntigravityToolCallUpdate { /** The input of a `call_mcp_tool` call holds these and nothing else. */ const WRAPPER_INPUT_KEYS = new Set(["ServerName", "ToolName", "Arguments"]); -/** A sign that the call runs a command or changes a file: never an MCP wrapper then. */ -function commandOrEditEvidence(update: AntigravityToolCallUpdate): boolean { +const DIRECT_MCP_TITLE_PREFIX = "Run mcp_"; + +/** + * Exact lookup of `Run mcp__` titles for Threadlines' own MCP + * servers, built from the canonical tool inventories so an external MCP server + * whose name shares a prefix (e.g. `threadlines_room_extra` + `status`) can + * never collide with `threadlines_room`. + */ +const DIRECT_THREADLINES_MCP_TITLES: ReadonlyMap< + string, + { readonly server: string; readonly tool: string } +> = (() => { + const entries = new Map(); + const register = (server: string, tools: ReadonlyArray) => { + for (const tool of tools) { + entries.set(`${DIRECT_MCP_TITLE_PREFIX}${server}_${tool}`, { server, tool }); + } + }; + register(ROOM_MCP_SERVER_NAME, [...ROOM_TOOL_NAMES, SCHEDULED_RUN_TOOL_NAME]); + register(PAGES_MCP_SERVER_NAME, [ + AGENT_PAGE_SHOW_TOOL_NAME, + AGENT_PAGE_PREVIEW_TOOL_NAME, + THEME_SHOW_TOOL_NAME, + THEME_PREVIEW_TOOL_NAME, + THEME_FIND_VSCODE_TOOL_NAME, + ]); + register(COMMANDS_MCP_SERVER_NAME, [ASK_USER_TO_RUN_TOOL_NAME]); + register( + DEVICE_MCP_SERVER_NAME, + DEVICE_TOOLS.map((tool) => tool.name), + ); + register(BROWSER_MCP_SERVER_NAME, [ + ...Object.keys(BrowserStandardToolkit.tools), + ...Object.keys(BrowserScreenshotToolkit.tools), + ]); + return entries; +})(); + +/** A sign that the call edits a file or runs a terminal. */ +function editOrTerminalEvidence(update: AntigravityToolCallUpdate): boolean { if (update.kind === "edit" || update.kind === "delete" || update.kind === "move") return true; if (update.content?.some((entry) => entry.type === "diff" || entry.type === "terminal")) return true; - if ((update.locations?.length ?? 0) > 0) return true; - return ( - isRecord(update.rawInput) && - Object.keys(update.rawInput).some((key) => COMMAND_LINE_FIELDS.has(key)) + return (update.locations?.length ?? 0) > 0; +} + +/** Whether merged `toolCall` data already carries edit, diff, terminal, or file location evidence. */ +function mergedEditOrTerminalEvidence(toolCall: AcpToolCallState): boolean { + if (toolCall.kind === "edit" || toolCall.kind === "delete" || toolCall.kind === "move") { + return true; + } + const { content, locations } = toolCall.data; + if ( + Array.isArray(content) && + content.some((entry) => isRecord(entry) && (entry.type === "diff" || entry.type === "terminal")) + ) { + return true; + } + return Array.isArray(locations) && locations.length > 0; +} + +function hasUnexpectedCommandField(rawInput: unknown, allowsLowercaseCommand: boolean): boolean { + if (!isRecord(rawInput)) return false; + return Object.keys(rawInput).some( + (key) => COMMAND_LINE_FIELDS.has(key) && !(allowsLowercaseCommand && key === "command"), ); } +/** A sign that the call runs a command or changes a file: never an MCP wrapper then. */ +function commandOrEditEvidence(update: AntigravityToolCallUpdate): boolean { + if (editOrTerminalEvidence(update)) return true; + return hasUnexpectedCommandField(update.rawInput, false); +} + /** Server and tool names kept, at most this long. */ const NAME_LIMIT = 256; @@ -314,6 +396,36 @@ export function antigravityProxiedMcpTool( return { server, tool, arguments: args }; } +/** + * The Threadlines MCP tool `agy acp` 1.5 invokes directly as `kind: "other"`, + * `title: "Run mcp__"` with tool arguments in `rawInput`. + * Matches only the exact registered Threadlines server/tool inventory and + * rejects edits, terminals, file locations, non-object inputs, and unexpected + * command-line fields (`ask_user_to_run`'s own `command` parameter is the sole + * exception). + */ +export function antigravityDirectMcpTool( + update: AntigravityToolCallUpdate, +): AntigravityProxiedMcpTool | undefined { + if (update.kind !== "other" || editOrTerminalEvidence(update)) return undefined; + if (typeof update.title !== "string") return undefined; + const matched = DIRECT_THREADLINES_MCP_TITLES.get(update.title); + if (matched === undefined) return undefined; + if (update.rawInput !== undefined && update.rawInput !== null && !isRecord(update.rawInput)) { + return undefined; + } + const allowsLowercaseCommand = + matched.server === COMMANDS_MCP_SERVER_NAME && matched.tool === ASK_USER_TO_RUN_TOOL_NAME; + if (hasUnexpectedCommandField(update.rawInput, allowsLowercaseCommand)) { + return undefined; + } + return { + server: matched.server, + tool: matched.tool, + ...(isRecord(update.rawInput) ? { arguments: update.rawInput } : {}), + }; +} + /** * What an approval for the call shows: the server and the tool first, then * its arguments, so a cut short loses the arguments' tail, never the target. @@ -324,9 +436,12 @@ export function antigravityMcpToolLabel(mcp: AntigravityProxiedMcpTool): string } /** The MCP tool a call was already shown as, from the fields `asMcpToolCall` set. */ -function shownMcpTool(toolCall: AcpToolCallState): { server: string; tool: string } | undefined { +function shownMcpTool( + toolCall: AcpToolCallState, +): { server: string; tool: string; mode: "wrapper" | "direct" } | undefined { const { server, tool } = toolCall.data; - return typeof server === "string" && typeof tool === "string" ? { server, tool } : undefined; + if (typeof server !== "string" || typeof tool !== "string") return undefined; + return { server, tool, mode: toolCall.mcpCallMode ?? "wrapper" }; } /** @@ -336,20 +451,23 @@ function shownMcpTool(toolCall: AcpToolCallState): { server: string; tool: strin function asMcpToolCall( toolCall: AcpToolCallState, names: { readonly server: string; readonly tool: string }, + mode: "wrapper" | "direct", ): AcpToolCallState { const { item: _item, command: _command, ...data } = toolCall.data; const { command: _shown, ...rest } = toolCall; const input = isRecord(data.rawInput) ? data.rawInput : undefined; + const rawArgs = mode === "wrapper" ? input?.Arguments : input; const mcp: AntigravityProxiedMcpTool = { server: boundAntigravityCommandLine(names.server, NAME_LIMIT), tool: boundAntigravityCommandLine(names.tool, NAME_LIMIT), - ...(isRecord(input?.Arguments) ? { arguments: input.Arguments } : {}), + ...(isRecord(rawArgs) ? { arguments: rawArgs } : {}), }; const { arguments: _old, ...withoutArguments } = data; return { ...rest, kind: "other", itemType: "mcp_tool_call", + mcpCallMode: mode, // The approval panel names a tool call by its title. title: mcp.tool, detail: antigravityMcpToolLabel(mcp), @@ -392,37 +510,87 @@ function withoutMcpTool( content: data.content as ReadonlyArray | undefined, locations: data.locations as ReadonlyArray | undefined, }); - const { itemType: _itemType, ...rest } = toolCall; + const { itemType: _itemType, mcpCallMode: _mcpCallMode, ...rest } = toolCall; return rebuilt ?? { ...rest, kind, data: { ...data, kind } }; } +function isWrapperInput(value: unknown, shown: { server: string; tool: string }): boolean { + if (!isRecord(value)) return false; + return ( + Object.keys(value).every((key) => WRAPPER_INPUT_KEYS.has(key)) && + value.ServerName === shown.server && + value.ToolName === shown.tool && + (value.Arguments === undefined || isRecord(value.Arguments)) + ); +} + /** * A tool call as the timeline should show it, given the update that just * arrived, as the agent sent it. A call the update positively shows to be - * `call_mcp_tool` is that MCP tool, with its server and tool, not a command; - * a later update with no command or edit about it keeps it so, with the - * newest arguments. Anything else stays, or goes back to, what the agent - * described. + * `call_mcp_tool` or a direct Threadlines MCP tool (`Run mcp__`) + * is that MCP tool, with its server and tool, not a command; a later update + * with no command or edit about it keeps it so, with the newest arguments. + * Anything else stays, or goes back to, what the agent described. */ export function normalizeAntigravityToolCall( toolCall: AcpToolCallState, update: AntigravityToolCallUpdate, ): AcpToolCallState { - const named = antigravityProxiedMcpTool(update); - if (named !== undefined) return asMcpToolCall(toolCall, named); const shown = shownMcpTool(toolCall); - if (shown === undefined) return toolCall; - const restated = isRecord(update.rawInput) ? update.rawInput : undefined; - const conflicting = - commandOrEditEvidence(update) || - (update.kind !== undefined && update.kind !== null && update.kind !== "execute") || - (update.title !== undefined && - update.title !== null && - update.title !== `MCP Tool ${shown.tool}`) || - (restated !== undefined && - (!Object.keys(restated).every((key) => WRAPPER_INPUT_KEYS.has(key)) || - restated.ServerName !== shown.server || - restated.ToolName !== shown.tool || - (restated.Arguments !== undefined && !isRecord(restated.Arguments)))); - return conflicting ? withoutMcpTool(toolCall, update) : asMcpToolCall(toolCall, shown); + + // If the call is already established as an MCP tool, validate strictly against + // that same wire form (`wrapper` vs `direct`) and merged state. + if (shown !== undefined) { + const restated = isRecord(update.rawInput) ? update.rawInput : undefined; + if (shown.mode === "direct") { + const allowsLowercaseCommand = + shown.server === COMMANDS_MCP_SERVER_NAME && shown.tool === ASK_USER_TO_RUN_TOOL_NAME; + const conflictingDirect = + mergedEditOrTerminalEvidence(toolCall) || + editOrTerminalEvidence(update) || + (update.kind !== undefined && update.kind !== null && update.kind !== "other") || + (update.title !== undefined && + update.title !== null && + update.title !== `${DIRECT_MCP_TITLE_PREFIX}${shown.server}_${shown.tool}`) || + (update.rawInput !== undefined && update.rawInput !== null && !isRecord(update.rawInput)) || + hasUnexpectedCommandField(restated, allowsLowercaseCommand) || + hasUnexpectedCommandField(toolCall.data.rawInput, allowsLowercaseCommand); + return conflictingDirect + ? withoutMcpTool(toolCall, update) + : asMcpToolCall(toolCall, shown, "direct"); + } + + const conflictingWrapper = + mergedEditOrTerminalEvidence(toolCall) || + commandOrEditEvidence(update) || + hasUnexpectedCommandField(toolCall.data.rawInput, false) || + (update.kind !== undefined && update.kind !== null && update.kind !== "execute") || + (update.title !== undefined && + update.title !== null && + update.title !== `MCP Tool ${shown.tool}`) || + (restated !== undefined && !isWrapperInput(restated, shown)); + return conflictingWrapper + ? withoutMcpTool(toolCall, update) + : asMcpToolCall(toolCall, shown, "wrapper"); + } + + // Never upgrade a call whose merged state already carries edit, diff, + // terminal, or file location evidence into an MCP tool call. + if (mergedEditOrTerminalEvidence(toolCall)) return toolCall; + + const named = antigravityProxiedMcpTool(update); + if (named !== undefined) { + return hasUnexpectedCommandField(toolCall.data.rawInput, false) + ? toolCall + : asMcpToolCall(toolCall, named, "wrapper"); + } + const direct = antigravityDirectMcpTool(update); + if (direct !== undefined) { + const allowsLowercaseCommand = + direct.server === COMMANDS_MCP_SERVER_NAME && direct.tool === ASK_USER_TO_RUN_TOOL_NAME; + return hasUnexpectedCommandField(toolCall.data.rawInput, allowsLowercaseCommand) + ? toolCall + : asMcpToolCall(toolCall, direct, "direct"); + } + return toolCall; } diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts index f5187ac7a..19fbb5316 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts @@ -82,7 +82,7 @@ type AgyDescriptor = ReturnType; const startAgy = ( scenario: string, adjust?: (descriptor: AgyDescriptor) => AgyDescriptor, - runtimeMode: "full-access" | "approval-required" | "auto-accept-edits" = "full-access", + runtimeMode: "full-access" | "approval-required" | "auto-accept-edits" | "auto" = "full-access", turnMachineSeams?: (seam: AcpTurnMachineSeam) => Effect.Effect, contextSeed?: ThreadContextSeed, startOverrides?: { readonly roomTools?: boolean }, @@ -1797,7 +1797,7 @@ describe("Antigravity tool rows and attachments", () => { ); it.live( - "auto-approves Threadlines room MCP calls in Supervised mode while still asking for browser and spoofed commands", + "auto-approves Threadlines room MCP calls (wrapper and direct) in Supervised mode while still asking for browser and spoofed commands", () => Effect.gen(function* () { const agy = yield* startAgy( @@ -1809,8 +1809,8 @@ describe("Antigravity tool rows and attachments", () => { { roomTools: true }, ); yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "go", attachments: [] }); - // Only browser_status and the spoofed command should open approval cards; room_ask is auto-approved. - for (let asked = 1; asked <= 2; asked += 1) { + // Only the two browser calls and the spoofed command should open approval cards; both room tools auto-approve. + for (let asked = 1; asked <= 3; asked += 1) { yield* agy.waitFor((events) => opened(events).length === asked); const request = opened(agy.events)[asked - 1]!; yield* agy.adapter.respondToRequest( @@ -1821,12 +1821,16 @@ describe("Antigravity tool rows and attachments", () => { } yield* agy.waitFor((events) => completedTurns(events).length === 1); const cards = opened(agy.events); - expect(cards).toHaveLength(2); + expect(cards).toHaveLength(3); expect(cards[0]?.payload).toMatchObject({ + requestType: "dynamic_tool_call", + detail: 'MCP tool threadlines_browser · browser_snapshot {"toolSummary":"Read page"}', + }); + expect(cards[1]?.payload).toMatchObject({ requestType: "exec_command_approval", detail: "MCP tool threadlines_browser · browser_status {}", }); - expect(cards[1]?.payload).toMatchObject({ + expect(cards[2]?.payload).toMatchObject({ requestType: "exec_command_approval", detail: "rm -rf build", }); @@ -1834,10 +1838,98 @@ describe("Antigravity tool rows and attachments", () => { { outcome: { outcome: "selected", optionId: "allow" } }, { outcome: { outcome: "selected", optionId: "allow" } }, { outcome: { outcome: "selected", optionId: "allow" } }, + { outcome: { outcome: "selected", optionId: "allow" } }, + { outcome: { outcome: "selected", optionId: "allow" } }, ]); }).pipe(Effect.scoped, Effect.provide(testServices)), ); + it.live( + "offers client-side session approvals for Antigravity, remembers scoped grants, resolves matching pending cards, and pauses grants in plan mode", + () => + Effect.gen(function* () { + const agy = yield* startAgy("session-approvals", undefined, "auto"); + yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "go", attachments: [] }); + + // 1. `gh pr view 101`: offers Always allow this session with the allow_once warning propagated. + yield* agy.waitFor((events) => opened(events).length === 1); + const ghViewCard = opened(agy.events)[0]!; + expect(ghViewCard.payload.availableDecisions).toEqual([ + "cancel", + "decline", + "acceptForSession", + "accept", + ]); + expect(ghViewCard.payload.decisionWarnings).toEqual({ + accept: "Network access. Runs outside the terminal sandbox.", + acceptForSession: "Network access. Runs outside the terminal sandbox.", + }); + yield* agy.adapter.respondToRequest( + agy.threadId, + ApprovalRequestId.make(String(ghViewCard.requestId)), + "acceptForSession", + ); + + // 2. `gh pr view 102` auto-approves; next card must be `gh pr merge 101`. + yield* agy.waitFor((events) => opened(events).length === 2); + const ghMergeCard = opened(agy.events)[1]!; + expect(ghMergeCard.payload.detail).toBe("gh pr merge 101 --squash"); + yield* agy.adapter.respondToRequest( + agy.threadId, + ApprovalRequestId.make(String(ghMergeCard.requestId)), + "accept", + ); + + // 3. Two concurrent `browser_snapshot` cards open; granting the first resolves both. + yield* agy.waitFor((events) => opened(events).length === 4); + const snapCard1 = opened(agy.events)[2]!; + expect(snapCard1.payload.detail).toContain( + "MCP tool threadlines_browser · browser_snapshot", + ); + yield* agy.adapter.respondToRequest( + agy.threadId, + ApprovalRequestId.make(String(snapCard1.requestId)), + "acceptForSession", + ); + + // 4. Third `browser_snapshot` auto-approves; next card must be `browser_click`. + yield* agy.waitFor((events) => opened(events).length === 5); + const clickCard = opened(agy.events)[4]!; + expect(clickCard.payload.detail).toContain("MCP tool threadlines_browser · browser_click"); + yield* agy.adapter.respondToRequest( + agy.threadId, + ApprovalRequestId.make(String(clickCard.requestId)), + "accept", + ); + + yield* agy.waitFor((events) => completedTurns(events).length === 1); + + // 5. Turn 2 in Plan mode: prior `gh pr view` grant must not auto-approve or offer acceptForSession. + yield* agy.adapter.sendTurn({ + threadId: agy.threadId, + input: "plan it", + attachments: [], + interactionMode: "plan", + }); + yield* agy.waitFor((events) => opened(events).length === 6); + const planCard = opened(agy.events)[5]!; + expect(planCard.payload.detail).toBe("gh pr view 103 --json state"); + expect(planCard.payload.availableDecisions).toEqual(["cancel", "decline", "accept"]); + yield* agy.adapter.respondToRequest( + agy.threadId, + ApprovalRequestId.make(String(planCard.requestId)), + "accept", + ); + yield* agy.waitFor((events) => completedTurns(events).length === 2); + + // Every answer sent to Antigravity is `allow` (allow_once), never an invented allow_always. + expect(answers(yield* agy.frames())).toHaveLength(8); + for (const reply of answers(yield* agy.frames())) { + expect(reply).toEqual({ outcome: { outcome: "selected", optionId: "allow" } }); + } + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + const opened = (events: ReadonlyArray) => events.filter((event) => event.type === "request.opened") as ReadonlyArray< Extract diff --git a/docs/providers/antigravity.md b/docs/providers/antigravity.md index 0c218c02a..834cd083a 100644 --- a/docs/providers/antigravity.md +++ b/docs/providers/antigravity.md @@ -218,13 +218,19 @@ turn stays open (see Turns above). ### Tool rows -- An MCP tool the agent reaches through `call_mcp_tool` shows as that tool (server and name), not - as a shell command, and doesn't hold the turn like a command. Only a call that is plainly that - wrapper does: one that also carries a command or an edit stays a command or an edit. Threadlines' - own room, page, command, and device tools are approved once without asking (matching Claude and - Codex); browser tools and other MCP servers still ask in Supervised mode, naming the server, the - tool, and its arguments. If a later update shows the call is something else, it goes back to what - that update says. +- An MCP tool the agent reaches through `call_mcp_tool` or as a direct Threadlines MCP tool (`Run + mcp__`) shows as that tool (server and name), not as a shell command, and doesn't + hold the turn like a command. Only a call that is plainly that wrapper or a known Threadlines MCP + tool does: one that also carries an unexpected command or an edit stays a command or an edit. + Threadlines' own room, page, command, and device tools are approved once without asking (matching + Claude and Codex); browser tools and other MCP servers still ask in Supervised and Auto modes, + naming the server, the tool, and its arguments. If a later update shows the call is something + else, it goes back to what that update says. +- `agy acp` sends only allow-once and deny options on permission requests. Threadlines adds Always + allow this session in memory for the open session (scoped to the MCP tool, strictly read-only + `git`/`gh` subcommand in the same working directory, exact command in the same working directory, + or verified workspace edit) and answers matching requests once automatically; grants clear when + the session ends, are never written to disk, and stay off in Plan mode. - An approval shows everything known about its call, even when Antigravity's request names only the call. If an update while you decide shows the approval is for something else, the card is withdrawn and asked again in the new words; the old card can't be answered.