Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(agents): add Antigravity (agy) as a builtin agent with hook status
Fabricio Casali025a1c3f07cd
diff --git a/src/core/agents/hook-server.hook-event-field.test.ts b/src/core/agents/hook-server.hook-event-field.test.tsnew file mode 100644index 000000000..4137b6d79--- /dev/null+++ b/src/core/agents/hook-server.hook-event-field.test.ts@@ -0,0 +1,129 @@+// The `nodeterm_hook_event` form field — how an agent whose payload carries no event name still+// reaches its normalizer with one.+//+// Antigravity (`agy` 1.2.3) sends five hook events and names none of them in the payload (measured+// on Windows 11 in a temporary HOME; the fixture pins it). The managed command exports the name, the script POSTs it as+// this field, and the hook server merges it into the parsed payload exactly like its siblings+// `nodeterm_pending_id` / `nodeterm_answered`. These cases pin the three promises that makes:+// the field reaches the normalizer, it beats a value planted inside the agent's JSON, and its+// absence degrades to "no event" without throwing.+import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest'+import { mkdtempSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { hookServer } from './hook-server'+import { initPlatform, resetPlatformForTests } from '../platform'+import { fakePlatform } from '../platform-fake'+import type { NormalizedAgentEvent } from '@shared/agents/normalize'++let dir = ''+let events: NormalizedAgentEvent[] = []+let raws: Record<string, unknown>[] = []++function post(agent: string, fields: Record<string, string>): Promise<Response> {+ return fetch(`http://127.0.0.1:${hookServer.getPort()}/hook/${agent}`, {+ method: 'POST',+ headers: {+ 'X-Nodeterm-Hook-Token': hookServer.getToken(),+ 'content-type': 'application/x-www-form-urlencoded'+ },+ body: new URLSearchParams(fields).toString()+ })+}++beforeAll(async () => {+ dir = mkdtempSync(join(tmpdir(), 'hooksrv-event-field-'))+ resetPlatformForTests()+ initPlatform(fakePlatform({ userDataDir: dir }))+ await hookServer.start()+ hookServer.setListener((e) => {+ events.push(e)+ })+ hookServer.setRawListener((_agent, _node, payload) => {+ raws.push(payload)+ })+})++afterAll(() => {+ hookServer.stop()+ rmSync(dir, { recursive: true, force: true })+})++beforeEach(() => {+ events = []+ raws = []+})++describe('the nodeterm_hook_event form field', () => {+ it('reaches the antigravity normalizer as the event name', async () => {+ const res = await post('antigravity', {+ nodeId: 'term-agy-1',+ nodeterm_hook_event: 'Stop',+ payload: JSON.stringify({ fullyIdle: true, conversationId: 'x' })+ })+ expect(res.status).toBe(204)+ expect(events).toHaveLength(1)+ expect(events[0]).toMatchObject({+ nodeId: 'term-agy-1',+ agentId: 'antigravity',+ kind: 'state',+ state: 'done',+ sessionId: 'x'+ })+ // The raw listener sees the merged field too, like its siblings.+ expect(raws[0]).toMatchObject({ nodeterm_hook_event: 'Stop' })+ })++ it('beats a value planted inside the agent JSON (assigned after the parse)', async () => {+ await post('antigravity', {+ nodeId: 'term-agy-1',+ nodeterm_hook_event: 'PreInvocation',+ payload: JSON.stringify({ nodeterm_hook_event: 'Stop', fullyIdle: true, conversationId: 'x' })+ })+ expect(events).toHaveLength(1)+ expect(events[0].state).toBe('working')+ })++ it('without the field, a planted value is all there is — and a POST without either maps to nothing', async () => {+ const res = await post('antigravity', {+ nodeId: 'term-agy-1',+ payload: JSON.stringify({ fullyIdle: true, conversationId: 'x' })+ })+ expect(res.status).toBe(204)+ expect(events).toHaveLength(0)+ // The raw listener still ran: an unnamed event is not an error.+ expect(raws).toHaveLength(1)+ })++ it('an unparseable payload with a field still answers 204 and never throws', async () => {+ const res = await post('antigravity', {+ nodeId: 'term-agy-1',+ nodeterm_hook_event: 'Stop',+ payload: '{not json'+ })+ expect(res.status).toBe(204)+ // `{}` + the field: a Stop with no fullyIdle reads as finished.+ expect(events).toHaveLength(1)+ expect(events[0].state).toBe('done')+ })++ it('an empty field is not merged', async () => {+ await post('antigravity', {+ nodeId: 'term-agy-1',+ nodeterm_hook_event: '',+ payload: JSON.stringify({ conversationId: 'x' })+ })+ expect(events).toHaveLength(0)+ expect(raws[0]).not.toHaveProperty('nodeterm_hook_event')+ })++ it('does not change what a claude POST normalizes to', async () => {+ await post('claude', {+ nodeId: 'term-claude-1',+ nodeterm_hook_event: 'PreInvocation',+ payload: JSON.stringify({ hook_event_name: 'Stop', session_id: 's' })+ })+ expect(events).toHaveLength(1)+ expect(events[0]).toMatchObject({ agentId: 'claude', state: 'done', sessionId: 's' })+ })+})diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.tsindex 7025d31bc..c726d1190 100644--- a/src/core/agents/hook-server.ts+++ b/src/core/agents/hook-server.ts@@ -753,6 +753,14 @@ class HookServer {// so the normalizer sees it and maps it to a synthetic working transition. See// docs/hook-reply-approvals.md.if (form.nodeterm_answered) payload.nodeterm_answered = form.nodeterm_answered+ // The EVENT NAME, for an agent whose hook payload does not carry one. Antigravity (`agy`)+ // sends five events with no name in any of them, and two of them (Pre/PostInvocation) have+ // identical keys, so the managed command exports the name and the script sends it as this+ // field. Assigned AFTER JSON.parse, so the form wins over a value planted in the agent's+ // JSON. Deliberately NOT `hook_event_name`: that is a real payload field for claude, codex,+ // gemini and copilot, and a name of our own cannot collide with any of them. The value is+ // only ever compared against a closed set (normalizeAntigravity), never interpolated.+ if (form.nodeterm_hook_event) payload.nodeterm_hook_event = form.nodeterm_hook_event// Raw listener first: it drives the transcript-tailing features (which need// transcript_path). Inside the try so a throwing raw listener still ends 204.this.rawListener?.(agentId, nodeId, payload, { verified })diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 95cf5038a..ce01806a0 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -7826,6 +7826,7 @@ export function Canvas() {'node.newAgent.opencode': () => { addAgentNode('opencode'); return true },'node.newAgent.grok': () => { addAgentNode('grok'); return true },'node.newAgent.copilot': () => { addAgentNode('copilot'); return true },+ 'node.newAgent.antigravity': () => { addAgentNode('antigravity'); return true },'node.newSticky': () => { addSticky(); return true },'node.newBrowser': () => { addBrowser(); return true },// Opening the URL prompt IS claiming the chord — a cancelled prompt creates nothing, but thediff --git a/src/renderer/lib/antigravityTurn.test.ts b/src/renderer/lib/antigravityTurn.test.tsnew file mode 100644index 000000000..6d2007459--- /dev/null+++ b/src/renderer/lib/antigravityTurn.test.ts@@ -0,0 +1,109 @@+// An antigravity station's errored turn must not hold its `--after`+// dependents forever.+//+// `lastTurnError` (issue #521) is retired ONLY by a `newTurn` event (agentStatus.ts), and until the+// fix `normalizeAntigravity` never emitted one: after one `Stop` with `terminationReason: 'ERROR'`+// every dependent stayed QUEUED for the rest of the app run, however many later turns succeeded.+// The fix marks the `PreInvocation` whose `invocationNum === 0` (the first model call of an agy+// execution) as the new turn.+//+// End to end, against the REAL store and the REAL launch gate: the normalizer's event is applied the+// way Canvas's hook listener applies it (`setState(nodeId, state, agentId, newTurn, pendingId,+// verified, errored)`), and `launchesToFire` is asked whether the dependent may go.+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { normalizeAntigravity, type NormalizedAgentEvent } from '@shared/agents/normalize'+import { DONE_HOLDOFF_MS, useAgentStatus } from '../state/agentStatus'+import { launchesToFire } from './pendingLaunch'++const UP = 'agy-up'+const LIVE = new Set([UP])+const DOWN = [{ id: 'down', data: { pendingLaunch: { after: [UP], command: 'go' } } }]++/** The hook server's envelope: agy's payload plus the merged `nodeterm_hook_event` form field. */+const hook = (event: string, payload: Record<string, unknown>): NormalizedAgentEvent => {+ const out = normalizeAntigravity({+ nodeId: UP,+ agentId: 'antigravity',+ payload: { conversationId: 'c1', ...payload, nodeterm_hook_event: event }+ })+ if (!out) throw new Error(`${event} normalized to null`)+ return out+}++/** Exactly what Canvas's `agent:status` listener does with a `state` event. */+const apply = (e: NormalizedAgentEvent): void => {+ if (e.kind === 'state' && e.state) {+ useAgentStatus.getState().setState(e.nodeId, e.state, e.agentId, e.newTurn, e.pendingId, e.verified, e.errored)+ }+}++const entry = () => useAgentStatus.getState().byId[UP]+const fires = (): boolean =>+ launchesToFire(DOWN, useAgentStatus.getState().byId, LIVE).some((l) => l.id === 'down')++beforeEach(() => {+ vi.useFakeTimers()+ useAgentStatus.setState({ byId: {} })+})+afterEach(() => {+ vi.useRealTimers()+})++describe('antigravity: an errored turn is retired by the next execution', () => {+ it('ERROR → recorded → PreInvocation(0) clears it → a clean Stop keeps it clear and releases the dependent', () => {+ apply(hook('PreInvocation', { invocationNum: 0 }))+ apply(hook('Stop', { fullyIdle: true, terminationReason: 'ERROR' }))+ expect(entry().state).toBe('done')+ expect(entry().lastTurnError).toBeDefined()+ expect(fires()).toBe(false)++ // The user sends another prompt, after the done-holdoff (an ordinary pace).+ vi.advanceTimersByTime(DONE_HOLDOFF_MS + 1000)+ apply(hook('PreInvocation', { invocationNum: 0 }))+ expect(entry().state).toBe('working')+ expect(entry().lastTurnError).toBeUndefined()+ expect(fires()).toBe(false) // working is not done++ apply(hook('PreInvocation', { invocationNum: 1 }))+ apply(hook('Stop', { fullyIdle: true, terminationReason: 'NO_TOOL_CALL' }))+ expect(entry().state).toBe('done')+ expect(entry().lastTurnError).toBeUndefined()+ expect(fires()).toBe(true)+ })++ it('a later model call of the same execution does NOT retire the error', () => {+ apply(hook('Stop', { fullyIdle: true, terminationReason: 'ERROR' }))+ vi.advanceTimersByTime(DONE_HOLDOFF_MS + 1000)+ apply(hook('PreInvocation', { invocationNum: 3 }))+ expect(entry().lastTurnError).toBeDefined()+ })++ it('the done-holdoff: a PreInvocation(0) right after a done still lights working', () => {+ apply(hook('PreInvocation', { invocationNum: 0 }))+ apply(hook('Stop', { fullyIdle: true, terminationReason: 'NO_TOOL_CALL' }))+ expect(entry().state).toBe('done')+ vi.advanceTimersByTime(500) // well inside DONE_HOLDOFF_MS: a quick follow-up prompt+ apply(hook('PreInvocation', { invocationNum: 0 }))+ expect(entry().state).toBe('working')+ })++ it('…while a late non-first PreInvocation inside the holdoff is still held off', () => {+ apply(hook('Stop', { fullyIdle: true, terminationReason: 'NO_TOOL_CALL' }))+ vi.advanceTimersByTime(500)+ apply(hook('PreInvocation', { invocationNum: 2 }))+ expect(entry().state).toBe('done')+ })++ it("a background tool's late PostToolUse neither retires the error nor releases the dependent", () => {+ apply(hook('Stop', { fullyIdle: true, terminationReason: 'ERROR' }))+ vi.advanceTimersByTime(DONE_HOLDOFF_MS + 1000)+ // A background tool's late PostToolUse says nothing (null) and must not release anything.+ const post = normalizeAntigravity({+ nodeId: UP,+ agentId: 'antigravity',+ payload: { nodeterm_hook_event: 'PostToolUse', toolCall: { name: 'run_command' } }+ })+ expect(post).toBeNull()+ expect(fires()).toBe(false)+ })+})diff --git a/src/shared/agents/__fixtures__/antigravity/hook-payloads.json b/src/shared/agents/__fixtures__/antigravity/hook-payloads.jsonnew file mode 100644index 000000000..b347258f8--- /dev/null+++ b/src/shared/agents/__fixtures__/antigravity/hook-payloads.json@@ -0,0 +1,205 @@+{+ "_provenance": "Captured live from the Antigravity CLI (agy) 1.2.3 on Windows 11, real Google account, 2026-09-15, with a temporary HOME. The 'event' of each entry is NOT from the payload: agy does not send the event name; the capture .cmd wrapper recorded it from an environment variable. Paths, conversationId and artifactDirectoryPath are anonymised; KEYS AND SHAPES ARE UNCHANGED (camelCase, as protojson emits them).",+ "_eventNameIsNotInPayload": true,+ "_terminationReasonEnum": [+ "UNSPECIFIED",+ "ERROR",+ "USER_CANCELED",+ "MAX_INVOCATIONS",+ "NO_TOOL_CALL",+ "MAX_FORCED_INVOCATIONS",+ "EARLY_CONTINUE",+ "TERMINAL_STEP_TYPE",+ "TERMINAL_CUSTOM_HOOK",+ "INJECTED_RESPONSE",+ "MAX_TOKEN_BUDGET_EXCEEDED",+ "HALTED_STEP"+ ],+ "_terminationReasonObserved": [+ "NO_TOOL_CALL",+ "TERMINAL_CUSTOM_HOOK"+ ],+ "events": [+ {+ "event": "PreInvocation",+ "note": "start of the turn; invocationNum starts at 0",+ "payload": {+ "artifactDirectoryPath": "C:/Users/user/.gemini/antigravity-cli/brain/00000000-0000-4000-8000-000000000001",+ "conversationId": "00000000-0000-4000-8000-000000000001",+ "initialNumSteps": 1,+ "invocationNum": 0,+ "modelName": "gemini-3.8-flash-high",+ "transcriptPath": "C:/Users/user/.gemini/antigravity-cli/brain/00000000-0000-4000-8000-000000000001/.system_generated/logs/transcript_full.jsonl",+ "workspacePaths": []+ }+ },+ {+ "event": "PreToolUse",+ "note": "an ordinary tool call (run_command in the background); args carries the readable toolAction/toolSummary",+ "payload": {+ "artifactDirectoryPath": "C:/Users/user/.gemini/antigravity-cli/brain/00000000-0000-4000-8000-000000000001",+ "conversationId": "00000000-0000-4000-8000-000000000001",+ "modelName": "gemini-3.8-flash-high",+ "stepIdx": 2,+ "toolCall": {+ "args": {+ "CommandLine": "ping -n 30 127.0.0.1",+ "Cwd": "C:\\Users\\user\\.gemini\\antigravity-cli\\scratch",+ "WaitMsBeforeAsync": 500,+ "toolAction": "Running ping command in background",+ "toolSummary": "Background ping"+ },+ "name": "run_command"+ },+ "transcriptPath": "C:/Users/user/.gemini/antigravity-cli/brain/00000000-0000-4000-8000-000000000001/.system_generated/logs/transcript_full.jsonl",+ "workspacePaths": []+ }+ },+ {+ "event": "PostToolUse",+ "note": "SAME stepIdx as its PreToolUse; arrived 27.5 s AFTER the Stop fullyIdle:false because the tool ran in the background",+ "payload": {+ "artifactDirectoryPath": "C:/Users/user/.gemini/antigravity-cli/brain/00000000-0000-4000-8000-000000000001",+ "conversationId": "00000000-0000-4000-8000-000000000001",+ "error": "",+ "modelName": "gemini-3.8-flash-high",+ "stepIdx": 2,+ "toolCall": {+ "args": {+ "CommandLine": "ping -n 30 127.0.0.1",+ "Cwd": "C:\\Users\\user\\.gemini\\antigravity-cli\\scratch",+ "WaitMsBeforeAsync": 500,+ "toolAction": "Running ping command in background",+ "toolSummary": "Background ping"+ },+ "name": "run_command"+ },+ "transcriptPath": "C:/Users/user/.gemini/antigravity-cli/brain/00000000-0000-4000-8000-000000000001/.system_generated/logs/transcript_full.jsonl",+ "workspacePaths": []+ }+ },+ {+ "event": "PostInvocation",+ "note": "same fields as PreInvocation",+ "payload": {+ "artifactDirectoryPath": "C:/Users/user/.gemini/antigravity-cli/brain/00000000-0000-4000-8000-000000000001",+ "conversationId": "00000000-0000-4000-8000-000000000001",+ "initialNumSteps": 1,+ "invocationNum": 0,+ "modelName": "gemini-3.8-flash-high",+ "transcriptPath": "C:/Users/user/.gemini/antigravity-cli/brain/00000000-0000-4000-8000-000000000001/.system_generated/logs/transcript_full.jsonl",+ "workspacePaths": []+ }+ },+ {+ "event": "Stop",+ "note": "INTERMEDIATE Stop: the model turn ended while a background task was still alive -> fullyIdle:false",+ "payload": {+ "artifactDirectoryPath": "C:/Users/user/.gemini/antigravity-cli/brain/00000000-0000-4000-8000-000000000001",+ "conversationId": "00000000-0000-4000-8000-000000000001",+ "error": "",+ "executionNum": 0,+ "fullyIdle": false,+ "modelName": "gemini-3.8-flash-high",+ "terminationReason": "NO_TOOL_CALL",+ "transcriptPath": "C:/Users/user/.gemini/antigravity-cli/brain/00000000-0000-4000-8000-000000000001/.system_generated/logs/transcript_full.jsonl",+ "workspacePaths": []+ }+ },+ {+ "event": "Stop",+ "note": "FINAL Stop of the same turn, after the background task finished",+ "payload": {+ "artifactDirectoryPath": "C:/Users/user/.gemini/antigravity-cli/brain/00000000-0000-4000-8000-000000000001",+ "conversationId": "00000000-0000-4000-8000-000000000001",+ "error": "",+ "executionNum": 0,+ "fullyIdle": true,+ "modelName": "gemini-3.8-flash-high",+ "terminationReason": "NO_TOOL_CALL",+ "transcriptPath": "C:/Users/user/.gemini/antigravity-cli/brain/00000000-0000-4000-8000-000000000001/.system_generated/logs/transcript_full.jsonl",+ "workspacePaths": []+ }+ },+ {+ "event": "PreToolUse",+ "note": "ask_question: the only measured path to NEEDS YOU; args.questions[].question/options carry the text",+ "payload": {+ "artifactDirectoryPath": "C:/Users/user/.gemini/antigravity-cli/brain/00000000-0000-4000-8000-000000000002",+ "conversationId": "00000000-0000-4000-8000-000000000002",+ "modelName": "gemini-3.8-flash-high",+ "stepIdx": 2,+ "toolCall": {+ "args": {+ "questions": [+ {+ "is_multi_select": false,+ "options": [+ "JSON",+ "YAML",+ "TOML"+ ],+ "question": "Qual formato de arquivo de configuração você prefere utilizar?"+ }+ ],+ "toolAction": "Asking format preference",+ "toolSummary": "Configuration format inquiry"+ },+ "name": "ask_question"+ },+ "transcriptPath": "C:/Users/user/.gemini/antigravity-cli/brain/00000000-0000-4000-8000-000000000002/.system_generated/logs/transcript_full.jsonl",+ "workspacePaths": [+ "C:/work/project"+ ]+ }+ },+ {+ "event": "PostToolUse",+ "note": "the pair of the ask_question: arrived only 63 s later, when the question left the screen",+ "payload": {+ "artifactDirectoryPath": "C:/Users/user/.gemini/antigravity-cli/brain/00000000-0000-4000-8000-000000000002",+ "conversationId": "00000000-0000-4000-8000-000000000002",+ "error": "",+ "modelName": "gemini-3.8-flash-high",+ "stepIdx": 2,+ "toolCall": {+ "args": {+ "questions": [+ {+ "is_multi_select": false,+ "options": [+ "JSON",+ "YAML",+ "TOML"+ ],+ "question": "Qual formato de arquivo de configuração você prefere utilizar?"+ }+ ],+ "toolAction": "Asking format preference",+ "toolSummary": "Configuration format inquiry"+ },+ "name": "ask_question"+ },+ "transcriptPath": "C:/Users/user/.gemini/antigravity-cli/brain/00000000-0000-4000-8000-000000000002/.system_generated/logs/transcript_full.jsonl",+ "workspacePaths": [+ "C:/work/project"+ ]+ }+ },+ {+ "event": "Stop",+ "note": "terminationReason TERMINAL_CUSTOM_HOOK, produced by PostInvocation answering terminationBehavior=terminate",+ "payload": {+ "artifactDirectoryPath": "C:/Users/user/.gemini/antigravity-cli/brain/00000000-0000-4000-8000-000000000003",+ "conversationId": "00000000-0000-4000-8000-000000000003",+ "error": "",+ "executionNum": 0,+ "fullyIdle": true,+ "modelName": "gemini-3.8-flash-high",+ "terminationReason": "TERMINAL_CUSTOM_HOOK",+ "transcriptPath": "C:/Users/user/.gemini/antigravity-cli/brain/00000000-0000-4000-8000-000000000003/.system_generated/logs/transcript_full.jsonl",+ "workspacePaths": []+ }+ }+ ]+}diff --git a/src/shared/agents/config.capabilities.test.ts b/src/shared/agents/config.capabilities.test.tsindex ec3dadcbf..0d4afd9d0 100644--- a/src/shared/agents/config.capabilities.test.ts+++ b/src/shared/agents/config.capabilities.test.ts@@ -24,7 +24,8 @@ import {RENAME_CAPABLE,hasSharedIdentity,agentLaunchProgram,- resumeCommand+ resumeCommand,+ reportsSessionEnd} from './config'describe('CONTEXT_LINK_CAPABLE', () => {@@ -272,6 +273,71 @@ describe('grok capabilities', () => {})})+/**+ * Antigravity (`agy`) joins with exactly ONE capability list: AGENT_HOOK_TARGETS. Its leaves are a+ * normalizer (normalizeAntigravity) and an installer for `~/.gemini/config/hooks.json`. Every other+ * list is a separate leaf it does not have yet, and joining one early lights a badge that never+ * updates or offers an action that silently does the wrong thing (rule 2 in CLAUDE.md). Each+ * exclusion below says which leaf is missing — measured facts (`agy` 1.2.3, Windows 11).+ */+describe('antigravity capabilities', () => {+ it('is a builtin that launches `agy`, prompt through --prompt-interactive', () => {+ expect(BUILTIN_AGENT_IDS).toContain('antigravity')+ expect(AGENT_CONFIG.antigravity.launchCmd).toBe('agy')+ expect(AGENT_CONFIG.antigravity.expectedProcess).toBe('agy')+ expect(AGENT_CONFIG.antigravity.label).toBe('Antigravity')+ expect(AGENT_CONFIG.antigravity.promptInjectionMode).toBe('flag-interactive')+ expect(AGENT_CONFIG.antigravity.promptFlag).toBe('--prompt-interactive')+ })++ it('is the only agent that overrides the interactive prompt flag', () => {+ // copilot's `--interactive` must stay the default, byte-identical.+ for (const id of BUILTIN_AGENT_IDS.filter((a) => a !== 'antigravity')) {+ expect(AGENT_CONFIG[id].promptFlag, id).toBeUndefined()+ }+ })++ it('reports status through its own hooks', () => {+ // Badge, unread, completion notification, `--after` dependency and trigger target all follow.+ expect(hasHooks('antigravity')).toBe(true)+ })++ it('does not claim the capabilities whose per-agent leaf is unwritten', () => {+ // No SessionEnd-shaped event exists among agy's five, so a DROPPED chip would be a coin flip.+ expect(reportsSessionEnd('antigravity')).toBe(false)+ // No token count and no stated window anywhere measured (the TUI's "1.1k tokens" is per+ // thought block, not context use) — rule 6: no trustworthy denominator, no meter. Joining would+ // also switch on context.ensure and the find-bar index.+ expect(hasUsage('antigravity')).toBe(false)+ // No transcript parser or locator yet (transcript_full.jsonl, not transcript.jsonl).+ expect(canChat('antigravity')).toBe(false)+ expect(readsClaudeShapedTranscript('antigravity')).toBe(false)+ expect(canTransferFrom('antigravity')).toBe(false)+ expect(canContextLink('antigravity')).toBe(false)+ // `agy --conversation <id>` resumes (measured), but it is a later slice: joining now makes cold+ // restore type an unvalidated resume line.+ expect(canResume('antigravity')).toBe(false)+ expect(mintsSessionId('antigravity')).toBe(false)+ // No subagent/recurring/branch events are wired (invoke_subagent exists in the enum, unmeasured).+ expect(canSubagent('antigravity')).toBe(false)+ expect(canRecur('antigravity')).toBe(false)+ expect(canBranch('antigravity')).toBe(false)+ // Canvas control needs a shim + a discovery file; none is installed for agy.+ expect(canControlCanvas('antigravity')).toBe(false)+ // Permission flags exist (--mode, --dangerously-skip-permissions) but the approval-mode table+ // has no antigravity row yet; model switching has no gateway mapping.+ expect(hasPermissionMode('antigravity')).toBe(false)+ expect(canSwitchModel('antigravity')).toBe(false)+ // Title lives in SQLite (unmeasured) and there is no rename command; read ⊇ write holds.+ expect(canReadTitle('antigravity')).toBe(false)+ expect(canRename('antigravity')).toBe(false)+ expect(RENAME_CAPABLE as readonly string[]).not.toContain('antigravity')+ // No shared app-server mode, and agy does not announce its own copies.+ expect(hasSharedIdentity('antigravity')).toBe(false)+ expect(reportsOwnCopy('antigravity')).toBe(false)+ })+})+describe('copy feedback', () => {it('stays quiet for claude, whose CLI announces its own copies', () => {// Claude Code captures the mouse and prints "copied N chars to tmux buffer · paste withdiff --git a/src/shared/agents/config.ts b/src/shared/agents/config.tsindex 5e15b49c2..203dfb857 100644--- a/src/shared/agents/config.ts+++ b/src/shared/agents/config.ts@@ -2,7 +2,14 @@// Design: an open AgentId string, a declarative config record, and// capabilities expressed as const membership lists (not a capability object).-export type BuiltinAgentId = 'claude' | 'codex' | 'gemini' | 'opencode' | 'grok' | 'copilot'+export type BuiltinAgentId =+ | 'claude'+ | 'codex'+ | 'gemini'+ | 'opencode'+ | 'grok'+ | 'copilot'+ | 'antigravity'// Open type — custom agents are any string ('custom:<uuid>'). Never restrict the set.export type AgentId = BuiltinAgentId | (string & {})@@ -17,6 +24,16 @@ export interface AgentConfig {color: string // node colorlaunchCmd: string // base launch commandpromptInjectionMode: PromptInjectionMode+ /**+ * The flag `flag-interactive` emits before the prompt. Absent = `--interactive`, which is+ * copilot's spelling and stays byte-identical for it.+ *+ * antigravity (`agy`) is the case that needs it: its interactive-with-prompt flag is+ * `--prompt-interactive` (`-i`), measured with `agy --help` on 1.2.3, and it has NO positional+ * prompt at all — the usage lists subcommands instead — so neither `argv` nor+ * `stdin-after-start` could deliver a prompt without producing a silently wrong command line.+ */+ promptFlag?: string/*** Put this between the command and an `argv` prompt — in practice `'--'`, and only for a CLI* whose grammar has BOTH a positional prompt and subcommands.@@ -57,7 +74,8 @@ export const BUILTIN_AGENT_IDS: readonly BuiltinAgentId[] = ['gemini','opencode','grok',- 'copilot'+ 'copilot',+ 'antigravity']export const AGENT_CONFIG: Record<BuiltinAgentId, AgentConfig> = {@@ -126,13 +144,35 @@ export const AGENT_CONFIG: Record<BuiltinAgentId, AgentConfig> = {// All `COPILOT_PROVIDER_*` gateway vars. Excludes `COPILOT_HOME` (config dir) and// `COPILOT_HOOK_*` (nodeterm constants).vanillaEnvPattern: '^COPILOT_PROVIDER_'+ },+ antigravity: {+ // Google Antigravity CLI. Measured on `agy` 1.2.3 (Windows 11) — docs/antigravity-agent.md.+ label: 'Antigravity',+ color: '#00a3a3',+ launchCmd: 'agy',+ // `agy` has no positional prompt (its usage lists subcommands in that slot), and its+ // interactive-with-prompt flag is `--prompt-interactive`, not copilot's `--interactive`.+ promptInjectionMode: 'flag-interactive',+ promptFlag: '--prompt-interactive',+ expectedProcess: 'agy'}}// Capabilities = const builtin membership lists. A custom agent resolves through its declared// base harness (capabilityAgentId); one with no base automatically gets only spawn + terminal-title// + process status.-export const AGENT_HOOK_TARGETS = ['claude', 'codex', 'gemini', 'opencode', 'grok', 'copilot'] as const+// antigravity joined with ONLY this list: its normalizer (normalizeAntigravity) and its+// installer are the leaves that exist. Every other list below is a separate leaf it does not have+// yet — see the `antigravity capabilities` block in config.capabilities.test.ts for each reason.+export const AGENT_HOOK_TARGETS = [+ 'claude',+ 'codex',+ 'gemini',+ 'opencode',+ 'grok',+ 'copilot',+ 'antigravity'+] as constexport const RESUMABLE_AGENTS = ['claude', 'codex', 'gemini', 'opencode', 'grok', 'copilot'] as const// Agents whose session id we MINT at launch (`--session-id <uuid>`) instead of learning it only// from hook events. Each member must have a measured caller-chosen-id grammar below.diff --git a/src/shared/agents/custom-agent.ts b/src/shared/agents/custom-agent.tsindex 8568a927c..70b1c5a75 100644--- a/src/shared/agents/custom-agent.ts+++ b/src/shared/agents/custom-agent.ts@@ -29,6 +29,8 @@ export interface EffectiveAgentConfig {launchCmd: stringpromptInjectionMode: PromptInjectionModeargvPromptSeparator?: string+ /** See `AgentConfig.promptFlag` — inherited from the base harness only, like the separator. */+ promptFlag?: stringexpectedProcess?: string/** `true` for a custom agent (`CustomAgent`), `false` for a builtin. */custom: boolean@@ -76,6 +78,7 @@ export function resolveAgentConfig(launchCmd,promptInjectionMode,argvPromptSeparator: base?.argvPromptSeparator,+ promptFlag: base?.promptFlag,expectedProcess: base?.expectedProcess,custom: true,baseAgent: customAgent?.baseAgentdiff --git a/src/shared/agents/hook-events.ts b/src/shared/agents/hook-events.tsindex 2931ddd17..7c33a6c65 100644--- a/src/shared/agents/hook-events.ts+++ b/src/shared/agents/hook-events.ts@@ -92,3 +92,37 @@ export const COPILOT_HOOK_EVENTS = ['Notification','SessionEnd'] as const++/**+ * Antigravity CLI (`agy`) hook events (→ normalizeAntigravity), subscribed in+ * `~/.gemini/config/hooks.json` under our own bundle key (core/agents/hooks/antigravity.ts).+ *+ * `agy` 1.2.3 publishes five events in TWO shapes (its bundled `hooks.md`, "Supported Event+ * Types"): the tool events are GROUPED (`{matcher, hooks: [...]}`) and the lifecycle events are a+ * FLAT list of handlers. The `{event, matcher}` form here marks the grouped ones; a plain string is+ * a flat one. The matcher is `*`, which is the value every capture of agy 1.2.3 ran with+ * and saw match every tool.+ *+ * FOUR of the five, and the choice is a cost the user accepted, not an accident:+ * - `PreInvocation` fires before every model call → `working`.+ * - `PreToolUse` / `PostToolUse` bracket each tool execution; `ask_question` between them is the+ * only NEEDS YOU a hook can see. SUBSCRIBING TO `PreToolUse` MAKES OUR HOOK A SYNCHRONOUS GATE+ * IN FRONT OF EVERY TOOL CALL OF EVERY `agy` ON THIS MACHINE, inside and outside nodeterm — see+ * `antigravityDecisionFor` for the stdout contract that keeps that gate open.+ * - `Stop` ends the loop; `fullyIdle` says whether it really ended.+ * - `PostInvocation` is left out: it adds no state the four above do not give, and every+ * subscribed event is one more SYNCHRONOUS hook process per occurrence.+ *+ * COST, measured on Windows 11 (20 runs, dispatched as agy does): the answer reaches stdout in ~100 ms, but agy waits for the PROCESS to exit, and that takes+ * ~520 ms per event inside a nodeterm node (Git Bash forks ~55 ms each for the token read, the temp+ * file and the path conversion before the POST is backgrounded) and ~155 ms in a plain terminal.+ * A tool step fires three of these four events, so ~1.6 s of hook per step inside nodeterm. The+ * earlier "~100 ms" figure measured a bare `.cmd` stand-in, not this script. Accepted for+ * now; backgrounding everything after the stdin read is a tracked follow-up.+ */+export const ANTIGRAVITY_HOOK_EVENTS: readonly ManagedHookEvent[] = [+ 'PreInvocation',+ { event: 'PreToolUse', matcher: '*' },+ { event: 'PostToolUse', matcher: '*' },+ 'Stop'+]diff --git a/src/shared/agents/launch.test.ts b/src/shared/agents/launch.test.tsindex 12efcf19d..1dfd6f15f 100644--- a/src/shared/agents/launch.test.ts+++ b/src/shared/agents/launch.test.ts@@ -143,6 +143,34 @@ describe('assembleLaunchCommand — builtins (byte-identical to the historical p).command).toBe("copilot --interactive 'fix it' --session-id=abc-123")})+ it('Antigravity delivers its prompt through --prompt-interactive, never a positional', () => {+ // `agy` 1.2.3 has no positional prompt (subcommands sit in that slot) and spells its+ // interactive-with-prompt flag `--prompt-interactive`; copilot's `--interactive` is an error.+ expect(+ assembleLaunchCommand({ agentId: 'antigravity', initialPrompt: 'fix it\nnow' }, ENV).command+ ).toBe("agy --prompt-interactive 'fix it now'")+ expect(assembleLaunchCommand({ agentId: 'antigravity' }, ENV).command).toBe('agy')+ // No minted id and no permission flag: antigravity is in neither list yet.+ expect(+ assembleLaunchCommand(+ { agentId: 'antigravity', sessionId: 'abc-123', sessionIdFlagSupported: true, permissionMode: 'plan' },+ ENV+ ).command+ ).toBe('agy')+ })+ it('a custom agent built on Antigravity inherits its prompt flag', () => {+ setCustomAgentBaseResolver((id) => (id === 'custom:agy' ? 'antigravity' : undefined))+ const agyCustom: CustomAgent = {+ id: 'custom:agy',+ label: 'agy (mine)',+ launchCmd: 'agy-wrapper',+ baseAgent: 'antigravity',+ promptInjectionMode: 'argv'+ }+ expect(+ assembleLaunchCommand({ agentId: 'custom:agy', customAgent: agyCustom, initialPrompt: 'go' }, ENV).command+ ).toBe("agy-wrapper --prompt-interactive 'go'")+ })it('adds a safely quoted model override after the ordinary Claude launch flags', () => {expect(assembleLaunchCommand(diff --git a/src/shared/agents/launch.ts b/src/shared/agents/launch.tsindex 2fd2aff0f..b68322d2d 100644--- a/src/shared/agents/launch.ts+++ b/src/shared/agents/launch.ts@@ -206,7 +206,7 @@ export function assembleLaunchCommand(eff.promptInjectionMode === 'flag-prompt'? '--prompt': eff.promptInjectionMode === 'flag-interactive'- ? '--interactive'+ ? (eff.promptFlag ?? '--interactive'): nullconst isFlagPrompt = !!promptFlagconst usesSep = !!promptArg && !!sep && !isFlagPromptdiff --git a/src/shared/agents/normalize.antigravity.test.ts b/src/shared/agents/normalize.antigravity.test.tsnew file mode 100644index 000000000..93d2f42ee--- /dev/null+++ b/src/shared/agents/normalize.antigravity.test.ts@@ -0,0 +1,243 @@+// Behavioural pin over REAL Antigravity CLI (`agy` 1.2.3) hook payloads.+//+// FIXTURE PROVENANCE: `__fixtures__/antigravity/hook-payloads.json` was captured live on Windows 11+// on 2026-09-15 with a temporary HOME. Paths and conversation ids are+// anonymised; KEYS AND SHAPES ARE UNCHANGED. The `event` of each entry did NOT come from the+// payload — `agy` never sends it — it was recorded by the capture wrapper, exactly as our managed+// hook sends it as the `nodeterm_hook_event` form field. The hook server merges that field into the+// parsed payload, and `envFor` below does the same.+import { describe, expect, it } from 'vitest'+import { readFileSync } from 'fs'+import path from 'path'+import { normalizeAntigravity, normalizeFor } from './normalize'+import type { RawHookEnvelope } from './normalize'++interface FixtureEntry {+ event: string+ note: string+ payload: Record<string, unknown>+}++const fixture = JSON.parse(+ readFileSync(path.join(__dirname, '__fixtures__/antigravity/hook-payloads.json'), 'utf8')+) as { events: FixtureEntry[]; _terminationReasonEnum: string[]; _eventNameIsNotInPayload: boolean }++const pick = (event: string, match: (p: Record<string, unknown>) => boolean = () => true): FixtureEntry => {+ const hit = fixture.events.filter((e) => e.event === event && match(e.payload))+ if (hit.length !== 1) throw new Error(`fixture must hold exactly one ${event} for this case, got ${hit.length}`)+ return hit[0]+}+const toolIs = (name: string) => (p: Record<string, unknown>) =>+ (p.toolCall as { name?: string } | undefined)?.name === name++/** The payload as the hook server hands it on: the agent's JSON plus the merged form field. */+const envFor = (event: string | undefined, payload: Record<string, unknown>): RawHookEnvelope => ({+ nodeId: 'node-1',+ agentId: 'antigravity',+ payload: event === undefined ? { ...payload } : { ...payload, nodeterm_hook_event: event }+})+const run = (e: FixtureEntry) => normalizeAntigravity(envFor(e.event, e.payload))++const finalStopMatch = (p: Record<string, unknown>) =>+ p.fullyIdle === true && p.terminationReason === 'NO_TOOL_CALL'++describe('normalizeAntigravity over captured agy 1.2.3 payloads', () => {+ it('the fixture really carries no event name — the premise of the form field', () => {+ expect(fixture._eventNameIsNotInPayload).toBe(true)+ for (const e of fixture.events) {+ for (const key of ['hookEventName', 'hook_event_name', 'event', 'type', 'nodeterm_hook_event']) {+ expect(e.payload[key], `${e.event} ${key}`).toBeUndefined()+ }+ }+ })++ it('the first PreInvocation of an execution (invocationNum 0) → working AND a new turn', () => {+ const e = pick('PreInvocation')+ expect(e.payload.invocationNum).toBe(0)+ expect(run(e)).toEqual({+ nodeId: 'node-1',+ agentId: 'antigravity',+ sessionId: e.payload.conversationId,+ kind: 'state',+ state: 'working',+ newTurn: true+ })+ })++ it('a later PreInvocation of the same execution is NOT a new turn', () => {+ // PreInvocation fires per MODEL CALL; only the call numbered 0 starts an execution.+ const p = pick('PreInvocation').payload+ for (const n of [1, 2, 13]) {+ const out = normalizeAntigravity(envFor('PreInvocation', { ...p, invocationNum: n }))+ expect(out?.state, String(n)).toBe('working')+ expect(out?.newTurn, String(n)).toBeUndefined()+ }+ })++ it('a missing or non-numeric invocationNum marks no turn (strict === 0)', () => {+ const p: Record<string, unknown> = { ...pick('PreInvocation').payload }+ delete p.invocationNum+ for (const v of [undefined, '0', null, false, -0.5, '']) {+ const payload = v === undefined ? p : { ...p, invocationNum: v }+ const out = normalizeAntigravity(envFor('PreInvocation', payload))+ expect(out?.state, String(v)).toBe('working')+ expect(out?.newTurn, String(v)).toBeUndefined()+ }+ })++ it('PostInvocation carries invocationNum 0 too, and still maps to nothing', () => {+ expect(pick('PostInvocation').payload.invocationNum).toBe(0)+ expect(run(pick('PostInvocation'))).toBeNull()+ })++ it('an ordinary PreToolUse → working', () => {+ expect(run(pick('PreToolUse', toolIs('run_command')))?.state).toBe('working')+ })++ it('PreToolUse ask_question → waiting (the only NEEDS YOU a hook can see)', () => {+ expect(run(pick('PreToolUse', toolIs('ask_question')))?.state).toBe('waiting')+ })++ it('PostToolUse ask_question → working (the question left the screen)', () => {+ expect(run(pick('PostToolUse', toolIs('ask_question')))?.state).toBe('working')+ })++ it('an ordinary PostToolUse says nothing new → null', () => {+ // The captured one arrived 27.5 s AFTER an intermediate Stop, for a background tool. Mapping it+ // to a state could only ever wipe something (a pending question); it cannot add information.+ expect(run(pick('PostToolUse', toolIs('run_command')))).toBeNull()+ })++ it('PostInvocation is not subscribed and maps to nothing', () => {+ expect(run(pick('PostInvocation'))).toBeNull()+ })++ it('Stop with fullyIdle:false is NOT terminal → working', () => {+ expect(run(pick('Stop', (p) => p.fullyIdle === false))?.state).toBe('working')+ })++ it('Stop with fullyIdle:true → done, not errored', () => {+ const out = run(pick('Stop', finalStopMatch))+ expect(out?.state).toBe('done')+ expect(out?.errored).toBeUndefined()+ })++ it('a hook-terminated Stop (TERMINAL_CUSTOM_HOOK) is an ordinary end, not an error', () => {+ const out = run(pick('Stop', (p) => p.terminationReason === 'TERMINAL_CUSTOM_HOOK'))+ expect(out?.state).toBe('done')+ expect(out?.errored).toBeUndefined()+ })+})++describe('normalizeAntigravity — the rules the capture could not produce', () => {+ const finalStop = pick('Stop', finalStopMatch)++ it("terminationReason 'ERROR' (UPPER_SNAKE) → done + errored", () => {+ // NOT produced on a device — the enum value is read from the binary. Pinned so a later "fix"+ // to the docs' lowercase spelling cannot silently disarm #521.+ expect(fixture._terminationReasonEnum).toContain('ERROR')+ const out = normalizeAntigravity(envFor('Stop', { ...finalStop.payload, terminationReason: 'ERROR' }))+ expect(out).toMatchObject({ state: 'done', errored: true })+ })++ it("lowercase 'error' is NOT the enum and does not set errored", () => {+ const out = normalizeAntigravity(envFor('Stop', { ...finalStop.payload, terminationReason: 'error' }))+ expect(out?.errored).toBeUndefined()+ })++ it('every other enum value is an unhappy end, never an error', () => {+ for (const reason of fixture._terminationReasonEnum.filter((r) => r !== 'ERROR')) {+ const out = normalizeAntigravity(envFor('Stop', { ...finalStop.payload, terminationReason: reason }))+ expect(out?.state, reason).toBe('done')+ expect(out?.errored, reason).toBeUndefined()+ }+ })++ it('a Stop WITHOUT fullyIdle reads as finished (strict === false)', () => {+ const rest: Record<string, unknown> = { ...finalStop.payload }+ delete rest.fullyIdle+ expect(normalizeAntigravity(envFor('Stop', rest))?.state).toBe('done')+ // A falsy-but-not-false oddity is also "finished"; only a literal false keeps it working.+ expect(normalizeAntigravity(envFor('Stop', { ...rest, fullyIdle: 0 }))?.state).toBe('done')+ // An empty payload (agy sent no stdin; the script POSTs `{}`) still ends the badge.+ expect(normalizeAntigravity(envFor('Stop', {}))?.state).toBe('done')+ })++ it('ask_permission is not a thing — it stays working (closed set, no substring)', () => {+ const base = pick('PreToolUse', toolIs('ask_question')).payload+ for (const name of ['ask_permission', 'ask_question_v2', 'Ask_Question', 'ask']) {+ const out = normalizeAntigravity(envFor('PreToolUse', { ...base, toolCall: { name } }))+ expect(out?.state, name).toBe('working')+ }+ })++ it('an unknown, missing or non-string event name → null, never a throw', () => {+ const p = pick('PreInvocation').payload+ expect(normalizeAntigravity(envFor(undefined, p))).toBeNull()+ expect(normalizeAntigravity(envFor('', p))).toBeNull()+ expect(normalizeAntigravity(envFor('stop', p))).toBeNull()+ expect(normalizeAntigravity(envFor('SessionEnd', p))).toBeNull()+ expect(+ normalizeAntigravity({ nodeId: 'n', agentId: 'antigravity', payload: { nodeterm_hook_event: 7 } })+ ).toBeNull()+ })++ it('a malformed toolCall or conversationId degrades instead of throwing', () => {+ expect(normalizeAntigravity(envFor('PreToolUse', { toolCall: null }))?.state).toBe('working')+ expect(normalizeAntigravity(envFor('PreToolUse', { toolCall: 'ask_question' }))?.state).toBe('working')+ expect(normalizeAntigravity(envFor('PostToolUse', { toolCall: { name: 42 } }))).toBeNull()+ expect(normalizeAntigravity(envFor('PreInvocation', { conversationId: 42 }))?.sessionId).toBeUndefined()+ })++ it('is reached through normalizeFor', () => {+ expect(normalizeFor('antigravity', envFor('PreInvocation', {}))?.state).toBe('working')+ })+})++describe('normalizeAntigravity — measured event orders', () => {+ const states = (seq: [string, Record<string, unknown>][]) =>+ seq.map(([ev, p]) => normalizeAntigravity(envFor(ev, p))?.state ?? null)++ it('background tool: the late PostToolUse neither ends nor restarts anything', () => {+ // log-bg.jsonl: the PostToolUse lands 27.5 s after `Stop fullyIdle:false`.+ const pre = pick('PreToolUse', toolIs('run_command')).payload+ const post = pick('PostToolUse', toolIs('run_command')).payload+ const mid = pick('Stop', (p) => p.fullyIdle === false).payload+ const end = pick('Stop', finalStopMatch).payload+ const inv = (n: number) => ({ ...pick('PreInvocation').payload, invocationNum: n })+ // The invocationNum order is log-bg.jsonl's: 0, 1, then 0 again when agy resumes after the+ // background tool — a new execution, and so a new turn.+ const seq: [string, Record<string, unknown>][] = [+ ['PreInvocation', inv(0)],+ ['PreToolUse', pre],+ ['PreInvocation', inv(1)],+ ['Stop', mid],+ ['PostToolUse', post],+ ['PreInvocation', inv(0)],+ ['Stop', end]+ ]+ expect(states(seq)).toEqual(['working', 'working', 'working', 'working', null, 'working', 'done'])+ expect(seq.map(([ev, p]) => normalizeAntigravity(envFor(ev, p))?.newTurn ?? false)).toEqual([+ true,+ false,+ false,+ false,+ false,+ true,+ false+ ])+ })++ it('a background PostToolUse during an open question does not clear NEEDS YOU', () => {+ const askPre = pick('PreToolUse', toolIs('ask_question')).payload+ const askPost = pick('PostToolUse', toolIs('ask_question')).payload+ const bgPost = pick('PostToolUse', toolIs('run_command')).payload+ expect(+ states([+ ['PreToolUse', askPre],+ ['PostToolUse', bgPost],+ ['PostToolUse', askPost]+ ])+ ).toEqual(['waiting', null, 'working'])+ })+})diff --git a/src/shared/agents/normalize.ts b/src/shared/agents/normalize.tsindex 2d3374ee7..a839984f5 100644--- a/src/shared/agents/normalize.ts+++ b/src/shared/agents/normalize.ts@@ -841,6 +841,107 @@ export function normalizeGrok(env: RawHookEnvelope): NormalizedAgentEvent | nullreturn null}+// Antigravity CLI (`agy`) hook payload — camelCase, as its protojson writer emits it. Measured on+// agy 1.2.3 (fixture: __fixtures__/antigravity/hook-payloads.json).+//+// THE EVENT NAME IS NOT IN THE PAYLOAD. None of the five events carries it, and PreInvocation and+// PostInvocation are indistinguishable by their keys. The managed hook command exports it as+// NODETERM_AGY_EVENT and the script POSTs it as the `nodeterm_hook_event` form field, which the hook+// server merges into this object AFTER parsing the agent's JSON — so a value planted inside the+// agent's payload never wins.+interface AntigravityPayload {+ nodeterm_hook_event?: unknown+ conversationId?: unknown+ fullyIdle?: unknown+ terminationReason?: unknown+ invocationNum?: unknown+ toolCall?: { name?: unknown } | null+}++/**+ * The tool names that put a human in the loop, matched EXACTLY (rule 7: a closed set, never a+ * substring). `ask_question` is the only one: `agy`'s own step-type enum (`CORTEX_STEP_TYPE_*`,+ * read out of the 1.2.3 binary) has ASK_QUESTION and no ASK_PERMISSION, so there is no+ * `ask_permission` tool to match.+ *+ * What this CANNOT see, and nobody should try to guess: `agy`'s own permission prompt ("Run this+ * command?") fires NO hook. A session parked on it looks exactly like a slow tool.+ */+const ANTIGRAVITY_ASK_TOOLS = new Set(['ask_question'])++const antigravityToolName = (p: AntigravityPayload): string | undefined => {+ const name = p.toolCall && typeof p.toolCall === 'object' ? p.toolCall.name : undefined+ return typeof name === 'string' ? name : undefined+}++/**+ * PURE — no state, on purpose. Three decisions carry the whole mapping:+ *+ * 1. `Stop` with `fullyIdle === false` is NOT terminal (→ `working`). `agy` stops its model loop+ * between steps while a background tool still runs, then reports `fullyIdle:true` at the real+ * end. Strict `=== false`: a payload missing the field reads as "finished", the safe direction+ * for a badge that would otherwise stick. With this rule the `PostToolUse` that arrives AFTER+ * such a Stop is simply the end of that background tool.+ *+ * 2. NEEDS YOU is bracketed by the ask tool itself, never by adjacency. `PreToolUse` and+ * `PostToolUse` do not alternate: a whole invocation can open and close between them (measured:+ * 63 s between the pair while a question sat on screen), and a BACKGROUND tool's `PostToolUse`+ * can land in the middle of a pending question. So only the ask tool's own `PostToolUse` clears+ * the question (→ `working`); every other tool's `PostToolUse` says nothing we did not already+ * know and maps to null, which keeps a finished background ping from wiping a live NEEDS YOU.+ * Correlating on `stepIdx` exactly would need state across events; naming the tool gives the+ * same answer for the one open question `agy` can have, without it.+ *+ * 3. `errored` is set only for `terminationReason === 'ERROR'`, UPPER_SNAKE — the real enum+ * (12 values, read from the binary; the bundled docs' lowercase example is wrong). It keeps an+ * `--after` dependent from launching on a broken turn (#521). NOT produced on a device yet: see+ * docs/antigravity-agent.md. `MAX_*`, `USER_CANCELED` and the rest are unhappy ends, not API+ * errors, and calling them errors would be a guess.+ *+ * 4. `newTurn` ONLY on the `PreInvocation` whose `invocationNum === 0`. `PreInvocation` fires per+ * MODEL CALL, so flagging every one would be wrong; but agy numbers the calls of one execution+ * from 0, and the measurement shows a 0 at the start of every execution — including the one that+ * resumes after a background tool finished (log-bg.jsonl: 0, 1, then 0 again). A turn boundary+ * IS load-bearing here: `lastTurnError` (#521) is retired only by `newTurn`, so without it one+ * errored turn would hold every `--after` dependent QUEUED for the rest of the app run; and the+ * done-holdoff drops a non-newTurn `working` that follows a `done` by < 3 s, which is exactly a+ * quick follow-up prompt. Strict `=== 0`: a missing or non-numeric value marks nothing. The+ * other effects of `newTurn` (fan-out clears, the prompt line) have nothing to act on for agy —+ * it emits no subagent events and no prompt text.+ */+export function normalizeAntigravity(env: RawHookEnvelope): NormalizedAgentEvent | null {+ const p = env.payload as AntigravityPayload+ const ev = typeof p.nodeterm_hook_event === 'string' ? p.nodeterm_hook_event : undefined+ const sessionId = typeof p.conversationId === 'string' ? p.conversationId : undefined+ const base = { nodeId: env.nodeId, agentId: env.agentId, sessionId }++ if (ev === 'PreInvocation') {+ return { ...base, kind: 'state', state: 'working', ...(p.invocationNum === 0 ? { newTurn: true } : {}) }+ }+ if (ev === 'PreToolUse') {+ const tool = antigravityToolName(p)+ const asks = tool !== undefined && ANTIGRAVITY_ASK_TOOLS.has(tool)+ return { ...base, kind: 'state', state: asks ? 'waiting' : 'working' }+ }+ if (ev === 'PostToolUse') {+ const tool = antigravityToolName(p)+ if (tool !== undefined && ANTIGRAVITY_ASK_TOOLS.has(tool)) {+ return { ...base, kind: 'state', state: 'working' }+ }+ return null+ }+ if (ev === 'Stop') {+ if (p.fullyIdle === false) return { ...base, kind: 'state', state: 'working' }+ return {+ ...base,+ kind: 'state',+ state: 'done',+ ...(p.terminationReason === 'ERROR' ? { errored: true } : {})+ }+ }+ return null+}+export function normalizeFor(agentId: AgentId, env: RawHookEnvelope): NormalizedAgentEvent | null {if (agentId === 'claude') return normalizeClaude(env)if (agentId === 'codex') return normalizeCodex(env)@@ -848,5 +949,6 @@ export function normalizeFor(agentId: AgentId, env: RawHookEnvelope): Normalizedif (agentId === 'opencode') return normalizeOpencode(env)if (agentId === 'grok') return normalizeGrok(env)if (agentId === 'copilot') return normalizeCopilot(env)+ if (agentId === 'antigravity') return normalizeAntigravity(env)return null}diff --git a/src/shared/agents/pane-owner-predicate.ts b/src/shared/agents/pane-owner-predicate.tsindex d703dae2d..433cdd0ad 100644--- a/src/shared/agents/pane-owner-predicate.ts+++ b/src/shared/agents/pane-owner-predicate.ts@@ -64,7 +64,8 @@ export const AGENT_BINARIES: Record<string, readonly string[]> = {copilot: ['copilot'],gemini: ['gemini'],opencode: ['opencode'],- grok: ['grok']+ grok: ['grok'],+ antigravity: ['agy']}/**diff --git a/src/shared/keybindings.test.ts b/src/shared/keybindings.test.tsindex 5b6092b91..ca8281251 100644--- a/src/shared/keybindings.test.ts+++ b/src/shared/keybindings.test.ts@@ -125,6 +125,8 @@ describe('registry invariants', () => {darwin: [], other: [] },{ id: 'node.newAgent.copilot', title: 'New GitHub Copilot node', group: 'Nodes',scope: 'canvas', darwin: [], other: [] },+ { id: 'node.newAgent.antigravity', title: 'New Antigravity node', group: 'Nodes',+ scope: 'canvas', darwin: [], other: [] },{ id: 'node.newSticky', title: 'New sticky note', group: 'Nodes', scope: 'canvas',darwin: [], other: [] },{ id: 'node.newBrowser', title: 'New browser node', group: 'Nodes', scope: 'canvas',@@ -205,7 +207,7 @@ describe('registry invariants', () => {'node.newDino','node.newFile']- expect(added).toHaveLength(11)+ expect(added).toHaveLength(12)for (const id of added) {const d = COMMANDS_BY_ID.get(id as CommandId)expect(d, id).toBeDefined()diff --git a/src/shared/keybindings.ts b/src/shared/keybindings.tsindex ddcf9fe9d..24f8735be 100644--- a/src/shared/keybindings.ts+++ b/src/shared/keybindings.ts@@ -59,7 +59,7 @@ export type CommandId =| 'canvas.groupSelection'| 'node.newTerminal'| 'node.newAgent'- // Per-builtin-agent creates. The six ids are spelled STATICALLY (never derived from+ // Per-builtin-agent creates. The seven ids are spelled STATICALLY (never derived from// BUILTIN_AGENT_IDS) so this union stays literal — `isCommandId`, the overrides map and the// handler table all depend on that.| 'node.newAgent.claude'@@ -68,6 +68,7 @@ export type CommandId =| 'node.newAgent.opencode'| 'node.newAgent.grok'| 'node.newAgent.copilot'+ | 'node.newAgent.antigravity'| 'node.newSticky'| 'node.newBrowser'| 'node.newWebView'@@ -173,6 +174,8 @@ export const COMMAND_DEFINITIONS: readonly CommandDefinition[] = [scope: 'canvas', defaultBindings: both() },{ id: 'node.newAgent.copilot', title: `New ${AGENT_CONFIG.copilot.label} node`, group: 'Nodes',scope: 'canvas', defaultBindings: both() },+ { id: 'node.newAgent.antigravity', title: `New ${AGENT_CONFIG.antigravity.label} node`,+ group: 'Nodes', scope: 'canvas', defaultBindings: both() },{ id: 'node.newSticky', title: 'New sticky note', group: 'Nodes', scope: 'canvas',defaultBindings: both() },{ id: 'node.newBrowser', title: 'New browser node', group: 'Nodes', scope: 'canvas',