Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat(cli): add agy (Antigravity) as the 13th engine

0xken155efe1fcdd2f1
diff --git a/.github/assets/engines/README.md b/.github/assets/engines/README.md
index a42d86a6e..a2da8a5f6 100644
--- a/.github/assets/engines/README.md
+++ b/.github/assets/engines/README.md
@@ -30,9 +30,14 @@ a retina display.
| `amp.png` | Amp's official app icon — the `apple-touch-icon` the site itself declares, <https://ampcode.com/app-icon.png?v=3>, fetched 2026-08-07 | 512 | `e5fc0d1178674b80c0dcbbf9811787b44df91f865fac9cd3ef44bb13ef728018` |
| `kilo.png` | Kilo's official mark SVG, <https://kilo.ai/favicon/favicon.svg?v=2>, rendered to a 512px PNG — see the note below | 512 | `03a348a04c622938a278d803cbb6333819de855d2b3127de8e412fd261db3701` |
| `grok.png` | SpaceXAI symbol used by the official `xai-org/grok-build` README, <https://media.x.ai/v1/website/spacexai-symbol-black-transparent-6435cf42.png>, fetched 2026-08-10 | 600 | `d2ce9e34b770aeb1e6155646e37573a9eabc380c3fe48e72f7fe19c4b0b59e07` |
+| `agy.png` | Antigravity's official gradient "A" mark — the logo the site itself declares, <https://antigravity.google/assets/image/antigravity-logo.png>, fetched 2026-08-18 | 200 | `8f0b95d2d21dbf930b4d100e2fdc4505673e900a731aa56ea633a4b59c312799` |
Open items, recorded rather than left implicit:
+- **`agy.png` is a 200px source.** Antigravity publishes the bare mark only at 200×184; the 512px
+ `icon.icns` inside the macOS app is an app TILE (a white rounded square with a small glyph),
+ not the same class of asset as the marks here. The site logo was taken and recorded rather
+ than swapped for the tile or upscaled to look bigger than it is.
- **`codex.png` and `muse.png` are still 104px sources** — fine at the 72px render, slightly soft on
a retina display. Everything above them is 180px or better. Replace when a larger official file
turns up; do not upscale these to fake it.
diff --git a/.github/assets/engines/agy.png b/.github/assets/engines/agy.png
new file mode 100644
index 000000000..bf02c087c
Binary files /dev/null and b/.github/assets/engines/agy.png differ
diff --git a/README.md b/README.md
index b3de883b1..2b5adee4c 100644
--- a/README.md
+++ b/README.md
@@ -41,6 +41,8 @@ It drives the agents you already use:
<img src=".github/assets/engines/kilo.png" height="72" alt="Kilo" title="Kilo">
&nbsp;&nbsp;
<img src=".github/assets/engines/grok.png" height="72" alt="Grok" title="Grok">
+ &nbsp;&nbsp;
+ <img src=".github/assets/engines/agy.png" height="72" alt="Antigravity" title="Antigravity">
</p>
## Add your agent to Harness
@@ -88,7 +90,8 @@ Your agents stay your processes, on your hardware, with your credentials.
`harness join` `harness join` your HTTP API
│ │ │
claude · codex hermes · muse agents running on
- cursor · amp · … opencode · kilo · grok your own servers
+ cursor · amp · … opencode · kilo · your own servers
+ grok · agy
└───────── CLI ─────────┘ └─────── API ───────┘
```
diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjs
index 5ba9a688f..74dbb4d46 100644
--- a/cli/hook/notify.mjs
+++ b/cli/hook/notify.mjs
@@ -83,7 +83,19 @@ function argValue(name, fallback) {
function argEngine() {
const i = process.argv.indexOf('--engine')
const value = i !== -1 ? process.argv[i + 1] : ''
- return value === 'codex' || value === 'cursor' || value === 'hermes' || value === 'commandcode' || value === 'devin' || value === 'muse' || value === 'grok' ? value : 'claude'
+ return value === 'codex' || value === 'cursor' || value === 'hermes' || value === 'commandcode' || value === 'devin' || value === 'muse' || value === 'grok' || value === 'agy' ? value : 'claude'
+}
+
+/**
+ * agy names its hook event nowhere in the payload, so the installer puts it on the command line.
+ *
+ * Everything else in the payload is camelCase (protojson): `conversationId`, `workspacePaths`,
+ * `transcriptPath`, `modelName`, and on Stop `terminationReason` / `fullyIdle`.
+ */
+function argAgyEvent() {
+ const i = process.argv.indexOf('--agy-event')
+ const value = i !== -1 ? process.argv[i + 1] : ''
+ return value === 'PreInvocation' || value === 'Stop' ? value : ''
}
function paths() {
@@ -96,6 +108,7 @@ function paths() {
const hermesHome = argValue('--hermes-home', process.env.HERMES_HOME || join(homedir(), '.hermes'))
const commandcodeHome = argValue('--commandcode-home', process.env.COMMANDCODE_HOME || join(homedir(), '.commandcode'))
const devinHome = argValue('--devin-home', process.env.DEVIN_HOME || join(homedir(), '.local', 'share', 'devin', 'cli'))
+ const agyHome = argValue('--agy-home', process.env.AGY_HOME || join(homedir(), '.gemini', 'antigravity-cli'))
return {
dataDir,
registryFile: join(dataDir, 'registry.json'),
@@ -109,9 +122,41 @@ function paths() {
commandcodeProjectsDir: join(commandcodeHome, 'projects'),
devinHome,
devinLocksDir: join(devinHome, 'session_locks'),
+ agyHome,
+ agyBrainDir: join(agyHome, 'brain'),
+ agyPresenceDir: join(agyHome, 'presence'),
+ }
+}
+
+/**
+ * Is this agy conversation the PANE's, or a sub-agent's?
+ *
+ * agy gives every sub-agent its own conversation id, its own transcript AND its own hooks — fired with
+ * the parent's `TMUX_PANE`. Registering those rebinds the pane to whichever child announced last:
+ * measured on a three-sub-agent run as one agent attaching to three different sessions in four
+ * seconds, after which the web pane showed the CHILDREN's messages and the parent's `Task` rows never
+ * rendered at all.
+ *
+ * The discriminator is `presence/<id>.lock`, which agy creates only for a top-level conversation —
+ * measured: four locks on this machine, all parents; the six sub-agent conversations have none. It is
+ * also ordered safely, created BEFORE the first hook of that conversation (lock 17:57:14, first hook
+ * 17:57:15, transcript not until 17:57:17), so a real new session is never mistaken for a child.
+ */
+function agyIsPaneConversation(p, conversationId) {
+ if (!conversationId) return false
+ try {
+ return statSync(join(p.agyPresenceDir, `${conversationId}.lock`)).isFile()
+ } catch {
+ return false
}
}
+/** agy's deterministic transcript layout, duplicated here because the hook cannot import from src/. */
+function agyTranscriptPath(p, conversationId) {
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(conversationId || '')) return undefined
+ return join(p.agyBrainDir, conversationId, '.system_generated', 'logs', 'transcript_full.jsonl')
+}
+
/** True when the path is a real file on disk right now (undefined/missing → false). */
function existsPath(file) {
if (typeof file !== 'string' || !file) return false
@@ -351,11 +396,12 @@ function processEntrypoint(args) {
const ENGINE_COMMANDS = {
claude: 'claude', codex: 'codex', cursor: 'agent', hermes: 'hermes', commandcode: 'cmd',
- devin: 'devin', muse: 'muse', grok: 'grok',
+ devin: 'devin', muse: 'muse', grok: 'grok', agy: 'agy',
}
const ENGINE_PATH_ENV = {
claude: 'CLAUDE_PATH', codex: 'CODEX_PATH', cursor: 'CURSOR_PATH', hermes: 'HERMES_PATH',
commandcode: 'COMMANDCODE_PATH', devin: 'DEVIN_PATH', muse: 'MUSE_PATH', grok: 'GROK_PATH',
+ agy: 'AGY_PATH',
}
function executableIdentity(path) {
@@ -752,6 +798,7 @@ function validTranscriptPath(engine, filePath, p) {
const root = realpathSync(
engine === 'codex' ? p.codexSessionsDir
: engine === 'grok' ? p.grokSessionsDir
+ : engine === 'agy' ? p.agyBrainDir
: engine === 'cursor' ? p.cursorProjectsDir
: engine === 'commandcode' ? p.commandcodeProjectsDir
: p.claudeProjectsDir,
@@ -1007,6 +1054,7 @@ function mergeRuntimes(current, observed) {
const REGISTRY_ENGINES = new Set([
'claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin', 'muse', 'amp', 'kilo', 'grok',
+ 'agy',
])
function validRegistryString(value, max = 4096) {
@@ -1102,7 +1150,7 @@ async function fallbackRegister(input, engine, tmuxPane) {
? rawSessionId
: (transcriptPath ? basename(transcriptPath).replace(/\.jsonl$/, '') : '')
if (!sessionId) return
- const transcriptOptional = ['cursor', 'opencode', 'kilo', 'pi', 'hermes', 'commandcode', 'devin', 'grok'].includes(engine)
+ const transcriptOptional = ['cursor', 'opencode', 'kilo', 'pi', 'hermes', 'commandcode', 'devin', 'grok', 'agy'].includes(engine)
if (!transcriptOptional && !transcriptPath) return
if (transcriptPath && !validTranscriptPath(engine, transcriptPath, p)) return
const observations = []
@@ -1216,6 +1264,65 @@ async function main() {
// the final assistant chunk, so treating Stop as authoritative would close the turn too early. The
// transcript's `turn_completed` record closes normal turns; only StopFailure is needed as an error
// fallback here.
+ // agy: the hook is the whole binding. Its `PreInvocation` fires before every model round-trip, so the
+ // FIRST one of a turn is the session announce; `Stop` fires exactly once when the execution loop ends
+ // and is the authoritative turn boundary (the transcript records no closing marker of its own, and a
+ // backgrounded step stays `status: RUNNING` forever because the file is append-only).
+ if (engine === 'agy') {
+ const agyEvent = argAgyEvent()
+ if (!agyEvent) return
+ const sessionId = input.conversationId
+ const p = paths()
+ // A sub-agent's hooks carry the parent's pane; only the pane's own conversation may register.
+ if (!agyIsPaneConversation(p, sessionId)) return
+ // Trust the payload's path when it resolves; agy's own docs show a workspace-scoped example that
+ // does not match what the CLI actually writes, so the derived path is the fallback that does.
+ const transcriptPath = existsPath(input.transcriptPath) ? input.transcriptPath : agyTranscriptPath(p, sessionId)
+ const cwd = Array.isArray(input.workspacePaths) ? input.workspacePaths[0] : undefined
+ if (agyEvent === 'Stop') {
+ // agy stops its execution loop as soon as the MODEL has nothing left to say — including the moment
+ // it has launched sub-agents and is waiting on them. Measured on a two-sub-agent run: the parent
+ // fired Stop twice, first `fullyIdle: false` at the "standing by for their reports" point, then
+ // again `fullyIdle: true` when the reports were in. Closing on the first one ended the turn and
+ // ran the recap while the work was still going ("chưa done đã recap").
+ //
+ // So `fullyIdle` is the turn boundary, not Stop itself. A build that omits the field is treated as
+ // idle, which is the pre-existing behaviour.
+ //
+ // A waiting Stop is still REPORTED, as `status: 'waiting'`, rather than swallowed: one measured run
+ // finished its sub-agents and never sent another Stop at all, leaving the turn open with nothing
+ // coming to close it. The daemon uses this to arm a pane-idle backstop.
+ // `terminationReason` is NO_TOOL_CALL on a clean finish; anything else ended the loop early.
+ const failed = typeof input.terminationReason === 'string'
+ && input.terminationReason !== ''
+ && input.terminationReason !== 'NO_TOOL_CALL'
+ && input.terminationReason !== 'model_stop'
+ const status = input.fullyIdle === false ? 'waiting' : failed || input.error ? 'error' : undefined
+ await post(port, '/api/hook/turn-stop', { sessionId, transcriptPath, status, ...mutationFields })
+ return
+ }
+ const body = {
+ engine,
+ hookEvent: 'SessionStart',
+ sessionId,
+ transcriptPath,
+ cwd,
+ ...terminalHookFields(tmuxPane),
+ model: modelName(input.modelName),
+ }
+ const registered = await post(port, '/api/hook/session-start', body)
+ if (!registered) {
+ await fallbackRegister({
+ ...input,
+ hook_event_name: 'SessionStart',
+ session_id: sessionId,
+ transcript_path: transcriptPath,
+ cwd,
+ }, engine, tmuxPane)
+ }
+ return
+ }
+
if (engine === 'grok') {
const grokEventName = grokHookEvent(event)
const sessionId = input.sessionId || input.session_id
@@ -1386,6 +1493,10 @@ main()
// Cursor and Hermes parse the hook's stdout as JSON; `{}` is the explicit no-op (for Hermes it also
// guarantees a pre_llm_call hook never injects context). Claude/Codex want no stdout at all.
const e = argEngine()
- if (e === 'cursor' || e === 'hermes') process.stdout.write('{}\n', () => process.exit(0))
+ // agy REQUIRES a JSON object on stdout. `{}` is the safe no-op for both events it fires: on Stop,
+ // only `{"decision":"continue"}` would block the stop. It is also why PreToolUse is never installed
+ // — there `decision` is required, and `{}` reads as a denial (measured: every tool call of the turn
+ // came back "Tool call denied by pre-tool hook").
+ if (e === 'cursor' || e === 'hermes' || e === 'agy') process.stdout.write('{}\n', () => process.exit(0))
else process.exit(0)
})
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 33657a241..6240dc00d 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -32,6 +32,7 @@ import { kiloMessagesToEvents, windowKiloMessages } from './engines/kilo/normali
import { museMessagesToEvents } from './engines/muse/normalizer.js'
import { ampMessagesToEvents } from './engines/amp/normalizer.js'
import { grokMessagesToEvents } from './engines/grok/normalizer.js'
+import { agyMessagesToEvents } from './engines/agy/normalizer.js'
import { ampThreadToEvents, readAmpThread } from './engines/amp/threadExport.js'
import { piMessagesToEvents, windowPiLines } from './engines/pi/normalizer.js'
import { commandcodeMessagesToEvents, windowCommandCodeLines } from './engines/commandcode/normalizer.js'
@@ -133,13 +134,20 @@ export function grokHistoryPage(lines: string[], paginated: boolean):
return paginated ? { events, hasMore: false, oldestCursor: null } : { events }
}
+/** agy has no transcript windower either; same both-shapes replay as grok, for the same reason. */
+export function agyHistoryPage(lines: string[], paginated: boolean):
+ { events: SessionEvent[]; hasMore?: false; oldestCursor?: null } {
+ const events = agyMessagesToEvents(lines)
+ return paginated ? { events, hasMore: false, oldestCursor: null } : { events }
+}
+
export function deviceAgentListItem(
raw: unknown,
-): { id: unknown; name?: string; engine?: 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin' | 'muse' | 'amp' | 'kilo' | 'grok'; selectedModel?: string | null } {
+): { id: unknown; name?: string; engine?: 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin' | 'muse' | 'amp' | 'kilo' | 'grok' | 'agy'; selectedModel?: string | null } {
const o = (raw ?? {}) as Record<string, unknown>
- const item: { id: unknown; name?: string; engine?: 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin' | 'muse' | 'amp' | 'kilo' | 'grok'; selectedModel?: string | null } = { id: o.id }
+ const item: { id: unknown; name?: string; engine?: 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin' | 'muse' | 'amp' | 'kilo' | 'grok' | 'agy'; selectedModel?: string | null } = { id: o.id }
if (typeof o.name === 'string') item.name = clipDeviceAgentName(o.name)
- if (o.engine === 'claude' || o.engine === 'codex' || o.engine === 'cursor' || o.engine === 'opencode' || o.engine === 'pi' || o.engine === 'hermes' || o.engine === 'commandcode' || o.engine === 'devin' || o.engine === 'muse' || o.engine === 'amp' || o.engine === 'kilo' || o.engine === 'grok') item.engine = o.engine
+ if (o.engine === 'claude' || o.engine === 'codex' || o.engine === 'cursor' || o.engine === 'opencode' || o.engine === 'pi' || o.engine === 'hermes' || o.engine === 'commandcode' || o.engine === 'devin' || o.engine === 'muse' || o.engine === 'amp' || o.engine === 'kilo' || o.engine === 'grok' || o.engine === 'agy') item.engine = o.engine
// Runtime model/effort profile (opaque runtime-v1:...) — lets the device render + change model/effort.
if (typeof o.selectedModel === 'string' || o.selectedModel === null) item.selectedModel = o.selectedModel
return item
@@ -825,12 +833,14 @@ export class BackendSocket {
? await ampHistory(sessionId, lines)
: s.engine === 'grok'
? grokHistoryPage(lines, false).events
+ : s.engine === 'agy'
+ ? agyHistoryPage(lines, false).events
: s.engine === 'pi'
? piMessagesToEvents(lines)
: s.engine === 'commandcode'
? commandcodeMessagesToEvents(lines)
: messagesToEvents(lines)
- if (s.engine !== 'cursor' && s.engine !== 'pi' && s.engine !== 'commandcode' && s.engine !== 'muse' && s.engine !== 'amp' && s.engine !== 'grok') await enrichSubagentStats(fullEvents, s.transcriptPath)
+ if (s.engine !== 'cursor' && s.engine !== 'pi' && s.engine !== 'commandcode' && s.engine !== 'muse' && s.engine !== 'amp' && s.engine !== 'grok' && s.engine !== 'agy') await enrichSubagentStats(fullEvents, s.transcriptPath)
reply(type, requestId, {
id: sessionId,
title: projectDisplayName(s),
@@ -848,20 +858,24 @@ export class BackendSocket {
// small: a real one measured 271 lines).
// Amp is in the same position as muse and for the same reason: no windower, so falling
// through would pair claude's line-uuid cursor with claude's normalizer and return nothing.
- if (s.engine === 'muse' || s.engine === 'amp' || s.engine === 'grok') {
- const grokPage = s.engine === 'grok' ? grokHistoryPage(lines, true) : null
+ if (s.engine === 'muse' || s.engine === 'amp' || s.engine === 'grok' || s.engine === 'agy') {
+ const wholePage = s.engine === 'grok'
+ ? grokHistoryPage(lines, true)
+ : s.engine === 'agy'
+ ? agyHistoryPage(lines, true)
+ : null
reply(type, requestId, {
id: sessionId,
title: projectDisplayName(s),
events: s.engine === 'amp'
? await ampHistory(sessionId, lines)
- : s.engine === 'grok'
- ? grokPage!.events
+ : wholePage
+ ? wholePage.events
: museMessagesToEvents(lines),
timestamp,
engine: s.engine,
- hasMore: grokPage?.hasMore ?? false,
- oldestCursor: grokPage?.oldestCursor ?? null,
+ hasMore: wholePage?.hasMore ?? false,
+ oldestCursor: wholePage?.oldestCursor ?? null,
})
return
}
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index a29b97ea6..b138e01f7 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -24,7 +24,7 @@ import { homedir } from 'os'
import { env } from './config/env.js'
import { VERSION } from './version.js'
import { registry, projectDisplayName, type RegisteredSession } from './lib/registry.js'
-import { installAmpPlugin, installCodexHooks, installCommandCodeHooks, installCursorHooks, installDevinHooks, installGrokHooks, installHermesHooks, installKiloPlugin, installOpencodePlugin, installPiExtension, installSessionHooks } from './lib/hooks.js'
+import { installAmpPlugin, installCodexHooks, installCommandCodeHooks, installCursorHooks, installDevinHooks, installGrokHooks, installAgyHooks, installHermesHooks, installKiloPlugin, installOpencodePlugin, installPiExtension, installSessionHooks } from './lib/hooks.js'
import { PID_FILE, TOKEN_FILE, daemonPort, isAlive, readPid } from './lib/daemonState.js'
import { flashCommand } from './lib/flash.js'
import { ENGINE_CLI_COMMANDS, ENGINES } from './lib/engineBin.js'
@@ -84,6 +84,9 @@ import { MuseNormalizer, lastMuseTurnText, museMessagesToEvents } from './engine
import { AmpNormalizer, lastAmpTurnText, ampMessagesToEvents } from './engines/amp/normalizer.js'
import { GrokNormalizer, lastGrokTurnText } from './engines/grok/normalizer.js'
import { findGrokTranscript } from './engines/grok/session.js'
+import { AgyNormalizer, lastAgyTurnText } from './engines/agy/normalizer.js'
+import { findAgyTranscript } from './engines/agy/session.js'
+import { agyPaneIdle } from './engines/agy/runtimeProfile.js'
import { PiNormalizer, lastPiTurnText } from './engines/pi/normalizer.js'
import { HermesReader, readHermesMessages } from './engines/hermes/reader.js'
import { DevinReader, readDevinMessages } from './engines/devin/reader.js'
@@ -794,6 +797,7 @@ async function runForeground(token: string): Promise<void> {
const museNormalizers = new Map<string, MuseNormalizer>()
const ampNormalizers = new Map<string, AmpNormalizer>()
const grokNormalizers = new Map<string, GrokNormalizer>()
+ const agyNormalizers = new Map<string, AgyNormalizer>()
const hermesReaders = new Map<string, HermesReader>()
const devinReaders = new Map<string, DevinReader>()
const commandcodeNormalizers = new Map<string, CommandCodeNormalizer>()
@@ -900,6 +904,7 @@ async function runForeground(token: string): Promise<void> {
|| museNormalizers.has(session.sessionId)
|| ampNormalizers.has(session.sessionId)
|| grokNormalizers.has(session.sessionId)
+ || agyNormalizers.has(session.sessionId)
|| hermesReaders.has(session.sessionId)
|| devinReaders.has(session.sessionId)
|| commandcodeNormalizers.has(session.sessionId)
@@ -994,6 +999,21 @@ async function runForeground(token: string): Promise<void> {
grokNormalizers.set(session.sessionId, normalizer)
const capture = await captureTerminal(session.agentId, 60)
if (capture) runtimeProfiles.ingestPane(session, capture, true)
+ } else if (session.engine === 'agy') {
+ // A JSONL tail like claude/grok. agy announces its model only in the hook payload and its pane
+ // footer, so the pane is read once on attach to fill the chip before the first turn.
+ const normalizer = new AgyNormalizer()
+ historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)
+ agyNormalizers.set(session.sessionId, normalizer)
+ const capture = await captureTerminal(session.agentId, 60)
+ if (capture) runtimeProfiles.ingestPane(session, capture, true)
+ // agy's transcript has no end-of-turn record - only its Stop hook does - so a fold of a FINISHED
+ // conversation still reports the last turn as open, and after a daemon restart nothing is ever
+ // coming to close it. The pane is the one place the answer exists; ask it.
+ if (historyTurnOpen && capture && agyPaneIdle(capture)) {
+ normalizer.closeTurn()
+ historyTurnOpen = false
+ }
} else if (session.engine === 'pi') {
const normalizer = new PiNormalizer('live')
// Hydrate state silently; never replay history live — except a turn left open, below.
@@ -1100,9 +1120,57 @@ async function runForeground(token: string): Promise<void> {
backend.sendCommander({ type: 'commander_event', agentId: agentIdFor(sessionId), dbSessionId: sessionId, payload: { kind: 'error', text: deviceErrorText(message, engine) } })
},
})
- const acquireTerminalControl = (id: string): (() => void) | null => {
+ /**
+ * agy only: close a turn whose final `Stop` never came.
+ *
+ * agy reports `fullyIdle: false` when it pauses for sub-agents, and normally sends one more Stop with
+ * `fullyIdle: true` once they report — measured, and that is the path a healthy turn takes. But one
+ * measured run completed its sub-agents, wrote its summary, and sent nothing further; the turn stayed
+ * open with no recap. The pane is the only other place the answer exists (`? for shortcuts` idle vs
+ * `esc to cancel` busy), so a waiting Stop arms a bounded poll of it.
+ *
+ * Bounded on purpose: it stops after AGY_IDLE_WATCH_MAX checks (~10 min) rather than polling a pane
+ * forever, and any real Stop clears it first.
+ */
+ const AGY_IDLE_WATCH_MS = 15_000
+ const AGY_IDLE_WATCH_MAX = 40
+ const agyIdleWatch = new Map<string, { timer: NodeJS.Timeout; checks: number }>()
+
+ const clearAgyIdleWatch = (sessionId: string): void => {
+ const watch = agyIdleWatch.get(sessionId)
+ if (!watch) return
+ clearTimeout(watch.timer)
+ agyIdleWatch.delete(sessionId)
+ }
+
+ const armAgyIdleWatch = (sessionId: string): void => {
+ const checks = agyIdleWatch.get(sessionId)?.checks ?? 0
+ clearAgyIdleWatch(sessionId)
+ if (checks >= AGY_IDLE_WATCH_MAX) return
+ const timer = setTimeout(() => {
+ void (async () => {
+ agyIdleWatch.delete(sessionId)
+ const normalizer = agyNormalizers.get(sessionId)
+ if (!normalizer?.turnOpen) return
+ const entry = registry.bySession(sessionId)
+ if (!entry) return
+ const capture = await captureTerminal(entry.agentId, 60)
+ if (!capture || !agyPaneIdle(capture)) { armAgyIdleWatch(sessionId); return }
+ await watcher.pollSession(sessionId)
+ if (!normalizer.turnOpen) return
+ console.log(`[turn] ${sid(sessionId)} closed by the agy idle backstop · no final Stop arrived`)
+ emitSessionEvents(sessionId, normalizer.closeTurn())
+ })().catch((err) => {
+ console.error('[agy] idle backstop failed:', err instanceof Error ? err.message : err)
+ })
+ }, AGY_IDLE_WATCH_MS)
+ timer.unref?.()
+ agyIdleWatch.set(sessionId, { timer, checks: checks + 1 })
+ }
+
+ const acquireTerminalControl = (id: string, opts?: { forAnswer?: boolean }): (() => void) | null => {
const agentId = registry.resolve(id)?.agentId ?? id
- const releaseInput = input.acquireControl(agentId)
+ const releaseInput = input.acquireControl(agentId, opts)
if (!releaseInput) return null
const releaseTerminal = pinTerminalControl(agentId)
if (!releaseTerminal) {
@@ -1191,6 +1259,7 @@ async function runForeground(token: string): Promise<void> {
if (s.engine === 'muse') return lastMuseTurnText(lines)
if (s.engine === 'amp') return lastAmpTurnText(lines)
if (s.engine === 'grok') return lastGrokTurnText(lines)
+ if (s.engine === 'agy') return lastAgyTurnText(lines)
if (s.engine === 'pi') return lastPiTurnText(lines)
if (s.engine === 'commandcode') return lastCommandCodeTurnText(lines)
return lastTurnTextFromRawLines(lines)
@@ -1263,6 +1332,7 @@ async function runForeground(token: string): Promise<void> {
?? museNormalizers.get(sessionId)?.turnOpen
?? ampNormalizers.get(sessionId)?.turnOpen
?? grokNormalizers.get(sessionId)?.turnOpen
+ ?? agyNormalizers.get(sessionId)?.turnOpen
?? hermesReaders.get(sessionId)?.turnOpen
?? devinReaders.get(sessionId)?.turnOpen
?? commandcodeNormalizers.get(sessionId)?.turnOpen
@@ -1368,6 +1438,8 @@ async function runForeground(token: string): Promise<void> {
museNormalizers.delete(sessionId)
ampNormalizers.delete(sessionId)
grokNormalizers.delete(sessionId)
+ agyNormalizers.delete(sessionId)
+ clearAgyIdleWatch(sessionId)
hermesReaders.get(sessionId)?.stop()
hermesReaders.delete(sessionId)
devinReaders.get(sessionId)?.stop()
@@ -1403,7 +1475,14 @@ async function runForeground(token: string): Promise<void> {
} else if (meta.evicted) {
forgetSession(meta.evicted, { force: true })
}
- const reset = meta.isNew || (entry.engine !== 'cursor' && meta.hookEvent === 'SessionStart')
+ // agy is excluded for the same reason as cursor, arriving by a different road: it has no
+ // session-start event at all. The closest thing is `PreInvocation`, which fires before EVERY model
+ // round-trip — four to seven times in one measured turn — and each one re-folded the transcript and
+ // re-emitted `turn_started` for a turn already open (measured: two turn_started, one turn_ended).
+ // Its first bind is covered by `meta.isNew`, and registry derives the transcript path from the
+ // conversation id, so nothing here depends on a later announcement carrying it.
+ const reset = meta.isNew
+ || (entry.engine !== 'cursor' && entry.engine !== 'agy' && meta.hookEvent === 'SessionStart')
// Deliberately NOT gated on `meta.isNew`. `isNew` is false in exactly the case this is meant to catch:
// a session announced once BEFORE its transcript exists and registered again when the file appears —
// the second announcement is the only one that can carry the path, and it reports `isNew=false`
@@ -1466,7 +1545,9 @@ async function runForeground(token: string): Promise<void> {
? await findCursorTranscript(env.CURSOR_HOME, sessionId) ?? undefined
: observed.engine === 'grok'
? await findGrokTranscript(env.GROK_HOME, observed.cwd, sessionId) ?? undefined
- : undefined
+ : observed.engine === 'agy'
+ ? await findAgyTranscript(env.AGY_HOME, sessionId) ?? undefined
+ : undefined
if ((observed.engine === 'cursor' || observed.engine === 'grok') && !transcriptPath) return
} else {
const attempts = repairAttempts.get(agent.agentId) ?? 0
@@ -1476,7 +1557,11 @@ async function runForeground(token: string): Promise<void> {
repairAttempts.set(agent.agentId, attempts + 1)
const startedAtMs = Date.parse(observed.processIdentity.startMarker)
if (!Number.isFinite(startedAtMs)) return
- const found = await findLiveSession(observed.engine, observed.cwd, startedAtMs, { bornOnly: true })
+ // agy cannot be found by directory — its repair reads the presence lock the process holds open.
+ const found = await findLiveSession(observed.engine, observed.cwd, startedAtMs, {
+ bornOnly: true,
+ pid: observed.processIdentity.pid,
+ })
if (!found || registry.has(found.sessionId) || isRecentlyDeleted(found.sessionId)) return
sessionId = found.sessionId
transcriptPath = found.transcriptPath
@@ -1739,6 +1824,37 @@ async function runForeground(token: string): Promise<void> {
})
return
}
+ // agy's Stop hook is the ONLY turn boundary it has. Nothing in the transcript says a turn ended:
+ // a backgrounded step is written `status: RUNNING` and, the file being append-only, stays that way
+ // forever. Drain first so the closing prose is on the wire before turn_ended, then force-close.
+ if (session.engine === 'agy') {
+ // `waiting` = agy's loop stopped only because it is standing by for its sub-agents. The turn is
+ // NOT over, so nothing closes here — but the run that proved this necessary also finished its
+ // sub-agents and then never sent another Stop, so a backstop watches the pane instead.
+ if (status === 'waiting') {
+ armAgyIdleWatch(sessionId)
+ return
+ }
+ clearAgyIdleWatch(sessionId)
+ void (async () => {
+ await watcher.pollSession(sessionId)
+ const normalizer = agyNormalizers.get(sessionId)
+ if (!normalizer?.turnOpen) return
+ await new Promise((r) => setTimeout(r, STOP_HOOK_GRACE_MS))
+ await watcher.pollSession(sessionId)
+ if (!normalizer.turnOpen) return
+ if (status === 'error') {
+ announceTurnAborted(sessionId, 'agy', 'agy ended the turn early')
+ emitSessionEvents(sessionId, normalizer.abortTurn())
+ return
+ }
+ console.log(`[turn] ${sid(sessionId)} closed by agy Stop hook (after grace)`)
+ emitSessionEvents(sessionId, normalizer.closeTurn())
+ })().catch((err) => {
+ console.error('[hooks] agy stop hook failed:', err instanceof Error ? err.message : err)
+ })
+ return
+ }
if (session.engine === 'grok') {
void (async () => {
await watcher.pollSession(sessionId)
@@ -1862,6 +1978,7 @@ async function runForeground(token: string): Promise<void> {
installDevinHooks(hookPort)
installCommandCodeHooks(hookPort)
installGrokHooks(hookPort)
+ installAgyHooks(hookPort)
}
backend.setDashboardPort(hookPort) // surfaced to the web (e2e_status) so it can link here to approve
console.log(`[cli] local dashboard → http://127.0.0.1:${hookPort}`)
@@ -1905,6 +2022,10 @@ async function runForeground(token: string): Promise<void> {
let normalizer = grokNormalizers.get(evt.sessionId)
if (!normalizer) { normalizer = new GrokNormalizer(); grokNormalizers.set(evt.sessionId, normalizer) }
events = normalizer.ingest(evt.text)
+ } else if (session.engine === 'agy') {
+ let normalizer = agyNormalizers.get(evt.sessionId)
+ if (!normalizer) { normalizer = new AgyNormalizer(); agyNormalizers.set(evt.sessionId, normalizer) }
+ events = normalizer.ingest(evt.text)
} else if (session.engine === 'pi') {
let normalizer = piNormalizers.get(evt.sessionId)
if (!normalizer) { normalizer = new PiNormalizer('live'); piNormalizers.set(evt.sessionId, normalizer) }
@@ -1949,6 +2070,7 @@ async function runForeground(token: string): Promise<void> {
?? museNormalizers.get(session.sessionId)?.turnOpen
?? ampNormalizers.get(session.sessionId)?.turnOpen
?? grokNormalizers.get(session.sessionId)?.turnOpen
+ ?? agyNormalizers.get(session.sessionId)?.turnOpen
?? hermesReaders.get(session.sessionId)?.turnOpen
?? devinReaders.get(session.sessionId)?.turnOpen
?? commandcodeNormalizers.get(session.sessionId)?.turnOpen
@@ -2013,7 +2135,9 @@ async function runForeground(token: string): Promise<void> {
//
// Read just the footer, and only while such a session exists. NOT silent: a real change has to push to
// the device, which is the whole point.
- const PANE_POLLED_ENGINES = new Set(['devin', 'cursor', 'grok'])
+ // agy joins these three: its model/effort exist only in the hook payload and the pane footer, never
+ // in the transcript, so the chip goes stale without a poll.
+ const PANE_POLLED_ENGINES = new Set(['devin', 'cursor', 'grok', 'agy'])
const PANE_POLL_MS = 15_000
setInterval(() => {
for (const session of registry.list()) {
@@ -2060,6 +2184,7 @@ async function runForeground(token: string): Promise<void> {
museNormalizers.get(sessionId)?.closeTurn()
ampNormalizers.get(sessionId)?.closeTurn()
grokNormalizers.get(sessionId)?.closeTurn()
+ agyNormalizers.get(sessionId)?.closeTurn()
hermesReaders.get(sessionId)?.closeTurn()
devinReaders.get(sessionId)?.closeTurn()
commandcodeNormalizers.get(sessionId)?.closeTurn()
diff --git a/cli/src/config/env.ts b/cli/src/config/env.ts
index de4aa9fda..62cfdee4b 100644
--- a/cli/src/config/env.ts
+++ b/cli/src/config/env.ts
@@ -104,6 +104,13 @@ const envSchema = z.object({
CODEX_HOME: z.string().default(join(homedir(), '.codex')),
// Grok state root. Conversation records live below <GROK_HOME>/sessions/<encoded-cwd>/<uuid>/updates.jsonl.
GROK_HOME: z.string().default(join(homedir(), '.grok')),
+ // Antigravity CLI state root. Conversation transcripts live below
+ // <AGY_HOME>/brain/<conversationId>/.system_generated/logs/transcript_full.jsonl — the `_full`
+ // sibling is the one to read: plain `transcript.jsonl` re-quotes tool arguments and truncates
+ // long content. The hook payload names the same path, so this default is only the fallback.
+ AGY_HOME: z.string().default(join(homedir(), '.gemini', 'antigravity-cli')),
+ // Where the Antigravity CLI reads its shared customization root (hooks.json lives here).
+ AGY_CONFIG_DIR: z.string().default(join(homedir(), '.gemini', 'config')),
// Cursor state root. Interactive transcripts live below <CURSOR_HOME>/projects and local
// subagent linkage metadata lives below <CURSOR_HOME>/chats.
CURSOR_HOME: z.string().default(join(homedir(), '.cursor')),
@@ -229,6 +236,9 @@ const envSchema = z.object({
KILO_PATH: z.string().optional(),
// Path to the xAI Grok CLI for interactive sessions and recap one-shots.
GROK_PATH: z.string().optional(),
+ // Path to the Antigravity CLI. Two binaries answer to `agy` on a typical PATH — the CLI itself and
+ // the Antigravity IDE launcher — so an override is worth having.
+ AGY_PATH: z.string().optional(),
// Model for the device turn-recap one-shot.
SUMMARY_MODEL: z.string().default('sonnet'),
// Balanced Codex counterpart used only for recap workers; never inherits the interactive CLI model.
@@ -241,6 +251,9 @@ const envSchema = z.object({
KILO_SUMMARY_MODEL: z.string().default(''),
// Grok recap model. Empty → use the user's Grok CLI default model.
GROK_SUMMARY_MODEL: z.string().default(''),
+ // Antigravity recap model (a slug from `agy models`). Flash at low effort: a recap is a short
+ // summarisation of text already in hand, so the cheapest tier in the catalog is the right one.
+ AGY_SUMMARY_MODEL: z.string().default('gemini-3.7-flash-low'),
// Pi recap model (`provider/model` or a model pattern). Empty → use the user's pi config default.
PI_SUMMARY_MODEL: z.string().default(''),
// Hermes recap model. Empty → use the user's ~/.hermes/config.yaml default (keeps their provider).
diff --git a/cli/src/engines/README.md b/cli/src/engines/README.md
index 71d4ed103..a1c1d3c12 100644
--- a/cli/src/engines/README.md
+++ b/cli/src/engines/README.md
@@ -206,11 +206,32 @@ and can see both `$TMUX_PANE` and the session id, so it registers instead of bei
OpenCode plugin, the Pi extension and the Amp plugin all do this from `lib/hooks.ts`; none of the
three needs an entry in `notify.mjs`, which is only for the shell-hook engines.
+Scanning is also not always possible by DIRECTORY. agy records no cwd in its transcript, names its
+folder by the conversation id, and keeps a `conversation_summaries.db` that looks like the index for
+exactly this and holds only IDE rows, never CLI ones. What it does leave is
+`presence/<conversationId>.lock`, held open by the live process — a pid→conversation map and a liveness
+test in one. `findLiveSession` takes an optional `pid` for that case (`lsof` on macOS,
+`/proc/<pid>/fd` on Linux). Look for a lock, a socket, or an open descriptor before concluding a
+directory scan is impossible.
+
Scanning also has to solve **which project a session belongs to**, and the answer is usually not in
the path. For Muse, nothing in `sessions/YYYY/MM/DD/<uuid>/session.jsonl` names the project;
`workspace_root` in the first record is the only link. Where the plugin writes the transcript itself
this is free — Amp's plugin puts `cwd` on the first line precisely so the ordinary scan works.
+**A hook can also break the agent, so install only the events you need.** agy's `PreToolUse` contract
+makes `decision` REQUIRED, and a handler that prints anything else — including the `{}` every other
+hook here returns — is read as a DENIAL: measured on a real pane as "Tool call denied by pre-tool hook"
+on every tool call of the turn. Harness installs only `PreInvocation` (announce) and `Stop` (turn
+boundary) for agy. Read each event's output contract before adding it; tool events come off the
+transcript anyway.
+
+**And check whether the announce event repeats.** agy has no session-start event at all; the nearest
+thing, `PreInvocation`, fires before EVERY model round-trip — four to seven times in one measured turn.
+Registration is idempotent, but `handleRegistered` treats a `SessionStart` hook as a reason to re-fold
+the transcript, so each repeat re-emitted `turn_started` for a turn already open (two `turn_started`,
+one `turn_ended`). agy is excluded from that reset in `cli.ts`, the way cursor already was.
+
Worth knowing even if you do not need it: some agents already record which terminal opened which
session. Amp keys `lastThreadByTerminal` in its `session.json` by `tmux:<pane>@<server-pid>,<session>`,
an exact pane→thread map. Harness does not use it (the repair path is asked about a directory, not a
@@ -268,6 +289,17 @@ never called at all. None of that is guessable from the tool names.
**Write the spec against the recording, not against your reading of the docs.** If your agent's
behaviour changes, we want a new recording, not an edited fixture.
+**Not every status word resolves.** agy writes a backgrounded step as `status: "RUNNING"` and, the file
+being append-only, that line is never rewritten to `DONE`. Holding the turn open on it pins the device
+tile on "Processing" for ever. The step still CLOSES its tool row — it is the call's result, it just
+says the work continues elsewhere.
+
+**If the transcript has no end-of-turn record at all, say where the answer actually lives.** agy's is
+its `Stop` hook. That works while the daemon is running and fails on restart: folding a FINISHED
+conversation reports the last turn as still open and nothing is ever coming to close it (measured:
+`turn_heartbeat` every second, indefinitely). Its pane knows — `? for shortcuts` when idle,
+`esc to cancel` while busy — so attach reads the pane once and closes the folded turn.
+
## Stage D — drive the agent
Only needed for the capabilities your agent actually has. Skip what does not apply.
diff --git a/cli/src/engines/agy/askQuestion.spec.ts b/cli/src/engines/agy/askQuestion.spec.ts
new file mode 100644
index 000000000..8649c9007
--- /dev/null
+++ b/cli/src/engines/agy/askQuestion.spec.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { fileURLToPath } from 'node:url'
+import { parseQuestionPane } from '../../lib/askQuestion.js'
+import { parseAgyQuestionPane } from './askQuestion.js'
+
+const read = (name: string) =>
+ readFileSync(fileURLToPath(new URL(`../../lib/__fixtures__/${name}`, import.meta.url)), 'utf8')
+
+describe('agy ask-the-user dialog', () => {
+ it('reads the question and its options off a real pane', () => {
+ const view = parseAgyQuestionPane(read('question-agy.txt'))
+ expect(view).not.toBeNull()
+ expect(view!.kind).toBe('question')
+ const question = view as Extract<typeof view, { kind: 'question' }>
+ expect(question.question).toBe('Which colour do you prefer?')
+ expect(question.rows.map((r) => r.label)).toEqual(['Red', 'Green', 'Blue'])
+ // "Write-in..." opens a free-text editor the device cannot drive, so it must never be offered.
+ expect(question.rows.some((r) => /write/i.test(r.label))).toBe(false)
+ expect(question.rows.map((r) => r.number)).toEqual(['1', '2', '3'])
+ })
+
+ it('does not fire on the permission prompt — the shared parser owns that one', () => {
+ expect(parseAgyQuestionPane(read('permission-agy.txt'))).toBeNull()
+ expect(parseQuestionPane(read('permission-agy.txt'))).not.toBeNull()
+ })
+
+ it('ignores an idle pane', () => {
+ expect(parseAgyQuestionPane('> \n? for shortcuts Gemini 3.7 Flash · high')).toBeNull()
+ })
+})
diff --git a/cli/src/engines/agy/askQuestion.ts b/cli/src/engines/agy/askQuestion.ts
new file mode 100644
index 000000000..cc391d7db
--- /dev/null
+++ b/cli/src/engines/agy/askQuestion.ts
@@ -0,0 +1,67 @@
+/**
+ * agy's ask-the-user dialog, read off a real pane.
+ *
+ * Measured on agy 1.1.14 (`__fixtures__/question-agy.txt`):
+ *
+ * ? Which colour do you prefer?
+ * Question
+ * ────────────────────────────────────────────
+ * Question 1/1: Which colour do you prefer?
+ * > 1. Red
+ * 2. Green
+ * 3. Blue
+ * 4. Write-in...
+ * ↑/↓ Navigate · enter Select · esc Skip
+ *
+ * The shared parser returns null here: its anchors are footers like `Press enter to confirm`, and
+ * agy's says `↑/↓ Navigate · enter Select · esc Skip`. The `Question N/M:` line is the reliable one —
+ * it is the only place the question text appears in a form that is neither a `?` echo nor the box
+ * heading, and it also says how many questions are queued behind this one.
+ *
+ * agy's PERMISSION prompt is a different dialog and the SHARED parser reads it correctly already
+ * (numbered rows under `Do you want to proceed?`), so it deliberately falls through.
+ *
+ * Selection is by digit: typing `3` on a live pane picked Blue immediately, with no Enter.
+ */
+
+import type { PaneView, QuestionRow } from '../../lib/askQuestion.js'
+
+const ESCAPES = /\u001b\[[0-9;:]*[A-Za-z]/g
+/** `Question 1/1: <text>` — the `N/M` counter is what tells this dialog apart from an echoed prompt. */
+const HEADING = /^Question\s+\d+\/\d+:\s*(.+?)\s*$/
+/** `> 1. Red` / ` 2. Green`; the caret marks the highlighted row and is not part of the label. */
+const ROW = /^\s*[>›]?\s*(\d+)\.\s+(.*?)\s*$/
+const FOOTER = /↑\/↓\s*Navigate/
+
+/**
+ * Rows that open a free-text editor.
+ *
+ * Dropped rather than offered: the device has no text input, so a "Write-in..." row is a dead end
+ * there — the same call muse's "None of the above" forced.
+ */
+const WRITE_IN = /^write[- ]?in\b/i
+
+export function parseAgyQuestionPane(capture: string): PaneView {
+ const lines = capture.replace(ESCAPES, '').split('\n').map((line) => line.trimEnd())
+ const footer = lines.findLastIndex((line) => FOOTER.test(line))
+ if (footer === -1) return null
+
+ const rows: QuestionRow[] = []
+ let question = ''
+ for (let i = footer - 1; i >= 0; i--) {
+ const line = lines[i]
+ if (!line.trim()) continue
+ const heading = HEADING.exec(line.trim())
+ if (heading) { question = heading[1]; break }
+ const row = ROW.exec(line)
+ if (!row) {
+ // A non-row, non-heading line between the rows and the heading means this is not the dialog.
+ if (rows.length) return null
+ continue
+ }
+ if (WRITE_IN.test(row[2])) continue
+ rows.unshift({ number: row[1], label: row[2], checked: false })
+ }
+ if (!question || rows.length < 2) return null
+ return { kind: 'question', question, rows, multi: false, typeRow: null }
+}
diff --git a/cli/src/engines/agy/history.spec.ts b/cli/src/engines/agy/history.spec.ts
new file mode 100644
index 000000000..b6123a254
--- /dev/null
+++ b/cli/src/engines/agy/history.spec.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { fileURLToPath } from 'node:url'
+import { agyHistoryPage } from '../../backendSocket.js'
+
+const LINES = readFileSync(fileURLToPath(new URL('../../lib/__fixtures__/agy-session.jsonl', import.meta.url)), 'utf8')
+ .split('\n').filter(Boolean)
+
+describe('agy session_get', () => {
+ // The web client always sends a `limit`, so it takes the PAGINATED branch. Handling only the full
+ // branch opens an empty pane — the failure this test exists to prevent.
+ it('answers both shapes with the same replay', () => {
+ const full = agyHistoryPage(LINES, false)
+ const page = agyHistoryPage(LINES, true)
+ expect(full.events.length).toBeGreaterThan(10)
+ expect(page.events).toEqual(full.events)
+ expect(page.hasMore).toBe(false)
+ expect(page.oldestCursor).toBeNull()
+ })
+
+ it('replays the conversation, not a lifecycle stream', () => {
+ const { events } = agyHistoryPage(LINES, true)
+ expect(events[0].type).toBe('user_message')
+ expect(events[events.length - 1]).toEqual({ type: 'done', payload: { result: 'success' } })
+ expect(events.some((e) => e.type === 'tool_start')).toBe(true)
+ expect(events.some((e) => e.type === 'text_delta')).toBe(true)
+ })
+})
diff --git a/cli/src/engines/agy/normalizer.spec.ts b/cli/src/engines/agy/normalizer.spec.ts
new file mode 100644
index 000000000..80f4dde58
--- /dev/null
+++ b/cli/src/engines/agy/normalizer.spec.ts
@@ -0,0 +1,197 @@
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { fileURLToPath } from 'node:url'
+import {
+ AgyNormalizer,
+ agyMessagesToEvents,
+ agyStep,
+ agyToolInput,
+ agyToolName,
+ agyUserText,
+ lastAgyTurnText,
+} from './normalizer.js'
+import type { LiveEvent } from '../../lib/normalize.js'
+
+const FIXTURE = fileURLToPath(new URL('../../lib/__fixtures__/agy-session.jsonl', import.meta.url))
+const LINES = readFileSync(FIXTURE, 'utf8').split('\n').filter(Boolean)
+
+function live(): LiveEvent[] {
+ const normalizer = new AgyNormalizer()
+ const events: LiveEvent[] = []
+ for (const line of LINES) events.push(...normalizer.ingest(line))
+ events.push(...normalizer.closeTurn())
+ return events
+}
+
+describe('agy normalizer, over a real recorded session', () => {
+ it('opens a turn on every user input and closes the last one on the Stop hook', () => {
+ const events = live()
+ const started = events.filter((e) => e.type === 'turn_started')
+ const ended = events.filter((e) => e.type === 'turn_ended')
+ // Four USER_INPUT steps: three of them close the turn before them, the Stop hook closes the last.
+ expect(started).toHaveLength(4)
+ expect(ended).toHaveLength(4)
+ expect(events[events.length - 1].type).toBe('turn_ended')
+ })
+
+ it('leaves no tool row open — every start has exactly one matching end', () => {
+ const events = live()
+ const starts = events.filter((e) => e.type === 'tool_start') as Array<Extract<LiveEvent, { type: 'tool_start' }>>
+ const ends = events.filter((e) => e.type === 'tool_end') as Array<Extract<LiveEvent, { type: 'tool_end' }>>
+ expect(starts.length).toBeGreaterThan(0)
+ expect(ends).toHaveLength(starts.length)
+ expect(ends.map((e) => e.payload.id).sort()).toEqual(starts.map((e) => e.payload.id).sort())
+ })
+
+ it('pairs results positionally, not by name — list_dir answers as LIST_DIRECTORY', () => {
+ const events = live()
+ const listStart = events.find((e) => e.type === 'tool_start' && e.payload.tool === 'ListDir')
+ expect(listStart).toBeDefined()
+ const id = (listStart as Extract<LiveEvent, { type: 'tool_start' }>).payload.id
+ const listEnd = events.find((e) => e.type === 'tool_end' && e.payload.id === id)
+ expect(listEnd).toBeDefined()
+ expect((listEnd as Extract<LiveEvent, { type: 'tool_end' }>).payload.isError).toBe(false)
+ })
+
+ it('marks an ERROR_MESSAGE result as a failed tool', () => {
+ const events = live()
+ const failed = events.filter((e) => e.type === 'tool_end' && e.payload.isError)
+ expect(failed.length).toBeGreaterThan(0)
+ })
+
+ it('a backgrounded RUNNING result still closes its row and never holds the turn open', () => {
+ const normalizer = new AgyNormalizer()
+ for (const line of LINES) {
+ const step = agyStep(line)
+ normalizer.ingest(line)
+ // The RUNNING background-task step is a result, so it must not leave the turn un-closable.
+ if (step?.status === 'RUNNING') expect(normalizer.turnOpen).toBe(true)
+ }
+ expect(normalizer.closeTurn().some((e) => e.type === 'turn_ended')).toBe(true)
+ expect(normalizer.turnOpen).toBe(false)
+ })
+
+ it('renders NOTHING for the routine checkpoint every conversation carries', () => {
+ const normalizer = new AgyNormalizer()
+ const checkpoint = LINES.find((line) => agyStep(line)?.type === 'CHECKPOINT')!
+ // Its body claims the conversation was truncated; it is a fixed template, and `{{ CHECKPOINT 0 }}`
+ // appears in every agy conversation — including four-step ones. Rendering it put a
+ // "Context compacted" banner under the first reply of every new agent.
+ expect(agyStep(checkpoint)!.content).toContain('CHECKPOINT 0')
+ expect(agyStep(checkpoint)!.content).toContain('have been truncated')
+ normalizer.ingest(LINES[0])
+ expect(normalizer.turnOpen).toBe(true)
+ expect(normalizer.ingest(checkpoint)).toEqual([])
+ expect(normalizer.turnOpen).toBe(true)
+ })
+
+ it('treats a higher checkpoint counter as a compaction, without touching turn state', () => {
+ const normalizer = new AgyNormalizer()
+ normalizer.ingest(LINES[0])
+ const later = JSON.stringify({
+ step_index: 99, source: 'SYSTEM', type: 'CHECKPOINT', status: 'DONE',
+ content: '{{ CHECKPOINT 1 }}\n **The earlier parts of this conversation have been truncated…',
+ })
+ const events = normalizer.ingest(later)
+ expect(events).toEqual([{ type: 'context_compact', payload: { message: '', trigger: 'auto' } }])
+ expect(normalizer.turnOpen).toBe(true)
+ })
+
+ it('closes a sub-agent row when the child reports back', () => {
+ const events = live()
+ const finished = events.filter((e) => e.type === 'subagent_finished')
+ expect(finished).toHaveLength(1)
+ const taskStart = events.find((e) => e.type === 'tool_start' && e.payload.tool === 'Task')
+ expect((finished[0] as Extract<LiveEvent, { type: 'subagent_finished' }>).payload.id)
+ .toBe((taskStart as Extract<LiveEvent, { type: 'tool_start' }>).payload.id)
+ })
+
+ it('summarises the sub-agent launch instead of dumping its JSON', () => {
+ const events = live()
+ const taskStart = events.find((e) => e.type === 'tool_start' && e.payload.tool === 'Task')!
+ const id = (taskStart as Extract<LiveEvent, { type: 'tool_start' }>).payload.id
+ const end = events.find((e) => e.type === 'tool_end' && e.payload.id === id) as Extract<LiveEvent, { type: 'tool_end' }>
+ // The raw result is a wall of conversationIds, file:// transcript URIs and workspace lists.
+ expect(end.payload.output).toMatch(/^Launched \d+ sub-agents?/)
+ expect(end.payload.output).not.toContain('logAbsoluteUri')
+ expect(end.payload.output).not.toContain('file://')
+ })
+
+ it('reports ONE finish for a call that spawned several children', () => {
+ // agy launches N sub-agents from a single `invoke_subagent`, so N report-backs share one row.
+ // Measured on a real three-agent run: firing per child produced three `subagent_finished` for the
+ // same id, on a row `tool_end` had already closed.
+ const normalizer = new AgyNormalizer()
+ const children = ['aaaaaaaa-1111-2222-3333-444444444444', 'bbbbbbbb-1111-2222-3333-444444444444']
+ const step = (o: Record<string, unknown>) => JSON.stringify({ step_index: 1, source: 'MODEL', status: 'DONE', ...o })
+ normalizer.ingest(step({ type: 'USER_INPUT', source: 'USER_EXPLICIT', content: 'go' }))
+ normalizer.ingest(step({ type: 'PLANNER_RESPONSE', tool_calls: [{ name: 'invoke_subagent', args: {} }] }))
+ normalizer.ingest(step({
+ type: 'INVOKE_SUBAGENT',
+ content: `Created the following subagents:\n${children.map((c) => `{ "conversationId": "${c}" }`).join('\n')}`,
+ }))
+ const first = normalizer.ingest(step({ type: 'SYSTEM_MESSAGE', source: 'SYSTEM', content: `[Message] sender=${children[0]} content=btc done` }))
+ expect(first.filter((e) => e.type === 'subagent_finished')).toHaveLength(0) // one still running
+ const second = normalizer.ingest(step({ type: 'SYSTEM_MESSAGE', source: 'SYSTEM', content: `[Message] sender=${children[1]} content=eth done` }))
+ expect(second.filter((e) => e.type === 'subagent_finished')).toHaveLength(1) // now the row is done
+ })
+
+ it('maps ask_question to the shared AskUserQuestion name with its structured options', () => {
+ const events = live()
+ const ask = events.find((e) => e.type === 'tool_start' && e.payload.tool === 'AskUserQuestion')
+ expect(ask).toBeDefined()
+ const input = (ask as Extract<LiveEvent, { type: 'tool_start' }>).payload.input as Record<string, unknown>
+ const questions = input.questions as Array<{ question: string; options: string[] }>
+ expect(questions[0].options.length).toBeGreaterThan(1)
+ })
+
+ it('strips the <USER_REQUEST> wrapper and the metadata block', () => {
+ const events = live()
+ const first = events.find((e) => e.type === 'user_message') as Extract<LiveEvent, { type: 'user_message' }>
+ expect(first.payload.content).not.toContain('<USER_REQUEST>')
+ expect(first.payload.content).not.toContain('ADDITIONAL_METADATA')
+ })
+
+ it('replay emits no lifecycle frames and terminates with done', () => {
+ const events: LiveEvent[] = agyMessagesToEvents(LINES)
+ expect(events.some((e) => e.type === 'turn_started')).toBe(false)
+ expect(events.some((e) => e.type === 'turn_ended')).toBe(false)
+ expect(events[0].type).toBe('user_message')
+ expect(events[events.length - 1]).toEqual({ type: 'done', payload: { result: 'success' } })
+ })
+
+ it('lastAgyTurnText returns the final exchange as the recap source', () => {
+ const last = lastAgyTurnText(LINES)
+ expect(last).not.toBeNull()
+ expect(last!.assistantText.length).toBeGreaterThan(0)
+ })
+
+ it('is inert on malformed input', () => {
+ const normalizer = new AgyNormalizer()
+ expect(normalizer.ingest('not json')).toEqual([])
+ expect(normalizer.ingest('{}')).toEqual([])
+ expect(normalizer.ingest('[]')).toEqual([])
+ expect(agyStep('{"step_index":1}')).toBeNull()
+ })
+})
+
+describe('agy pure mappings', () => {
+ it('maps measured tool names and title-cases the rest', () => {
+ expect(agyToolName('run_command')).toBe('Bash')
+ expect(agyToolName('ask_question')).toBe('AskUserQuestion')
+ expect(agyToolName('invoke_subagent')).toBe('Task')
+ expect(agyToolName('some_future_tool')).toBe('Some Future Tool')
+ })
+
+ it('reshapes arguments onto the keys the shared cards read, keeping the originals', () => {
+ const bash = agyToolInput('Bash', { CommandLine: 'pwd', Cwd: '/tmp' })
+ expect(bash.command).toBe('pwd')
+ expect(bash.CommandLine).toBe('pwd')
+ expect(agyToolInput('Grep', { Query: 'test' }).pattern).toBe('test')
+ })
+
+ it('unwraps the user request', () => {
+ expect(agyUserText('<USER_REQUEST>\nhello\n</USER_REQUEST>\n<ADDITIONAL_METADATA>\nx\n</ADDITIONAL_METADATA>')).toBe('hello')
+ expect(agyUserText('bare text')).toBe('bare text')
+ })
+})
diff --git a/cli/src/engines/agy/normalizer.ts b/cli/src/engines/agy/normalizer.ts
new file mode 100644
index 000000000..5988d6170
--- /dev/null
+++ b/cli/src/engines/agy/normalizer.ts
@@ -0,0 +1,385 @@
+/**
+ * Antigravity CLI (`agy`) `transcript_full.jsonl` -> Harness's shared event vocabulary.
+ *
+ * Measured on agy 1.1.14. The engine appends one JSON "step" per line to
+ * `<AGY_HOME>/brain/<conversationId>/.system_generated/logs/transcript_full.jsonl`. Read the `_full`
+ * file, not its `transcript.jsonl` sibling: the short one re-quotes tool arguments
+ * (`"query": "\"bitcoin…\""`) and truncates long content.
+ *
+ * The shape is regular and positional:
+ *
+ * USER_INPUT the turn opens; content is wrapped in <USER_REQUEST>
+ * PLANNER_RESPONSE tool_calls:[…] the model's text/thinking, plus N tool calls
+ * <RESULT> exactly N result steps follow, in call order
+ * …
+ * PLANNER_RESPONSE closing prose, no tool_calls
+ *
+ * A result step's `type` is the tool's own step type — `run_command` answers as `RUN_COMMAND`,
+ * `search_web` as `SEARCH_WEB` — but the mapping is NOT a round-trip: `list_dir` answers as
+ * `LIST_DIRECTORY`, and any failed call answers as `ERROR_MESSAGE` whatever the tool was. Pairing is
+ * therefore by POSITION against the calls queued by the preceding PLANNER_RESPONSE, never by name.
+ *
+ * Two things that are deliberately NOT turn boundaries:
+ *
+ * - `status: "RUNNING"`. A backgrounded tool (`schedule`, long shell) writes its result step as
+ * RUNNING and, because the file is strictly append-only, that line is never rewritten to DONE.
+ * Holding a turn open on it pins the device tile on "Processing" forever. It still CLOSES its tool
+ * row — the step is the call's result, it just says the work continues elsewhere.
+ * - `CHECKPOINT`. Despite a body that says the conversation "has been truncated", `{{ CHECKPOINT 0 }}`
+ * is written into EVERY conversation near its start — see the branch below. Only a higher counter
+ * is treated as a compaction, and even then it must not touch turn state.
+ *
+ * The real close is agy's `Stop` hook, handled in `cli.ts` (drain → grace → drain → force-close).
+ */
+
+import type { EngineNormalizer } from '../types.js'
+import type { LastTurnText, LiveEvent, SessionEvent } from '../../lib/normalize.js'
+
+type JsonObject = Record<string, unknown>
+
+const MAX_OUTPUT = 2_000
+const MAX_THINKING = 500
+
+/**
+ * Only tool names observed in real agy sessions belong here; unknown tools stay visibly generic.
+ *
+ * There is no planning tool to map. Asked three times on a real pane to "make a todo list and do it,
+ * do not just describe it", agy wrote markdown checkboxes in prose and called nothing — and the full
+ * `CORTEX_STEP_TYPE_*` vocabulary in the binary contains no todo/task-list step. The device checklist
+ * for this engine is empty by measurement.
+ */
+const TOOL_NAMES: Record<string, string> = {
+ run_command: 'Bash',
+ view_file: 'Read',
+ list_dir: 'ListDir',
+ grep_search: 'Grep',
+ codebase_search: 'Grep',
+ find_by_name: 'Glob',
+ search_web: 'WebSearch',
+ read_url_content: 'WebFetch',
+ write_to_file: 'Write',
+ replace_file_content: 'Edit',
+ edit_file: 'Edit',
+ ask_question: 'AskUserQuestion',
+ invoke_subagent: 'Task',
+ manage_subagents: 'TaskWait',
+ send_message: 'SendMessage',
+ schedule: 'Schedule',
+}
+
+export function agyToolName(name: string): string {
+ if (TOOL_NAMES[name]) return TOOL_NAMES[name]
+ const words = name.split(/[_\s-]+/).filter(Boolean)
+ return words.length ? words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(' ') : 'Tool'
+}
+
+function obj(value: unknown): JsonObject | null {
+ return value && typeof value === 'object' && !Array.isArray(value) ? value as JsonObject : null
+}
+
+function str(value: unknown): string {
+ return typeof value === 'string' ? value : ''
+}
+
+function clip(value: string, max: number): string {
+ return value.length <= max ? value : `${value.slice(0, max)}\n...[truncated]`
+}
+
+export interface AgyStep {
+ stepIndex: number
+ source: string
+ type: string
+ status: string
+ content: string
+ thinking: string
+ toolCalls: Array<{ name: string; args: JsonObject }>
+ exitCode: number | null
+}
+
+export function agyStep(line: string): AgyStep | null {
+ let raw: JsonObject | null
+ try { raw = obj(JSON.parse(line)) } catch { return null }
+ if (!raw) return null
+ const type = str(raw.type)
+ if (!type) return null
+ const calls: Array<{ name: string; args: JsonObject }> = []
+ if (Array.isArray(raw.tool_calls)) {
+ for (const entry of raw.tool_calls) {
+ const call = obj(entry)
+ const name = str(call?.name)
+ if (name) calls.push({ name, args: obj(call?.args) ?? {} })
+ }
+ }
+ return {
+ stepIndex: typeof raw.step_index === 'number' ? raw.step_index : -1,
+ source: str(raw.source),
+ type,
+ status: str(raw.status),
+ content: str(raw.content),
+ thinking: str(raw.thinking),
+ toolCalls: calls,
+ exitCode: typeof raw.exit_code === 'number' ? raw.exit_code : null,
+ }
+}
+
+/**
+ * Steps that carry no user-visible content and must not be mistaken for a tool result.
+ *
+ * CONVERSATION_HISTORY is agy's own context-priming record (always empty content). SYSTEM_MESSAGE is
+ * how a sub-agent reports back to its parent and is handled separately.
+ */
+const NON_RESULT_TYPES = new Set(['USER_INPUT', 'PLANNER_RESPONSE', 'CHECKPOINT', 'CONVERSATION_HISTORY', 'SYSTEM_MESSAGE'])
+
+/** `<USER_REQUEST>…</USER_REQUEST>` plus the metadata block agy appends to every prompt. */
+export function agyUserText(content: string): string {
+ const request = /<USER_REQUEST>\s*([\s\S]*?)\s*<\/USER_REQUEST>/.exec(content)
+ const body = request ? request[1] : content.replace(/<ADDITIONAL_METADATA>[\s\S]*?<\/ADDITIONAL_METADATA>/g, '')
+ return body.trim()
+}
+
+/**
+ * Strip the timestamp preamble every tool result step carries.
+ *
+ * Measured: `Created At: …\nCompleted At: …\n\n<the actual output>`. Left in, every tool card opens
+ * with two lines of clock before it says anything.
+ */
+export function agyToolOutput(step: AgyStep): string {
+ const body = step.content
+ .replace(/^Created At: [^\n]*\n?/, '')
+ .replace(/^Completed At: [^\n]*\n?/, '')
+ .trim()
+ return clip(body, MAX_OUTPUT)
+}
+
+/** Normalize the measured argument names that otherwise render blank shared cards. */
+export function agyToolInput(tool: string, args: JsonObject): JsonObject {
+ // `toolAction`/`toolSummary` are agy's own card labels; keep them, they are useful in the expansion.
+ if (tool === 'Bash' && str(args.CommandLine)) return { ...args, command: str(args.CommandLine) }
+ if (tool === 'Read' && str(args.AbsolutePath)) return { ...args, file_path: str(args.AbsolutePath) }
+ if (tool === 'ListDir' && str(args.DirectoryPath)) return { ...args, path: str(args.DirectoryPath) }
+ if (tool === 'Grep' && str(args.Query)) return { ...args, pattern: str(args.Query) }
+ if (tool === 'WebSearch' && str(args.query)) return args
+ return args
+}
+
+interface PendingCall {
+ id: string
+ tool: string
+ rawName: string
+}
+
+interface AgyTurnState {
+ open: boolean
+ seq: number
+ /** Calls announced by the last PLANNER_RESPONSE, waiting for their result steps, in order. */
+ pending: PendingCall[]
+ /** Tool rows opened and not yet closed, so an interrupted turn can close them all. */
+ openRows: Map<string, string>
+ /**
+ * Row id -> the child conversations it spawned that have not reported back yet.
+ *
+ * One `invoke_subagent` call spawns N children (measured: three in one call), so N report-backs
+ * share ONE row. Emitting `subagent_finished` per child fired the same id three times for a row
+ * already closed; the row is finished when the LAST child has reported.
+ */
+ subagentRows: Map<string, Set<string>>
+ /** Child conversation id -> its row, so a report-back can find the row it belongs to. */
+ subagentOwner: Map<string, string>
+}
+
+export function newAgyTurnState(): AgyTurnState {
+ return { open: false, seq: 0, pending: [], openRows: new Map(), subagentRows: new Map(), subagentOwner: new Map() }
+}
+
+function closeRows(state: AgyTurnState, events: LiveEvent[], status: string): void {
+ for (const [id, tool] of state.openRows) {
+ events.push({ type: 'tool_end', payload: { id, tool, output: `Tool ${status}`, isError: status === 'failed', summary: '' } })
+ }
+ state.openRows.clear()
+ state.pending = []
+}
+
+/** `Created the following subagents:\n{ "conversationId": "…", … }{ … }` -> the child ids. */
+function subagentIds(content: string): string[] {
+ return [...content.matchAll(/"conversationId":\s*"([0-9a-f-]{16,})"/gi)].map((match) => match[1])
+}
+
+/**
+ * The `invoke_subagent` result is a wall of JSON — one object per child with its conversation id, a
+ * `file://` transcript URI and its workspace list — and rendering it raw filled the card with machine
+ * addresses nobody can act on (measured on a real three-agent run). The count is the useful part; the
+ * children's work arrives as their report-backs.
+ */
+function subagentSummary(content: string, children: string[]): string {
+ const roles = [...content.matchAll(/"role"\s*:\s*"([^"]+)"/g)].map((match) => match[1])
+ const what = roles.length ? `: ${roles.join(', ')}` : ''
+ return `Launched ${children.length} sub-agent${children.length === 1 ? '' : 's'}${what}`
+}
+
+/** A child's report-back arrives as `[Message] … sender=<child conversation id> … content=<text>`. */
+function systemMessageSender(content: string): { sender: string; text: string } | null {
+ const sender = /sender=([0-9a-f-]{16,})/i.exec(content)
+ if (!sender) return null
+ const text = /content=([\s\S]*)$/.exec(content)
+ return { sender: sender[1], text: (text ? text[1] : '').trim() }
+}
+
+export function agyStepToEvents(step: AgyStep, state: AgyTurnState, mode: 'live' | 'replay'): LiveEvent[] {
+ const events: LiveEvent[] = []
+
+ if (step.type === 'USER_INPUT') {
+ const userMessage = agyUserText(step.content)
+ if (mode === 'live') {
+ if (state.open) {
+ closeRows(state, events, 'interrupted')
+ events.push({ type: 'turn_ended', payload: {} })
+ }
+ state.open = true
+ state.pending = []
+ events.push({ type: 'turn_started', payload: { userMessage } })
+ }
+ events.push({ type: 'user_message', payload: { content: userMessage } })
+ return events
+ }
+
+ if (step.type === 'CHECKPOINT') {
+ // NOT automatically a compaction, whatever its text says.
+ //
+ // Every agy conversation carries exactly one `{{ CHECKPOINT 0 }}` at step 3 or 4 — measured across
+ // all ten conversations on this machine, including a four-step one whose only turn was "hi". Its
+ // body always claims "the earlier parts of this conversation have been truncated", because it is a
+ // fixed template (`{{ CHECKPOINT %d }}` in the binary), not a report. Rendering it put a
+ // "Context compacted" banner under the FIRST reply of every new agent.
+ //
+ // The counter is what carries the information: 0 is the routine bookkeeping record. A higher one
+ // ought to be a real compaction, but no conversation here ran long enough to produce one, so that
+ // branch is unverified — and an unparseable header is treated as routine, because a missing banner
+ // is a far smaller error than one on every first message.
+ const checkpoint = /\{\{\s*CHECKPOINT\s+(\d+)\s*\}\}/.exec(step.content)
+ if (!checkpoint || checkpoint[1] === '0') return events
+ // Deliberately does not touch `state.open`, and deliberately carries no body: agy's checkpoint text
+ // is prompt scaffolding for itself (log paths, "this summary is just for your reference"), not
+ // something a person reads. The surfaces render their own sentence for an empty message.
+ events.push({ type: 'context_compact', payload: { message: '', trigger: 'auto' } })
+ return events
+ }
+
+ if (step.type === 'CONVERSATION_HISTORY') return events
+
+ if (step.type === 'SYSTEM_MESSAGE') {
+ const message = systemMessageSender(step.content)
+ const row = message ? state.subagentOwner.get(message.sender) : undefined
+ if (message && row) {
+ state.subagentOwner.delete(message.sender)
+ const outstanding = state.subagentRows.get(row)
+ outstanding?.delete(message.sender)
+ // One row, N children: report it finished once, when the last of them has answered.
+ if (outstanding && outstanding.size === 0) {
+ state.subagentRows.delete(row)
+ events.push({ type: 'subagent_finished', payload: { id: row, status: 'completed', summary: clip(message.text, MAX_OUTPUT) } })
+ }
+ }
+ return events
+ }
+
+ if (step.type === 'PLANNER_RESPONSE') {
+ if (step.thinking) events.push({ type: 'thinking_delta', payload: { content: clip(step.thinking, MAX_THINKING) } })
+ const text = step.content.trim()
+ if (text) events.push({ type: 'text_delta', payload: { content: text } })
+ for (const call of step.toolCalls) {
+ const tool = agyToolName(call.name)
+ const id = `agy-${step.stepIndex}-${state.seq++}`
+ state.pending.push({ id, tool, rawName: call.name })
+ state.openRows.set(id, tool)
+ events.push({ type: 'tool_start', payload: { id, tool, input: agyToolInput(tool, call.args) } })
+ }
+ return events
+ }
+
+ if (NON_RESULT_TYPES.has(step.type)) return events
+
+ // Everything else is a tool RESULT, paired positionally with the call that queued it.
+ const call = state.pending.shift()
+ if (!call) return events
+ state.openRows.delete(call.id)
+ const isError = step.type === 'ERROR_MESSAGE' || (step.exitCode !== null && step.exitCode !== 0)
+ const output = agyToolOutput(step)
+ let cardOutput = output
+ if (call.rawName === 'invoke_subagent') {
+ const children = subagentIds(step.content)
+ if (children.length) {
+ state.subagentRows.set(call.id, new Set(children))
+ for (const child of children) state.subagentOwner.set(child, call.id)
+ cardOutput = subagentSummary(step.content, children)
+ }
+ }
+ events.push({
+ type: 'tool_end',
+ payload: { id: call.id, tool: call.tool, output: cardOutput, isError, summary: '' },
+ })
+ return events
+}
+
+export class AgyNormalizer implements EngineNormalizer {
+ private state = newAgyTurnState()
+
+ get turnOpen(): boolean { return this.state.open }
+
+ /** The `Stop` hook fired: close every row this turn opened, then the turn. */
+ closeTurn(): LiveEvent[] {
+ if (!this.state.open) return []
+ const events: LiveEvent[] = []
+ closeRows(this.state, events, 'completed')
+ this.state.open = false
+ this.state.subagentRows.clear()
+ this.state.subagentOwner.clear()
+ events.push({ type: 'turn_ended', payload: {} })
+ return events
+ }
+
+ abortTurn(): LiveEvent[] {
+ if (!this.state.open) return []
+ const events: LiveEvent[] = []
+ closeRows(this.state, events, 'failed')
+ this.state.open = false
+ this.state.subagentRows.clear()
+ this.state.subagentOwner.clear()
+ events.push({ type: 'turn_ended', payload: { aborted: true } })
+ return events
+ }
+
+ ingest(line: string): LiveEvent[] {
+ const step = agyStep(line)
+ return step ? agyStepToEvents(step, this.state, 'live') : []
+ }
+
+ finishReplay(): LiveEvent[] { return [] }
+}
+
+export function agyMessagesToEvents(lines: string[]): SessionEvent[] {
+ const state = newAgyTurnState()
+ const events: SessionEvent[] = []
+ for (const line of lines) {
+ const step = agyStep(line)
+ if (step) events.push(...agyStepToEvents(step, state, 'replay') as SessionEvent[])
+ }
+ events.push({ type: 'done', payload: { result: 'success' } })
+ return events
+}
+
+export function lastAgyTurnText(lines: string[]): LastTurnText | null {
+ let userMessage = ''
+ let assistantText = ''
+ for (const line of lines) {
+ const step = agyStep(line)
+ if (!step) continue
+ if (step.type === 'USER_INPUT') {
+ userMessage = agyUserText(step.content)
+ assistantText = ''
+ } else if (step.type === 'PLANNER_RESPONSE') {
+ const text = step.content.trim()
+ if (text) assistantText += `${assistantText ? '\n\n' : ''}${text}`
+ }
+ }
+ return assistantText ? { userMessage, assistantText } : null
+}
diff --git a/cli/src/engines/agy/runtimeProfile.spec.ts b/cli/src/engines/agy/runtimeProfile.spec.ts
new file mode 100644
index 000000000..6a280a9d2
--- /dev/null
+++ b/cli/src/engines/agy/runtimeProfile.spec.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { fileURLToPath } from 'node:url'
+import { agyPaneIdle, parseAgyFooterProfile, parseAgyModelsOutput } from './runtimeProfile.js'
+
+/** Verbatim `agy models` output (1.1.14), including the stderr notice a merged capture would carry. */
+const MODELS = `Fetching available models...
+gemini-3.7-flash-high\tGemini 3.7 Flash (High)
+gemini-3.7-flash-medium\tGemini 3.7 Flash (Medium)
+gemini-3.7-flash-low\tGemini 3.7 Flash (Low)
+gemini-3.6-flash-high\tGemini 3.6 Flash (High)
+gemini-3.6-flash-medium\tGemini 3.6 Flash (Medium)
+gemini-3.6-flash-low\tGemini 3.6 Flash (Low)
+gemini-3.5-flash-high\tGemini 3.5 Flash (High)
+gemini-3.5-flash-medium\tGemini 3.5 Flash (Medium)
+gemini-3.5-flash-low\tGemini 3.5 Flash (Low)
+gemini-3.1-pro-high\tGemini 3.1 Pro (High)
+gemini-3.1-pro-low\tGemini 3.1 Pro (Low)
+claude-sonnet-4-6\tClaude Sonnet 4.6 (Thinking)
+claude-opus-4-6-thinking\tClaude Opus 4.6 (Thinking)
+gpt-oss-120b-medium\tGPT-OSS 120B (Medium)
+`
+
+describe('agy model catalog', () => {
+ it('parses every row the real catalog prints, and drops the progress notice', () => {
+ const models = parseAgyModelsOutput(MODELS)
+ // 14 catalog rows in, 14 slugs out — the count is the assertion that matters: a character class
+ // that misses one vendor's punctuation drops models from the picker with no error anywhere.
+ expect(models).toHaveLength(14)
+ expect(models).toContain('gemini-3.7-flash-high')
+ expect(models).toContain('claude-opus-4-6-thinking')
+ expect(models).toContain('gpt-oss-120b-medium')
+ expect(models.some((m) => m.startsWith('Fetching'))).toBe(false)
+ })
+})
+
+describe('agy pane footer', () => {
+ it('reads the idle footer as a catalog slug plus its effort', () => {
+ const capture = [
+ ' ↑/↓ Navigate · enter Select · esc Skip',
+ 'esc to cancel Gemini 3.7 Flash · high',
+ ].join('\n')
+ expect(parseAgyFooterProfile(capture)).toEqual({ model: 'gemini-3.7-flash-high', effort: 'high' })
+ })
+
+ it('reads the footer off a real captured pane, escapes and all', () => {
+ const capture = readFileSync(fileURLToPath(new URL('../../lib/__fixtures__/permission-agy.txt', import.meta.url)), 'utf8')
+ expect(parseAgyFooterProfile(capture)).toEqual({ model: 'gemini-3.7-flash-high', effort: 'high' })
+ })
+
+ it('ignores a pane with no footer', () => {
+ expect(parseAgyFooterProfile('> just a prompt\nno footer here')).toBeNull()
+ })
+})
+
+describe('agy pane busy/idle', () => {
+ it('reads a real captured pane', () => {
+ const idle = readFileSync(fileURLToPath(new URL('../../lib/__fixtures__/question-agy.txt', import.meta.url)), 'utf8')
+ // The question fixture was captured with a dialog open, so the pane is NOT idle.
+ expect(parseAgyFooterProfile(idle)).not.toBeNull()
+ })
+
+ it('treats "? for shortcuts" as idle and "esc to cancel" as busy', () => {
+ expect(agyPaneIdle('>\n? for shortcuts Gemini 3.7 Flash · high')).toBe(true)
+ expect(agyPaneIdle(' ↑/↓ Navigate\nesc to cancel Gemini 3.7 Flash · high')).toBe(false)
+ expect(agyPaneIdle('nothing familiar here')).toBe(false)
+ })
+})
diff --git a/cli/src/engines/agy/runtimeProfile.ts b/cli/src/engines/agy/runtimeProfile.ts
new file mode 100644
index 000000000..804afc23c
--- /dev/null
+++ b/cli/src/engines/agy/runtimeProfile.ts
@@ -0,0 +1,67 @@
+/**
+ * agy's model/effort surface.
+ *
+ * Two facts settled on the real CLI (1.1.14):
+ * - the idle footer reads `Gemini 3.7 Flash · high` — display name, then the effort word;
+ * - `agy models` prints `<slug>\t<Display Name>` and bakes the effort into most slugs
+ * (`gemini-3.7-flash-high`), the way Cursor does, while ALSO accepting a separate
+ * `--effort low|medium|high`. The slug is what `--model` takes, so the slug is what we report.
+ */
+
+const EFFORTS = new Set(['low', 'medium', 'high'])
+
+/** `agy models` rows: `gemini-3.7-flash-high\tGemini 3.7 Flash (High)`. */
+export function parseAgyModelsOutput(output: string): string[] {
+ const models: string[] = []
+ const seen = new Set<string>()
+ for (const line of output.split('\n')) {
+ // The first line is a progress notice ("Fetching available models..."), which has no tab.
+ const match = /^\s*([A-Za-z0-9][A-Za-z0-9._:@/-]*)\t/.exec(line)
+ const slug = match?.[1]
+ if (!slug || seen.has(slug)) continue
+ seen.add(slug)
+ models.push(slug)
+ }
+ return models
+}
+
+/**
+ * The idle footer, right-aligned on the last pane row: `Gemini 3.7 Flash · high`.
+ *
+ * Reported as the slug rather than the display name so the chip matches what `agy models` and
+ * `--model` speak: `Gemini 3.7 Flash` + `high` is `gemini-3.7-flash-high`. Where the catalog has no
+ * effort-suffixed slug (Claude models on agy do not), the base slug is still correct.
+ */
+export function parseAgyFooterProfile(capture: string): { model: string; effort: string } | null {
+ const lines = capture.replace(/\u001b\[[0-9;:]*[A-Za-z]/g, '').split('\n')
+ for (let i = lines.length - 1; i >= 0; i--) {
+ // The footer is right-aligned, so the pane row carries unrelated status text on the left ("esc to
+ // cancel", "? for shortcuts"). Anchor on the run of whitespace that separates them, or the model
+ // name swallows whatever the CLI happened to print beside it.
+ const match = /(?:^|\s{2,})([A-Za-z][A-Za-z0-9.]*(?: [A-Za-z0-9.]+)*)\s+[·|]\s+(low|medium|high)\s*$/.exec(lines[i].trimEnd())
+ if (!match) continue
+ const effort = match[2].toLowerCase()
+ if (!EFFORTS.has(effort)) continue
+ const base = match[1].trim().toLowerCase().replace(/\s+/g, '-')
+ if (!base || base.length < 3) continue
+ return { model: `${base}-${effort}`, effort }
+ }
+ return null
+}
+
+/**
+ * Is the pane sitting idle?
+ *
+ * agy's transcript carries no end-of-turn marker at all - the `Stop` hook is the only one - so after a
+ * daemon restart a folded history leaves the turn open forever, and the device tile spins with nothing
+ * left to close it (measured: `turn_heartbeat` every second, indefinitely).
+ *
+ * The pane does know. Its bottom row reads `? for shortcuts` when the composer is free and
+ * `esc to cancel` while a turn, a question or a permission prompt is live. Checked only at attach; the
+ * live lifecycle stays on USER_INPUT -> Stop.
+ */
+export function agyPaneIdle(capture: string): boolean {
+ const tail = capture.replace(/\u001b\[[0-9;:]*[A-Za-z]/g, '').split('\n').filter((line) => line.trim()).slice(-4).join('\n')
+ if (/esc to cancel/i.test(tail)) return false
+ return /\?\s*for shortcuts/i.test(tail)
+}
diff --git a/cli/src/engines/agy/session.ts b/cli/src/engines/agy/session.ts
new file mode 100644
index 000000000..45e45642a
--- /dev/null
+++ b/cli/src/engines/agy/session.ts
@@ -0,0 +1,105 @@
+import { execFile } from 'child_process'
+import { readdir, readlink, stat } from 'fs/promises'
+import { basename, join, sep } from 'path'
+import { promisify } from 'util'
+
+const execFileAsync = promisify(execFile)
+
+const CONVERSATION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
+
+/** `<AGY_HOME>/brain/<conversationId>/.system_generated/logs/transcript_full.jsonl`. */
+export function agyTranscriptPath(agyHome: string, conversationId: string): string | null {
+ if (!CONVERSATION_ID.test(conversationId)) return null
+ return join(agyHome, 'brain', conversationId, '.system_generated', 'logs', 'transcript_full.jsonl')
+}
+
+async function isFile(path: string): Promise<boolean> {
+ try { return (await stat(path)).isFile() } catch { return false }
+}
+
+/**
+ * Resolve a live agy transcript.
+ *
+ * The hook payload names this exact path, so this is the fallback for a session discovered without
+ * one. The `_full` file is the one to tail — see the normalizer header for why.
+ */
+export async function findAgyTranscript(agyHome: string, conversationId: string): Promise<string | null> {
+ const path = agyTranscriptPath(agyHome, conversationId)
+ return path && await isFile(path) ? path : null
+}
+
+export interface AgyConversation {
+ conversationId: string
+ transcriptPath: string
+ /** Last write to the transcript — the only ordering signal agy leaves for the CLI. */
+ mtimeMs: number
+ birthMs: number
+}
+
+/**
+ * Every conversation with a transcript on disk, newest write first.
+ *
+ * agy's `conversation_summaries.db` looks like the index for this and is NOT one: measured on 1.1.14
+ * it holds only IDE (`app_data_dir='antigravity'`) rows, and CLI conversations never appear in it.
+ * The brain directory is the authority.
+ */
+export async function listAgyConversations(agyHome: string): Promise<AgyConversation[]> {
+ const root = join(agyHome, 'brain')
+ const entries = await readdir(root, { withFileTypes: true }).catch(() => [])
+ const found: AgyConversation[] = []
+ for (const entry of entries) {
+ if (!entry.isDirectory() || !CONVERSATION_ID.test(entry.name)) continue
+ const transcriptPath = join(root, entry.name, '.system_generated', 'logs', 'transcript_full.jsonl')
+ const info = await stat(transcriptPath).catch(() => null)
+ if (!info?.isFile()) continue
+ found.push({
+ conversationId: entry.name,
+ transcriptPath,
+ mtimeMs: info.mtimeMs,
+ birthMs: info.birthtimeMs || info.ctimeMs,
+ })
+ }
+ return found.sort((a, b) => b.mtimeMs - a.mtimeMs)
+}
+
+/**
+ * The conversation a live `agy` process is holding, read from the lock it keeps open.
+ *
+ * agy flocks `<AGY_HOME>/presence/<conversationId>.lock` for the life of a conversation and holds the
+ * descriptor open (measured: pid 91701 ↔ `ae51057a…`). That makes it the one pid→conversation map the
+ * CLI leaves behind, and it doubles as a liveness test — a stale lock file has no holder.
+ *
+ * It is the only route available to process-repair: agy's transcript records no cwd, its directory is
+ * named by the conversation id, and `ANTIGRAVITY_CONVERSATION_ID` is exported to hook children but not
+ * into agy's own environment, so neither the file nor `/proc/<pid>/environ` can answer this.
+ */
+export async function agyConversationForPid(agyHome: string, pid: number): Promise<string | null> {
+ const marker = join(agyHome, 'presence') + sep
+ const paths = process.platform === 'linux' ? await linuxFdTargets(pid) : await lsofTargets(pid)
+ for (const path of paths) {
+ if (!path.startsWith(marker) || !path.endsWith('.lock')) continue
+ const id = basename(path, '.lock')
+ if (CONVERSATION_ID.test(id)) return id
+ }
+ return null
+}
+
+async function linuxFdTargets(pid: number): Promise<string[]> {
+ const dir = `/proc/${pid}/fd`
+ const entries = await readdir(dir).catch(() => [])
+ const targets: string[] = []
+ for (const entry of entries) {
+ const target = await readlink(join(dir, entry)).catch(() => '')
+ if (target) targets.push(target)
+ }
+ return targets
+}
+
+async function lsofTargets(pid: number): Promise<string[]> {
+ // -Fn prints one `n<path>` record per descriptor and nothing else; -w silences the warnings lsof
+ // emits for file systems it cannot stat, which would otherwise land on stderr on every poll.
+ const out = await execFileAsync('lsof', ['-w', '-p', String(pid), '-Fn'], { timeout: 4_000 })
+ .then((r) => r.stdout)
+ .catch((err: { stdout?: string }) => err.stdout ?? '')
+ return out.split('\n').filter((line) => line.startsWith('n')).map((line) => line.slice(1))
+}
diff --git a/cli/src/engines/types.ts b/cli/src/engines/types.ts
index 90679d274..77ba079ba 100644
--- a/cli/src/engines/types.ts
+++ b/cli/src/engines/types.ts
@@ -10,7 +10,7 @@ import type { RegisteredSession } from '../lib/registry.js'
*/
export const ENGINES = [
'claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes',
- 'commandcode', 'devin', 'muse', 'amp', 'kilo', 'grok',
+ 'commandcode', 'devin', 'muse', 'amp', 'kilo', 'grok', 'agy',
] as const
export type AgentEngine = (typeof ENGINES)[number]
diff --git a/cli/src/lib/__fixtures__/agy-session.jsonl b/cli/src/lib/__fixtures__/agy-session.jsonl
new file mode 100644
index 000000000..3c92b55a2
--- /dev/null
+++ b/cli/src/lib/__fixtures__/agy-session.jsonl
@@ -0,0 +1,28 @@
+{"step_index": 0, "source": "USER_EXPLICIT", "type": "USER_INPUT", "status": "DONE", "created_at": "2026-08-18T09:43:26Z", "content": "<USER_REQUEST>\nMake a todo list of 3 items for tidying this folder, then run pwd, then list the files. Do it, do not just describe it.\n</USER_REQUEST>\n<ADDITIONAL_METADATA>\nThe current local time is: 2026-08-18T16:43:26+07:00.\n</ADDITIONAL_METADATA>\n<USER_SETTINGS_CHANGE>\nThe user changed setting `Model Selection` from None to Gemini 3.7 Flash (High). No need to comment on this change if the user doesn't ask about it. If reporting what model you are, please use a human readable name instead of the exact string.\n</USER_SETTINGS_CHANGE>"}
+{"step_index": 1, "source": "SYSTEM", "type": "CONVERSATION_HISTORY", "status": "DONE", "created_at": "2026-08-18T09:43:26Z"}
+{"step_index": 2, "source": "MODEL", "type": "PLANNER_RESPONSE", "status": "DONE", "created_at": "2026-08-18T09:43:26Z", "tool_calls": [{"name": "run_command", "args": {"CommandLine": "pwd", "Cwd": "/Users/dev/Work/tmp", "WaitMsBeforeAsync": 5000, "toolAction": "Running pwd", "toolSummary": "Run pwd"}}]}
+{"step_index": 3, "source": "MODEL", "type": "RUN_COMMAND", "status": "DONE", "exit_code": 0, "created_at": "2026-08-18T09:43:28Z", "content": "Created At: 2026-08-18T16:43:28+07:00\nCompleted At: 2026-08-18T16:43:28+07:00\n\nThe command exited with code 0.\nOutput:\n/Users/dev/Work/tmp\n\n"}
+{"step_index": 4, "source": "SYSTEM", "type": "CHECKPOINT", "status": "DONE", "created_at": "2026-08-18T09:43:28Z", "content": "{{ CHECKPOINT 0 }}\n **The earlier parts of this conversation have been truncated due to its long length. The following content summarizes the truncated context so that you may continue your work. **\n\n\n# USER Objective:\nFolder Cleanup Task Execution\n\n# User Requests\nThe following were user requests from the truncated conversation in chronological order:\n1. Make a todo list of 3 items for tidying this folder, then run pwd, then list the files. Do it, do not just describe it.\n\n# Conversation Logs\n\nReference the following log files for the full, untruncated conversation:\n\n- /Users/dev/.gemini/antigravity-cli/brain/8c92ceb6-49c9-4e08-868b-41ae7ddac75a/.system_generated/logs/transcript.jsonl\n\n**IMPORTANT: this summary is just for your reference. You may respond to my previous and future messages, but DO NOT ACKNOWLEDGE THIS CHECKPOINT MESSAGE. JUST READ IT BUT DO NOT MENTION IT, RESPOND TO IT, OR TAKE ACTION BECAUSE OF IT.**"}
+{"step_index": 5, "source": "MODEL", "type": "PLANNER_RESPONSE", "status": "DONE", "created_at": "2026-08-18T09:43:28Z", "tool_calls": [{"name": "run_command", "args": {"CommandLine": "ls -la", "Cwd": "/Users/dev/Work/tmp", "WaitMsBeforeAsync": 5000, "toolAction": "Listing files", "toolSummary": "List files"}}]}
+{"step_index": 6, "source": "MODEL", "type": "RUN_COMMAND", "status": "DONE", "exit_code": 0, "created_at": "2026-08-18T09:43:30Z", "content": "Created At: 2026-08-18T16:43:30+07:00\nCompleted At: 2026-08-18T16:43:30+07:00\n\nThe command exited with code 0.\nOutput:\ntotal 0\ndrwxr-xr-x 2 dev staff 64 Aug 14 13:22 .\ndrwxr-xr-x 140 dev staff 4480 Aug 14 13:22 ..\n\n"}
+{"step_index": 7, "source": "MODEL", "type": "PLANNER_RESPONSE", "status": "DONE", "created_at": "2026-08-18T09:43:30Z", "tool_calls": [{"name": "list_dir", "args": {"DirectoryPath": "/Users/dev/Work/tmp", "toolAction": "Listing directory contents", "toolSummary": "List directory"}}]}
+{"step_index": 8, "source": "MODEL", "type": "LIST_DIRECTORY", "status": "DONE", "created_at": "2026-08-18T09:43:32Z", "content": "Created At: 2026-08-18T16:43:32+07:00\nCompleted At: 2026-08-18T16:43:32+07:00\nEmpty directory"}
+{"step_index": 9, "source": "MODEL", "type": "PLANNER_RESPONSE", "status": "DONE", "created_at": "2026-08-18T09:43:32Z", "content": "### Todo List for Tidying `/Users/dev/Work/tmp`\n- [ ] **Audit & Archive**: Review any leftover temporary files or caches and remove obsolete artifacts.\n- [ ] **Structure & Categorize**: Create dedicated subdirectories for incoming temporary work (e.g., `scratch/`, `experiments/`, `builds/`).\n- [ ] **Set Cleanup Policy**: Establish an automated cleanup routine or rule to periodically purge outdated files.\n\n---\n\n### Command Executions\n\n#### 1. `pwd`\n```\n/Users/dev/Work/tmp\n```\n\n#### 2. `ls -la`\n```\ntotal 0\ndrwxr-xr-x 2 dev staff 64 Aug 14 13:22 .\ndrwxr-xr-x 140 dev staff 4480 Aug 14 13:22 ..\n```\n*(Directory [tmp](file:///Users/dev/Work/tmp) is currently clean and empty).*"}
+{"step_index": 10, "source": "USER_EXPLICIT", "type": "USER_INPUT", "status": "DONE", "created_at": "2026-08-18T09:45:04Z", "content": "<USER_REQUEST>\nNow just reply with the single word DONE.\n</USER_REQUEST>\n<ADDITIONAL_METADATA>\nThe current local time is: 2026-08-18T16:45:04+07:00.\n</ADDITIONAL_METADATA>"}
+{"step_index": 11, "source": "MODEL", "type": "PLANNER_RESPONSE", "status": "DONE", "created_at": "2026-08-18T09:45:04Z", "content": "DONE"}
+{"step_index": 12, "source": "USER_EXPLICIT", "type": "USER_INPUT", "status": "DONE", "created_at": "2026-08-18T09:45:57Z", "content": "<USER_REQUEST>\nUse your ask question tool to ask me which colour I prefer, with the options red, green and blue. Ask, do not assume.\n</USER_REQUEST>\n<ADDITIONAL_METADATA>\nThe current local time is: 2026-08-18T16:45:57+07:00.\n</ADDITIONAL_METADATA>"}
+{"step_index": 13, "source": "MODEL", "type": "PLANNER_RESPONSE", "status": "DONE", "created_at": "2026-08-18T09:45:57Z", "tool_calls": [{"name": "ask_question", "args": {"questions": [{"is_multi_select": false, "options": ["Red", "Green", "Blue"], "question": "Which colour do you prefer?"}], "toolAction": "Asking color preference", "toolSummary": "Color preference question"}}]}
+{"step_index": 14, "source": "MODEL", "type": "ASK_QUESTION", "status": "DONE", "created_at": "2026-08-18T09:46:19Z", "content": "Created At: 2026-08-18T16:46:19+07:00\nCompleted At: 2026-08-18T16:46:48+07:00\nA1: Blue"}
+{"step_index": 15, "source": "MODEL", "type": "PLANNER_RESPONSE", "status": "DONE", "created_at": "2026-08-18T09:46:48Z", "content": "You selected **Blue**."}
+{"step_index": 16, "source": "MODEL", "type": "PLANNER_RESPONSE", "status": "DONE", "created_at": "2026-08-18T09:41:29Z", "tool_calls": [{"name": "run_command", "args": {"CommandLine": "pwd", "Cwd": "/Users/dev/Work/tmp", "WaitMsBeforeAsync": 5000, "toolAction": "Running pwd command", "toolSummary": "Run pwd"}}]}
+{"step_index": 17, "source": "MODEL", "type": "ERROR_MESSAGE", "status": "DONE", "created_at": "2026-08-18T09:41:32Z", "content": "Created At: 2026-08-18T16:41:32+07:00\nCompleted At: 2026-08-18T16:41:32+07:00\nError invalid tool call: model output error: invalid tool call error (invalid_args) tool call denied with reason: "}
+{"step_index": 18, "source": "USER_EXPLICIT", "type": "USER_INPUT", "status": "DONE", "created_at": "2026-08-18T10:52:02Z", "content": "<USER_REQUEST>\nRun three sub-agents in parallel (launching all three simultaneously), with each agent performing an independent task and reporting back: Agent 1: Report BTC price, Agent 2: Report ETH price,,Agent 3: Report BNB price\n</USER_REQUEST>\n<ADDITIONAL_METADATA>\nThe current local time is: 2026-08-18T17:52:02+07:00.\n</ADDITIONAL_METADATA>"}
+{"step_index": 19, "source": "MODEL", "type": "PLANNER_RESPONSE", "status": "DONE", "created_at": "2026-08-18T10:52:03Z", "thinking": "**Initiating Parallel Agents**\n\nI'm now focusing on launching three sub-agents in parallel. My plan involves invoking these agents simultaneously: one to report the Bitcoin price, ", "tool_calls": [{"name": "invoke_subagent", "args": {"Subagents": [{"Model": "flash", "Prompt": "Search the web for the current Bitcoin (BTC) price in USD and report back the latest price.", "Role": "BTC Price Reporter", "TypeName": "research"}, {"Model": "flash", "Prompt": "Search the web for the current Ethereum (ETH) price in USD and report back the latest price.", "Role": "ETH Price Reporter", "TypeName": "research"}, {"Model": "flash", "Prompt": "Search the web for the current Binance Coin (BNB) price in USD and report back the latest price.", "Role": "BNB Price Reporter", "TypeName": "research"}], "toolAction": "Launching 3 sub-agents to fetch crypto prices", "toolSummary": "Sub-agent invocation"}}]}
+{"step_index": 20, "source": "MODEL", "type": "INVOKE_SUBAGENT", "status": "DONE", "created_at": "2026-08-18T10:52:06Z", "content": "Created At: 2026-08-18T17:52:06+07:00\nCompleted At: 2026-08-18T17:52:06+07:00\nCreated the following subagents:\n{\n \"conversationId\": \"477d6fe5-adf9-44b4-9388-14a8aea07fe7\",\n \"logAbsoluteUri\": \"file:///Users/dev/.gemini/antigravity-cli/brain/477d6fe5-adf9-44b4-9388-14a8aea07fe7/.system_generated/logs/transcript.jsonl\",\n \"workspaceUris\": [\n \"file:///Users/dev/Work/tmp\"\n ]\n}\n{\n \"conversationId\": \"370a6593-c986-4d83-aa58-963937d78396\",\n \"logAbsoluteUri\": \"file:///Users/dev/.gemini/antigravity-cli/brain/370a6593-c986-4d83-aa58-963937d78396/.system_generated/logs/transcript.jsonl\",\n \"workspaceUris\": [\n \"file:///Users/dev/Work/tmp\"\n ]\n}\n{\n \"conversationId\": \"8bf2b1a6-a22e-4af9-ae5d-0af8c209b296\",\n \"logAbsoluteUri\": \"file:///Users/dev/.gemini/antigravity-cli/brain/8bf2b1a6-a22e-4af9-ae5d-0af8c209b296/.system_generated/logs/transcript.jsonl\",\n \"workspaceUris\": [\n \"file:///Users/dev/Work/tmp\"\n ]\n}\nThe subagents will send you a message when they have completed their task or require guidance. There is no need to poll for their responses."}
+{"step_index": 21, "source": "MODEL", "type": "PLANNER_RESPONSE", "status": "DONE", "created_at": "2026-08-18T10:52:07Z", "content": "I have launched all three sub-agents in parallel:\n\n1. **BTC Price Reporter** (`477d6fe5-adf9-44b4-9388-14a8aea07fe7`): Fetching Bitcoin (BTC) price.\n2. **ETH Price Reporter** (`370a6593-c986-4d83-aa58-963937d78396`): Fetching Ethereum (ETH) price.\n3. **BNB Price Reporter** (`8bf2b1a6-a22e-4af9-ae5d-0af8c209b296`): Fetching Binance Coin (BNB) price.\n\nI will compile and present their reports as soon as they complete."}
+{"step_index": 22, "source": "SYSTEM", "type": "SYSTEM_MESSAGE", "status": "DONE", "created_at": "2026-08-18T10:52:16Z", "content": "The following is a <SYSTEM_MESSAGE> not actually sent by the user. It is provided by the system as important information to pay attention to.\n\n<SYSTEM_MESSAGE>\n[Message] timestamp=2026-08-18T10:52:15Z sender=477d6fe5-adf9-44b4-9388-14a8aea07fe7 priority=MESSAGE_PRIORITY_HIGH content=Based on the latest web search results, the current price of Bitcoin (BTC) is approximately **$64,100 – $64,300 USD** (varying slightly depending on the exchange, e.g., CoinMarketCap, TradingView, Kraken).\n</SYSTEM_MESSAGE>"}
+{"step_index": 23, "source": "MODEL", "type": "PLANNER_RESPONSE", "status": "DONE", "created_at": "2026-08-18T10:52:16Z", "content": "Agent 1 has reported back. Waiting for Agent 2 (ETH) and Agent 3 (BNB) to finish..."}
+{"step_index": 24, "source": "SYSTEM", "type": "SYSTEM_MESSAGE", "status": "DONE", "created_at": "2026-08-18T10:52:19Z", "content": "The following is a <SYSTEM_MESSAGE> not actually sent by the user. It is provided by the system as important information to pay attention to.\n\n<SYSTEM_MESSAGE>\n[Message] timestamp=2026-08-18T10:52:18Z sender=370a6593-c986-4d83-aa58-963937d78396 priority=MESSAGE_PRIORITY_HIGH content=Here is the latest Ethereum (ETH) price information:\n\n- **Current Price:** Approximately **$1,896 USD** (trading in the range of ~$1,895 – $1,900 USD)\n- **Market Cap:** ~$228 Billion USD\n- **Circulating Supply:** ~120.6 Million ETH\n\n*Sources: CoinMarketCap, CoinGecko, Coinbase, Kraken (as of August 18, 2026).*\n</SYSTEM_MESSAGE>"}
+{"step_index": 25, "source": "MODEL", "type": "PLANNER_RESPONSE", "status": "DONE", "created_at": "2026-08-18T10:52:19Z", "content": "Agent 2 has reported back. Waiting for Agent 3 (BNB) to finish..."}
+{"step_index": 26, "source": "SYSTEM", "type": "SYSTEM_MESSAGE", "status": "DONE", "created_at": "2026-08-18T10:52:21Z", "content": "The following is a <SYSTEM_MESSAGE> not actually sent by the user. It is provided by the system as important information to pay attention to.\n\n<SYSTEM_MESSAGE>\n[Message] timestamp=2026-08-18T10:52:21Z sender=8bf2b1a6-a22e-4af9-ae5d-0af8c209b296 priority=MESSAGE_PRIORITY_HIGH content=Here is the current market data for Binance Coin (BNB):\n\n- **Current Price:** Approximately **$603.00 USD**\n- **24-Hour Trading Range:** ~$599 – $605 USD\n- **Market Cap:** ~$80 Billion USD\n\nData aggregated across major exchanges and tracking platforms (Binance, CoinMarketCap, Kraken, TradingView, CoinGecko).\n</SYSTEM_MESSAGE>"}
+{"step_index": 27, "source": "MODEL", "type": "PLANNER_RESPONSE", "status": "DONE", "created_at": "2026-08-18T10:52:21Z", "content": "All three sub-agents have completed their tasks and reported back with the latest market prices:\n\n| Asset | Sub-Agent | Current Price (USD) | Additional Details |\n| :--- | :--- | :--- | :--- |\n| **Bitcoin (BTC)** | [Agent 1](conversation://477d6fe5-adf9-44b4-9388-14a8aea07fe7) | **~$64,100 – $64,300** | Range across major exchanges (CoinMarketCap, TradingView, Kraken) |\n| **Ethereum (ETH)** | [Agent 2](conversation://370a6593-c986-4d83-aa58-963937d78396) | **~$1,896** | 24h range ~$1,895 – $1,900; Market cap ~$228B |\n| **Binance Coin (BNB)** | [Agent 3](conversation://8bf2b1a6-a22e-4af9-ae5d-0af8c209b296) | **~$603.00** | 24h range ~$599 – $605; Market cap ~$80B |"}
diff --git a/cli/src/lib/__fixtures__/permission-agy.txt b/cli/src/lib/__fixtures__/permission-agy.txt
new file mode 100644
index 000000000..1cc1c1d6b
--- /dev/null
+++ b/cli/src/lib/__fixtures__/permission-agy.txt
@@ -0,0 +1,50 @@
+export PATH="$HOME/.local/bin:$PATH"; agy
+dev@MacbookPro tmp % export PATH="$HOME/.local/bin:$PATH"; agy
+
+ ▄▀▀▄ Antigravity CLI 1.1.14
+ ▀▀▀▀▀▀ [[email protected] (Google AI Pro)
+ ▀▀▀▀▀▀▀▀ Gemini 3.7 Flash (High)
+ ▄▀▀ ▀▀▄ ~/Work/tmp
+ ▄▀▀ ▀▀▄
+
+────────────────────────────────────────────────────────────
+> Run the shell command: echo hello-from-agy
+
+● Bash(echo hello-from-agy) (ctrl+o to expand)
+
+Command
+────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+Requesting permission for:
+ echo hello-from-agy
+
+Do you want to proceed?
+> 1. Yes
+ 2. Yes, and always allow in this conversation for commands that start with 'echo'
+ 3. Yes, and always allow for commands that start with 'echo' (Persist to settings.json)
+ 4. No
+
+ ↑/↓ Navigate · tab Amend · ctrl+g edit/expand command
+esc to cancel Gemini 3.7 Flash · high
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/cli/src/lib/__fixtures__/question-agy.txt b/cli/src/lib/__fixtures__/question-agy.txt
new file mode 100644
index 000000000..50d549543
--- /dev/null
+++ b/cli/src/lib/__fixtures__/question-agy.txt
@@ -0,0 +1,50 @@
+
+────────────────────────────────────────────────────────────
+> Make a todo list of 3 items for tidying this folder, then run pwd, then list the files. Do it, do not just describe it.
+
+● Bash(pwd)
+● Bash(ls -la)
+● ListDir(~/Work/tmp) (ctrl+o to expand)
+
+ ### Todo List for Tidying /Users/dev/Work/tmp
+
+ [ ] Audit & Archive: Review any leftover temporary files or caches and remove obsolete artifacts.
+ [ ] Structure & Categorize: Create dedicated subdirectories for incoming temporary work (e.g., scratch/, experiments/, builds/).
+ [ ] Set Cleanup Policy: Establish an automated cleanup routine or rule to periodically purge outdated files.
+ ──────
+ ### Command Executions
+
+ #### 1. pwd
+
+ /Users/dev/Work/tmp
+
+ #### 2. ls -la
+
+ total 0
+ drwxr-xr-x 2 dev staff 64 Aug 14 13:22 .
+ drwxr-xr-x 140 dev staff 4480 Aug 14 13:22 ..
+
+ (Directory tmp is currently clean and empty).
+
+────────────────────────────────────────────────────────────
+> Now just reply with the single word DONE.
+
+ DONE
+
+────────────────────────────────────────────────────────────
+> Use your ask question tool to ask me which colour I prefer, with the options red, green and blue. Ask, do not assume.
+
+? Which colour do you prefer?
+
+Question
+────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+Question 1/1: Which colour do you prefer?
+
+> 1. Red
+ 2. Green
+ 3. Blue
+ 4. Write-in...
+
+ ↑/↓ Navigate · enter Select · esc Skip
+esc to cancel Gemini 3.7 Flash · high
diff --git a/cli/src/lib/analytics/contract.ts b/cli/src/lib/analytics/contract.ts
index db314e6b2..1d6521622 100644
--- a/cli/src/lib/analytics/contract.ts
+++ b/cli/src/lib/analytics/contract.ts
@@ -18,7 +18,7 @@ export const ANALYTICS_SCHEMA_VERSION = 1
export const ENGINES = [
'claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes',
- 'commandcode', 'devin', 'muse', 'amp', 'kilo', 'grok',
+ 'commandcode', 'devin', 'muse', 'amp', 'kilo', 'grok', 'agy',
] as const
export type Engine = (typeof ENGINES)[number]
diff --git a/cli/src/lib/askQuestion.ts b/cli/src/lib/askQuestion.ts
index 18eb62656..27aed5115 100644
--- a/cli/src/lib/askQuestion.ts
+++ b/cli/src/lib/askQuestion.ts
@@ -29,6 +29,7 @@ import { kiloSelectionKeys, parseKiloQuestionPane } from '../engines/kilo/askQue
import { parseCursorPermissionPane } from '../engines/cursor/askQuestion.js'
import { parseDevinPermissionPane, parseDevinQuestionPane } from '../engines/devin/askQuestion.js'
import { parseGrokQuestionPane } from '../engines/grok/askQuestion.js'
+import { parseAgyQuestionPane } from '../engines/agy/askQuestion.js'
/** Device-facing question shape — byte-for-byte the hosted runtime’s `commanderQuestions()` output. */
export interface ShapedQuestion {
@@ -145,6 +146,10 @@ export function parseEngineQuestionPane(engine: AgentEngine, capture: string): P
// it is a fork of opencode that did not keep opencode's dialog.
if (engine === 'kilo') return parseKiloQuestionPane(capture)
if (engine === 'grok') return parseGrokQuestionPane(capture)
+ // agy's ask-the-user dialog anchors on `Question N/M:` under an `↑/↓ Navigate` footer, which the
+ // shared parser cannot see. Its PERMISSION prompt is numbered rows under `Do you want to proceed?`
+ // and the shared parser reads that one exactly, so it falls through.
+ if (engine === 'agy') return parseAgyQuestionPane(capture) ?? parseQuestionPane(capture)
// Hermes and OpenCode paint Claude's dialog inside a box; peel the border and the shared parser fits.
if (engine === 'hermes') return parseQuestionPane(unframe(capture))
if (engine === 'opencode') {
@@ -540,7 +545,7 @@ export interface AskQuestionDeps {
sendText: (terminalTarget: string, text: string) => Promise<boolean>
sendKey: (terminalTarget: string, key: string) => Promise<boolean>
/** Pins one backend locator for the whole multi-step dialog drive. */
- acquireControl?: (sessionId: string) => (() => void) | null
+ acquireControl?: (sessionId: string, opts?: { forAnswer?: boolean }) => (() => void) | null
/** Injected for tests. */
wait?: (ms: number) => Promise<void>
}
@@ -583,9 +588,18 @@ export class AskQuestionController {
console.warn(`[question] no terminal target for ${sessionId.slice(0, 8)} — answer dropped`)
return false
}
- if (this.driving.has(sessionId)) return false
- const release = this.deps.acquireControl?.(terminalTarget)
- if (this.deps.acquireControl && !release) return false
+ if (this.driving.has(sessionId)) {
+ console.warn(`[question] ${sessionId.slice(0, 8)} answer dropped · already driving this dialog`)
+ return false
+ }
+ // `forAnswer`: a dialog is the engine waiting for input mid-turn, so the open turn must not block it.
+ const release = this.deps.acquireControl?.(terminalTarget, { forAnswer: true })
+ // Silence here is the failure mode this whole file exists to prevent: the device sends an answer,
+ // nothing keys it in, and the pane sits on the dialog looking like a hung agent.
+ if (this.deps.acquireControl && !release) {
+ console.warn(`[question] ${sessionId.slice(0, 8)} answer dropped · terminal control unavailable`)
+ return false
+ }
this.driving.add(sessionId)
try {
const ok = await this.drive(terminalTarget, answers, this.deps.getSession(sessionId)?.engine ?? 'claude')
@@ -705,7 +719,7 @@ const POLL_MS = 1500
// cancel` footer, which is the shared parser's anchor exactly (`__fixtures__/permission-codex.txt`), and
// the question it lands on is the command itself. Membership in this set is what starts the poll, so an
// engine belongs here only once something can actually read its pane.
-const QUESTION_ENGINES = new Set<AgentEngine>(['claude', 'commandcode', 'codex', 'cursor', 'devin', 'hermes', 'opencode', 'muse', 'amp', 'kilo', 'grok'])
+const QUESTION_ENGINES = new Set<AgentEngine>(['claude', 'commandcode', 'codex', 'cursor', 'devin', 'hermes', 'opencode', 'muse', 'amp', 'kilo', 'grok', 'agy'])
/** Does this engine ever paint a question dialog? Callers use it to decide whether to watch its pane. */
export function pollsQuestions(engine: AgentEngine): boolean {
diff --git a/cli/src/lib/engineBin.spec.ts b/cli/src/lib/engineBin.spec.ts
index f5a56eb8a..89faceb87 100644
--- a/cli/src/lib/engineBin.spec.ts
+++ b/cli/src/lib/engineBin.spec.ts
@@ -20,7 +20,7 @@ afterEach(() => {
})
describe('canonical engine CLI commands', () => {
- it('keeps the user-facing 12-engine command contract exact and ordered', () => {
+ it('keeps the user-facing 13-engine command contract exact and ordered', () => {
expect(ENGINES.map((engine) => [engine, ENGINE_CLI_COMMANDS[engine]])).toEqual([
['claude', 'claude'],
['codex', 'codex'],
@@ -34,6 +34,7 @@ describe('canonical engine CLI commands', () => {
['amp', 'amp'],
['kilo', 'kilo'],
['grok', 'grok'],
+ ['agy', 'agy'],
])
})
diff --git a/cli/src/lib/engineBin.ts b/cli/src/lib/engineBin.ts
index 4ac66b16f..1030aab56 100644
--- a/cli/src/lib/engineBin.ts
+++ b/cli/src/lib/engineBin.ts
@@ -13,6 +13,7 @@ import type { AgentEngine } from '../engines/types.js'
/** Every engine the adapter can discover and drive. */
export const ENGINES: readonly AgentEngine[] = [
'claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin', 'muse', 'amp', 'kilo', 'grok',
+ 'agy',
] as const
/** Public vendor command shown to users and matched by the real-binary smoke matrix. */
@@ -29,6 +30,7 @@ export const ENGINE_CLI_COMMANDS: Readonly<Record<AgentEngine, string>> = {
amp: 'amp',
kilo: 'kilo',
grok: 'grok',
+ agy: 'agy',
}
export interface ExecutableFileIdentity {
@@ -212,6 +214,7 @@ export function enginePathOverride(engine: AgentEngine): string | undefined {
case 'amp': return env.AMP_PATH
case 'kilo': return env.KILO_PATH
case 'grok': return env.GROK_PATH
+ case 'agy': return env.AGY_PATH
}
}
@@ -231,5 +234,6 @@ export function engineBin(engine: AgentEngine): string {
case 'amp': return env.AMP_PATH || ENGINE_CLI_COMMANDS.amp
case 'kilo': return env.KILO_PATH || ENGINE_CLI_COMMANDS.kilo
case 'grok': return env.GROK_PATH || ENGINE_CLI_COMMANDS.grok
+ case 'agy': return env.AGY_PATH || ENGINE_CLI_COMMANDS.agy
}
}
diff --git a/cli/src/lib/hooks.ts b/cli/src/lib/hooks.ts
index 0822603ef..eae84a72e 100644
--- a/cli/src/lib/hooks.ts
+++ b/cli/src/lib/hooks.ts
@@ -16,6 +16,10 @@ const SETTINGS_PATH = join(homedir(), '.claude', 'settings.json')
const CODEX_HOOKS_PATH = join(process.env.CODEX_HOME || join(homedir(), '.codex'), 'hooks.json')
const GROK_HOOKS_PATH = join(env.GROK_HOME, 'hooks', 'harness.json')
const CURSOR_HOOKS_PATH = join(process.env.CURSOR_HOME || join(homedir(), '.cursor'), 'hooks.json')
+// agy reads hooks from its SHARED customization root (~/.gemini/config), not from its own state dir —
+// the CLI's changelog records the move, "ensuring hooks remain synchronized between the TUI and the
+// backend". Verified live: a hooks.json placed there fires for `agy` in a pane.
+const AGY_HOOKS_PATH = join(env.AGY_CONFIG_DIR, 'hooks.json')
// notify.mjs location depends on the layout (import.meta.url is the REAL executing file at runtime):
// - packaged/bundled: cli.js at ~/.harness/cli/cli.js → notify.mjs is a SIBLING (dist/ bundle too).
@@ -49,7 +53,7 @@ function shellQuote(value: string): string {
return `'${value.replace(/'/g, `'\\''`)}'`
}
-function command(port: number, engine: 'claude' | 'codex' | 'cursor' | 'hermes' | 'commandcode' | 'devin' | 'grok'): string {
+function command(port: number, engine: 'claude' | 'codex' | 'cursor' | 'hermes' | 'commandcode' | 'devin' | 'grok' | 'agy'): string {
return [
'node',
shellQuote(HOOK_SCRIPT),
@@ -62,6 +66,7 @@ function command(port: number, engine: 'claude' | 'codex' | 'cursor' | 'hermes'
'--hermes-home', shellQuote(env.HERMES_HOME),
'--commandcode-home', shellQuote(env.COMMANDCODE_HOME),
'--devin-home', shellQuote(env.DEVIN_HOME),
+ '--agy-home', shellQuote(env.AGY_HOME),
...(engine !== 'claude' ? ['--engine', engine] : []),
].join(' ')
}
@@ -216,6 +221,60 @@ export function installGrokHooks(port: number): void {
}
}
+/**
+ * agy's hook file is a map of NAMED blocks, each holding per-event handler lists — a different shape
+ * from every other engine here, so it gets its own writer rather than reusing `Settings`.
+ *
+ * Only two events are installed, and the omissions are the point:
+ *
+ * - `PreToolUse` and `PostToolUse` are DELIBERATELY absent. `PreToolUse`'s contract makes `decision`
+ * REQUIRED, and a handler that prints anything else — including the `{}` every other hook here
+ * returns — is read as a denial: measured on a real pane as "Tool call denied by pre-tool hook" on
+ * every call of the turn. Tool events come off the transcript anyway, so there is nothing to gain
+ * and a working agent to lose.
+ * - `PostInvocation` fires per model round-trip, not per turn, so it would add noise without adding a
+ * boundary. `PreInvocation` is installed only for its FIRST firing, which announces the session.
+ *
+ * `Stop` is the turn boundary. Its output is safe: `{"decision":"continue"}` would BLOCK the stop, and
+ * notify.mjs never prints that.
+ */
+type AgyHookHandler = { type?: string; command: string; timeout?: number }
+type AgyHookFile = Record<string, { enabled?: boolean } & Record<string, unknown>>
+
+export function installAgyHooks(port: number): void {
+ let file: AgyHookFile = {}
+ if (existsSync(AGY_HOOKS_PATH)) {
+ try {
+ file = JSON.parse(readFileSync(AGY_HOOKS_PATH, 'utf-8')) as AgyHookFile
+ } catch {
+ console.error(`[hooks] agy hooks file is invalid JSON; leaving it unchanged: ${AGY_HOOKS_PATH}`)
+ console.error('[hooks] fix the file, then restart harness join')
+ return
+ }
+ }
+ if (!file || typeof file !== 'object' || Array.isArray(file)) file = {}
+
+ const cmd = command(port, 'agy')
+ const handler = (event: string): AgyHookHandler => ({ type: 'command', command: `${cmd} --agy-event ${event}`, timeout: 10 })
+ const block = { PreInvocation: [handler('PreInvocation')], Stop: [handler('Stop')] }
+
+ const existing = file['harness'] as Record<string, AgyHookHandler[]> | undefined
+ const same = JSON.stringify(existing) === JSON.stringify(block)
+ if (same) {
+ console.log('[hooks] agy lifecycle hooks already installed')
+ return
+ }
+ // Every other named block belongs to the user; only ours is replaced.
+ file['harness'] = block
+ try {
+ writeJsonAtomic(AGY_HOOKS_PATH, file)
+ console.log(`[hooks] installed agy lifecycle hooks → ${AGY_HOOKS_PATH}`)
+ console.log('[hooks] (takes effect on the next agy session start)')
+ } catch (err) {
+ console.error('[hooks] failed to write agy hook file:', err)
+ }
+}
+
interface CursorHook {
command: string
failClosed?: boolean
diff --git a/cli/src/lib/oneshot.ts b/cli/src/lib/oneshot.ts
index 6b3d9030a..e65bafb15 100644
--- a/cli/src/lib/oneshot.ts
+++ b/cli/src/lib/oneshot.ts
@@ -1079,6 +1079,128 @@ export async function runGrokOneShot(opts: OneShotOptions): Promise<OneShotResul
}
}
+/**
+ * The measured Antigravity 1.1.14 headless invocation.
+ *
+ * `-p` takes the prompt on argv, so this cannot be pre-warmed into the worker pool.
+ *
+ * Two deliberate omissions:
+ * - **No scratch data dir.** `ANTIGRAVITY_EXECUTABLE_DATA_DIR` looks like the override and is not one
+ * (measured: the run still wrote to the real `~/.gemini/antigravity-cli`), and a scratch `HOME` DOES
+ * isolate the store but takes the credentials with it — the re-auth prompt makes it unusable for a
+ * background worker. So the run lands in the user's store and is deleted afterwards by id.
+ * - **No workspace.** `-p` opens none, and agy refuses every tool without one ("no active workspace"),
+ * which is exactly the confinement a recap wants: it cannot read or write the user's files at all.
+ */
+export function agyOneShotSpawn(
+ opts: Pick<OneShotOptions, 'prompt' | 'model' | 'effort'>,
+ parentEnv: NodeJS.ProcessEnv = process.env,
+): { args: string[]; env: NodeJS.ProcessEnv } {
+ const args = [
+ '--output-format', 'json',
+ // A recap prompt is user text; without this a leading `/` would be expanded as a slash command.
+ '--disable-slash-commands',
+ ...(opts.model ? ['--model', opts.model] : []),
+ ...(opts.effort ? ['--effort', opts.effort] : []),
+ '-p', opts.prompt,
+ ]
+ const childEnv = scrubTerminalContext({ ...parentEnv })
+ delete childEnv.MACHINE_ID
+ return { args, env: childEnv }
+}
+
+interface AgyOneShotOutput {
+ text: string
+ conversationId: string
+}
+
+/** agy prints one JSON object: `{conversation_id, status, response, duration_seconds, usage}`. */
+export function agyOutputText(stdout: string): AgyOneShotOutput {
+ const raw = stdout.trim()
+ // The id is needed for cleanup even when the envelope does not parse, so read it directly too.
+ const idMatch = /"conversation_id"\s*:\s*"([0-9a-f-]{16,})"/i.exec(raw)
+ const conversationId = idMatch ? idMatch[1] : ''
+ for (const candidate of [raw, ...raw.split('\n').reverse()]) {
+ if (!candidate) continue
+ try {
+ const parsed = JSON.parse(candidate) as { response?: unknown; conversation_id?: unknown }
+ if (typeof parsed.response === 'string') {
+ return { text: parsed.response.trim(), conversationId: typeof parsed.conversation_id === 'string' ? parsed.conversation_id : conversationId }
+ }
+ } catch { /* try the next complete JSON value */ }
+ }
+ return { text: '', conversationId }
+}
+
+/**
+ * Remove the conversation a recap created.
+ *
+ * One `-p` run leaves exactly five artifacts, all named by the conversation id (measured):
+ * `brain/<id>/`, `conversations/<id>.db` plus its `-wal`/`-shm`, and `presence/<id>.lock`. Deleting by
+ * id touches nothing else, so a concurrent interactive agy session is never at risk.
+ */
+async function removeAgyConversation(conversationId: string): Promise<void> {
+ if (!/^[0-9a-f-]{16,}$/i.test(conversationId)) return
+ const targets = [
+ join(env.AGY_HOME, 'brain', conversationId),
+ join(env.AGY_HOME, 'conversations', `${conversationId}.db`),
+ join(env.AGY_HOME, 'conversations', `${conversationId}.db-wal`),
+ join(env.AGY_HOME, 'conversations', `${conversationId}.db-shm`),
+ join(env.AGY_HOME, 'presence', `${conversationId}.lock`),
+ ]
+ for (const target of targets) await rm(target, { recursive: true, force: true }).catch(() => {})
+}
+
+export async function runAgyOneShot(opts: OneShotOptions): Promise<OneShotResult> {
+ if (opts.signal?.aborted) throw Object.assign(new Error('agy one-shot aborted'), { name: 'AbortError' })
+ const { args, env: processEnv } = agyOneShotSpawn(opts)
+ const timeoutMs = opts.timeoutMs ?? 60_000
+ let created = ''
+ try {
+ return await new Promise<OneShotResult>((resolve, reject) => {
+ const child = spawn(env.AGY_PATH || 'agy', args, {
+ cwd: opts.cwd, env: processEnv, detached: true, stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ let stdout = ''
+ let stderr = ''
+ let settled = false
+ const finish = (fn: () => void): void => {
+ if (settled) return
+ settled = true
+ clearTimeout(timer)
+ opts.signal?.removeEventListener('abort', onAbort)
+ fn()
+ }
+ const kill = (): void => killGroup(child)
+ const onAbort = (): void => {
+ created = created || agyOutputText(stdout).conversationId
+ finish(() => reject(Object.assign(new Error('agy one-shot aborted'), { name: 'AbortError' })))
+ kill()
+ }
+ const timer = setTimeout(() => {
+ created = created || agyOutputText(stdout).conversationId
+ finish(() => reject(new Error(`agy one-shot timed out after ${timeoutMs}ms`)))
+ kill()
+ }, timeoutMs)
+ opts.signal?.addEventListener('abort', onAbort)
+ child.stdout?.on('data', (chunk: Buffer) => { stdout += chunk.toString() })
+ child.stderr?.on('data', (chunk: Buffer) => { stderr += chunk.toString() })
+ child.on('error', (err) => finish(() => reject(err)))
+ child.on('close', (code) => {
+ const { text, conversationId } = agyOutputText(stdout)
+ created = conversationId
+ finish(() => {
+ if (!text) reject(new Error(`agy one-shot exited ${code}: ${stderr.slice(0, 500)}`))
+ else resolve({ text, sessionId: null })
+ })
+ })
+ })
+ } finally {
+ // An aborted run may still have created the conversation before it died, so this runs either way.
+ if (created) await removeAgyConversation(created)
+ }
+}
+
function hermesBin(): string {
return env.HERMES_PATH || 'hermes'
}
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index dae287f48..410b4d210 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -37,6 +37,7 @@ import { env } from '../config/env.js'
import { readCodexRolloutMeta, resolveCodexRollout } from '../engines/codex/rollout.js'
import type { AgentEngine } from '../engines/types.js'
import { commandcodeTranscriptPath } from '../engines/commandcode/transcript.js'
+import { agyTranscriptPath } from '../engines/agy/session.js'
import { hardenPrivateStateFileIfPresent, readPrivateStateFile, secureStateDirectory } from './secureState.js'
import { mergeTerminalRuntimes, processIdentityKey, terminalPlacementKey, terminalRouteKey } from './terminalRuntime.js'
import type { HookTerminalHint, ProcessIdentity, TerminalRuntimeRef } from './terminalTypes.js'
@@ -144,6 +145,7 @@ const PANE_RE = /^%\d+$/
const GROK_SESSION_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
const AGENT_ENGINES = new Set<AgentEngine>([
'claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin', 'muse', 'amp', 'kilo', 'grok',
+ 'agy',
])
const LOCK_WAIT_MS = 20
const LOCK_ATTEMPTS = 100
@@ -455,6 +457,8 @@ export function validTranscriptPath(engine: AgentEngine, filePath: string): bool
? join(env.CODEX_HOME, 'sessions')
: engine === 'grok'
? join(env.GROK_HOME, 'sessions')
+ : engine === 'agy'
+ ? join(env.AGY_HOME, 'brain')
: engine === 'cursor'
? join(env.CURSOR_HOME, 'projects')
: engine === 'pi'
@@ -625,7 +629,7 @@ class Registry {
}
let changed = false
for (const raw of Array.isArray(arr) ? arr : []) {
- const engine: AgentEngine = raw?.engine === 'codex' || raw?.engine === 'cursor' || raw?.engine === 'opencode' || raw?.engine === 'pi' || raw?.engine === 'hermes' || raw?.engine === 'commandcode' || raw?.engine === 'devin' || raw?.engine === 'muse' || raw?.engine === 'amp' || raw?.engine === 'kilo' || raw?.engine === 'grok' ? raw.engine : 'claude'
+ const engine: AgentEngine = raw?.engine === 'codex' || raw?.engine === 'cursor' || raw?.engine === 'opencode' || raw?.engine === 'pi' || raw?.engine === 'hermes' || raw?.engine === 'commandcode' || raw?.engine === 'devin' || raw?.engine === 'muse' || raw?.engine === 'amp' || raw?.engine === 'kilo' || raw?.engine === 'grok' || raw?.engine === 'agy' ? raw.engine : 'claude'
const runtimes = normalizedRuntimes(raw?.runtimes, raw?.tmuxPane)
const pane = tmuxProjection(runtimes)
let transcriptPath =
@@ -861,7 +865,7 @@ class Registry {
const sessionId =
input.sessionId || (transcriptPath ? basename(transcriptPath).replace(/\.jsonl$/, '') : '')
const engine: AgentEngine =
- input.engine === 'codex' || input.engine === 'cursor' || input.engine === 'opencode' || input.engine === 'pi' || input.engine === 'hermes' || input.engine === 'commandcode' || input.engine === 'devin' || input.engine === 'muse' || input.engine === 'amp' || input.engine === 'kilo' || input.engine === 'grok' ? input.engine : 'claude'
+ input.engine === 'codex' || input.engine === 'cursor' || input.engine === 'opencode' || input.engine === 'pi' || input.engine === 'hermes' || input.engine === 'commandcode' || input.engine === 'devin' || input.engine === 'muse' || input.engine === 'amp' || input.engine === 'kilo' || input.engine === 'grok' || input.engine === 'agy' ? input.engine : 'claude'
const pane = input.tmuxPane
// Hooks carry process metadata, not ownership. The already-discovered pane+engine process chooses the
// agent; an optional legacy launcherId is intentionally ignored.
@@ -876,7 +880,9 @@ class Registry {
|| !agentId
|| !inputRuntimes.length
|| (engine === 'grok' && !GROK_SESSION_RE.test(sessionId))
- || (engine !== 'cursor' && engine !== 'opencode' && engine !== 'kilo' && engine !== 'pi' && engine !== 'hermes' && engine !== 'commandcode' && engine !== 'devin' && engine !== 'grok' && !transcriptPath)
+ // agy's session id IS its conversation id, and it names the directory the transcript lives in.
+ || (engine === 'agy' && !GROK_SESSION_RE.test(sessionId))
+ || (engine !== 'cursor' && engine !== 'opencode' && engine !== 'kilo' && engine !== 'pi' && engine !== 'hermes' && engine !== 'commandcode' && engine !== 'devin' && engine !== 'grok' && engine !== 'agy' && !transcriptPath)
|| (transcriptPath && !validTranscriptPath(engine, transcriptPath))
) return null
if (engine === 'codex' && transcriptPath && readCodexRolloutMeta(transcriptPath)?.isSubagent) return null
@@ -909,7 +915,11 @@ class Registry {
? commandcodeTranscriptPath(input.cwd ?? existing?.cwd, sessionId)
: !transcriptPath && engine === 'grok' && (input.cwd ?? existing?.cwd)
? join(env.GROK_HOME, 'sessions', encodeURIComponent((input.cwd ?? existing?.cwd)!), sessionId, 'updates.jsonl')
- : null
+ // agy's layout is deterministic from the conversation id alone, and its `PreInvocation` hook can
+ // land before the first line is flushed — derive rather than wait a turn for the path.
+ : !transcriptPath && engine === 'agy'
+ ? agyTranscriptPath(env.AGY_HOME, sessionId)
+ : null
const effectiveTranscriptPath = transcriptPath ?? existing?.transcriptPath ?? derived ?? null
const entry: RegisteredSession = {
schemaVersion: 2,
@@ -919,7 +929,7 @@ class Registry {
boundAt: isNew ? now : existing?.boundAt ?? now,
engine,
transcriptPath: effectiveTranscriptPath,
- projectDir: engine === 'grok'
+ projectDir: engine === 'grok' || engine === 'agy'
? basename(input.cwd ?? existing?.cwd ?? '') || sessionId
: effectiveTranscriptPath
? basename(dirname(effectiveTranscriptPath))
diff --git a/cli/src/lib/runtimeProfile.ts b/cli/src/lib/runtimeProfile.ts
index 4f29a7d00..9b736f211 100644
--- a/cli/src/lib/runtimeProfile.ts
+++ b/cli/src/lib/runtimeProfile.ts
@@ -44,6 +44,7 @@ import {
parsePiModelsOutput,
} from '../engines/pi/runtimeProfile.js'
import { parseGrokFooterProfile } from '../engines/grok/runtimeProfile.js'
+import { parseAgyFooterProfile } from '../engines/agy/runtimeProfile.js'
export interface RuntimeProfile {
id: string
@@ -108,7 +109,7 @@ interface CodexCache {
models?: CodexCacheModel[]
}
-const PROFILE_RE = /^runtime-v1:([^:]+):(claude|codex|cursor|commandcode|pi|devin|opencode|hermes|muse|amp|kilo|grok):([^@]+)@([a-z0-9_-]+)$/i
+const PROFILE_RE = /^runtime-v1:([^:]+):(claude|codex|cursor|commandcode|pi|devin|opencode|hermes|muse|amp|kilo|grok|agy):([^@]+)@([a-z0-9_-]+)$/i
const CODEX_EFFORTS = new Set(['auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'])
const CLAUDE_EFFORTS = new Set(['auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])
const CURSOR_EFFORTS = new Set(['auto', 'none', 'low', 'medium', 'high', 'xhigh', 'max'])
@@ -868,6 +869,15 @@ export class RuntimeProfileManager {
state.effort = footer.effort
state.observedAt = Date.now()
}
+ } else if (session.engine === 'agy') {
+ // agy's transcript never names the model, so the pane footer is the only continuous source; the
+ // hook payload's `modelName` seeds it at session start.
+ const footer = parseAgyFooterProfile(paneText)
+ if (footer) {
+ state.model = footer.model
+ state.effort = footer.effort
+ state.observedAt = Date.now()
+ }
} else {
const header = /(Fable|Opus|Sonnet|Haiku)\s+(\d+(?:\.\d+)*)(\s+\(1M context\))?\s+with\s+(low|medium|high|xhigh|max|ultracode)\s+effort/gi
const matches = [...paneText.matchAll(header)]
diff --git a/cli/src/lib/sessionInput.ts b/cli/src/lib/sessionInput.ts
index a109e7436..ddb16a83f 100644
--- a/cli/src/lib/sessionInput.ts
+++ b/cli/src/lib/sessionInput.ts
@@ -41,6 +41,10 @@ const AMP_SUBMIT_VERIFY_MS = 6_000
// user_message_chunk. The isolated real run took ~4.4s from paste to watcher-visible turn start; 2.5s
// pressed Enter a second time on every fresh agent even though the first submission was accepted.
const GROK_SUBMIT_VERIFY_MS = 6_000
+// agy's first `PreInvocation` is what clears the fingerprint, and it only fires once the model call
+// starts. Measured 3-5s from Enter to the first hook on a warm session; 8s leaves headroom without
+// making a genuinely dropped message wait too long for its error.
+const AGY_SUBMIT_VERIFY_MS = 8_000
const CURSOR_TURN_SETTLE_MS = 750
const SUBMIT_MAX_RETRIES = 2
// Non-cursor engines re-observe the pane (instead of erroring) while an accepted-but-not-yet-started
@@ -132,12 +136,25 @@ export class SessionInputController {
}
/** Reserve this pane for a short native control interaction such as `/model`. */
- acquireControl(sessionId: string): (() => void) | null {
+ /**
+ * Take the terminal for a write that is not a new message.
+ *
+ * `forAnswer` exists because an engine's ask-the-user dialog opens INSIDE its turn — claude, agy and
+ * every other engine with a question tool — so the `turnOpen` guard, which is there to stop an
+ * INJECTED message colliding with a running turn, also blocked the one write that is only ever valid
+ * during a turn. Measured on both claude and agy: the device's answer arrived, was refused here, and
+ * the pane sat on the dialog looking like a hung agent, with nothing logged.
+ *
+ * Every other guard still applies: another writer holding the lock, a submit awaiting confirmation, a
+ * settling turn, or queued messages all still refuse.
+ */
+ acquireControl(sessionId: string, opts?: { forAnswer?: boolean }): (() => void) | null {
const session = this.controlSession(sessionId)
if (!session) return null
const state = this.state(sessionId)
this.dropExpired(sessionId, state)
- if (state.controlLocked || state.turnOpen || state.awaitingFingerprint || state.settling || state.queue.length > 0) return null
+ const turnBlocks = state.turnOpen && !opts?.forAnswer
+ if (state.controlLocked || turnBlocks || state.awaitingFingerprint || state.settling || state.queue.length > 0) return null
state.controlLocked = true
let released = false
return () => {
@@ -313,6 +330,8 @@ export class SessionInputController {
? KILO_SUBMIT_VERIFY_MS
: session.engine === 'grok'
? GROK_SUBMIT_VERIFY_MS
+ : session.engine === 'agy'
+ ? AGY_SUBMIT_VERIFY_MS
: SUBMIT_VERIFY_MS)
}
@@ -339,7 +358,7 @@ export class SessionInputController {
return
}
} else if (session.engine === 'opencode' || session.engine === 'kilo' || session.engine === 'pi' || session.engine === 'hermes' || session.engine === 'muse'
- || session.engine === 'amp' || session.engine === 'grok') {
+ || session.engine === 'amp' || session.engine === 'grok' || session.engine === 'agy') {
// OpenCode has no composer glyph, and the submitted text stays visible in the message area, so a
// pane scrape can't tell "still in the composer" from "already sent". Rely purely on the reader-
// derived turn_started (a new user row in opencode.db) to clear awaitingFingerprint; if it hasn't
diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.ts
index 767a09d07..448012d42 100644
--- a/cli/src/lib/sessionRepair.ts
+++ b/cli/src/lib/sessionRepair.ts
@@ -22,6 +22,7 @@ import { env } from '../config/env.js'
import { museEvent, museWorkspaceRoot } from '../engines/muse/normalizer.js'
import type { AgentEngine } from '../engines/types.js'
import { readCodexRolloutMeta } from '../engines/codex/rollout.js'
+import { agyConversationForPid, findAgyTranscript } from '../engines/agy/session.js'
const execFileAsync = promisify(execFile)
@@ -206,7 +207,7 @@ export async function findLiveSession(
engine: AgentEngine,
cwd: string,
startedAtMs: number,
- opts?: { bornOnly?: boolean },
+ opts?: { bornOnly?: boolean; pid?: number },
): Promise<RepairedSession | null> {
const sinceMs = startedAtMs - START_SLACK_MS
// The DB engines match on a directory STRING, so ask for both spellings of it (see sameDir).
@@ -304,7 +305,26 @@ export async function findLiveSession(
+ ` AND (created_at >= ${Math.trunc(sinceMs / 1000)} OR last_activity_at >= ${Math.trunc(sinceMs / 1000)})`
+ ` ORDER BY last_activity_at DESC LIMIT 2;`,
)
+ case 'agy':
+ // The one engine here that cannot be found by directory. agy's transcript records no cwd, its
+ // brain directory is named by the conversation id, and `conversation_summaries.db` — which looks
+ // like the index for exactly this — holds only IDE rows, never CLI ones (measured on 1.1.14).
+ //
+ // What it does leave is `presence/<conversationId>.lock`, held open by the live process for the
+ // life of the conversation. That is a pid→conversation map and a liveness test in one, so repair
+ // asks the process rather than the directory. Without a pid there is nothing to ask.
+ return opts?.pid ? agySession(opts.pid) : null
default:
return null
}
}
+
+/** The conversation the given `agy` pid is holding, if its transcript exists yet. */
+async function agySession(pid: number): Promise<RepairedSession | null> {
+ const conversationId = await agyConversationForPid(env.AGY_HOME, pid)
+ if (!conversationId) return null
+ const transcriptPath = await findAgyTranscript(env.AGY_HOME, conversationId)
+ // A conversation with no transcript is one agy has opened but not written to; registry derives the
+ // path anyway, so bind it and let the watcher pick the file up when it appears.
+ return { sessionId: conversationId, transcriptPath: transcriptPath ?? undefined }
+}
diff --git a/cli/src/lib/summarize.ts b/cli/src/lib/summarize.ts
index 2a12adbda..1bf467eed 100644
--- a/cli/src/lib/summarize.ts
+++ b/cli/src/lib/summarize.ts
@@ -29,6 +29,7 @@ import {
runMuseOneShot,
runAmpOneShot,
runGrokOneShot,
+ runAgyOneShot,
setOneShotPoolActiveCounts,
setOneShotPoolDeviceConnected,
shutdownOneShotPool,
@@ -63,7 +64,7 @@ export function syncSummaryPoolSessions(sessions: Array<{ engine: AgentEngine }>
// Hermes, Devin, Muse and Amp take their recap prompt as argv (`muse exec <prompt>`, `amp -x <prompt>`),
// so they cannot be pre-warmed the way a stdin-fed CLI can — no pooled worker for them.
if (session.engine === 'hermes' || session.engine === 'devin' || session.engine === 'muse'
- || session.engine === 'amp' || session.engine === 'grok') continue
+ || session.engine === 'amp' || session.engine === 'grok' || session.engine === 'agy') continue
counts[session.engine]++
}
setOneShotPoolActiveCounts(counts)
@@ -324,6 +325,8 @@ export async function summarizeTurnText(
? env.KILO_SUMMARY_MODEL
: engine === 'grok'
? env.GROK_SUMMARY_MODEL
+ : engine === 'agy'
+ ? env.AGY_SUMMARY_MODEL
: env.OPENCODE_SUMMARY_MODEL
const effort = engine === 'cursor' ? 'model-defined' : env.SUMMARY_EFFORT
console.log(
@@ -353,6 +356,8 @@ export async function summarizeTurnText(
? runKiloOneShot
: engine === 'grok'
? runGrokOneShot
+ : engine === 'agy'
+ ? runAgyOneShot
: runOpencodeOneShot
// One shape for both paths so the language-drift retry and the two-part capping below stay single-source.
const run: (options: OneShotOptions) => Promise<{ text: string; sessionId: string | null }> = gatewayKey
diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.ts
index 24b3f0569..fdca707f5 100644
--- a/cli/src/lib/tmux.ts
+++ b/cli/src/lib/tmux.ts
@@ -316,6 +316,15 @@ export function engineProcessMatchScore(
if (agentAliasOwner([row.imageFileKey, row.entrypointFileKey], ownership) === 'grok') return 4
return /\.grok[\/\\]bin[\/\\]grok$/.test(entrypoint) ? 2 : 0
}
+ if (engine === 'agy') {
+ // Two binaries answer to `agy` on a machine with Antigravity installed: the CLI at
+ // ~/.local/bin/agy (a single 177MB Go binary that does NOT re-exec — the pane process stays `agy`)
+ // and ~/.antigravity/antigravity/bin/agy, a symlink into the IDE's app bundle. The IDE one is not
+ // an engine, so an entrypoint inside a `.app` is rejected rather than scored.
+ if (/\.app[\/\\]Contents[\/\\]/.test(entrypoint)) return 0
+ if (executable === 'agy' || entrybase === 'agy') return 3
+ return /[\/\\]\.local[\/\\]bin[\/\\]agy$/.test(entrypoint) ? 2 : 0
+ }
if (executable === 'claude' || entrybase === 'claude') return 3
return /@anthropic-ai[\/\\]claude-code[\/\\]cli\.js$/.test(entrypoint) ? 2 : 0
}
@@ -394,6 +403,9 @@ const RESUME_ARGS: Partial<Record<RegisteredSession['engine'], { flags: string[]
amp: { flags: ['continue', '-c'], id: /^T-[0-9a-f-]{16,}$/i },
// Grok 1.0.0 accepts both spellings and persists UUID session ids below ~/.grok/sessions.
grok: { flags: ['--resume', '-r'], id: /^[0-9a-f-]{16,}$/i },
+ // `agy --conversation <uuid>` resumes by conversation id; `-c`/`--continue` names nothing and falls
+ // through to the presence-lock lookup in sessionRepair.
+ agy: { flags: ['--conversation'], id: /^[0-9a-f-]{16,}$/i },
}
/** The session id an engine was told to resume, or null when argv does not name one. */