Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
105 changes: 105 additions & 0 deletions apps/cli/__tests__/agents/acp/antigravity-mode-substitute.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof vi.fn>;
setSessionMode: ReturnType<typeof vi.fn>;
} | null;
sessionId: string | null;
}

function makeClient(sandboxAvailable: boolean): {
client: AcpClient;
setSessionMode: ReturnType<typeof vi.fn>;
} {
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);
});
});
55 changes: 55 additions & 0 deletions apps/cli/__tests__/agents/acp/textGlue.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof mapSessionUpdate>[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.');
});
});
14 changes: 14 additions & 0 deletions apps/cli/src/agents/acp/adapters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<Record<string, ModeSubstitute>>;
}

/**
Expand Down Expand Up @@ -306,10 +314,16 @@ const REGISTRY: Partial<Record<AgentId, () => 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
Expand Down
49 changes: 45 additions & 4 deletions apps/cli/src/agents/acp/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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)}`);
}

Expand Down Expand Up @@ -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;
Expand All @@ -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<void> {
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;
Expand All @@ -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,
}));
}

Expand Down
4 changes: 3 additions & 1 deletion apps/cli/src/agents/acp/command-handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1678,7 +1678,9 @@ async function setModeH(ctx: AcpCommandContext): Promise<void> {
// 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})`,
Expand Down
22 changes: 17 additions & 5 deletions apps/cli/src/agents/acp/mappers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down
14 changes: 14 additions & 0 deletions apps/cli/src/agents/acp/modes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Loading
Loading