From 1768c5f3e592fab507c6242428256faf771605ea Mon Sep 17 00:00:00 2001 From: Edgar Durand Date: Mon, 23 Nov 2026 21:40:51 -0300 Subject: [PATCH 1/2] fix(cli): agy commands run in containers, and agy replies render as one message agy's auto mode runs every command in its terminal sandbox, a user-namespace re-exec of agy that a container without user namespaces refuses (codespaces, the Box): 'Command failed to run: fork/exec /usr/local/bin/agy: operation not permitted'. Reproduced with agy acp + set_mode auto in a temp clone on the owner's codespace; default mode + an allow runs the same command. Where 'unshare --user --map-root-user true' fails, the adapter now runs auto as agy default and the CLI approves through its own permission gate (internal-path guard, guardrails); a session agy restores in auto is moved too. agy sends agent_message_chunk without messageId. The mapper minted a UUID per chunk, the runner read each as a new message and inserted a paragraph break mid-word and inside inline code ('confirm' / 'ados'), and the API lifted the orphaned path lines into read file cards. Id-less chunks now share one id; the tool call between two texts is their message boundary. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 5 + .../acp/antigravity-mode-substitute.test.ts | 105 ++++++++++++++++++ .../cli/__tests__/agents/acp/textGlue.test.ts | 55 +++++++++ apps/cli/src/agents/acp/adapters.ts | 14 +++ apps/cli/src/agents/acp/client.ts | 49 +++++++- apps/cli/src/agents/acp/command-handlers.ts | 4 +- apps/cli/src/agents/acp/mappers.ts | 22 +++- apps/cli/src/agents/acp/modes.ts | 14 +++ apps/cli/src/agents/acp/runner.ts | 16 ++- .../agents/antigravity/terminal-sandbox.ts | 88 +++++++++++++++ 10 files changed, 361 insertions(+), 11 deletions(-) create mode 100644 apps/cli/__tests__/agents/acp/antigravity-mode-substitute.test.ts create mode 100644 apps/cli/src/agents/antigravity/terminal-sandbox.ts diff --git a/CLAUDE.md b/CLAUDE.md index c802a6c2..1255600e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -198,6 +198,11 @@ Tests live next to the modules in `packages/shared/__tests__/` and run via `(cd JetBrains plugin is Kotlin and does **not** consume the shared package — if the same logic ever needs to exist there, port it deliberately and annotate the port. +### Antigravity (`agy acp`) quirks + +- **`auto` mode needs agy's terminal sandbox** (a user-namespace re-exec of agy on Linux). A container that blocks unprivileged user namespaces (GitHub Codespaces, the Box with `--cap-drop ALL`) refuses it, and every command fails `Command failed to run: fork/exec /usr/local/bin/agy: operation not permitted`. `agy acp` still advertises and accepts `auto` (its own `-p --mode auto` refuses it), and `enableTerminalSandbox:false` in settings.json does not change it. `agents/antigravity/terminal-sandbox.ts` probes `unshare --user --map-root-user true` once; where it fails, the adapter's `modeSubstitutes` runs `auto` as agy `default` (asks, then runs the command outside the sandbox) and `AcpClient.modeAutoApproves` makes the CLI approve, so every command still goes through our permission gate (internal-path guard, guardrails). A session agy restores in `auto` is moved to `default` too. (2026-11-24) +- **agy sends `agent_message_chunk` without `messageId`.** Those chunks share `NO_MESSAGE_ID` (`mappers.ts`); a UUID per chunk read as a new message each time, and the runner's new-message paragraph break split the reply mid-word and inside inline code, and the API lifted the orphaned path lines into "read" file cards. The message boundary of an id-less agent is the tool call between two texts (`StreamingState.toolSinceLastText`). Only the Claude and Codex adapters are known to send it. (2026-11-24) + ### PTY handling (CLI) `apps/cli/src/services/claude.service.ts` spawns Claude Code inside a Python PTY helper so Claude sees `stdin.isTTY === true` even when the CLI itself was launched from a non-TTY context. On Windows or when Python is unavailable it falls back to direct spawn. diff --git a/apps/cli/__tests__/agents/acp/antigravity-mode-substitute.test.ts b/apps/cli/__tests__/agents/acp/antigravity-mode-substitute.test.ts new file mode 100644 index 00000000..83fc882d --- /dev/null +++ b/apps/cli/__tests__/agents/acp/antigravity-mode-substitute.test.ts @@ -0,0 +1,105 @@ +/** + * Antigravity `auto` on a host without agy's terminal sandbox (owner's + * codespace, 2026-11-24): `agy acp` accepts `session/set_mode auto` and then + * runs every command in its namespace sandbox, which a container without user + * namespaces refuses — "Command failed to run: fork/exec /usr/local/bin/agy: + * operation not permitted" for `git status`, `ls`, `curl`. There the client + * keeps `auto` on the picker, sets agy `default` (asks, then runs outside the + * sandbox), and the CLI's own permission gate approves. + */ +import { describe, it, expect, vi } from 'vitest'; +import { AcpClient } from '../../../src/agents/acp/client'; +import type { AcpClientOptions } from '../../../src/agents/acp/client'; +import type { AdapterSpec } from '../../../src/agents/acp/adapters'; +import { antigravityModeSubstitutes } from '../../../src/agents/antigravity/terminal-sandbox'; + +const AGY_MODES = { + currentModeId: 'default', + availableModes: [ + { id: 'default', name: 'Default', description: 'Ask before edits and commands.' }, + { id: 'accept-edits', name: 'Accept edits' }, + { id: 'auto', name: 'Auto', description: 'Approve edits and safe commands.' }, + { id: 'plan', name: 'Plan' }, + ], +}; + +interface Internals { + connection: { + newSession: ReturnType; + setSessionMode: ReturnType; + } | null; + sessionId: string | null; +} + +function makeClient(sandboxAvailable: boolean): { + client: AcpClient; + setSessionMode: ReturnType; +} { + const adapter: AdapterSpec = { + command: 'agy', + args: ['acp'], + requiresAgentBinary: 'agy', + waitForBinary: async () => true, + modeSubstitutes: antigravityModeSubstitutes(sandboxAvailable), + }; + const opts: AcpClientOptions = { + adapter, + cwd: '/tmp/w', + onSessionUpdate: () => undefined, + onRequestPermission: async () => ({ outcome: { outcome: 'cancelled' } }), + }; + const client = new AcpClient(opts); + const setSessionMode = vi.fn(async () => undefined); + const internals = client as unknown as Internals; + internals.connection = { + newSession: vi.fn(async () => ({ sessionId: 'sess-1', modes: AGY_MODES, configOptions: [] })), + setSessionMode, + }; + return { client, setSessionMode }; +} + +describe('Antigravity auto mode without the terminal sandbox', () => { + it('sends agy `default` for `auto`, keeps reporting `auto`, and auto-approves', async () => { + const { client, setSessionMode } = makeClient(false); + await client.newConversation(); + await client.setMode('auto'); + + expect(setSessionMode).toHaveBeenCalledWith({ sessionId: 'sess-1', modeId: 'default' }); + expect(client.getCurrentModeId()).toBe('auto'); + expect(client.modeAutoApproves('auto')).toBe(true); + expect(client.modeAutoApproves('default')).toBe(false); + expect(client.getAvailableModes().find((m) => m.id === 'auto')?.description).toMatch( + /guardrails still apply/, + ); + }); + + it('moves a session agy restored in `auto` onto `default`', async () => { + const { client, setSessionMode } = makeClient(false); + const internals = client as unknown as Internals; + internals.connection!.newSession = vi.fn(async () => ({ + sessionId: 'sess-2', + modes: { ...AGY_MODES, currentModeId: 'auto' }, + configOptions: [], + })); + await client.newConversation(); + + expect(setSessionMode).toHaveBeenCalledWith({ sessionId: 'sess-2', modeId: 'default' }); + expect(client.getCurrentModeId()).toBe('auto'); + }); + + it('other modes pass through unchanged', async () => { + const { client, setSessionMode } = makeClient(false); + await client.newConversation(); + await client.setMode('accept-edits'); + expect(setSessionMode).toHaveBeenCalledWith({ sessionId: 'sess-1', modeId: 'accept-edits' }); + expect(client.modeAutoApproves('accept-edits')).toBe(false); + }); + + it('where the sandbox works, `auto` is agy’s own mode', async () => { + const { client, setSessionMode } = makeClient(true); + await client.newConversation(); + await client.setMode('auto'); + expect(setSessionMode).toHaveBeenCalledWith({ sessionId: 'sess-1', modeId: 'auto' }); + expect(client.modeAutoApproves('auto')).toBe(false); + }); +}); diff --git a/apps/cli/__tests__/agents/acp/textGlue.test.ts b/apps/cli/__tests__/agents/acp/textGlue.test.ts index 55e51071..481bd0dc 100644 --- a/apps/cli/__tests__/agents/acp/textGlue.test.ts +++ b/apps/cli/__tests__/agents/acp/textGlue.test.ts @@ -99,3 +99,58 @@ describe('ACP text — a new message after a finished sentence is a new paragrap expect(text).toBe('v1.2.Final'); }); }); + +/** + * Antigravity (agy) sends `agent_message_chunk` WITHOUT a `messageId`. The + * mapper used to mint a UUID per chunk, so every chunk read as a new message + * and got a paragraph break: "confirm" / "ados", "`feat: text-to" / "-speech", + * and orphaned path lines ("durand/pasito.git`") the API lifted into "read" + * file cards (owner's codespace, 2026-11-24). The exact delta sequence from + * that turn's CLI log must render as ONE markdown message, byte-for-byte. + */ +describe('ACP text — an agent without message ids streams one message', () => { + const AGY_DELTAS = [ + 'Los cambios ya fueron confirm', + 'ados y subidos a `main`:\n\n- **Commit:** `c256c30` (`feat: text-to', + '-speech, resumen de habitos y suite de pruebas`)\n- **Repositorio:** `https://github.com/edgar-', + 'durand/pasito.git`\n- **Archivos actualizados:**\n - `src/utils/speech.ts` (', + 'Text-to-Speech)\n - `src/components/TaskCard.tsx` (Botón de audio por', + ' tarea)\n - `src/screens/parent/ParentHome.tsx` (Métricas de hábitos)\n ', + '- `src/theme.ts` (Estilo `bodyBold`)\n - `scripts/test-smoke', + '.js` y `package.json` (Script de pruebas)', + ]; + + it('the 2026-11-24 agy reply is the plain concatenation of its deltas', async () => { + const { state, lastText } = makeState(); + const text = await runTurn( + state, + AGY_DELTAS.map((d) => messageChunk(null, d)), + ); + expect(text).toBe(AGY_DELTAS.join('')); + expect(lastText()).toBe(AGY_DELTAS.join('')); + expect(text).not.toContain('confirm\n\nados'); + expect(text).toContain('`https://github.com/edgar-durand/pasito.git`'); + }); + + it('an absent messageId (undefined, not null) is the same single stream', async () => { + const { state } = makeState(); + const note = (text: string) => + ({ + sessionId: 'sess-1', + update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text } }, + }) as unknown as Parameters[0]; + const text = await runTurn(state, [note('Los cambios ya fueron confirm'), note('ados.')]); + expect(text).toBe('Los cambios ya fueron confirmados.'); + }); + + it('text after a tool call is still a new paragraph without message ids', async () => { + const { state } = makeState(); + const text = await runTurn(state, [ + messageChunk(null, 'Checking the '), + messageChunk(null, 'files.'), + toolCall('call_104'), + messageChunk(null, 'Found it.'), + ]); + expect(text).toBe('Checking the files.\n\nFound it.'); + }); +}); diff --git a/apps/cli/src/agents/acp/adapters.ts b/apps/cli/src/agents/acp/adapters.ts index bba666ec..7f3113b5 100644 --- a/apps/cli/src/agents/acp/adapters.ts +++ b/apps/cli/src/agents/acp/adapters.ts @@ -35,6 +35,8 @@ import { import { ensureKimiInstalled, augmentKimiPath } from '../kimi/installer'; import { ensureOpencodeInstalled, augmentOpencodePath } from '../opencode/installer'; import { ensureAntigravityInstalled } from '../antigravity/installer'; +import { antigravityModeSubstitutes } from '../antigravity/terminal-sandbox'; +import type { ModeSubstitute } from './modes'; import { isLocalSession } from '../../baton/gate'; // CommonJS module — `require` is already in scope. Aliased so we @@ -73,6 +75,12 @@ export interface AdapterSpec { * fails the prompt on the first match instead of waiting out the idle window. */ fatalTurnStderr?: RegExp; + /** + * Advertised agent modes this host cannot run natively, keyed by mode id + * (Antigravity's `auto` where its terminal sandbox cannot start, see + * `antigravity/terminal-sandbox.ts`). Undefined when every mode works. + */ + modeSubstitutes?: Readonly>; } /** @@ -306,10 +314,16 @@ const REGISTRY: Partial AdapterSpec | null>> = { // agy sends normal `session/request_permission` requests and OUR runner // answers them (auto-approve on codespace/self-hosted, the mobile prompt on a // local pair; see `permission-gate.ts`), exactly as for every other agent. + // + // ⚠️ `auto` runs commands in agy's terminal sandbox, which cannot start in a + // container without user namespaces (codespaces, the Box): every command + // failed "fork/exec /usr/local/bin/agy: operation not permitted". There + // `modeSubstitutes` runs `auto` as agy `default` + our auto-approve. antigravity: () => ({ command: 'agy', args: ['acp'], requiresAgentBinary: 'agy', + modeSubstitutes: antigravityModeSubstitutes(), waitForBinary: async (o) => { if (isLocalSession()) await ensureAntigravityInstalled(); // install.sh drops agy in ~/.local/bin — fold it into a stale PATH (an diff --git a/apps/cli/src/agents/acp/client.ts b/apps/cli/src/agents/acp/client.ts index c92e735a..c5ebadf2 100644 --- a/apps/cli/src/agents/acp/client.ts +++ b/apps/cli/src/agents/acp/client.ts @@ -807,6 +807,7 @@ export class AcpClient { // axis than models. Sets availableModes + currentModeId (empty/undefined // when the agent advertises no modes — NO hardcoded fallback). this.captureModes(newSession.modes ?? null); + await this.applyModeSubstitute(newSession.sessionId); // `currentServiceTier` is a legacy non-standard codex-acp field surfaced // only in the welcome banner — not part of the native model contract. // ⚠️ VALIDATE, don't trust the cast. Adapters have been observed sending @@ -1191,6 +1192,7 @@ export class AcpClient { // brand-new SessionModeState, NOT a clone of the initial session's. this.captureModelConfig(ns.configOptions ?? []); this.captureModes(ns.modes ?? null); + await this.applyModeSubstitute(ns.sessionId); // ⚠️ A fresh `session/new` starts in the agent's DEFAULT (ask-per-tool) mode // — it does NOT inherit the initial session's `INITIAL_AGENT_MODE=agent-full- // access` env (that env is applied by the agent only to its first session). @@ -1381,7 +1383,10 @@ export class AcpClient { // Re-capture the native session modes too — the resumed conversation may sit // on a different mode than the one at spawn (`loadSession` returns the same // `modes` shape as `newSession`). - if (loaded?.modes !== undefined) this.captureModes(loaded.modes ?? null); + if (loaded?.modes !== undefined) { + this.captureModes(loaded.modes ?? null); + await this.applyModeSubstitute(sessionId); + } log.info('acpClient', `loadSession ← ok sessionId=${sessionId.slice(0, 8)}`); } @@ -1635,11 +1640,17 @@ export class AcpClient { if (this.availableModes.length === 0) { throw new Error('mode selection not available: this agent advertises no ACP session modes'); } - log.info('acpClient', `setMode → ${modeId}`); + // A mode this host can't run natively goes to the agent as its substitute; + // the picker keeps showing the mode the user chose. + const agentModeId = this.opts.adapter.modeSubstitutes?.[modeId]?.agentModeId ?? modeId; + log.info( + 'acpClient', + `setMode → ${modeId}${agentModeId !== modeId ? ` (agent mode ${agentModeId})` : ''}`, + ); // Typed native RPC (`session/set_mode`) — request is `{ sessionId, modeId }`. await this.connection.setSessionMode({ sessionId: this.sessionId, - modeId, + modeId: agentModeId, }); // Track the in-use mode so a subsequent list_modes reports it as current. this.currentModeId = modeId; @@ -1656,6 +1667,35 @@ export class AcpClient { return this.availableModes; } + /** + * True when the CLI itself must approve every permission request in this + * mode: a full-bypass mode, or a substituted mode whose agent-side stand-in + * asks (see {@link AdapterSpec.modeSubstitutes}). + */ + modeAutoApproves(modeId: string): boolean { + return ( + modeIsFullAutoApprove(modeId) || this.opts.adapter.modeSubstitutes?.[modeId]?.autoApprove === true + ); + } + + /** + * A session the agent created or restored in a mode this host can't run + * (agy reloads a conversation in the mode it was saved in) is moved to the + * substitute, and keeps reporting the chosen mode. Best-effort. + */ + private async applyModeSubstitute(sessionId: string): Promise { + const current = this.currentModeId; + const sub = current ? this.opts.adapter.modeSubstitutes?.[current] : undefined; + if (!sub || !this.connection) return; + try { + await this.connection.setSessionMode({ sessionId, modeId: sub.agentModeId }); + log.info('acpClient', `mode ${current} runs as agent mode ${sub.agentModeId} on this host`); + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + log.warn('acpClient', `could not apply the ${current} mode substitute: ${msg}`); + } + } + /** The native current mode id (or undefined if the agent advertises no modes). */ getCurrentModeId(): string | undefined { return this.currentModeId; @@ -1674,10 +1714,11 @@ export class AcpClient { return; } this.currentModeId = modes.currentModeId; + const subs = this.opts.adapter.modeSubstitutes; this.availableModes = (modes.availableModes ?? []).map((mode) => ({ id: mode.id, label: mode.name, - description: mode.description ?? undefined, + description: subs?.[mode.id]?.description ?? mode.description ?? undefined, })); } diff --git a/apps/cli/src/agents/acp/command-handlers.ts b/apps/cli/src/agents/acp/command-handlers.ts index 1b941a14..6ba09054 100644 --- a/apps/cli/src/agents/acp/command-handlers.ts +++ b/apps/cli/src/agents/acp/command-handlers.ts @@ -1678,7 +1678,9 @@ async function setModeH(ctx: AcpCommandContext): Promise { // full-bypass mode keeps auto-approve; every ask-mode flips it false so the // agent's permission prompts RELAY to mobile. A headless session never sends // set_mode, so it stays auto. - opts.autoApprovePermissions = modeIsFullAutoApprove(modeId); + // A substituted mode (agy `auto` without its terminal sandbox) runs on an + // agent mode that asks, so the CLI approves in its place. + opts.autoApprovePermissions = client.modeAutoApproves(modeId); log.info( 'acpRunner', `set_mode → ${modeId} (autoApprovePermissions=${opts.autoApprovePermissions})`, diff --git a/apps/cli/src/agents/acp/mappers.ts b/apps/cli/src/agents/acp/mappers.ts index 40c9a7cb..96335734 100644 --- a/apps/cli/src/agents/acp/mappers.ts +++ b/apps/cli/src/agents/acp/mappers.ts @@ -293,16 +293,28 @@ export function mapPermissionRequest( // ─── Helpers ───────────────────────────────────────────────────────── +/** + * The chunkId of every message chunk an agent sends WITHOUT a `messageId` + * (Antigravity omits it; the Claude and Codex adapters send one). + */ +export const NO_MESSAGE_ID = 'acp-message'; + /** * ACP messages carry an optional `messageId` so chunks belonging to - * the same agent turn cluster together. When present, we use it as - * the chunkId so the backend can splice multiple text deltas into - * one mobile bubble; when absent, we generate a fresh UUID per - * chunk (each becomes its own bubble — degraded but correct). + * the same agent message cluster together. When present, it is the chunkId. + * When absent, every chunk gets the same {@link NO_MESSAGE_ID}: they are the + * continuation of one stream, NOT one message each. + * + * ⚠️ It used to be a fresh UUID per chunk. The runner reads a changed id as a + * new message and starts a new paragraph, so an agent without message ids got + * a paragraph break at every chunk boundary — mid-word ("confirm" / "ados") + * and inside inline code, whose orphaned path lines the API then lifted into + * "read" file cards (Antigravity, 2026-11-24). The runner finds the message + * boundary of these agents at the tool call between them instead. */ function messageChunkId(messageId: string | null | undefined): string { if (typeof messageId === 'string' && messageId.length > 0) return messageId; - return randomUUID(); + return NO_MESSAGE_ID; } /** diff --git a/apps/cli/src/agents/acp/modes.ts b/apps/cli/src/agents/acp/modes.ts index ced3a40d..3369255c 100644 --- a/apps/cli/src/agents/acp/modes.ts +++ b/apps/cli/src/agents/acp/modes.ts @@ -16,3 +16,17 @@ export const FULL_AUTO_MODE_RE = /bypass|yolo|danger|full.?access|skip.?perm|aut export function modeIsFullAutoApprove(modeId: string): boolean { return FULL_AUTO_MODE_RE.test(modeId); } + +/** + * An advertised agent mode this host cannot run natively (see + * `AdapterSpec.modeSubstitutes`). The mode stays on the picker under its own + * id; the client sets `agentModeId` on the agent instead, and when + * `autoApprove` is set the CLI's own permission gate answers the agent's + * prompts in its place. + */ +export interface ModeSubstitute { + agentModeId: string; + autoApprove: boolean; + /** Replaces the agent's description, which no longer says what happens. */ + description?: string; +} diff --git a/apps/cli/src/agents/acp/runner.ts b/apps/cli/src/agents/acp/runner.ts index b45c57c8..70f8ab6a 100644 --- a/apps/cli/src/agents/acp/runner.ts +++ b/apps/cli/src/agents/acp/runner.ts @@ -368,6 +368,15 @@ export class StreamingState { */ private lastTextMessageId: string | null = null; + /** + * A tool call (tool_use / tool_result) arrived since the last text delta. + * The text after it is a new message even when the adapter sends no message + * ids (Antigravity: every chunk shares one id, see + * `NO_MESSAGE_ID` in mappers.ts) — so "Checking the files." → tool → + * "Found it." still starts a new paragraph. + */ + private toolSinceLastText = false; + /** * Stable chunkId that ALL `thinking` segments of the current turn collapse * onto (set to the first thought chunk's id, reset each {@link beginTurn}) — @@ -579,6 +588,7 @@ export class StreamingState { this.streamingChunks.clear(); this.turnTextChunkId = null; this.lastTextMessageId = null; + this.toolSinceLastText = false; this.turnThoughtChunkId = null; // New turn → new namespace, so a reused adapter chunkId (e.g. `toolu_01`) // never collides with a prior turn's already-finalized chunk on the feed. @@ -661,12 +671,16 @@ export class StreamingState { // the same reply reconciles as REPLACE and is left alone) starts a new // paragraph — never glue it onto the previous message's last byte. const newMessage = - this.lastTextMessageId !== null && this.lastTextMessageId !== delta.chunkId; + this.lastTextMessageId !== null && + (this.lastTextMessageId !== delta.chunkId || this.toolSinceLastText); const appended = cumulativeContent === prior + delta.delta; if (newMessage && appended && /\S$/.test(prior) && !/^\s/.test(delta.delta)) { cumulativeContent = `${prior}\n\n${delta.delta}`; } this.lastTextMessageId = delta.chunkId; + this.toolSinceLastText = false; + } else if (delta.kind === 'tool_use' || delta.kind === 'tool_result') { + this.toolSinceLastText = true; } this.streamingChunks.set(chunkId, { kind: delta.kind, content: cumulativeContent }); diff --git a/apps/cli/src/agents/antigravity/terminal-sandbox.ts b/apps/cli/src/agents/antigravity/terminal-sandbox.ts new file mode 100644 index 00000000..797dbd12 --- /dev/null +++ b/apps/cli/src/agents/antigravity/terminal-sandbox.ts @@ -0,0 +1,88 @@ +/** + * Antigravity's terminal sandbox and the hosts that cannot run it. + * + * agy's `auto` mode runs every shell command inside its own terminal sandbox: + * on Linux it re-executes itself in a new user namespace. A container whose + * seccomp profile blocks unprivileged user namespaces (GitHub Codespaces, our + * CodeAgent Box with `--cap-drop ALL`) refuses that clone, and every command + * fails with + * + * Command failed to run: fork/exec /usr/local/bin/agy: operation not permitted + * + * (`git status`, `ls`, `curl` — owner's codespace, 2026-11-24; reproduced with + * `agy acp` + `session/set_mode auto` in a temp clone). The model may retry + * with `BypassSandbox`, or may give up and tell the user to run the command. + * agy's own `--mode auto` print mode refuses the mode on this host, but + * `agy acp` still advertises `auto` and accepts it. `enableTerminalSandbox: + * false` in settings.json does not change what `auto` does. + * + * In `default` mode agy asks before each command and runs it OUTSIDE the + * sandbox once allowed (verified on the same host). So on a host without the + * sandbox the client keeps `auto` on the picker, sets agy to `default`, and the + * CLI's own auto-approve answers the prompts. Every command then goes through + * our permission gate (internal-path guard, guardrails), which agy's own + * `auto` skips. The container is the isolation. + */ + +import { spawnSync } from 'node:child_process'; +import { readFileSync } from 'node:fs'; +import type { ModeSubstitute } from '../acp/modes'; + +let cached: boolean | undefined; + +function readKnob(file: string): string | null { + try { + return readFileSync(file, 'utf8').trim(); + } catch { + return null; + } +} + +/** + * True when agy's terminal sandbox can run here. macOS and Windows use their + * own OS sandboxes, which agy handles itself. On Linux we attempt the same + * thing agy does, an unprivileged user namespace, with `unshare`: our process + * runs under the same seccomp profile as the agy it spawns. Cached for the + * process lifetime. + */ +export function agyTerminalSandboxAvailable(): boolean { + if (cached !== undefined) return cached; + cached = probe(); + return cached; +} + +function probe(): boolean { + if (process.platform !== 'linux') return true; + const r = spawnSync('unshare', ['--user', '--map-root-user', 'true'], { + stdio: 'ignore', + timeout: 5_000, + }); + if (!r.error) return r.status === 0; + // No `unshare` binary: fall back to the kernel switches that disable them. + return ( + readKnob('/proc/sys/user/max_user_namespaces') !== '0' && + readKnob('/proc/sys/kernel/unprivileged_userns_clone') !== '0' + ); +} + +/** Test seam: forget the cached probe result. */ +export function resetAgyTerminalSandboxProbe(): void { + cached = undefined; +} + +/** + * The agy modes this host cannot run natively. Empty when the sandbox works. + */ +export function antigravityModeSubstitutes( + sandboxAvailable: boolean = agyTerminalSandboxAvailable(), +): Readonly> | undefined { + if (sandboxAvailable) return undefined; + return { + auto: { + agentModeId: 'default', + autoApprove: true, + description: + 'Approve edits and commands without asking. CodeAgent guardrails still apply.', + }, + }; +} From c6b9b2c2593740f3f07f9803640e7d859312f246 Mon Sep 17 00:00:00 2001 From: Edgar Durand Date: Mon, 23 Nov 2026 21:41:33 -0300 Subject: [PATCH 2/2] refactor(cli): drop the unused sandbox probe reset seam Co-Authored-By: Claude Opus 5.5 --- apps/cli/src/agents/antigravity/terminal-sandbox.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/apps/cli/src/agents/antigravity/terminal-sandbox.ts b/apps/cli/src/agents/antigravity/terminal-sandbox.ts index 797dbd12..1d7c097e 100644 --- a/apps/cli/src/agents/antigravity/terminal-sandbox.ts +++ b/apps/cli/src/agents/antigravity/terminal-sandbox.ts @@ -65,11 +65,6 @@ function probe(): boolean { ); } -/** Test seam: forget the cached probe result. */ -export function resetAgyTerminalSandboxProbe(): void { - cached = undefined; -} - /** * The agy modes this host cannot run natively. Empty when the sandbox works. */