Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(agents): install the Antigravity hook as a safe synchronous gate
Fabricio Casali9c1b24be8281
diff --git a/src/core/agents/hooks/antigravity-autorun.test.ts b/src/core/agents/hooks/antigravity-autorun.test.tsnew file mode 100644index 000000000..18c8504ac--- /dev/null+++ b/src/core/agents/hooks/antigravity-autorun.test.ts@@ -0,0 +1,466 @@+// The Antigravity installer refuses a machine where cmd.exe runs an+// AutoRun command, and refuses when it cannot tell.+//+// The registry is NEVER written here. The reader is exercised over a fake `reg query` that answers+// the way reg.exe does (exit 0 + listing, or exit 1 with a localized message that we must not+// parse), and the real reader is only ever READ from, on Windows, to prove it answers.+import { afterAll, describe, expect, it, vi } from 'vitest'+import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import {+ CMD_AUTORUN_KEYS,+ checkCmdAutoRun,+ listingHasSubkey,+ parseAutoRunValue,+ readCmdAutoRun,+ makeRegQuery,+ type ExecFile,+ type CmdAutoRunCheck,+ type RegQuery+} from './antigravity-autorun'+import { ANTIGRAVITY_BUNDLE_KEY, installAntigravityHooks, removeAntigravityHooks } from './antigravity'++const [HKCU, HKLM, WOW] = CMD_AUTORUN_KEYS+// Every install here happens on a machine that HAS agy (the no-agy refusal is tested in antigravity.test.ts).+const HAS_AGY = (): string => 'C:/fake/agy.exe'++const listing = (key: string, values: string[] = [], subkeys: string[] = []): string =>+ ['', key, ...values.map((v) => ` ${v}`), '', ...subkeys.map((s) => `${key}\\${s}`), ''].join('\r\n')++/** A fake registry: `keys` maps a key to its listing; anything else answers like a missing key. */+const fakeReg = (keys: Record<string, string>, calls: string[] = []): RegQuery => {+ return (key) => {+ calls.push(key)+ const hit = Object.entries(keys).find(([k]) => k.toLowerCase() === key.toLowerCase())+ return hit+ ? { status: 0, stdout: hit[1] }+ : { status: 1, stdout: '' } // reg's own message goes to stderr, localized — never read+ }+}++/** The parents every lookup may climb to, all listable, with the usual children. */+const PARENTS: Record<string, string> = {+ HKEY_CURRENT_USER: listing('HKEY_CURRENT_USER', [], ['Software']),+ 'HKEY_CURRENT_USER\\Software': listing('HKEY_CURRENT_USER\\Software', [], ['Microsoft']),+ 'HKEY_CURRENT_USER\\Software\\Microsoft': listing('HKEY_CURRENT_USER\\Software\\Microsoft', [], ['Windows']),+ HKEY_LOCAL_MACHINE: listing('HKEY_LOCAL_MACHINE', [], ['SOFTWARE']),+ 'HKEY_LOCAL_MACHINE\\Software': listing('HKEY_LOCAL_MACHINE\\Software', [], ['Microsoft', 'WOW6432Node']),+ 'HKEY_LOCAL_MACHINE\\Software\\Microsoft': listing('HKEY_LOCAL_MACHINE\\Software\\Microsoft', [], ['Command Processor']),+ 'HKEY_LOCAL_MACHINE\\Software\\WOW6432Node\\Microsoft': listing(+ 'HKEY_LOCAL_MACHINE\\Software\\WOW6432Node\\Microsoft',+ [],+ ['Command Processor']+ )+}+const CP_PLAIN = ['CompletionChar REG_DWORD 0x9', 'EnableExtensions REG_DWORD 0x1']++describe('parsing', () => {+ it('reads an AutoRun value, any case, SZ or EXPAND_SZ', () => {+ expect(parseAutoRunValue(listing(HKCU, [...CP_PLAIN, 'AutoRun REG_SZ echo hi']))).toBe('echo hi')+ expect(parseAutoRunValue(listing(HKCU, ['autorun REG_EXPAND_SZ %USERPROFILE%\\x.cmd']))).toBe(+ '%USERPROFILE%\\x.cmd'+ )+ })++ it('an absent or empty AutoRun is no AutoRun', () => {+ expect(parseAutoRunValue(listing(HKLM, CP_PLAIN))).toBeUndefined()+ expect(parseAutoRunValue(listing(HKLM, ['AutoRun REG_SZ ']))).toBeUndefined()+ expect(parseAutoRunValue(listing(HKLM, ['AutoRun REG_SZ']))).toBeUndefined()+ // A value whose NAME merely contains the word is not it.+ expect(parseAutoRunValue(listing(HKLM, ['AutoRunDisabled REG_SZ x']))).toBeUndefined()+ })++ it('finds a subkey line in a parent listing, any case, exact only', () => {+ const l = listing('HKEY_LOCAL_MACHINE\\Software', [], ['WOW6432Node', 'Microsoft'])+ expect(listingHasSubkey(l, 'hkey_local_machine\\software\\wow6432node')).toBe(true)+ expect(listingHasSubkey(l, 'HKEY_LOCAL_MACHINE\\Software\\WOW6432')).toBe(false)+ })+})++describe('checkCmdAutoRun over a fake reg', () => {+ const machine = (extra: Record<string, string>): Record<string, string> => ({+ ...PARENTS,+ [HKLM]: listing(HKLM, CP_PLAIN),+ [WOW]: listing(WOW, CP_PLAIN),+ ...extra+ })++ it('clear: HKCU has no Command Processor key (the usual case) and HKLM has no AutoRun', () => {+ expect(checkCmdAutoRun(fakeReg(machine({})))).toEqual({ kind: 'clear' })+ })++ it.each([+ ['HKCU', HKCU],+ ['HKLM', HKLM],+ ['WOW6432Node', WOW]+ ])('set: an AutoRun under %s', (_n, key) => {+ const reg = machine({ [key]: listing(key, [...CP_PLAIN, 'AutoRun REG_SZ @echo off & echo hello']) })+ expect(checkCmdAutoRun(fakeReg(reg))).toEqual({+ kind: 'set',+ entries: [{ key, value: '@echo off & echo hello' }]+ })+ })++ it('clear: an empty AutoRun value', () => {+ const reg = machine({ [HKCU]: listing(HKCU, ['AutoRun REG_SZ ']) })+ expect(checkCmdAutoRun(fakeReg(reg))).toEqual({ kind: 'clear' })+ })++ it('clear: a 32-bit Windows with no WOW6432Node at all (the parent says it is absent)', () => {+ const reg = machine({+ 'HKEY_LOCAL_MACHINE\\Software': listing('HKEY_LOCAL_MACHINE\\Software', [], ['Microsoft'])+ })+ delete reg[WOW]+ delete reg['HKEY_LOCAL_MACHINE\\Software\\WOW6432Node\\Microsoft']+ expect(checkCmdAutoRun(fakeReg(reg))).toEqual({ kind: 'clear' })+ })++ it('UNREADABLE: the key exists (its parent lists it) but cannot be listed', () => {+ const reg = machine({})+ delete reg[HKLM] // listed by its parent, fails itself — e.g. access denied+ const out = checkCmdAutoRun(fakeReg(reg))+ expect(out.kind).toBe('unreadable')+ })++ it('UNREADABLE: nothing can be listed at all (reg missing or blocked)', () => {+ const none: RegQuery = () => ({ status: null, stdout: '' })+ expect(checkCmdAutoRun(none).kind).toBe('unreadable')+ })++ it('UNREADABLE: a reg that throws', () => {+ const boom: RegQuery = () => {+ throw new Error('spawn failed')+ }+ expect(checkCmdAutoRun(boom).kind).toBe('unreadable')+ })++ it('never decides absence from the failing query itself — it asks the parent', () => {+ const calls: string[] = []+ checkCmdAutoRun(fakeReg(machine({}), calls))+ expect(calls).toContain(HKCU)+ expect(calls).toContain('HKEY_CURRENT_USER\\Software\\Microsoft')+ })+})++describe('the installer refuses before writing anything', () => {+ const root = mkdtempSync(join(tmpdir(), 'nt agy autorun '))+ afterAll(() => rmSync(root, { recursive: true, force: true, maxRetries: 8, retryDelay: 250 }))+ let n = 0+ const attempt = (readAutoRun: () => CmdAutoRunCheck, platform = 'win32') => {+ const home = join(root, `h${++n}`, 'John Doe')+ mkdirSync(home, { recursive: true })+ const hooksJson = join(home, '.gemini', 'config', 'hooks.json')+ const script = join(home, '.nodeterm', 'agent-hooks', 'antigravity.sh')+ let consulted = 0+ installAntigravityHooks({ findAgy: HAS_AGY,+ hooksJson,+ platform,+ scriptPath: script,+ readAutoRun: () => {+ consulted+++ return readAutoRun()+ }+ })+ return {+ consulted,+ hooksJson: existsSync(hooksJson),+ script: existsSync(script),+ wrapper: existsSync(join(home, '.nodeterm', 'agent-hooks', 'antigravity-hook.cmd'))+ }+ }++ it('an AutoRun is set → no hooks.json, no script, no wrapper', () => {+ expect(attempt(() => ({ kind: 'set', entries: [{ key: HKCU, value: 'echo hi' }] }))).toEqual({+ consulted: 1,+ hooksJson: false,+ script: false,+ wrapper: false+ })+ })++ it('the registry is unreadable → nothing written (the side that cannot deny a tool)', () => {+ expect(attempt(() => ({ kind: 'unreadable', reason: 'test' }))).toMatchObject({+ hooksJson: false,+ script: false,+ wrapper: false+ })+ })++ it('the reader throws → nothing written', () => {+ expect(+ attempt(() => {+ throw new Error('boom')+ })+ ).toMatchObject({ hooksJson: false, script: false, wrapper: false })+ })++ it('clear → installs (the refusal is the only thing the check changes)', () => {+ expect(attempt(() => ({ kind: 'clear' }))).toMatchObject({ consulted: 1, hooksJson: true, script: true })+ })++ it('off Windows the registry is never consulted', () => {+ expect(attempt(() => ({ kind: 'set', entries: [] }), 'linux')).toMatchObject({ consulted: 0, hooksJson: true })+ })+})++describe.skipIf(process.platform !== 'win32')('the real reader (read-only)', () => {+ it('answers clear or set on this machine — never unreadable', () => {+ const out = readCmdAutoRun()+ expect(out.kind).not.toBe('unreadable')+ })+})++describe('a refusal WITHDRAWS a bundle an earlier launch installed, so a later AutoRun cannot keep denying tools through it', () => {+ const root = mkdtempSync(join(tmpdir(), 'nt agy withdraw '))+ afterAll(() => rmSync(root, { recursive: true, force: true, maxRetries: 8, retryDelay: 250 }))+ let n = 0+ const FOREIGN = {+ 'other-tool': { Stop: [{ type: 'command', command: 'C:\\other-tool\\Stop.cmd' }] },+ mine: { enabled: false }+ }+ /** A home with our bundle installed by a CLEAR launch, plus foreign keys. */+ const installed = () => {+ const home = join(root, `w${++n}`, 'John Doe')+ const hooksJson = join(home, '.gemini', 'config', 'hooks.json')+ mkdirSync(join(home, '.gemini', 'config'), { recursive: true })+ writeFileSync(hooksJson, JSON.stringify(FOREIGN), 'utf8')+ const script = join(home, '.nodeterm', 'agent-hooks', 'antigravity.sh')+ installAntigravityHooks({ findAgy: HAS_AGY, hooksJson, platform: 'win32', scriptPath: script, readAutoRun: () => ({ kind: 'clear' }) })+ const before = JSON.parse(readFileSync(hooksJson, 'utf8')) as Record<string, unknown>+ expect(before[ANTIGRAVITY_BUNDLE_KEY]).toBeDefined()+ return { home, hooksJson, script }+ }+ const after = (hooksJson: string) => JSON.parse(readFileSync(hooksJson, 'utf8')) as Record<string, unknown>++ it.each<[string, CmdAutoRunCheck | 'throw']>([+ ['set', { kind: 'set', entries: [{ key: HKCU, value: 'echo hi' }] }],+ ['unreadable', { kind: 'unreadable', reason: 'test' }],+ ['a throwing reader', 'throw']+ ])('%s → our bundle is gone, foreign keys intact', (_name, verdict) => {+ const { hooksJson, script } = installed()+ installAntigravityHooks({ findAgy: HAS_AGY,+ hooksJson,+ platform: 'win32',+ scriptPath: script,+ readAutoRun: () => {+ if (verdict === 'throw') throw new Error('boom')+ return verdict+ }+ })+ const data = after(hooksJson)+ expect(data[ANTIGRAVITY_BUNDLE_KEY]).toBeUndefined()+ expect(data).toEqual(FOREIGN)+ })++ it('no quote-free command for the layout → our bundle is gone, foreign keys intact', () => {+ const { hooksJson } = installed()+ installAntigravityHooks({ findAgy: HAS_AGY,+ hooksJson,+ platform: 'win32',+ // The script now lives across a directory with a space: no quote-free relative path.+ scriptPath: join(root, 'Other Dir', 'agent-hooks', 'antigravity.sh'),+ writeScript: false,+ readAutoRun: () => ({ kind: 'clear' })+ })+ expect(after(hooksJson)).toEqual(FOREIGN)+ })++ it('an unreadable hooks.json stays byte-for-byte intact under a refusal', () => {+ const home = join(root, `w${++n}`)+ const hooksJson = join(home, 'hooks.json')+ mkdirSync(home, { recursive: true })+ writeFileSync(hooksJson, '{ not json', 'utf8')+ installAntigravityHooks({ findAgy: HAS_AGY,+ hooksJson,+ platform: 'win32',+ scriptPath: join(home, 'antigravity.sh'),+ readAutoRun: () => ({ kind: 'set', entries: [] })+ })+ expect(readFileSync(hooksJson, 'utf8')).toBe('{ not json')+ })++ it('a hooks.json with nothing of ours is not rewritten (not even reformatted)', () => {+ const home = join(root, `w${++n}`)+ const hooksJson = join(home, 'hooks.json')+ mkdirSync(home, { recursive: true })+ const body = '{"mine": {"enabled":false}}'+ writeFileSync(hooksJson, body, 'utf8')+ installAntigravityHooks({ findAgy: HAS_AGY,+ hooksJson,+ platform: 'win32',+ scriptPath: join(home, 'antigravity.sh'),+ readAutoRun: () => ({ kind: 'set', entries: [] })+ })+ expect(readFileSync(hooksJson, 'utf8')).toBe(body)+ })+})++describe('the real reg query wrapper: absolute reg.exe only, and the 64-bit view of HKLM', () => {+ const recorder = () => {+ const calls: { file: string; args: readonly string[] }[] = []+ const exec: ExecFile = (file, args) => {+ calls.push({ file, args })+ return 'listing'+ }+ return { calls, exec }+ }++ it('without SystemRoot or windir it runs NOTHING and answers status null → unreadable', () => {+ const { calls, exec } = recorder()+ const query = makeRegQuery(exec, { PATH: 'C:\\evil' })+ expect(query(HKCU)).toEqual({ status: null, stdout: '' })+ expect(calls).toHaveLength(0)+ expect(checkCmdAutoRun(query).kind).toBe('unreadable')+ })++ it('uses the absolute reg.exe, falling back from SystemRoot to windir', () => {+ const a = recorder()+ makeRegQuery(a.exec, { SystemRoot: 'C:\\Windows' })(HKCU)+ expect(a.calls[0].file).toBe('C:\\Windows\\System32\\reg.exe')+ const b = recorder()+ makeRegQuery(b.exec, { windir: 'D:\\WIN' })(HKCU)+ expect(b.calls[0].file).toBe('D:\\WIN\\System32\\reg.exe')+ })++ it('passes /reg:64 on every HKLM query (parents included) and never on HKCU', () => {+ const { calls, exec } = recorder()+ const query = makeRegQuery(exec, { SystemRoot: 'C:\\Windows' })+ for (const key of [HKLM, WOW, 'HKEY_LOCAL_MACHINE\\Software', 'HKEY_LOCAL_MACHINE', HKCU, 'HKEY_CURRENT_USER']) {+ query(key)+ }+ expect(calls.map((c) => c.args)).toEqual([+ ['query', HKLM, '/reg:64'],+ ['query', WOW, '/reg:64'],+ ['query', 'HKEY_LOCAL_MACHINE\\Software', '/reg:64'],+ ['query', 'HKEY_LOCAL_MACHINE', '/reg:64'],+ ['query', HKCU],+ ['query', 'HKEY_CURRENT_USER']+ ])+ })++ it('a failing exec reports its exit status; one that never ran reports null', () => {+ const query1 = makeRegQuery(+ () => {+ throw Object.assign(new Error('exit 1'), { status: 1, stdout: '' })+ },+ { SystemRoot: 'C:\\Windows' }+ )+ expect(query1(HKCU)).toEqual({ status: 1, stdout: '' })+ const query2 = makeRegQuery(+ () => {+ throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' })+ },+ { SystemRoot: 'C:\\Windows' }+ )+ expect(query2(HKCU).status).toBeNull()+ })+})++describe('the refusal logs what the withdrawal REALLY did, so a failed write is not reported as done', () => {+ const root = mkdtempSync(join(tmpdir(), 'nt agy withdraw note '))+ afterAll(() => rmSync(root, { recursive: true, force: true, maxRetries: 8, retryDelay: 250 }))+ let n = 0+ const SET: CmdAutoRunCheck = { kind: 'set', entries: [{ key: HKCU, value: 'echo hi' }] }+ const home = () => {+ const h = join(root, `d${++n}`, 'John Doe')+ mkdirSync(join(h, '.gemini', 'config'), { recursive: true })+ return { hooksJson: join(h, '.gemini', 'config', 'hooks.json'), script: join(h, '.nodeterm', 'agent-hooks', 'antigravity.sh') }+ }+ const installClear = (hooksJson: string, script: string) =>+ installAntigravityHooks({ findAgy: HAS_AGY, hooksJson, platform: 'win32', scriptPath: script, readAutoRun: () => ({ kind: 'clear' }) })++ /** Refuse with `verdict`; returns the warning text and whether our bundle was present WHEN it was logged. */+ const refuse = (+ hooksJson: string,+ script: string,+ verdict: CmdAutoRunCheck,+ writeFile?: (file: string, data: Record<string, unknown>) => void+ ) => {+ const seen: { text: string; bundleAtLogTime: boolean }[] = []+ const spy = vi.spyOn(console, 'warn').mockImplementation((...args: unknown[]) => {+ const text = args.map(String).join(' ')+ const bundleAtLogTime = existsSync(hooksJson) && readFileSync(hooksJson, 'utf8').includes(ANTIGRAVITY_BUNDLE_KEY)+ seen.push({ text, bundleAtLogTime })+ })+ try {+ installAntigravityHooks({ findAgy: HAS_AGY, hooksJson, platform: 'win32', scriptPath: script, readAutoRun: () => verdict, writeFile })+ } finally {+ spy.mockRestore()+ }+ expect(seen).toHaveLength(1)+ return seen[0]+ }++ it('withdrawn: says so, and says it only after the bundle is really gone', () => {+ const { hooksJson, script } = home()+ installClear(hooksJson, script)+ const w = refuse(hooksJson, script, SET)+ expect(w.text).toContain('was withdrawn')+ expect(w.bundleAtLogTime).toBe(false)+ })++ it('absent: says there was nothing to withdraw (and the unreadable branch says it too)', () => {+ const a = home()+ expect(refuse(a.hooksJson, a.script, SET).text).toContain('nothing to withdraw')+ const b = home()+ expect(refuse(b.hooksJson, b.script, { kind: 'unreadable', reason: 'x' }).text).toContain('nothing to withdraw')+ })++ it('failed: a write that fails is REPORTED as a failure, and the bundle is still there', () => {+ const { hooksJson, script } = home()+ installClear(hooksJson, script)+ const w = refuse(hooksJson, script, SET, () => {+ throw Object.assign(new Error('EPERM'), { code: 'EPERM' })+ })+ expect(w.text).toContain('FAILED')+ expect(w.text).not.toContain('was withdrawn')+ expect(w.bundleAtLogTime).toBe(true)+ expect(readFileSync(hooksJson, 'utf8')).toContain(ANTIGRAVITY_BUNDLE_KEY)+ })++ it('unparseable: says the file was left untouched', () => {+ const { hooksJson, script } = home()+ writeFileSync(hooksJson, '{ nope', 'utf8')+ expect(refuse(hooksJson, script, SET).text).toContain('left untouched')+ })++ it('the no-quote-free-command branch reports the real result too', () => {+ const { hooksJson, script } = home()+ installClear(hooksJson, script)+ const spy = vi.spyOn(console, 'warn').mockImplementation(() => {})+ try {+ installAntigravityHooks({ findAgy: HAS_AGY,+ hooksJson,+ platform: 'win32',+ scriptPath: join(root, 'Other Dir', 'agent-hooks', 'antigravity.sh'),+ writeScript: false,+ readAutoRun: () => ({ kind: 'clear' }),+ writeFile: () => {+ throw new Error('EBUSY')+ }+ })+ expect(String(spy.mock.calls[0]?.[0])).toContain('FAILED')+ } finally {+ spy.mockRestore()+ }+ })++ it('removeAntigravityHooks returns each outcome directly', () => {+ const { hooksJson, script } = home()+ expect(removeAntigravityHooks({ hooksJson })).toBe('absent')+ installClear(hooksJson, script)+ expect(+ removeAntigravityHooks({+ hooksJson,+ writeFile: () => {+ throw new Error('x')+ }+ })+ ).toBe('failed')+ expect(removeAntigravityHooks({ hooksJson })).toBe('withdrawn')+ expect(removeAntigravityHooks({ hooksJson })).toBe('absent')+ writeFileSync(hooksJson, '[]', 'utf8')+ expect(removeAntigravityHooks({ hooksJson })).toBe('unparseable')+ })+})diff --git a/src/core/agents/hooks/antigravity-autorun.ts b/src/core/agents/hooks/antigravity-autorun.tsnew file mode 100644index 000000000..6eda7f8b1--- /dev/null+++ b/src/core/agents/hooks/antigravity-autorun.ts@@ -0,0 +1,146 @@+// Does `cmd.exe` run an AutoRun command on this machine?+//+// `agy` runs every hook through `cmd /c` WITHOUT `/d`, so cmd.exe first executes the AutoRun+// command from the registry (`cmd /?`: "/D Disable execution of AutoRun commands from registry").+// Anything that AutoRun prints lands on the hook's stdout AHEAD of our answer — non-JSON, which agy+// 1.2.3 treats as a DENY (measured on agy 1.2.3, Windows 11, in a temporary HOME). A silent AutoRun can still hurt: a `cd` moves+// the cwd our relative command depends on (the guard then falls silent, and the badge goes dark).+// Our install is what makes agy open a cmd.exe at all, so the installer refuses to arm the hook+// while any AutoRun is set. Not reproduced on a device (that would mean writing the registry); the+// behaviour is cmd.exe's documented one.+//+// HOW IT READS. `reg query` — no PowerShell (~4× the start cost) and no native module. Three+// values, the ones cmd.exe consults: HKCU, HKLM, and the 32-bit view of HKLM.+//+// The trap is that `reg` answers exit 1 with a LOCALIZED message both for "that key does not exist"+// and for a real failure, and a missing `Command Processor` key under HKCU is the normal case (it is+// missing on the machine this was written on). So absence is never read from an error. A key that+// fails to list is judged by listing its PARENT: if the parent lists and the key is not among its+// subkeys, the key is absent — a positive answer, in key names reg does not translate. If the+// parent fails too, the same question is asked one level up; a hive root that cannot be listed is+// an unreadable registry.+//+// UNREADABLE ⇒ DO NOT INSTALL. The choice between the two safe-looking sides is not symmetric: not+// installing costs the badge; installing over an AutoRun that prints costs every tool call of every+// agy on the machine. When we cannot tell, we take the side that cannot deny a tool.+import { execFileSync } from 'child_process'++/** The three values cmd.exe reads, as `reg` spells the hives in its own output. */+export const CMD_AUTORUN_KEYS = [+ 'HKEY_CURRENT_USER\\Software\\Microsoft\\Command Processor',+ 'HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Command Processor',+ 'HKEY_LOCAL_MACHINE\\Software\\WOW6432Node\\Microsoft\\Command Processor'+] as const++/** One `reg query <key>`: exit status and stdout. `status: null` = the process did not run. */+export type RegQuery = (key: string) => { status: number | null; stdout: string }++export type CmdAutoRunCheck =+ | { kind: 'clear' }+ | { kind: 'set'; entries: { key: string; value: string }[] }+ | { kind: 'unreadable'; reason: string }++/**+ * The AutoRun value in one key's `reg query` listing, or undefined when the value is absent or+ * empty. Value names are case-insensitive in the registry; the type may be REG_SZ or REG_EXPAND_SZ.+ */+export function parseAutoRunValue(listing: string): string | undefined {+ for (const line of listing.split(/\r?\n/)) {+ const m = /^\s+AutoRun\s+REG_[A-Z_]+(?:\s+(.*))?$/i.exec(line)+ if (m) {+ const value = (m[1] ?? '').trim()+ return value === '' ? undefined : value+ }+ }+ return undefined+}++/** Does a parent's `reg query` listing name `key` among its subkeys? (Exact line, any case.) */+export function listingHasSubkey(listing: string, key: string): boolean {+ const want = key.toLowerCase()+ return listing.split(/\r?\n/).some((line) => line.trim().toLowerCase() === want)+}++const parentOf = (key: string): string | null => {+ const i = key.lastIndexOf('\\')+ return i > 0 ? key.slice(0, i) : null+}++type KeyListing = { kind: 'listing'; stdout: string } | { kind: 'absent' } | { kind: 'unreadable'; reason: string }++/** List a key, telling "absent" from "failed" by asking the parent (recursively, up to the hive). */+function listKey(query: RegQuery, key: string): KeyListing {+ const r = query(key)+ if (r.status === 0) return { kind: 'listing', stdout: r.stdout }+ const parent = parentOf(key)+ if (!parent) return { kind: 'unreadable', reason: `cannot list ${key} (reg exit ${r.status})` }+ const up = listKey(query, parent)+ if (up.kind === 'absent') return up+ if (up.kind === 'unreadable') return up+ return listingHasSubkey(up.stdout, key)+ ? { kind: 'unreadable', reason: `${key} exists but could not be listed (reg exit ${r.status})` }+ : { kind: 'absent' }+}++/** Pure over the injected query: the verdict for the three AutoRun values. */+export function checkCmdAutoRun(query: RegQuery): CmdAutoRunCheck {+ const entries: { key: string; value: string }[] = []+ for (const key of CMD_AUTORUN_KEYS) {+ let listing: KeyListing+ try {+ listing = listKey(query, key)+ } catch (e) {+ return { kind: 'unreadable', reason: `reg query threw: ${String(e)}` }+ }+ if (listing.kind === 'unreadable') return listing+ if (listing.kind === 'absent') continue+ const value = parseAutoRunValue(listing.stdout)+ if (value !== undefined) entries.push({ key, value })+ }+ return entries.length ? { kind: 'set', entries } : { kind: 'clear' }+}++/** Runs one program and returns its stdout; throws like `execFileSync` on a non-zero exit. */+export type ExecFile = (file: string, args: readonly string[]) => string++const defaultExec: ExecFile = (file, args) =>+ execFileSync(file, [...args], {+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'pipe'],+ timeout: 5000,+ windowsHide: true+ })++/**+ * The real `reg query`, READ-ONLY, over an injectable exec.+ *+ * - `reg.exe` by ABSOLUTE path under `%SystemRoot%` (or `%windir%`). With neither variable set there+ * is no trustworthy path, and a `reg.*` planted earlier on PATH could answer "no AutoRun" — so the+ * query does not run at all and answers `status: null`, which the checker turns into+ * `unreadable` (= do not install).+ * - `/reg:64` on every HKLM query (parent listings included). In a 32-bit process+ * `System32\reg.exe` is redirected to the SysWOW64 copy and plain HKLM\Software reads the 32-bit+ * view, hiding the 64-bit AutoRun that agy's 64-bit cmd.exe actually runs. On this 64-bit machine+ * the answers with and without the switch were byte-identical (read-only check).+ * HKCU\Software is not redirected, so it is queried plainly.+ */+export function makeRegQuery(+ exec: ExecFile = defaultExec,+ env: Readonly<Record<string, string | undefined>> = process.env+): RegQuery {+ return (key) => {+ const root = env.SystemRoot || env.windir+ if (!root) return { status: null, stdout: '' }+ const reg = `${root}\\System32\\reg.exe`+ const args = ['query', key]+ if (/^HKEY_LOCAL_MACHINE(\\|$)/i.test(key)) args.push('/reg:64')+ try {+ return { status: 0, stdout: exec(reg, args) }+ } catch (e) {+ const err = e as { status?: number | null; stdout?: string }+ return { status: typeof err.status === 'number' ? err.status : null, stdout: err.stdout ?? '' }+ }+ }+}++export const readCmdAutoRun = (): CmdAutoRunCheck => checkCmdAutoRun(makeRegQuery())diff --git a/src/core/agents/hooks/antigravity-decision.ts b/src/core/agents/hooks/antigravity-decision.tsnew file mode 100644index 000000000..60c1d0534--- /dev/null+++ b/src/core/agents/hooks/antigravity-decision.ts@@ -0,0 +1,97 @@+// THE stdout contract of an Antigravity CLI (`agy`) hook — written ONCE, consumed by every place+// that can answer `agy`: the POSIX managed script, the missing-script fallback inside the+// hooks.json command, and the Windows batch wrapper's bail path.+//+// WHY THIS MATTERS MORE THAN ANYTHING ELSE IN THE INTEGRATION. `agy` runs hooks SYNCHRONOUSLY and+// reads their stdout as a decision. Our hook is installed in the GLOBAL `~/.gemini/config/hooks.json`+// and subscribes to `PreToolUse`, so it stands in front of every tool call of every `agy` on the+// machine — inside nodeterm and outside it. What `agy` 1.2.3 does with each stdout, measured+// on agy 1.2.3, Windows 11, in a temporary HOME, every row reproduced with a real run):+//+// PreToolUse stdout result+// (nothing), exit 0 tool RUNS+// {} DENIED ("tool call denied by pre-tool hook")+// {"decision":""} DENIED+// {"decision":"ask"} runs under the user's normal policy (respects "always allow";+// loses to --dangerously-skip-permissions, measured)+// {"decision":"allow"} runs with no prompt — approves what the USER did not approve+// non-JSON text DENIED (protojson unmarshal error)+// (nothing), exit 1 DENIED+//+// Hence the table below, and the rules around it:+// - PreToolUse answers `ask`: safe under both readings (it runs here, and it is what an older+// `agy` that denied silence also accepted). NEVER `allow` (we would be approving on the user's+// behalf) and NEVER `force_ask` (re-opens the prompt, ignoring the user's cache).+// - Stop answers an empty decision. `"continue"` would PREVENT `agy` from stopping.+// - The lifecycle events answer `{}`.+// - An UNKNOWN or EMPTY event answers NOTHING. `{}` is the tempting default and it is exactly+// wrong: if the event name is ever lost and the real event was PreToolUse, `{}` denies the tool.+// Silence was measured running normally for all five events.+// - Nothing else may ever reach stdout. `PreInvocation` accepts `injectSteps`, so our stdout can+// become a message in the user's conversation; and a stray byte from curl turns into "non-JSON →+// DENY". The script redirects stdout to /dev/null right after answering.+//+// Two copies of this table already diverged once within fifteen minutes during development.+// Keep it here.++export type AntigravityHookEvent = 'PreInvocation' | 'PostInvocation' | 'PreToolUse' | 'PostToolUse' | 'Stop'++const DECISIONS: Readonly<Record<AntigravityHookEvent, string>> = {+ PreToolUse: '{"decision":"ask"}',+ Stop: '{"decision":""}',+ PreInvocation: '{}',+ PostInvocation: '{}',+ PostToolUse: '{}'+}++/** Every event `agy` knows, in a stable order (generators iterate it). */+export const ANTIGRAVITY_EVENTS: readonly AntigravityHookEvent[] = [+ 'PreInvocation',+ 'PostInvocation',+ 'PreToolUse',+ 'PostToolUse',+ 'Stop'+]++/**+ * What a hook must print for `event`, or `null` for "print nothing". The lookup is by OWN key only,+ * so `constructor`/`__proto__` and every other non-event string answer `null` (silence).+ */+export function antigravityDecisionFor(event: string | undefined | null): string | null {+ if (typeof event !== 'string' || !Object.hasOwn(DECISIONS, event)) return null+ return DECISIONS[event as AntigravityHookEvent]+}++/**+ * The env var carrying the event name from the hooks.json command into the script (POSIX) or+ * from the wrapper's argument into the script (Windows). Shared so neither side can misspell it.+ */+export const ANTIGRAVITY_EVENT_ENV = 'NODETERM_AGY_EVENT'++// The generators interpolate the table into shell and batch source. Every value is checked here+// so a future edit that introduces a quote or a batch metacharacter fails at import, loudly,+// instead of emitting a command that answers wrong.+for (const [event, out] of Object.entries(DECISIONS)) {+ if (!/^[A-Za-z]+$/.test(event)) throw new Error(`antigravity event name not shell-safe: ${event}`)+ if (/['\r\n%!^&|<>()]/.test(out)) throw new Error(`antigravity decision not shell/batch-safe: ${out}`)+}++/**+ * POSIX `case` answering from `$NODETERM_AGY_EVENT`. No default branch: an unknown event prints+ * nothing. `printf` rather than `echo` — some shells' `echo` interprets backslashes.+ */+export function antigravityDecisionCaseSh(): string {+ const arms = ANTIGRAVITY_EVENTS.map((ev) => ` ${ev}) printf '%s\\n' '${DECISIONS[ev]}' ;;`)+ return [`case "$${ANTIGRAVITY_EVENT_ENV}" in`, ...arms, 'esac'].join('\n')+}++/**+ * Batch lines answering from `%NODETERM_AGY_EVENT%`, one `if` per event, case-SENSITIVE (no `/i`:+ * `stop` is not an event). Nothing matches an unknown value, so nothing is echoed. The values hold+ * no batch metacharacter (checked above); `echo` prints the braces and quotes literally.+ */+export function antigravityDecisionBatch(): string[] {+ return ANTIGRAVITY_EVENTS.map(+ (ev) => `if "%${ANTIGRAVITY_EVENT_ENV}%"=="${ev}" echo ${DECISIONS[ev]}`+ )+}diff --git a/src/core/agents/hooks/antigravity-script.test.ts b/src/core/agents/hooks/antigravity-script.test.tsnew file mode 100644index 000000000..7d9d280ef--- /dev/null+++ b/src/core/agents/hooks/antigravity-script.test.ts@@ -0,0 +1,337 @@+// The Antigravity hook, EXECUTED — never grepped.+//+// Our hook sits in front of every tool call of every `agy` on the machine and `agy` reads its+// stdout as a decision (see antigravity-decision.ts for the measured table). A string assertion+// would stay green while a stray byte ahead of the answer turned every tool call into a DENY, so+// every case below runs the generated script under a real `sh` with a fake `curl` on PATH and+// checks stdout BYTE FOR BYTE, the exit status, and what (if anything) was POSTed.+//+// On Windows `sh` is Git for Windows' MSYS shell — the exact interpreter the wrapper hands the+// script to — so these run there too; they are slower there (a process start is ~60 ms), hence+// the generous timeouts.+import { describe, it, expect, afterAll } from 'vitest'+import { spawnSync } from 'node:child_process'+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { createHash } from 'node:crypto'+import path, { join } from 'node:path'+import { buildManagedScript } from './managed-script'+import { buildManagedHookCommand } from './install-helper'+import {+ ANTIGRAVITY_EVENTS,+ ANTIGRAVITY_EVENT_ENV,+ antigravityDecisionFor,+ antigravityDecisionBatch,+ antigravityDecisionCaseSh+} from './antigravity-decision'++const T = 60_000+const probe = spawnSync('sh', ['-c', 'exit 0'])+const shAvailable = probe.status === 0 && !probe.error++const root = shAvailable ? mkdtempSync(join(tmpdir(), 'nt agy script ')) : ''+afterAll(() => {+ if (root) rmSync(root, { recursive: true, force: true })+})++let seq = 0+interface Run {+ dir: string+ stdout: string+ stderr: string+ status: number | null+ /** Every fake-curl invocation's argv, once the (backgrounded) POST has finished. */+ posts: () => string[]+}++/** A stand-in curl that appends its argv (and nothing to stdout) to a log. */+const FAKE_CURL = (log: string): string =>+ ['#!/bin/sh', `printf 'ARGV %s\\n' "$*" >> '${log.replaceAll('\\', '/')}'`, 'cat >/dev/null', 'exit 0', ''].join('\n')++function runScript(opts: {+ event?: string+ nodeId?: string | null+ input?: string | Buffer+ /** Extra lines appended to the script, to prove nothing written after the answer escapes. */+ append?: string+ /** No endpoint file at all: the POST has nowhere to go. */+ noEndpoint?: boolean+}): Run {+ const dir = join(root, `case-${++seq}`)+ const bin = join(dir, 'bin')+ const home = join(dir, 'home dir')+ mkdirSync(bin, { recursive: true })+ mkdirSync(join(home, '.nodeterm'), { recursive: true })+ const log = join(dir, 'curl.log')+ writeFileSync(join(bin, 'curl'), FAKE_CURL(log), { encoding: 'utf8', mode: 0o755 })+ const endpoint = join(home, '.nodeterm', 'hook-endpoint.env')+ if (!opts.noEndpoint) {+ writeFileSync(endpoint, 'NODETERM_HOOK_PORT=45999\nNODETERM_HOOK_TOKEN=t\nNODETERM_HOOK_VERSION=2\n', 'utf8')+ }+ const script = join(dir, 'antigravity.sh')+ const body = buildManagedScript('antigravity', null).replace(/\nexit 0\n$/, `\n${opts.append ?? ''}\nexit 0\n`)+ writeFileSync(script, body, { encoding: 'utf8', mode: 0o755 })+ const env: Record<string, string> = {+ PATH: `${bin}${path.delimiter}${process.env.PATH ?? ''}`,+ HOME: home,+ NODETERM_HOOK_ENDPOINT: endpoint+ }+ if (process.env.SystemRoot) env.SystemRoot = process.env.SystemRoot+ if (opts.nodeId !== null) env.NODETERM_NODE_ID = opts.nodeId ?? 'term-agy-1'+ if (opts.event !== undefined) env[ANTIGRAVITY_EVENT_ENV] = opts.event+ const res = spawnSync('sh', [script], { input: opts.input ?? '{"conversationId":"c1"}', env, timeout: T })+ return {+ dir,+ stdout: res.stdout.toString('utf8'),+ stderr: res.stderr.toString('utf8'),+ status: res.status,+ posts: () => {+ // The POST is backgrounded (the hot path never waits on the network); poll for it.+ const deadline = Date.now() + 15_000+ let last = ''+ while (Date.now() < deadline) {+ last = existsSync(log) ? readFileSync(log, 'utf8') : ''+ if (last) break+ sleep(100)+ }+ return last.split('\n').filter((l) => l.startsWith('ARGV '))+ }+ }+}++function sleep(ms: number): void {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)+}++describe('the decision table', () => {+ it('answers exactly the measured contract, and silence for anything else', () => {+ expect(antigravityDecisionFor('PreToolUse')).toBe('{"decision":"ask"}')+ expect(antigravityDecisionFor('Stop')).toBe('{"decision":""}')+ expect(antigravityDecisionFor('PreInvocation')).toBe('{}')+ expect(antigravityDecisionFor('PostInvocation')).toBe('{}')+ expect(antigravityDecisionFor('PostToolUse')).toBe('{}')+ for (const unknown of ['', 'stop', 'pretooluse', 'SessionEnd', 'constructor', '__proto__', 'toString']) {+ expect(antigravityDecisionFor(unknown), unknown).toBeNull()+ }+ expect(antigravityDecisionFor(undefined)).toBeNull()+ expect(antigravityDecisionFor(null)).toBeNull()+ })++ it('never approves, never force-asks, never keeps agy running', () => {+ for (const ev of ANTIGRAVITY_EVENTS) {+ const out = antigravityDecisionFor(ev) ?? ''+ expect(out, ev).not.toMatch(/allow|force_ask|continue|deny/)+ }+ })++ it('the sh and batch renderings are generated from the same table', () => {+ const sh = antigravityDecisionCaseSh()+ const batch = antigravityDecisionBatch().join('\n')+ for (const ev of ANTIGRAVITY_EVENTS) {+ expect(sh).toContain(` ${ev}) printf '%s\\n' '${antigravityDecisionFor(ev)}' ;;`)+ expect(batch).toContain(`if "%${ANTIGRAVITY_EVENT_ENV}%"=="${ev}" echo ${antigravityDecisionFor(ev)}`)+ }+ // No catch-all: an unknown event must print nothing.+ expect(sh).not.toMatch(/\*\)/)+ })+})++describe('the managed script for antigravity', () => {+ it('answers before anything else and swallows every later byte', () => {+ const s = buildManagedScript('antigravity', '/fixed/identity-root')+ const lines = s.split('\n')+ // shebang, comment, then the case statement — ahead of the codex prelude and the gate.+ expect(lines[2]).toBe(`case "$${ANTIGRAVITY_EVENT_ENV}" in`)+ const answer = s.indexOf(`case "$${ANTIGRAVITY_EVENT_ENV}" in`)+ const silence = s.indexOf('command exec >/dev/null 2>&1 || :')+ expect(answer).toBeGreaterThan(0)+ expect(silence).toBeGreaterThan(answer)+ for (const later of ['CODEX_THREAD_ID', 'if [ -z "$NODETERM_NODE_ID" ]', 'payload=$(cat)', '. "$NODETERM_HOOK_ENDPOINT"']) {+ expect(s.indexOf(later), later).toBeGreaterThan(silence)+ }+ })++ it('sends the event name on BOTH transports, and only antigravity does', () => {+ const s = buildManagedScript('antigravity', null)+ expect(s.match(/--data-urlencode "nodeterm_hook_event=\$\{NODETERM_AGY_EVENT\}"/g)).toHaveLength(2)+ for (const other of ['claude', 'codex', 'gemini', 'opencode', 'grok', 'copilot']) {+ const o = buildManagedScript(other, null)+ expect(o, other).not.toContain('nodeterm_hook_event')+ expect(o, other).not.toContain('command exec')+ }+ })++ it('leaves the other six scripts byte-identical to the pre-antigravity build', () => {+ // sha256 of each agent's script at the commit this integration branched from (f2449a8f),+ // computed from that commit's managed-script.ts. If the SHARED script legitimately changes,+ // recompute these deliberately — a silent diff here is exactly the regression to catch.+ const expected: Record<string, [string, string]> = {+ claude: [+ '991a3232392304f670e3aa11a05ce1e5bb0ea366432b69524d57a74fbdf4926e',+ 'b7f9a979e57c58b61acb5582a007c45b63bdfab2e830d7b483ddcc40155a1eb1'+ ],+ codex: [+ '1766f60fb5e769433a0661ebc10e539e9e805c77debb9243b959bc985662458d',+ '7ff83cffda070d45fd71ed3916d8db852859591a8402d7537f322dba066a6cd9'+ ],+ gemini: [+ '92a71a09bcd2e82be4bb554414455ba9bb520374245064408b48bec15d138182',+ '73db0f4dd7af188b8356ecf8014bffb7353e14b3c12117244cf738dc151c2cc5'+ ],+ opencode: [+ '66d338220e6830fdf573ae5c2b5ff7bf84853e854c7274f69c30d3312a56482c',+ 'a031e5507eb43f6a9410171756ebe072ef7794da7a53cb340330a46c98962aa7'+ ],+ grok: [+ '12bdc358a872d8adb0182b3214363116200c61598a44dd150d5a5ab0f2d6eeb1',+ 'bd11826628532617f418ce3dc0060f82ec9ff3962cb87612da2c31647573733e'+ ],+ copilot: [+ 'e9c3b8153f2fd0723f993dade6d248cb5bca532ee41d5746afbdd137c10bbea5',+ '7d8709ff9a479822ba49e97c0e0f4e4c98e11bd5531d3985136c43489c81e109'+ ]+ }+ const sha = (s: string): string => createHash('sha256').update(s).digest('hex')+ for (const [agent, [noRoot, withRoot]] of Object.entries(expected)) {+ expect(sha(buildManagedScript(agent, null)), `${agent} (no identity root)`).toBe(noRoot)+ expect(sha(buildManagedScript(agent, '/fixed/identity-root')), `${agent} (identity root)`).toBe(withRoot)+ }+ })+})++describe.skipIf(!shAvailable)('the managed script for antigravity, executed under sh', () => {+ it.each(ANTIGRAVITY_EVENTS)('%s: stdout is exactly the table row, exit 0, and the event is POSTed', (ev) => {+ const r = runScript({ event: ev })+ expect(r.status).toBe(0)+ expect(r.stdout).toBe(`${antigravityDecisionFor(ev)}\n`)+ expect(r.stderr).toBe('')+ const posts = r.posts()+ expect(posts).toHaveLength(1)+ expect(posts[0]).toContain(`nodeterm_hook_event=${ev}`)+ expect(posts[0]).toContain('/hook/antigravity')+ expect(posts[0]).toContain('nodeId=term-agy-1')+ }, T)++ it.each(['', 'stop', 'SessionEnd', 'PreToolUse ', 'constructor'])(+ 'unknown event %j: NOTHING on stdout, exit 0',+ (ev) => {+ const r = runScript({ event: ev })+ expect(r.status).toBe(0)+ expect(r.stdout).toBe('')+ expect(r.stderr).toBe('')+ },+ T+ )++ it('no event variable at all: nothing on stdout, exit 0', () => {+ const r = runScript({})+ expect(r.status).toBe(0)+ expect(r.stdout).toBe('')+ }, T)++ it("outside nodeterm (no NODETERM_NODE_ID): the SAME answer, exit 0, and no POST", () => {+ for (const ev of ANTIGRAVITY_EVENTS) {+ const r = runScript({ event: ev, nodeId: null })+ expect(r.status, ev).toBe(0)+ expect(r.stdout, ev).toBe(`${antigravityDecisionFor(ev)}\n`)+ expect(r.stderr, ev).toBe('')+ }+ // Give a (wrongly) backgrounded POST time to land, then check none did.+ const r = runScript({ event: 'Stop', nodeId: null })+ sleep(1500)+ expect(existsSync(join(r.dir, 'curl.log'))).toBe(false)+ }, T)++ it('empty stdin: the answer, exit 0, and the event is still POSTed (with a {} payload)', () => {+ const r = runScript({ event: 'Stop', input: '' })+ expect(r.status).toBe(0)+ expect(r.stdout).toBe('{"decision":""}\n')+ const posts = r.posts()+ expect(posts).toHaveLength(1)+ expect(posts[0]).toContain('nodeterm_hook_event=Stop')+ // The payload goes by file (payload@...), never on argv.+ expect(posts[0]).toMatch(/payload@/)+ }, T)++ it('a 200 KB payload: the answer, exit 0, no EPIPE, and the body stays off argv', () => {+ const big = JSON.stringify({ conversationId: 'c1', toolCall: { name: 'run_command', args: { blob: 'x'.repeat(200_000) } } })+ const r = runScript({ event: 'PreToolUse', input: big })+ expect(r.status).toBe(0)+ expect(r.stdout).toBe('{"decision":"ask"}\n')+ expect(r.stderr).toBe('')+ const posts = r.posts()+ expect(posts).toHaveLength(1)+ expect(posts[0].length).toBeLessThan(2000)+ }, T)++ it('nothing written AFTER the answer reaches stdout or stderr', () => {+ const r = runScript({+ event: 'PreToolUse',+ append: [+ 'echo THIS-MUST-NOT-APPEAR',+ 'printf "%s" "NOR-THIS" >&2',+ 'ls /definitely/not/a/path',+ 'curl --version'+ ].join('\n')+ })+ expect(r.status).toBe(0)+ expect(r.stdout).toBe('{"decision":"ask"}\n')+ expect(r.stderr).toBe('')+ }, T)++ it('an unreachable endpoint still ends with the answer only and exit 0', () => {+ // No endpoint file, no port, no socket: nt_request_post returns 1, the walk finds nothing.+ const r = runScript({ event: 'PreToolUse', noEndpoint: true })+ expect(r.status).toBe(0)+ expect(r.stdout).toBe('{"decision":"ask"}\n')+ expect(r.stderr).toBe('')+ sleep(1500)+ expect(existsSync(join(r.dir, 'curl.log'))).toBe(false)+ }, T)+})++describe('the hooks.json command (POSIX form)', () => {+ it('exports the event and answers from the table when the script is gone', () => {+ const cmd = buildManagedHookCommand('/h/.nodeterm/agent-hooks/antigravity.sh', {+ env: { [ANTIGRAVITY_EVENT_ENV]: 'PreToolUse' },+ fallbackStdout: '{"decision":"ask"}'+ })+ expect(cmd).toBe(+ "NODETERM_AGY_EVENT='PreToolUse'; export NODETERM_AGY_EVENT; " ++ "if [ -r '/h/.nodeterm/agent-hooks/antigravity.sh' ]; then sh '/h/.nodeterm/agent-hooks/antigravity.sh'; " ++ "else printf '%s\\n' '{\"decision\":\"ask\"}'; cat >/dev/null 2>&1 || :; fi"+ )+ })++ it('is byte-identical for callers that pass no options', () => {+ expect(buildManagedHookCommand("/it's/claude.sh")).toBe(+ "if [ -r '/it'\\''s/claude.sh' ]; then sh '/it'\\''s/claude.sh'; else cat >/dev/null 2>&1 || :; fi"+ )+ })++ it('refuses an env name that is not a name', () => {+ expect(() => buildManagedHookCommand('/x.sh', { env: { 'A;rm -rf /': 'v' } })).toThrow()+ })++ it.skipIf(!shAvailable)(+ 'runs under sh: script present → script answers; script missing → command answers; both exit 0',+ () => {+ const dir = join(root, `cmd-${++seq}`)+ mkdirSync(dir, { recursive: true })+ const script = join(dir, 'antigravity.sh').replaceAll('\\', '/')+ const missing = join(dir, 'gone.sh').replaceAll('\\', '/')+ writeFileSync(script, buildManagedScript('antigravity', null), { encoding: 'utf8', mode: 0o755 })+ for (const ev of ANTIGRAVITY_EVENTS) {+ const answer = antigravityDecisionFor(ev)!+ for (const target of [script, missing]) {+ const cmd = buildManagedHookCommand(target, { env: { [ANTIGRAVITY_EVENT_ENV]: ev }, fallbackStdout: answer })+ const env: Record<string, string> = { PATH: process.env.PATH ?? '', HOME: dir }+ const res = spawnSync('sh', ['-c', cmd], { input: '{"conversationId":"c"}', env, timeout: T })+ expect(res.status, `${ev} ${target}`).toBe(0)+ expect(res.stdout.toString(), `${ev} ${target}`).toBe(`${answer}\n`)+ }+ }+ },+ T+ )+})diff --git a/src/core/agents/hooks/antigravity-windows-wrapper.ts b/src/core/agents/hooks/antigravity-windows-wrapper.tsnew file mode 100644index 000000000..0fa6ba61d--- /dev/null+++ b/src/core/agents/hooks/antigravity-windows-wrapper.ts@@ -0,0 +1,90 @@+// The Windows entry point for the Antigravity (`agy`) managed hook.+//+// `agy` runs a hook command through `cmd /c` on Windows (its bundled hooks.md, "Hook Handler+// Fields"), so the POSIX one-liner every other agent's hooks.json carries cannot run there. Like+// the codex wrapper (codex-windows-wrapper.ts, whose shell search this reuses) this file does ONE+// thing: find Git Bash and hand it the same `antigravity.sh`. It is not a second implementation of+// the hook protocol.+//+// What it owes on top of the codex wrapper, because `agy` reads hook stdout as a DECISION:+// 1. The event name arrives as the FIRST ARGUMENT (`... antigravity-hook.cmd " PreToolUse`), one+// wrapper for all events, and is exported as NODETERM_AGY_EVENT for the script.+// 2. When there is no shell or no script it must still ANSWER — from the same table the script+// uses (antigravity-decision.ts) — and drain stdin.+// 3. It always exits 0. A non-zero exit is a DENY on `PreToolUse` (measured). The script itself+// exits 0 on every branch; this makes a crashed `sh.exe` degrade to "no opinion" instead.+//+// `DisableDelayedExpansion`: `!` is legal in a Windows path, and delayed expansion would eat it.+// `%` in the profile path remains a known limit, shared with the codex wrapper.+import { antigravityDecisionBatch, ANTIGRAVITY_EVENT_ENV } from './antigravity-decision'+import { windowsShProbeBatch } from './codex-windows-wrapper'++/** The wrapper's file name, beside the managed script it runs. */+export const ANTIGRAVITY_WINDOWS_WRAPPER_FILE = 'antigravity-hook.cmd'+/** The managed script's file name (shared with the POSIX command). */+export const ANTIGRAVITY_SCRIPT_FILE = 'antigravity.sh'++/** The batch wrapper's content. CRLF, whatever host generated it — cmd.exe is line-oriented. */+export function buildAntigravityWindowsWrapper(): string {+ const lines = [+ '@echo off',+ 'rem Managed by nodeterm (agent-hooks). Regenerated on every app launch; edits are lost.',+ 'setlocal EnableExtensions DisableDelayedExpansion',+ `set "${ANTIGRAVITY_EVENT_ENV}=%~1"`,+ `set "NT_SCRIPT=%~dp0${ANTIGRAVITY_SCRIPT_FILE}"`,+ 'if not exist "%NT_SCRIPT%" goto :nt_bail',+ 'set "NT_SH="',+ ...windowsShProbeBatch(),+ 'if not defined NT_SH goto :nt_bail',+ 'set "NT_ARG=%NT_SCRIPT:\\=/%"',+ '"%NT_SH%" "%NT_ARG%"',+ 'exit /b 0',+ ':nt_bail',+ 'rem No shell or no script: answer from the same table the script uses, drain stdin, succeed.',+ ...antigravityDecisionBatch(),+ 'findstr /r ".*" >nul 2>&1',+ 'exit /b 0',+ ''+ ]+ return lines.join('\r\n')+}++/**+ * The characters a relative wrapper path may contain. No space, no quote, no batch metacharacter,+ * no drive colon — see `buildAntigravityWindowsCommand` for why each matters.+ */+const SAFE_RELATIVE_DIR = /^[A-Za-z0-9._\\-]+$/++/**+ * The hooks.json command on Windows:+ *+ * if exist ..\..\.nodeterm\agent-hooks\antigravity-hook.cmd (call ..\..\.nodeterm\agent-hooks\antigravity-hook.cmd <Event>) & exit 0+ *+ * WHY NO QUOTES. `agy` (a Go binary) hands this string to `cmd /c` as ONE argument escaped the+ * MSVCRT way — wrapped in quotes, every inner `"` written as `\"`. cmd.exe does not understand `\"`,+ * so the codex form (`cmd.exe /d /c call "<wrapper> " <Event>`) failed with exit 1 under the real+ * `agy` 1.2.3 — and exit 1 on `PreToolUse` DENIES the tool, in every `agy` on the machine. Without+ * quotes an absolute path breaks at the first space of a profile like `C:\Users\John Doe`.+ *+ * WHY RELATIVE. `agy` runs a hook with its cwd set to the directory holding the hooks.json+ * (vendor-documented in its `hooks.md`, and measured on agy 1.2.3). Our script dir and that directory+ * both live under the same home, so the relative path carries no profile name and no space, and+ * the hooks.json reads the same on every machine. IF A FUTURE `agy` CHANGES THAT CWD, the guard+ * below finds nothing and the command falls silent: tools keep running, only the badge goes dark.+ *+ * WHY THE GUARD. A missing target makes cmd print "is not recognized" and exit 1 — a DENY for+ * every tool. `if exist` turns "nodeterm is gone" into silence, and `& exit 0` pins the status+ * (silence + exit 0 was measured running normally for every event). No `/d`-carrying nested+ * cmd.exe: the outer `cmd /c` is agy's own, and nesting only reintroduced quoting.+ *+ * `relativeDir` is the wrapper's directory relative to the hooks.json directory; the event is one+ * of `agy`'s own names. Both are refused unless they are made of characters that need no quoting.+ */+export function buildAntigravityWindowsCommand(relativeDir: string, event: string): string {+ if (!/^[A-Za-z]+$/.test(event)) throw new Error(`invalid antigravity event: ${event}`)+ if (!SAFE_RELATIVE_DIR.test(relativeDir)) {+ throw new Error(`antigravity wrapper dir is not a quote-free relative path: ${relativeDir}`)+ }+ const target = `${relativeDir.replace(/\\+$/, '')}\\${ANTIGRAVITY_WINDOWS_WRAPPER_FILE}`+ return `if exist ${target} (call ${target} ${event}) & exit 0`+}diff --git a/src/core/agents/hooks/antigravity.test.ts b/src/core/agents/hooks/antigravity.test.tsnew file mode 100644index 000000000..2d77f1e44--- /dev/null+++ b/src/core/agents/hooks/antigravity.test.ts@@ -0,0 +1,844 @@+// The Antigravity installer and its Windows wrapper.+//+// Every case here writes into a TEMP directory. The real `~/.gemini/config/hooks.json` is global —+// a mistake there denies tools in every `agy` on the machine — so nothing in this file may default+// to it: the installer is called with `hooksJson`/`scriptPath`, or with its defaults under a spied+// `os.homedir` pointing at a temp dir (and that case also checks the real file was not touched).+import { describe, it, expect, afterAll, afterEach, beforeAll, vi } from 'vitest'+import { createServer, type Server } from 'node:http'+import type { AddressInfo } from 'node:net'+import osDefault from 'os'+import { spawnSync } from 'node:child_process'+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync, statSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import {+ ANTIGRAVITY_BUNDLE_KEY,+ ANTIGRAVITY_HOOK_TIMEOUT,+ agyFallbackPaths,+ antigravityCommandFor,+ findAgy,+ antigravityHooksJsonPath,+ applyAntigravityBundle,+ buildAntigravityBundle,+ installAntigravityHooks,+ installAntigravityHooksWithProbe,+ isAntigravityManagedCommand,+ removeAntigravityHooks+} from './antigravity'+import {+ ANTIGRAVITY_WINDOWS_WRAPPER_FILE,+ buildAntigravityWindowsCommand,+ buildAntigravityWindowsWrapper+} from './antigravity-windows-wrapper'+import { buildCodexWindowsWrapper } from './codex-windows-wrapper'+import { defaultWindowsCmdExe } from './codex'+import { buildManagedScript } from './managed-script'+import { ANTIGRAVITY_EVENTS, antigravityDecisionFor } from './antigravity-decision'+import { ANTIGRAVITY_HOOK_EVENTS } from '@shared/agents/hook-events'+import type { CmdAutoRunCheck } from './antigravity-autorun'++const T = 60_000+const root = mkdtempSync(join(tmpdir(), 'nt agy install '))+// BEST EFFORT on purpose. On Windows the dispatch cases leave the hook's backgrounded POST running+// under Git's `bin\sh.exe` launcher with its cwd inside this tree, and that holds a directory until+// the worker exits (measured: the same rmSync succeeds right after the run). A leftover temp dir is+// not a test failure.+afterAll(() => {+ try {+ rmSync(root, { recursive: true, force: true, maxRetries: 8, retryDelay: 250 })+ } catch {+ /* left in the OS temp dir */+ }+})+let seq = 0+const fresh = (): string => {+ const d = join(root, `c${++seq}`)+ mkdirSync(d, { recursive: true })+ return d+}++const POSIX_SCRIPT = '/home/u/.nodeterm/agent-hooks/antigravity.sh'+// The registry is never read by these tests: every Windows install gets an injected AutoRun verdict.+const CLEAR = (): CmdAutoRunCheck => ({ kind: 'clear' })+// Every install here happens on a machine that HAS agy (the no-agy refusal has its own tests).+const HAS_AGY = (): string => 'C:/fake/agy.exe'+const read = (f: string): Record<string, unknown> => JSON.parse(readFileSync(f, 'utf8'))+const install = (hooksJson: string, platform = 'linux') =>+ installAntigravityHooks({ findAgy: HAS_AGY, hooksJson, platform, scriptPath: POSIX_SCRIPT, writeScript: false })++describe('where it writes', () => {+ it('targets ~/.gemini/config/hooks.json — never settings.json or GEMINI.md', () => {+ expect(antigravityHooksJsonPath('/h')).toBe(join('/h', '.gemini', 'config', 'hooks.json'))+ })+})++describe('the bundle', () => {+ it('subscribes exactly the four events, in the two shapes agy expects', () => {+ const bundle = buildAntigravityBundle((ev) => `cmd-${ev}`)+ expect(Object.keys(bundle)).toEqual(['PreInvocation', 'PreToolUse', 'PostToolUse', 'Stop'])+ expect(bundle.PreInvocation).toEqual([{ type: 'command', command: 'cmd-PreInvocation', timeout: 5 }])+ expect(bundle.Stop).toEqual([{ type: 'command', command: 'cmd-Stop', timeout: 5 }])+ expect(bundle.PreToolUse).toEqual([+ { matcher: '*', hooks: [{ type: 'command', command: 'cmd-PreToolUse', timeout: 5 }] }+ ])+ expect(bundle.PostToolUse).toEqual([+ { matcher: '*', hooks: [{ type: 'command', command: 'cmd-PostToolUse', timeout: 5 }] }+ ])+ expect(ANTIGRAVITY_HOOK_TIMEOUT).toBe(5)+ // PostInvocation is deliberately not subscribed.+ expect(ANTIGRAVITY_HOOK_EVENTS.map((e) => (typeof e === 'string' ? e : e.event))).not.toContain('PostInvocation')+ })++ it('POSIX command: exports the event and carries the table answer as its fallback', () => {+ for (const ev of ['PreInvocation', 'PreToolUse', 'PostToolUse', 'Stop']) {+ const c = antigravityCommandFor(POSIX_SCRIPT, ev, 'linux')+ expect(c.startsWith(`NODETERM_AGY_EVENT='${ev}'; export NODETERM_AGY_EVENT; `)).toBe(true)+ expect(c).toContain(`printf '%s\\n' '${antigravityDecisionFor(ev)}'; cat >/dev/null`)+ expect(isAntigravityManagedCommand(c)).toBe(true)+ }+ })++ it('Windows command: relative to the hooks.json dir, guarded, no quotes, then the event', () => {+ const c = antigravityCommandFor(+ 'C:\\Users\\John Doe\\.nodeterm\\agent-hooks\\antigravity.sh',+ 'Stop',+ 'win32',+ 'C:\\Users\\John Doe\\.gemini\\config\\hooks.json'+ )+ expect(c).toBe(+ 'if exist ..\\..\\.nodeterm\\agent-hooks\\antigravity-hook.cmd ' ++ '(call ..\\..\\.nodeterm\\agent-hooks\\antigravity-hook.cmd Stop) & exit 0'+ )+ expect(c).not.toContain('"')+ expect(c).not.toContain('John Doe')+ expect(isAntigravityManagedCommand(c)).toBe(true)+ })++ it('Windows command: refuses anything that would need quoting', () => {+ const rel = '..\\..\\.nodeterm\\agent-hooks'+ expect(() => buildAntigravityWindowsCommand(rel, 'Stop & calc')).toThrow()+ expect(() => buildAntigravityWindowsCommand(rel, '')).toThrow()+ for (const bad of ['..\\Other Dir\\agent-hooks', 'D:\\x\\agent-hooks', '..\\a"b', '..\\a&b', '..\\a(b)', '..\\%x%', '']) {+ expect(() => buildAntigravityWindowsCommand(bad, 'Stop'), bad).toThrow()+ }+ // A different drive has no relative path at all: path.win32.relative answers absolute.+ expect(() =>+ antigravityCommandFor('D:\\nt\\agent-hooks\\antigravity.sh', 'Stop', 'win32', 'C:\\h\\.gemini\\config\\hooks.json')+ ).toThrow()+ })++ it('recognizes both leaves on every platform, and nothing foreign', () => {+ expect(isAntigravityManagedCommand('sh /x/agent-hooks/antigravity.sh')).toBe(true)+ expect(isAntigravityManagedCommand('C:\\x\\agent-hooks\\antigravity-hook.cmd Stop')).toBe(true)+ expect(isAntigravityManagedCommand('sh /x/agent-hooks/gemini.sh')).toBe(false)+ expect(isAntigravityManagedCommand('/opt/other-tool/antigravity.sh')).toBe(false)+ expect(isAntigravityManagedCommand(undefined)).toBe(false)+ expect(isAntigravityManagedCommand(7)).toBe(false)+ })+})++describe('installAntigravityHooks / removeAntigravityHooks', () => {+ it('creates a missing hooks.json (and its directory) with exactly our bundle', () => {+ const f = join(fresh(), 'config', 'hooks.json')+ install(f)+ const data = read(f)+ expect(Object.keys(data)).toEqual([ANTIGRAVITY_BUNDLE_KEY])+ expect(data[ANTIGRAVITY_BUNDLE_KEY]).toEqual(buildAntigravityBundle((ev) => antigravityCommandFor(POSIX_SCRIPT, ev, 'linux')))+ })++ it('installing twice leaves ONE entry per event (#558)', () => {+ const f = join(fresh(), 'hooks.json')+ install(f)+ install(f)+ const bundle = read(f)[ANTIGRAVITY_BUNDLE_KEY] as Record<string, unknown[]>+ for (const ev of Object.keys(bundle)) expect(bundle[ev], ev).toHaveLength(1)+ expect(JSON.stringify(read(f)).match(/agent-hooks\/antigravity\.sh/g)).toHaveLength(8)+ })++ it('keeps every foreign bundle exactly as it was, another tool\'s included', () => {+ const f = join(fresh(), 'hooks.json')+ const otherTool = {+ PreToolUse: [{ matcher: '*', hooks: [{ type: 'command', command: 'C:\\other-tool\\PreToolUse.cmd' }] }],+ Stop: [{ type: 'command', command: 'C:\\other-tool\\Stop.cmd' }]+ }+ const mine = { enabled: false, PreInvocation: [{ type: 'command', command: 'echo hi', timeout: 30 }] }+ writeFileSync(f, JSON.stringify({ 'other-tool': otherTool, 'my-bundle': mine, weird: 42 }), 'utf8')+ install(f)+ const data = read(f)+ expect(data['other-tool']).toEqual(otherTool)+ expect(data['my-bundle']).toEqual(mine)+ expect(data.weird).toBe(42)+ expect(Object.keys(data)).toEqual(['other-tool', 'my-bundle', 'weird', ANTIGRAVITY_BUNDLE_KEY])+ })++ it('sweeps a stray entry of ours out of another bundle, keeping its neighbours', () => {+ const f = join(fresh(), 'hooks.json')+ writeFileSync(+ f,+ JSON.stringify({+ other: {+ Stop: [+ { type: 'command', command: 'C:\\Users\\u\\.nodeterm\\agent-hooks\\antigravity-hook.cmd Stop' },+ { type: 'command', command: 'keep-me' }+ ],+ PreToolUse: [+ { matcher: '*', hooks: [{ type: 'command', command: "sh '/u/.nodeterm/agent-hooks/antigravity.sh'" }] }+ ]+ }+ }),+ 'utf8'+ )+ install(f)+ expect(read(f).other).toEqual({ Stop: [{ type: 'command', command: 'keep-me' }] })+ })++ it('a malformed or non-object hooks.json is left byte-for-byte alone and nothing throws', () => {+ for (const body of ['{ not json', '[1,2,3]', '"a string"', 'null']) {+ const f = join(fresh(), 'hooks.json')+ writeFileSync(f, body, 'utf8')+ expect(() => install(f)).not.toThrow()+ expect(readFileSync(f, 'utf8')).toBe(body)+ expect(() => removeAntigravityHooks({ hooksJson: f })).not.toThrow()+ expect(readFileSync(f, 'utf8')).toBe(body)+ }+ })++ it('a foreign value it cannot interpret survives untouched', () => {+ const f = join(fresh(), 'hooks.json')+ const odd = { Stop: 'not-an-array', PreToolUse: [null, 3, { matcher: '*', hooks: 'x' }] }+ writeFileSync(f, JSON.stringify({ odd }), 'utf8')+ install(f)+ expect(read(f).odd).toEqual(odd)+ })++ it('remove leaves everything of the user and nothing of ours', () => {+ const f = join(fresh(), 'hooks.json')+ const mine = { Stop: [{ type: 'command', command: 'keep-me' }] }+ writeFileSync(f, JSON.stringify({ mine }), 'utf8')+ install(f)+ removeAntigravityHooks({ hooksJson: f })+ expect(read(f)).toEqual({ mine })+ // Removing again, or from a file that does not exist, is a no-op.+ removeAntigravityHooks({ hooksJson: f })+ const missing = join(fresh(), 'hooks.json')+ removeAntigravityHooks({ hooksJson: missing })+ expect(existsSync(missing)).toBe(false)+ })++ it('a top-level "__proto__" key survives install AND withdrawal (a plain assignment would set the prototype and drop it)', () => {+ const f = join(fresh(), 'hooks.json')+ writeFileSync(f, '{"__proto__":{"Stop":[{"type":"command","command":"keep"}]},"mine":{"enabled":false}}', 'utf8')+ const own = (o: object, k: string) => Object.prototype.hasOwnProperty.call(o, k)+ install(f)+ const installed = read(f)+ expect(own(installed, '__proto__')).toBe(true)+ expect(Object.getOwnPropertyDescriptor(installed, '__proto__')?.value).toEqual({+ Stop: [{ type: 'command', command: 'keep' }]+ })+ expect(own(installed, ANTIGRAVITY_BUNDLE_KEY)).toBe(true)+ expect(removeAntigravityHooks({ hooksJson: f })).toBe('withdrawn')+ const removed = read(f)+ expect(Object.keys(removed)).toEqual(['__proto__', 'mine'])+ expect(own(removed, ANTIGRAVITY_BUNDLE_KEY)).toBe(false)+ })++ it('a "__proto__" key inside a foreign bundle survives the sweep of a stray entry of ours', () => {+ const out = applyAntigravityBundle(+ JSON.parse(+ '{"other":{"__proto__":[{"type":"command","command":"keep"}],"Stop":[{"type":"command","command":"sh /u/agent-hooks/antigravity.sh"}]}}'+ ),+ null+ )+ expect(JSON.stringify(out)).toBe('{"other":{"__proto__":[{"type":"command","command":"keep"}]}}')+ })++ it('a file with nothing of ours but a "__proto__" key is left byte-for-byte on withdrawal', () => {+ const f = join(fresh(), 'hooks.json')+ const body = '{"__proto__":{"x":1}, "mine":{}}'+ writeFileSync(f, body, 'utf8')+ expect(removeAntigravityHooks({ hooksJson: f })).toBe('absent')+ expect(readFileSync(f, 'utf8')).toBe(body)+ })++ it('applyAntigravityBundle returns an untouched foreign bundle by identity', () => {+ const foreign = { Stop: [{ type: 'command', command: 'x' }], PreToolUse: [] }+ expect(applyAntigravityBundle({ foreign }, null).foreign).toBe(foreign)+ })++ it("keeps a foreign event that was already empty when it sweeps another of that bundle's events", () => {+ const out = applyAntigravityBundle(+ { foreign: { PostToolUse: [], Stop: [{ type: 'command', command: 'sh /u/agent-hooks/antigravity.sh' }] } },+ null+ )+ expect(out.foreign).toEqual({ PostToolUse: [] })+ })++ it('the default hooks.json path follows a spied os.homedir, so a registry test cannot reach the real file', () => {+ const fake = fresh()+ const spy = vi.spyOn(osDefault, 'homedir').mockReturnValue(fake)+ try {+ expect(antigravityHooksJsonPath()).toBe(join(fake, '.gemini', 'config', 'hooks.json'))+ } finally {+ spy.mockRestore()+ }+ })++ it('on win32 every event points at the one wrapper, relative and guarded, with the event as its argument', () => {+ const home = join(fresh(), 'John Doe')+ const f = join(home, '.gemini', 'config', 'hooks.json')+ installAntigravityHooks({ findAgy: HAS_AGY,+ hooksJson: f,+ platform: 'win32',+ readAutoRun: CLEAR,+ scriptPath: join(home, '.nodeterm', 'agent-hooks', 'antigravity.sh'),+ writeScript: false+ })+ const data = read(f)+ const text = JSON.stringify(data)+ for (const ev of ['PreInvocation', 'PreToolUse', 'PostToolUse', 'Stop']) {+ expect(text).toContain(+ JSON.stringify(+ `if exist ..\\..\\.nodeterm\\agent-hooks\\antigravity-hook.cmd (call ..\\..\\.nodeterm\\agent-hooks\\antigravity-hook.cmd ${ev}) & exit 0`+ )+ )+ }+ // No profile name (and so no space) and no quote anywhere in a command.+ for (const cmd of text.match(/"command":"[^"\\]*(?:\\.[^"\\]*)*"/g) ?? []) {+ expect(cmd).not.toContain('John Doe')+ expect(JSON.parse(`{${cmd}}`).command).not.toContain('"')+ }+ expect(text).not.toContain('[ -r')+ })++ it('on win32 a layout that would need quotes installs NOTHING (a quoted command is a DENY)', () => {+ const f = join(fresh(), 'hooks.json')+ // The script dir is outside the hooks.json tree through a directory with a space.+ installAntigravityHooks({ findAgy: HAS_AGY,+ hooksJson: f,+ platform: 'win32',+ readAutoRun: CLEAR,+ scriptPath: join(fresh(), 'Other Dir', 'agent-hooks', 'antigravity.sh'),+ writeScript: false+ })+ expect(existsSync(f)).toBe(false)+ })+})++describe('the Windows wrapper (content)', () => {+ const w = buildAntigravityWindowsWrapper()++ it('is CRLF, disables delayed expansion, exports the event, and always exits 0', () => {+ expect(w).toContain('\r\n')+ expect(w.replace(/\r\n/g, '')).not.toContain('\n')+ expect(w).toContain('setlocal EnableExtensions DisableDelayedExpansion')+ expect(w).toContain('set "NODETERM_AGY_EVENT=%~1"')+ expect(w).not.toMatch(/exit \/b %ERRORLEVEL%|exit \/b [1-9]/)+ expect(w).not.toContain('powershell')+ })++ it('answers from the shared table on the bail path, then drains stdin', () => {+ for (const ev of ANTIGRAVITY_EVENTS) {+ expect(w).toContain(`if "%NODETERM_AGY_EVENT%"=="${ev}" echo ${antigravityDecisionFor(ev)}`)+ }+ expect(w.indexOf('findstr /r ".*" >nul 2>&1')).toBeGreaterThan(w.indexOf(':nt_bail'))+ })++ it('shares the shell search with the codex wrapper, which stays unchanged', () => {+ const codex = buildCodexWindowsWrapper()+ for (const line of codex.split('\r\n').filter((l) => l.startsWith('if not defined NT_SH'))) {+ if (line === 'if not defined NT_SH goto :nt_drain') continue+ expect(w).toContain(line)+ }+ // Pinned bytes of the codex wrapper as it was before the probe lines were shared.+ expect(codex).toBe(+ [+ '@echo off',+ 'rem Managed by nodeterm (agent-hooks). Regenerated on every app launch; edits are lost.',+ 'setlocal EnableExtensions',+ 'set "NT_SCRIPT=%~dp0codex.sh"',+ 'if not exist "%NT_SCRIPT%" goto :nt_drain',+ 'set "NT_SH="',+ 'if not defined NT_SH if exist "%ProgramFiles%\\Git\\bin\\sh.exe" set "NT_SH=%ProgramFiles%\\Git\\bin\\sh.exe"',+ 'if not defined NT_SH if exist "%ProgramFiles%\\Git\\usr\\bin\\sh.exe" set "NT_SH=%ProgramFiles%\\Git\\usr\\bin\\sh.exe"',+ 'if not defined NT_SH if exist "%ProgramFiles(x86)%\\Git\\bin\\sh.exe" set "NT_SH=%ProgramFiles(x86)%\\Git\\bin\\sh.exe"',+ 'if not defined NT_SH if exist "%ProgramFiles(x86)%\\Git\\usr\\bin\\sh.exe" set "NT_SH=%ProgramFiles(x86)%\\Git\\usr\\bin\\sh.exe"',+ 'if not defined NT_SH if exist "%LOCALAPPDATA%\\Programs\\Git\\bin\\sh.exe" set "NT_SH=%LOCALAPPDATA%\\Programs\\Git\\bin\\sh.exe"',+ 'if not defined NT_SH if exist "%LOCALAPPDATA%\\Programs\\Git\\usr\\bin\\sh.exe" set "NT_SH=%LOCALAPPDATA%\\Programs\\Git\\usr\\bin\\sh.exe"',+ 'if not defined NT_SH for %%I in (sh.exe) do if not defined NT_SH set "NT_SH=%%~$PATH:I"',+ 'if not defined NT_SH goto :nt_drain',+ 'set "NT_ARG=%NT_SCRIPT:\\=/%"',+ '"%NT_SH%" "%NT_ARG%"',+ 'exit /b %ERRORLEVEL%',+ ':nt_drain',+ 'rem No shell or no script: consume the payload codex wrote to our stdin, then succeed.',+ 'rem Bailing without reading can EPIPE the writer mid-payload (#186/#187).',+ 'findstr /r ".*" >nul 2>&1',+ 'exit /b 0',+ ''+ ].join('\r\n')+ )+ })+})++/**+ * AS AGY DISPATCHES IT. `agy` (a Go binary) passes the hooks.json command to `cmd /c` as ONE+ * argument, escaped the MSVCRT way: wrapped in quotes, inner `"` written as `\"`, with the hook's+ * cwd set to the directory holding hooks.json. Node's default (non-verbatim) spawn uses the same+ * escaping, and it reproduced agy 1.2.3's behaviour byte for byte on Windows 11 — so these cases run+ * the real command WITHOUT `windowsVerbatimArguments`, from the hooks.json directory, under a home+ * with a space in its name (a profile like `C:\Users\John Doe`).+ *+ * The POST is observed on a REAL loopback listener, not a fake curl: the wrapper picks Git's+ * `bin\sh.exe`, a launcher that puts Git's own curl first on PATH, so a PATH-planted stand-in is+ * never reached. (The real-agy runs posted to a listener the same way.)+ */+describe.skipIf(process.platform !== 'win32')('the Windows command as agy dispatches it', () => {+ const received: Record<string, string>[] = []+ let port = 0+ let server: Server | undefined+ beforeAll(async () => {+ server = createServer((req, res) => {+ const chunks: Buffer[] = []+ req.on('data', (c: Buffer) => chunks.push(c))+ req.on('end', () => {+ received.push(Object.fromEntries(new URLSearchParams(Buffer.concat(chunks).toString('utf8'))))+ res.writeHead(204)+ res.end()+ })+ })+ await new Promise<void>((resolve) => server!.listen(0, '127.0.0.1', resolve))+ port = (server.address() as AddressInfo).port+ })+ afterAll(() => {+ server?.close()+ })++ let nodeSeq = 0+ interface Layout {+ home: string+ configDir: string+ hooksDir: string+ nodeId: string+ command: (ev: string) => string+ }+ const layout = (opts: { wrapper: boolean; script: boolean }): Layout => {+ const home = join(fresh(), 'John Doe')+ const configDir = join(home, '.gemini', 'config')+ const hooksDir = join(home, '.nodeterm', 'agent-hooks')+ mkdirSync(configDir, { recursive: true })+ mkdirSync(hooksDir, { recursive: true })+ const script = join(hooksDir, 'antigravity.sh')+ if (opts.wrapper) writeFileSync(join(hooksDir, ANTIGRAVITY_WINDOWS_WRAPPER_FILE), buildAntigravityWindowsWrapper(), 'utf8')+ if (opts.script) writeFileSync(script, buildManagedScript('antigravity', null), 'utf8')+ writeFileSync(+ join(home, '.nodeterm', 'hook-endpoint.env'),+ `NODETERM_HOOK_PORT=${port}\nNODETERM_HOOK_TOKEN=t\nNODETERM_HOOK_VERSION=2\n`,+ 'utf8'+ )+ const hooksJson = join(configDir, 'hooks.json')+ const nodeId = `term-agy-dispatch-${++nodeSeq}`+ return { home, configDir, hooksDir, nodeId, command: (ev) => antigravityCommandFor(script, ev, 'win32', hooksJson) }+ }+ const dispatch = (l: Layout, command: string, input = '{"conversationId":"c"}') => {+ const env: Record<string, string | undefined> = {+ ...process.env,+ HOME: l.home,+ USERPROFILE: l.home,+ NODETERM_NODE_ID: l.nodeId,+ NODETERM_HOOK_ENDPOINT: join(l.home, '.nodeterm', 'hook-endpoint.env')+ }+ delete env.NODETERM_AGY_EVENT+ // NO windowsVerbatimArguments: Node escapes the command exactly as agy does.+ return spawnSync(process.env.ComSpec || 'cmd.exe', ['/c', command], { input, env, cwd: l.configDir, timeout: T })+ }+ const out = (r: ReturnType<typeof dispatch>): string => r.stdout.toString().replace(/\r\n/g, '\n')+ /** One node's POSTs, waiting ASYNCHRONOUSLY so the listener gets to run. */+ const posts = async (nodeId: string, count: number): Promise<Record<string, string>[]> => {+ const deadline = Date.now() + 15_000+ for (;;) {+ const mine = received.filter((r) => r.nodeId === nodeId)+ if (mine.length >= count || Date.now() > deadline) return mine+ await new Promise((r) => setTimeout(r, 100))+ }+ }++ it('wrapper and script present: every event answers its table row, exit 0, and is POSTed', async () => {+ for (const ev of ANTIGRAVITY_EVENTS) {+ const l = layout({ wrapper: true, script: true })+ const r = dispatch(l, l.command(ev))+ expect(r.status, ev).toBe(0)+ expect(out(r), ev).toBe(`${antigravityDecisionFor(ev)}\n`)+ const p = await posts(l.nodeId, 1)+ expect(p, ev).toHaveLength(1)+ expect(p[0].nodeterm_hook_event, ev).toBe(ev)+ expect(JSON.parse(p[0].payload), ev).toEqual({ conversationId: 'c' })+ }+ }, T)++ it('wrapper ABSENT: stdout empty, exit 0, no POST — silence, never a DENY', async () => {+ for (const ev of ANTIGRAVITY_EVENTS) {+ const l = layout({ wrapper: false, script: true })+ const r = dispatch(l, l.command(ev))+ expect(r.status, ev).toBe(0)+ expect(out(r), ev).toBe('')+ expect(r.stderr.toString(), ev).toBe('')+ await new Promise((res) => setTimeout(res, 300))+ expect(received.filter((x) => x.nodeId === l.nodeId), ev).toHaveLength(0)+ }+ }, T)++ it('script ABSENT: the wrapper answers the table row itself, exit 0', () => {+ for (const ev of ANTIGRAVITY_EVENTS) {+ const l = layout({ wrapper: true, script: false })+ const r = dispatch(l, l.command(ev))+ expect(r.status, ev).toBe(0)+ expect(out(r), ev).toBe(`${antigravityDecisionFor(ev)}\n`)+ }+ }, T)++ it('an unknown event prints nothing, exit 0', () => {+ const l = layout({ wrapper: true, script: true })+ const r = dispatch(l, buildAntigravityWindowsCommand('..\\..\\.nodeterm\\agent-hooks', 'Bogus'))+ expect(r.status).toBe(0)+ expect(out(r)).toBe('')+ }, T)++ it('a 200 KB stdin neither blocks nor breaks the answer', () => {+ const l = layout({ wrapper: true, script: true })+ const r = dispatch(l, l.command('PreToolUse'), JSON.stringify({ blob: 'x'.repeat(200_000) }))+ expect(r.status).toBe(0)+ expect(out(r)).toBe('{"decision":"ask"}\n')+ }, T)++ it('NEVER GO BACK: the codex-style quoted command fails under this dispatch (exit 1 = DENY)', () => {+ // The form first adopted from codex.ts. Against the real agy 1.2.3 it failed with+ // `'\"C:\...\antigravity-hook.cmd \"' is not recognized`, exit 1, denying every tool. Pinned so+ // nobody "fixes" the command back to it.+ const l = layout({ wrapper: true, script: true })+ const quoted = `${defaultWindowsCmdExe()} /d /c call "${l.hooksDir}\\${ANTIGRAVITY_WINDOWS_WRAPPER_FILE} " PreToolUse`+ const r = dispatch(l, quoted)+ expect(r.status).toBe(1)+ expect(out(r)).toBe('')+ expect(r.stderr.toString()).toContain('\\"')+ }, T)+})++/**+ * The installer-registry test+ * (`index.test.ts`) spies `os.homedir` and calls the installers with their DEFAULTS. Once this+ * installer is registered, that call must land in the fake home — script, wrapper AND the global+ * hooks.json — and never in the real one. This calls the installer the same way, with the same spy.+ */+describe('the default install follows a spied os.homedir (as index.test.ts calls it)', () => {+ it('writes hooks.json, script and wrapper under the fake home, and leaves the real hooks.json alone', () => {+ const realHooks = antigravityHooksJsonPath()+ const before = existsSync(realHooks) ? statSync(realHooks).mtimeMs : null+ const fake = join(fresh(), 'Fake Home')+ mkdirSync(fake, { recursive: true })+ const spy = vi.spyOn(osDefault, 'homedir').mockReturnValue(fake)+ try {+ installAntigravityHooks({ findAgy: HAS_AGY, readAutoRun: CLEAR })+ } finally {+ spy.mockRestore()+ }+ const hooksJson = join(fake, '.gemini', 'config', 'hooks.json')+ expect(existsSync(hooksJson)).toBe(true)+ expect(Object.keys(read(hooksJson))).toEqual([ANTIGRAVITY_BUNDLE_KEY])+ expect(existsSync(join(fake, '.nodeterm', 'agent-hooks', 'antigravity.sh'))).toBe(true)+ expect(existsSync(join(fake, '.nodeterm', 'agent-hooks', ANTIGRAVITY_WINDOWS_WRAPPER_FILE))).toBe(+ process.platform === 'win32'+ )+ const after = existsSync(realHooks) ? statSync(realHooks).mtimeMs : null+ expect(after).toBe(before)+ expect(realHooks.startsWith(fake)).toBe(false)+ })+})++/**+ * The hook exists only where agy does. Without agy there is no gate to install in front of anybody's+ * tools, and nothing of ours should be on disk; an agy installed later gets the hook at the next+ * launch, and a bundle left from a machine that once had agy is withdrawn.+ */+describe('install only where agy is installed', () => {+ const NO_AGY = (): null => null+ const layout = () => {+ const home = join(fresh(), 'John Doe')+ const hooksJson = join(home, '.gemini', 'config', 'hooks.json')+ const script = join(home, '.nodeterm', 'agent-hooks', 'antigravity.sh')+ return {+ hooksJson,+ script,+ wrapper: join(home, '.nodeterm', 'agent-hooks', ANTIGRAVITY_WINDOWS_WRAPPER_FILE)+ }+ }++ it.each(['win32', 'linux'])('no agy, no file (%s) → nothing written, nothing logged, registry never read', (platform) => {+ const l = layout()+ let registryReads = 0+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ try {+ installAntigravityHooks({+ hooksJson: l.hooksJson,+ platform,+ scriptPath: l.script,+ findAgy: NO_AGY,+ readAutoRun: () => {+ registryReads+++ return { kind: 'clear' }+ }+ })+ expect(warn).not.toHaveBeenCalled()+ } finally {+ warn.mockRestore()+ }+ expect(existsSync(l.hooksJson)).toBe(false)+ expect(existsSync(l.script)).toBe(false)+ expect(existsSync(l.wrapper)).toBe(false)+ expect(registryReads).toBe(0)+ })++ it('no agy, our bundle present → withdrawn, foreign keys intact, and the log says why', () => {+ const l = layout()+ mkdirSync(join(l.hooksJson, '..'), { recursive: true })+ writeFileSync(l.hooksJson, JSON.stringify({ mine: { enabled: false } }), 'utf8')+ installAntigravityHooks({ hooksJson: l.hooksJson, platform: 'win32', scriptPath: l.script, findAgy: HAS_AGY, readAutoRun: CLEAR })+ expect(read(l.hooksJson)[ANTIGRAVITY_BUNDLE_KEY]).toBeDefined()++ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ try {+ installAntigravityHooks({ hooksJson: l.hooksJson, platform: 'win32', scriptPath: l.script, findAgy: NO_AGY, readAutoRun: CLEAR })+ const text = warn.mock.calls.map((c) => String(c[0])).join('\n')+ expect(text).toContain('agy is not installed')+ expect(text).toContain('was withdrawn')+ } finally {+ warn.mockRestore()+ }+ expect(read(l.hooksJson)).toEqual({ mine: { enabled: false } })+ })++ it('a detector that throws counts as "not installed"', () => {+ const l = layout()+ installAntigravityHooks({+ hooksJson: l.hooksJson,+ platform: 'linux',+ scriptPath: l.script,+ findAgy: () => {+ throw new Error('EACCES')+ }+ })+ expect(existsSync(l.hooksJson)).toBe(false)+ })++ it('agy present → installs exactly as before', () => {+ const l = layout()+ installAntigravityHooks({ hooksJson: l.hooksJson, platform: 'win32', scriptPath: l.script, findAgy: HAS_AGY, readAutoRun: CLEAR })+ expect(Object.keys(read(l.hooksJson))).toEqual([ANTIGRAVITY_BUNDLE_KEY])+ expect(existsSync(l.script)).toBe(true)+ expect(existsSync(l.wrapper)).toBe(true)+ })++ it('the vendor install locations, per platform', () => {+ expect(agyFallbackPaths('win32', 'C:\\Users\\John Doe', { LOCALAPPDATA: 'D:\\Local' })).toEqual([+ 'D:\\Local\\agy\\bin\\agy.exe'+ ])+ expect(agyFallbackPaths('win32', 'C:\\Users\\John Doe', {})).toEqual([+ 'C:\\Users\\John Doe\\AppData\\Local\\agy\\bin\\agy.exe'+ ])+ expect(agyFallbackPaths('darwin', '/Users/jd', {})).toEqual(['/Users/jd/.local/bin/agy'])+ expect(agyFallbackPaths('linux', '/home/jd', { LOCALAPPDATA: 'ignored' })).toEqual(['/home/jd/.local/bin/agy'])+ })++ describe('findAgy against a fake machine (a file lookup, never a spawn)', () => {+ const saved = { PATH: process.env.PATH, LOCALAPPDATA: process.env.LOCALAPPDATA }+ afterEach(() => {+ process.env.PATH = saved.PATH+ if (saved.LOCALAPPDATA === undefined) delete process.env.LOCALAPPDATA+ else process.env.LOCALAPPDATA = saved.LOCALAPPDATA+ vi.restoreAllMocks()+ })+ const binName = process.platform === 'win32' ? 'agy.exe' : 'agy'+ const plant = (dir: string): string => {+ mkdirSync(dir, { recursive: true })+ const file = join(dir, binName)+ writeFileSync(file, '', { mode: 0o755 })+ return file+ }+ const same = (a: string | null, b: string) => expect(a?.toLowerCase()).toBe(b.toLowerCase())++ it('finds agy on the PATH', () => {+ const dir = join(fresh(), 'path bin')+ const file = plant(dir)+ const emptyHome = fresh()+ vi.spyOn(osDefault, 'homedir').mockReturnValue(emptyHome)+ process.env.LOCALAPPDATA = join(emptyHome, 'nothing-here')+ process.env.PATH = dir+ same(findAgy(), file)+ })++ it('finds agy at the vendor install location when the PATH does not have it', () => {+ const home = fresh()+ vi.spyOn(osDefault, 'homedir').mockReturnValue(home)+ process.env.PATH = join(fresh(), 'empty')+ let file: string+ if (process.platform === 'win32') {+ process.env.LOCALAPPDATA = join(home, 'AppData', 'Local')+ file = plant(join(home, 'AppData', 'Local', 'agy', 'bin'))+ } else {+ file = plant(join(home, '.local', 'bin'))+ }+ same(findAgy(), file)+ })++ it('answers null when neither has it', () => {+ const home = fresh()+ vi.spyOn(osDefault, 'homedir').mockReturnValue(home)+ process.env.LOCALAPPDATA = join(home, 'AppData', 'Local')+ process.env.PATH = join(fresh(), 'empty')+ expect(findAgy()).toBeNull()+ })+ })+})++/**+ * Two passes around the login-shell PATH probe. At boot the lookup may only see a GUI app's minimal+ * PATH, so a miss there must decide nothing; the decision is made once the probe has settled.+ */+describe('installAntigravityHooksWithProbe — boot pass, then a final pass after the PATH probe', () => {+ const deferred = () => {+ let resolve!: () => void+ let reject!: (e: Error) => void+ const promise = new Promise<void>((res, rej) => {+ resolve = res+ reject = rej+ })+ return { promise, resolve, reject }+ }+ /** A detector that answers from a script of results, and counts its calls. */+ const detector = (...answers: (string | null)[]) => {+ const d = { calls: 0, find: (): string | null => answers[Math.min(d.calls++, answers.length - 1)] }+ return d+ }+ const setup = () => {+ const home = join(fresh(), 'John Doe')+ return {+ hooksJson: join(home, '.gemini', 'config', 'hooks.json'),+ scriptPath: join(home, '.nodeterm', 'agent-hooks', 'antigravity.sh')+ }+ }+ const base = (l: { hooksJson: string; scriptPath: string }, find: () => string | null) => ({+ ...l,+ platform: 'win32' as const,+ findAgy: find,+ readAutoRun: CLEAR+ })++ it('not found at boot, found after the probe → installed by the final pass', async () => {+ const l = setup()+ const d = detector(null, 'C:/x/agy.exe')+ const probe = deferred()+ const done = installAntigravityHooksWithProbe(base(l, d.find), () => probe.promise)+ expect(existsSync(l.hooksJson)).toBe(false)+ probe.resolve()+ await expect(done).resolves.toBe('installed')+ expect(Object.keys(read(l.hooksJson))).toEqual([ANTIGRAVITY_BUNDLE_KEY])+ expect(d.calls).toBe(2)+ })++ it('not found in either pass, with our bundle → withdrawn ONLY by the final pass', async () => {+ const l = setup()+ installAntigravityHooks({ ...base(l, HAS_AGY) })+ mkdirSync(join(l.hooksJson, '..'), { recursive: true })+ const withOther = { ...read(l.hooksJson), 'other-tool': { enabled: false } }+ writeFileSync(l.hooksJson, JSON.stringify(withOther), 'utf8')+ const before = readFileSync(l.hooksJson, 'utf8')++ const probe = deferred()+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ try {+ const done = installAntigravityHooksWithProbe(base(l, detector(null, null).find), () => probe.promise)+ expect(readFileSync(l.hooksJson, 'utf8')).toBe(before) // the boot pass touched nothing+ expect(warn).not.toHaveBeenCalled()+ probe.resolve()+ await expect(done).resolves.toBe('no-agy')+ expect(read(l.hooksJson)).toEqual({ 'other-tool': { enabled: false } })+ expect(String(warn.mock.calls[0]?.[0])).toContain('agy is not installed')+ } finally {+ warn.mockRestore()+ }+ })++ it('not found in either pass, no bundle → nothing written, nothing logged', async () => {+ const l = setup()+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ try {+ await expect(+ installAntigravityHooksWithProbe(base(l, detector(null, null).find), () => Promise.resolve())+ ).resolves.toBe('no-agy')+ expect(warn).not.toHaveBeenCalled()+ } finally {+ warn.mockRestore()+ }+ expect(existsSync(l.hooksJson)).toBe(false)+ expect(existsSync(l.scriptPath)).toBe(false)+ })++ it('found at boot → installed once; no second pass, nothing rewritten', async () => {+ const l = setup()+ const d = detector('C:/x/agy.exe')+ let probed = 0+ const writes: string[] = []+ const done = installAntigravityHooksWithProbe(+ {+ ...base(l, d.find),+ writeFile: (file, data) => {+ writes.push(file)+ mkdirSync(join(file, '..'), { recursive: true })+ writeFileSync(file, `${JSON.stringify(data, null, 2)}\n`, 'utf8')+ }+ },+ () => {+ probed+++ return Promise.resolve()+ }+ )+ await expect(done).resolves.toBe('installed')+ await new Promise((r) => setTimeout(r, 20))+ expect(probed).toBe(0)+ expect(d.calls).toBe(1)+ expect(writes).toEqual([l.hooksJson])+ expect(JSON.stringify(read(l.hooksJson)).match(/antigravity-hook\.cmd/g)).toHaveLength(8)+ })++ it('a probe that FAILS still runs the final pass (with the inherited PATH)', async () => {+ const l = setup()+ const done = installAntigravityHooksWithProbe(base(l, detector(null, 'C:/x/agy.exe').find), () =>+ Promise.reject(new Error('login shell hung'))+ )+ await expect(done).resolves.toBe('installed')+ expect(existsSync(l.hooksJson)).toBe(true)+ })++ it('the final pass writes where the boot pass would have, even if os.homedir changed in between', async () => {+ const fake = join(fresh(), 'Fake Home')+ mkdirSync(fake, { recursive: true })+ const realHooks = antigravityHooksJsonPath()+ const realBefore = existsSync(realHooks) ? statSync(realHooks).mtimeMs : null+ const probe = deferred()+ const spy = vi.spyOn(osDefault, 'homedir').mockReturnValue(fake)+ let done: Promise<unknown>+ try {+ done = installAntigravityHooksWithProbe(+ { platform: 'win32', findAgy: detector(null, 'C:/x/agy.exe').find, readAutoRun: CLEAR },+ () => probe.promise+ )+ } finally {+ spy.mockRestore() // the test that spied is over before the probe answers+ }+ probe.resolve()+ await done+ expect(existsSync(join(fake, '.gemini', 'config', 'hooks.json'))).toBe(true)+ const realAfter = existsSync(realHooks) ? statSync(realHooks).mtimeMs : null+ expect(realAfter).toBe(realBefore)+ })+})diff --git a/src/core/agents/hooks/antigravity.ts b/src/core/agents/hooks/antigravity.tsnew file mode 100644index 000000000..b5689c489--- /dev/null+++ b/src/core/agents/hooks/antigravity.ts@@ -0,0 +1,496 @@+// Antigravity CLI (`agy`) status-hook installer — registered in hooks/index.ts (runs at every launch).+//+// WHERE. `agy` reads its global hooks from `~/.gemini/config/hooks.json` (its bundled+// `json_configs.md`/`hooks.md`: "placed in your customization root directory (e.g., `.agents/` in+// your project, or `~/.gemini/config/` globally)"). The file is keyed by BUNDLE: each top-level key+// is one named bundle whose value maps event names to handlers, and bundles are merged and run in+// sequence. We own exactly one bundle, `nodeterm-status`, and nothing else in the file:+// - every other top-level key survives untouched (another tool's bundle, the user's own);+// - our bundle is REWRITTEN whole on every install (it is ours; there is nothing of the user's+// inside it), which is also what collapses a duplicated install back to one entry (#558);+// - a handler carrying OUR script tail found in any OTHER bundle is swept out, matched through+// `normalizeHookCommand` on both sides (the #558 lesson: Windows separators);+// - `~/.gemini/settings.json` and `~/.gemini/GEMINI.md` are never touched here — they belong to+// the Gemini CLI, and `agy` does not read hooks from settings.json (measured).+//+// Two shapes, per `hooks.md` "Supported Event Types": the tool events are GROUPED+// (`[{matcher, hooks: [handler]}]`) and the lifecycle events are a FLAT handler list.+//+// A hooks.json we cannot parse (or whose top level is not an object) is LEFT ALONE and the install+// is skipped with a warning — the codex installer's precedent. Overwriting would destroy whatever+// the user had in it, and it is their file, not ours.+//+// SAFETY. Subscribing to `PreToolUse` puts this hook in front of every tool call of every `agy` on+// the machine. What keeps that gate open is the stdout contract (antigravity-decision.ts), answered+// by the script, by the POSIX command's own fallback when the script is missing, by the Windows+// wrapper when there is no shell, and — when the wrapper itself is missing — by the Windows+// command's `if exist` guard, which falls silent (see buildAntigravityWindowsCommand). `timeout: 5`+// bounds a hung shell (agy's default is 30 s; our curl is capped at 1.5 s and the POST is+// backgrounded).+import path from 'path'+import os from 'os'+import { readFileSync, mkdirSync, existsSync, chmodSync } from 'fs'+import { ANTIGRAVITY_HOOK_EVENTS, type ManagedHookEvent } from '@shared/agents/hook-events'+import {+ buildManagedHookCommand,+ normalizeHookCommand,+ writeManagedHookFileAtomic+} from './install-helper'+import { buildManagedScript } from './managed-script'+import { ANTIGRAVITY_EVENT_ENV, antigravityDecisionFor } from './antigravity-decision'+import {+ ANTIGRAVITY_SCRIPT_FILE,+ ANTIGRAVITY_WINDOWS_WRAPPER_FILE,+ buildAntigravityWindowsCommand,+ buildAntigravityWindowsWrapper+} from './antigravity-windows-wrapper'+import { readCmdAutoRun, type CmdAutoRunCheck } from './antigravity-autorun'+import { findExecutableSync, resolveShellPath } from '../../exec-path'++/**+ * Where the vendor's own installer puts `agy` (antigravity.google/docs/cli/install): `~/.local/bin`+ * on macOS/Linux, `%LOCALAPPDATA%\agy\bin` on Windows (also where it sits on the machine this was+ * measured on). Checked AFTER the PATH, and they matter because a GUI app on macOS does not inherit+ * the login shell's PATH, and the login-shell PATH probe usually has not answered yet at boot.+ * Pure over its arguments; the home comes from `os.homedir()` via the default import at the call+ * site, so a spied home redirects these too.+ */+export function agyFallbackPaths(+ platform: NodeJS.Platform | string,+ home: string,+ env: Readonly<Record<string, string | undefined>>+): string[] {+ if (platform === 'win32') {+ const local = env.LOCALAPPDATA || path.win32.join(home, 'AppData', 'Local')+ return [path.win32.join(local, 'agy', 'bin', 'agy.exe')]+ }+ return [path.posix.join(home, '.local', 'bin', 'agy')]+}++/**+ * Is `agy` installed on this machine? A file lookup only — PATH (with PATHEXT on Windows) through+ * the shared `findExecutableSync`, then the vendor's install locations. It NEVER runs `agy`: this is+ * asked at every launch, and a `--version` would cost a process start (and, for this CLI, can+ * touch the account). Returns the path found, or null.+ */+export function findAgy(): string | null {+ return findExecutableSync('agy', agyFallbackPaths(process.platform, os.homedir(), process.env))+}++/** Our bundle's key in hooks.json. */+export const ANTIGRAVITY_BUNDLE_KEY = 'nodeterm-status'+/** Seconds `agy` waits for one handler (its own default is 30 s). */+export const ANTIGRAVITY_HOOK_TIMEOUT = 5++export interface AntigravityHandler {+ type: 'command'+ command: string+ timeout: number+}+export interface AntigravityGroup {+ matcher: string+ hooks: AntigravityHandler[]+}+export type AntigravityBundle = Record<string, AntigravityHandler[] | AntigravityGroup[]>+export type AntigravityHooksFile = Record<string, unknown>++// `os.homedir()` through the DEFAULT import, not a named one: a test that spies `os.homedir` (the+// installer-registry test does) then redirects THIS path too. The shared helpers use the named+// import, which the spy does not reach, and the suite rewrites the real `~/.claude/settings.json`+// that way today — for this file, the global agy gate, that is not acceptable.+export function antigravityHooksJsonPath(home: string = os.homedir()): string {+ return path.join(home, '.gemini', 'config', 'hooks.json')+}++const eventName = (e: ManagedHookEvent): string => (typeof e === 'string' ? e : e.event)++/**+ * The command for one event. `platform` is the platform of the machine that will RUN agy (the+ * same parameter rule as codex's builder): Windows gets the guarded relative wrapper call, everything else+ * the POSIX one-liner with the event exported and the table's answer as its missing-script+ * fallback.+ */+export function antigravityCommandFor(+ scriptPath: string,+ event: string,+ platform: NodeJS.Platform | string = process.platform,+ hooksJsonPath: string = antigravityHooksJsonPath()+): string {+ if (platform === 'win32') {+ // Relative to the hooks.json DIRECTORY, which is agy's cwd for the hook (see+ // buildAntigravityWindowsCommand for why the command carries no absolute path and no quotes).+ const rel = path.win32.relative(path.win32.dirname(hooksJsonPath), path.win32.dirname(scriptPath))+ return buildAntigravityWindowsCommand(rel, event)+ }+ const answer = antigravityDecisionFor(event)+ return buildManagedHookCommand(scriptPath, {+ env: { [ANTIGRAVITY_EVENT_ENV]: event },+ ...(answer !== null ? { fallbackStdout: answer } : {})+ })+}++/** Pure: our whole bundle, one handler per subscribed event, in the shape each event takes. */+export function buildAntigravityBundle(+ commandFor: (event: string) => string,+ events: readonly ManagedHookEvent[] = ANTIGRAVITY_HOOK_EVENTS+): AntigravityBundle {+ const bundle: AntigravityBundle = {}+ for (const e of events) {+ const handler: AntigravityHandler = {+ type: 'command',+ command: commandFor(eventName(e)),+ timeout: ANTIGRAVITY_HOOK_TIMEOUT+ }+ bundle[eventName(e)] = typeof e === 'string' ? [handler] : [{ matcher: e.matcher, hooks: [handler] }]+ }+ return bundle+}++/** Does a handler command belong to us? Both leaves, on every platform (codex's #558 rule). */+export function isAntigravityManagedCommand(command: unknown): boolean {+ if (typeof command !== 'string') return false+ const c = normalizeHookCommand(command)+ return (+ c.includes(`agent-hooks/${ANTIGRAVITY_SCRIPT_FILE}`) ||+ c.includes(`agent-hooks/${ANTIGRAVITY_WINDOWS_WRAPPER_FILE}`)+ )+}++const isRecord = (v: unknown): v is Record<string, unknown> =>+ typeof v === 'object' && v !== null && !Array.isArray(v)++/**+ * Copy a key as an OWN property. `JSON.parse` makes a `"__proto__"` key an own property, but+ * `obj['__proto__'] = v` on a plain object sets its PROTOTYPE instead, and `JSON.stringify` then+ * drops the key — so a user's file would lose it on the way through us. Defining the property keeps+ * it, for every key alike.+ */+function setOwn(target: Record<string, unknown>, key: string, value: unknown): void {+ Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true })+}++/**+ * Strip our handlers out of one foreign bundle, leaving everything else as found. Returns the+ * SAME object when nothing of ours is in it, so an untouched bundle is untouched by identity.+ * Anything we cannot interpret is left exactly as found.+ */+function sweepBundle(bundle: unknown): unknown {+ if (!isRecord(bundle)) return bundle+ let changed = false+ const next: Record<string, unknown> = {}+ for (const [event, entries] of Object.entries(bundle)) {+ if (!Array.isArray(entries)) {+ setOwn(next, event, entries)+ continue+ }+ const kept: unknown[] = []+ let removed = false+ for (const entry of entries) {+ if (!isRecord(entry)) {+ kept.push(entry)+ continue+ }+ if (Array.isArray(entry.hooks)) {+ const hooks = entry.hooks.filter((h) => !(isRecord(h) && isAntigravityManagedCommand(h.command)))+ if (hooks.length === entry.hooks.length) kept.push(entry)+ else {+ removed = true+ if (hooks.length) kept.push({ ...entry, hooks })+ }+ continue+ }+ if (isAntigravityManagedCommand(entry.command)) {+ removed = true+ continue+ }+ kept.push(entry)+ }+ if (!removed) {+ setOwn(next, event, entries)+ continue+ }+ changed = true+ // An event we emptied goes away; an event that was already empty is someone else's and stays.+ if (kept.length) setOwn(next, event, kept)+ }+ return changed ? next : bundle+}++/** Pure: the file with our bundle set to `bundle` (or removed when null) and no stray entry of ours. */+export function applyAntigravityBundle(+ file: AntigravityHooksFile,+ bundle: AntigravityBundle | null+): AntigravityHooksFile {+ const next: AntigravityHooksFile = {}+ for (const [key, value] of Object.entries(file)) {+ if (key === ANTIGRAVITY_BUNDLE_KEY) continue+ setOwn(next, key, sweepBundle(value))+ }+ if (bundle) setOwn(next, ANTIGRAVITY_BUNDLE_KEY, bundle)+ return next+}++/** undefined = the file is absent; null = present but not a JSON object we may rewrite. */+function readHooksFile(file: string): AntigravityHooksFile | null | undefined {+ if (!existsSync(file)) return undefined+ try {+ const parsed: unknown = JSON.parse(readFileSync(file, 'utf8'))+ return isRecord(parsed) ? parsed : null+ } catch {+ return null+ }+}++function writeHooksFile(file: string, data: AntigravityHooksFile): void {+ mkdirSync(path.dirname(file), { recursive: true })+ writeManagedHookFileAtomic(file, `${JSON.stringify(data, null, 2)}\n`)+}++/**+ * The machine-wide script location — the same `~/.nodeterm/agent-hooks/` as every other agent+ * (`managedHookScriptPath`), but resolved through `os.homedir()` (default import) for the same+ * reason as `antigravityHooksJsonPath`: a test that spies `os.homedir` must redirect the WHOLE+ * install, script included. `installManagedHookScript` resolves through the named import.+ */+export function antigravityScriptPath(home: string = os.homedir()): string {+ return path.join(home, '.nodeterm', 'agent-hooks', ANTIGRAVITY_SCRIPT_FILE)+}++function writeScriptFile(script: string): void {+ mkdirSync(path.dirname(script), { recursive: true })+ writeManagedHookFileAtomic(script, buildManagedScript('antigravity'), undefined, 0o755)+ try {+ chmodSync(script, 0o755)+ } catch {+ /* fail open */+ }+}++/** The wrapper beside the script — Windows only, and before hooks.json points agy at it. */+function writeWindowsWrapper(scriptPath: string): void {+ const file = path.join(path.dirname(scriptPath), ANTIGRAVITY_WINDOWS_WRAPPER_FILE)+ mkdirSync(path.dirname(file), { recursive: true })+ writeManagedHookFileAtomic(file, buildAntigravityWindowsWrapper())+}++export interface AntigravityInstallOptions {+ /** Defaults to the real `~/.gemini/config/hooks.json`. Tests pass a temp path. */+ hooksJson?: string+ platform?: NodeJS.Platform | string+ /** Where the script lives; defaults to the machine-wide `~/.nodeterm/agent-hooks/`. */+ scriptPath?: string+ /** Write the script + wrapper (true in production; tests may point at a pre-written script). */+ writeScript?: boolean+ /**+ * The cmd.exe AutoRun check, consulted on Windows before anything is written. Injected so tests+ * never depend on (or touch) the real registry; defaults to a read-only `reg query`.+ */+ readAutoRun?: () => CmdAutoRunCheck+ /** Is `agy` installed? Defaults to `findAgy` (a file lookup, never a spawn). Injected by tests. */+ findAgy?: () => string | null+ /**+ * `boot`: the lookup may not have seen the login-shell PATH yet, so a miss decides NOTHING — no+ * write, no withdrawal, no warning. `final` (the default): a miss withdraws our bundle. See+ * `installAntigravityHooksWithProbe`.+ */+ phase?: 'boot' | 'final'+ /** How hooks.json is published (atomic by default). Injected by tests to simulate a failed write. */+ writeFile?: (file: string, data: AntigravityHooksFile) => void+}++/** What one install pass did: `installed`, `no-agy` (agy not found), or `refused` (any other+ * reason nothing was installed: AutoRun, unreadable registry, layout, a failed write). */+export type AntigravityInstallOutcome = 'installed' | 'no-agy' | 'refused'++export function installAntigravityHooks(opts: AntigravityInstallOptions = {}): AntigravityInstallOutcome {+ const platform = opts.platform ?? process.platform+ const hooksJson = opts.hooksJson ?? antigravityHooksJsonPath()+ const script = opts.scriptPath ?? antigravityScriptPath()+ // No agy on this machine ⇒ no gate in front of anybody's tools, and nothing of ours on disk. This+ // is asked FIRST (before the registry read) and on every launch, so an agy installed later gets+ // the hook the next time nodeterm opens — and an agy removed since loses the bundle we wrote.+ let agy: string | null+ try {+ agy = (opts.findAgy ?? findAgy)()+ } catch {+ agy = null+ }+ if (!agy) {+ // Before the login-shell PATH is known a miss proves nothing (a GUI app on macOS/Linux starts+ // with a minimal PATH), so the boot pass leaves the machine exactly as it found it.+ if (opts.phase === 'boot') return 'no-agy'+ const withdrawal = removeAntigravityHooks({ hooksJson, writeFile: opts.writeFile })+ // Silent when there was nothing to do: that is every launch on a machine that never had agy.+ if (withdrawal !== 'absent') {+ console.warn(+ `[agent-hooks] antigravity install skipped: agy is not installed on this machine. ` ++ withdrawalNote(withdrawal, hooksJson)+ )+ }+ return 'no-agy'+ }+ if (platform === 'win32') {+ // agy runs the hook as `cmd /c` WITHOUT /d, so a registry AutoRun runs first and anything it+ // prints turns our answer into a DENY (antigravity-autorun.ts). Refuse before writing anything;+ // an unreadable registry is refused too — not installing costs the badge, installing wrongly+ // costs every tool call. A refusal also WITHDRAWS a bundle an earlier launch installed: this+ // runs at every launch, and an AutoRun that appeared since would otherwise keep denying tools+ // through the old bundle. Removing our bundle can never deny a tool.+ let autoRun: CmdAutoRunCheck+ try {+ autoRun = (opts.readAutoRun ?? readCmdAutoRun)()+ } catch (e) {+ autoRun = { kind: 'unreadable', reason: String(e) }+ }+ if (autoRun.kind === 'set') {+ // Withdraw FIRST, then say what actually happened — the log is the only diagnostic there is.+ const withdrawal = removeAntigravityHooks({ hooksJson, writeFile: opts.writeFile })+ console.warn(+ `[agent-hooks] antigravity install skipped: cmd.exe runs an AutoRun command ` ++ `(${autoRun.entries.map((e) => `${e.key}\\AutoRun`).join(', ')}), and agy starts every hook ` ++ `through cmd without /d — its output would deny tools. ${withdrawalNote(withdrawal, hooksJson)} ` ++ `Remove the AutoRun value to enable Antigravity status.`+ )+ return 'refused'+ }+ if (autoRun.kind === 'unreadable') {+ const withdrawal = removeAntigravityHooks({ hooksJson, writeFile: opts.writeFile })+ console.warn(+ `[agent-hooks] antigravity install skipped: could not read the cmd.exe AutoRun settings ` ++ `(${autoRun.reason}); not installing is the side that cannot deny a tool. ` ++ withdrawalNote(withdrawal, hooksJson)+ )+ return 'refused'+ }+ }+ if (opts.writeScript !== false) {+ try {+ writeScriptFile(script)+ // Before hooks.json points agy at it: the first events after an install must find it.+ if (platform === 'win32') writeWindowsWrapper(script)+ } catch (e) {+ console.warn('[agent-hooks] antigravity script/wrapper write failed', e)+ return 'refused'+ }+ }+ const current = readHooksFile(hooksJson)+ if (current === null) {+ console.warn(`[agent-hooks] antigravity install: ${hooksJson} is not a JSON object; left as is, skipping`)+ return 'refused'+ }+ let bundle: AntigravityBundle+ try {+ bundle = buildAntigravityBundle((ev) => antigravityCommandFor(script, ev, platform, hooksJson))+ } catch (e) {+ // A relative path we cannot write without quotes (different drive, odd characters): writing+ // anything would risk a command that exits 1, i.e. a DENY. Install nothing, and withdraw what+ // an earlier layout installed (it may point at a wrapper that is no longer reachable).+ const withdrawal = removeAntigravityHooks({ hooksJson, writeFile: opts.writeFile })+ console.warn(+ `[agent-hooks] antigravity install skipped: no quote-free command for this layout. ` ++ withdrawalNote(withdrawal, hooksJson),+ e+ )+ return 'refused'+ }+ try {+ ;(opts.writeFile ?? writeHooksFile)(hooksJson, applyAntigravityBundle(current ?? {}, bundle))+ return 'installed'+ } catch (e) {+ console.warn('[agent-hooks] antigravity install failed', e)+ return 'refused'+ }+}++/**+ * The launch-time install, in two passes — the same shape as grok's `$GROK_HOME` re-install in+ * `installManagedAgentHooks`: act now on what is known, and ask again once the login shell has+ * answered.+ *+ * The `agy` lookup walks `cachedShellPath ?? process.env.PATH`, and at boot the login-shell PATH is+ * usually still being probed. A GUI app on macOS/Linux starts with a minimal PATH, so an `agy` that+ * only `.zshrc` puts on the PATH (Homebrew, npm, nvm) is invisible to the first pass. Hence:+ * - BOOT pass: found ⇒ install; not found ⇒ nothing at all (no write, no withdrawal, no warning);+ * - after `resolveShellPath()` settles — it never rejects, and a failed probe leaves the inherited+ * PATH in charge — a FINAL pass, but only if the boot pass did not find agy: found ⇒ install;+ * not found ⇒ withdraw a bundle of ours.+ * One pass per phase per launch; no loop and no timer. On Windows `resolveShellPath()` resolves+ * `null` at once (the inherited PATH is already the user's full PATH), so the final pass simply+ * repeats the same lookup.+ */+export function installAntigravityHooksWithProbe(+ opts: Omit<AntigravityInstallOptions, 'phase'> = {},+ probe: () => Promise<unknown> = resolveShellPath+): Promise<AntigravityInstallOutcome> {+ // Both passes write to the SAME files, resolved once, now. The final pass runs later, and a+ // spied `os.homedir` (the installer-registry test) may have been restored by then: resolving+ // the paths again at that point would send a test's late pass into the real home.+ opts = {+ ...opts,+ hooksJson: opts.hooksJson ?? antigravityHooksJsonPath(),+ scriptPath: opts.scriptPath ?? antigravityScriptPath()+ }+ let first: AntigravityInstallOutcome+ try {+ first = installAntigravityHooks({ ...opts, phase: 'boot' })+ } catch (e) {+ console.warn('[agent-hooks] antigravity install failed', e)+ first = 'no-agy'+ }+ if (first !== 'no-agy') return Promise.resolve(first)+ return Promise.resolve()+ .then(probe)+ .catch(() => null)+ .then((): AntigravityInstallOutcome => {+ try {+ return installAntigravityHooks({ ...opts, phase: 'final' })+ } catch (e) {+ console.warn('[agent-hooks] antigravity install failed', e)+ return 'refused'+ }+ })+}++/**+ * What `removeAntigravityHooks` did:+ * - `withdrawn` — our bundle (or a stray entry of ours) was in the file and has been removed;+ * - `absent` — nothing of ours there (or no file): the file was not touched;+ * - `unparseable` — the file is not a JSON object, so it was left alone and we cannot say what+ * agy makes of it;+ * - `failed` — something of ours IS there and the write failed: the bundle is still active.+ */+export type AntigravityWithdrawal = 'withdrawn' | 'absent' | 'unparseable' | 'failed'++/** The sentence a refusal logs about the withdrawal — written AFTER it, from what really happened. */+export function withdrawalNote(result: AntigravityWithdrawal, hooksJson: string): string {+ switch (result) {+ case 'withdrawn':+ return `The nodeterm-status bundle already in ${hooksJson} was withdrawn.`+ case 'absent':+ return `${hooksJson} holds no nodeterm-status bundle; nothing to withdraw.`+ case 'unparseable':+ return `${hooksJson} is not a JSON object and was left untouched; if it still carries a nodeterm-status bundle, remove it by hand.`+ case 'failed':+ return `WITHDRAWING the nodeterm-status bundle from ${hooksJson} FAILED — it is still active and may deny agy tools; remove it by hand.`+ }+}++export function removeAntigravityHooks(+ opts: Pick<AntigravityInstallOptions, 'hooksJson' | 'writeFile'> = {}+): AntigravityWithdrawal {+ const hooksJson = opts.hooksJson ?? antigravityHooksJsonPath()+ const current = readHooksFile(hooksJson)+ if (current === undefined) return 'absent'+ if (current === null) return 'unparseable'+ const next = applyAntigravityBundle(current, null)+ // Nothing of ours in it: leave the user's file byte-for-byte (a refused launch calls this every+ // time, and re-serializing would reformat a file we do not own). Own keys only — `setOwn` keeps a+ // `__proto__` key as data, so it compares like any other.+ if (JSON.stringify(next) === JSON.stringify(current)) return 'absent'+ try {+ ;(opts.writeFile ?? writeHooksFile)(hooksJson, next)+ return 'withdrawn'+ } catch {+ return 'failed'+ }+}diff --git a/src/core/agents/hooks/codex-windows-wrapper.ts b/src/core/agents/hooks/codex-windows-wrapper.tsindex 834860187..554b183cd 100644--- a/src/core/agents/hooks/codex-windows-wrapper.ts+++ b/src/core/agents/hooks/codex-windows-wrapper.ts@@ -77,10 +77,20 @@ export const CODEX_WINDOWS_WRAPPER_FILE = 'codex-hook.cmd'* written with CRLF regardless of the host that generated it (an SSH host never runs it — see* `buildManagedCommand`'s platform parameter).*/+/**+ * The batch lines that leave `NT_SH` naming a POSIX shell (or undefined): the candidates above in+ * order, then PATH. Shared with the antigravity wrapper so the two cannot disagree about where Git+ * Bash lives. The caller must `set "NT_SH="` first.+ */+export function windowsShProbeBatch(): string[] {+ return [+ ...WINDOWS_SH_CANDIDATES.map((p) => `if not defined NT_SH if exist "${p}" set "NT_SH=${p}"`),+ // PATH last: least predictable, and a WSL shim there cannot run a Windows-path script.+ 'if not defined NT_SH for %%I in (sh.exe) do if not defined NT_SH set "NT_SH=%%~$PATH:I"'+ ]+}+export function buildCodexWindowsWrapper(): string {- const probe = WINDOWS_SH_CANDIDATES.map(- (p) => `if not defined NT_SH if exist "${p}" set "NT_SH=${p}"`- )const lines = ['@echo off','rem Managed by nodeterm (agent-hooks). Regenerated on every app launch; edits are lost.',@@ -88,9 +98,7 @@ export function buildCodexWindowsWrapper(): string {'set "NT_SCRIPT=%~dp0codex.sh"','if not exist "%NT_SCRIPT%" goto :nt_drain','set "NT_SH="',- ...probe,- // PATH last: least predictable, and a WSL shim there cannot run a Windows-path script.- 'if not defined NT_SH for %%I in (sh.exe) do if not defined NT_SH set "NT_SH=%%~$PATH:I"',+ ...windowsShProbeBatch(),'if not defined NT_SH goto :nt_drain','set "NT_ARG=%NT_SCRIPT:\\=/%"','"%NT_SH%" "%NT_ARG%"',diff --git a/src/core/agents/hooks/index.ts b/src/core/agents/hooks/index.tsindex 16d5bb8a9..254213022 100644--- a/src/core/agents/hooks/index.ts+++ b/src/core/agents/hooks/index.ts@@ -8,6 +8,7 @@ import { installOpencodeHooks, removeOpencodeHooks } from './opencode'import { installGrokHooks, removeGrokHooks } from './grok'import { ensureGrokHomeProbed, grokHomeDir, grokHomeFallbackWasSilent } from '../grok-paths'import { installCopilotHooks, removeCopilotHooks } from './copilot'+import { installAntigravityHooksWithProbe, removeAntigravityHooks } from './antigravity'type HookInstaller = readonly [string, () => void]@@ -17,7 +18,12 @@ export const MANAGED_HOOK_INSTALLERS: readonly HookInstaller[] = [['gemini', installGeminiHooks],['opencode', installOpencodeHooks],['grok', installGrokHooks],- ['copilot', installCopilotHooks]+ ['copilot', installCopilotHooks],+ // Writes the GLOBAL ~/.gemini/config/hooks.json: a synchronous gate in front of every agy tool+ // call on the machine. Only where agy is installed, decided in two passes around the login-shell+ // PATH probe (the same shape as grok's $GROK_HOME re-install below); refuses on Windows while+ // cmd.exe has an AutoRun (antigravity-autorun.ts).+ ['antigravity', () => void installAntigravityHooksWithProbe()]]export const MANAGED_HOOK_REMOVERS: readonly HookInstaller[] = [@@ -26,7 +32,8 @@ export const MANAGED_HOOK_REMOVERS: readonly HookInstaller[] = [['gemini', removeGeminiHooks],['opencode', removeOpencodeHooks],['grok', removeGrokHooks],- ['copilot', removeCopilotHooks]+ ['copilot', removeCopilotHooks],+ ['antigravity', () => removeAntigravityHooks()]]export function installManagedAgentHooks(): void {diff --git a/src/core/agents/hooks/install-helper.ts b/src/core/agents/hooks/install-helper.tsindex 9df5b72e1..8efe6aa0f 100644--- a/src/core/agents/hooks/install-helper.ts+++ b/src/core/agents/hooks/install-helper.ts@@ -101,10 +101,36 @@ export function installManagedHookScript(agentId: string, scriptFileName: string* Codex builds its own equivalent (`buildManagedCommand` in codex.ts) — its exact bytes are* hashed into config.toml's trust entries, so the two must stay separate.*/-export function buildManagedHookCommand(scriptPath: string): string {+export interface ManagedHookCommandOptions {+ /**+ * Variables exported to the script. Emitted as `NAME='value'; export NAME; ` BEFORE the `if`+ * (an assignment prefix cannot precede a compound command). Antigravity is the one user: its+ * payload carries no event name, so the command carries it.+ */+ env?: Readonly<Record<string, string>>+ /**+ * Printed by the missing-script branch BEFORE it drains stdin. For an agent that reads hook+ * stdout as a decision (antigravity), "the script is gone" must still answer — silence there is+ * the wrong answer for some events. Omitted ⇒ the branch prints nothing, as it always has.+ */+ fallbackStdout?: string+}++const shQuote = (s: string): string => `'${s.replaceAll("'", "'\\''")}'`++export function buildManagedHookCommand(scriptPath: string, opts: ManagedHookCommandOptions = {}): string {// POSIX single-quote escape so $, `, " and \ in the path are taken literally.- const q = `'${scriptPath.replaceAll("'", "'\\''")}'`- return `if [ -r ${q} ]; then sh ${q}; else cat >/dev/null 2>&1 || :; fi`+ const q = shQuote(scriptPath)+ const prefix = Object.entries(opts.env ?? {})+ .map(([name, value]) => {+ // A name is interpolated bare, so it must be a name — refuse rather than emit a command+ // that runs something else.+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new Error(`invalid env var name: ${name}`)+ return `${name}=${shQuote(value)}; export ${name}; `+ })+ .join('')+ const answer = opts.fallbackStdout !== undefined ? `printf '%s\\n' ${shQuote(opts.fallbackStdout)}; ` : ''+ return `${prefix}if [ -r ${q} ]; then sh ${q}; else ${answer}cat >/dev/null 2>&1 || :; fi`}/**diff --git a/src/core/agents/hooks/managed-script.ts b/src/core/agents/hooks/managed-script.tsindex 2917a7c08..16fd4ae7d 100644--- a/src/core/agents/hooks/managed-script.ts+++ b/src/core/agents/hooks/managed-script.ts@@ -89,6 +89,7 @@ import { codexThreadIdentityRoot } from '../../codex-identity-proxy'import { HOOK_CURL_HEADERS_SH } from '../hook-curl-config-sh'import { NODE_TOKEN_READ_SH } from '../node-token-sh'import { HOOK_ENDPOINT_FALLBACK_SH } from '../hook-endpoint-failover-sh'+import { ANTIGRAVITY_EVENT_ENV, antigravityDecisionCaseSh } from './antigravity-decision'/*** Bumped by hand whenever this script's CONTRACT with the server changes. Not a git sha and not a@@ -125,12 +126,42 @@ function safeIdentityRoot(): string | null {}}+/**+ * ANTIGRAVITY ONLY, emitted at BUILD time (every other agent's script is byte-identical without+ * it). `agy` reads a hook's stdout as a DECISION and our hook sits in front of every tool call of+ * every `agy` on the machine, so the answer is the FIRST thing the script does — before the codex+ * prelude, before the NODETERM_NODE_ID gate (a user's own terminal gets the same answer), before+ * stdin is read, before the endpoint file is sourced. The table is `antigravity-decision.ts`.+ *+ * Then stdout AND stderr go to /dev/null for the rest of the run. That is a stronger guarantee than+ * auditing every line below: a stray byte (a curl message, a sourced file's echo, a shell warning)+ * would become "non-JSON → DENY", and on `PreInvocation` it could be injected into the user's+ * conversation (`injectSteps`). `command exec` rather than a bare `exec`: a redirection failure on+ * a SPECIAL builtin exits a POSIX shell non-zero, and a non-zero exit is DENY; through `command` it+ * is an ordinary failure, and `|| :` absorbs it.+ */+function antigravityAnswerFirst(): string[] {+ return [+ '# ANSWER FIRST (antigravity): agy reads this stdout as a decision — see antigravity-decision.ts.',+ antigravityDecisionCaseSh(),+ '# Nothing after the answer may reach stdout or stderr (a stray byte is a DENY, or a message',+ '# injected into the conversation).',+ 'command exec >/dev/null 2>&1 || :'+ ]+}+export function buildManagedScript(agentId: string,identityRoot: string | null = safeIdentityRoot()): string {+ const antigravity = agentId === 'antigravity'+ // The event name rides the POST for antigravity only — its payload never carries one.+ const eventField = antigravity+ ? [` --data-urlencode "nodeterm_hook_event=\${${ANTIGRAVITY_EVENT_ENV}}" \\`]+ : []return ['#!/bin/sh',+ ...(antigravity ? antigravityAnswerFirst() : []),...(identityRoot ? [codexThreadIdentityResolverSh(identityRoot)] : []),'# GATE FIRST, and drain stdin before bailing (issues #186/#187). Order is load-bearing twice:','# - The codex thread-identity prelude above may DERIVE the node id (and endpoint) from its',@@ -186,7 +217,14 @@ export function buildManagedScript(HOOK_CURL_HEADERS_SH,'payload=$(cat)','if [ -z "$payload" ]; then',- ' exit 0',+ ...(antigravity+ ? [+ // agy can fire a hook with NO stdin. The answer is already out; still report the event —+ // a Stop with no body is still the end of the turn (the normalizer reads a missing+ // fullyIdle as finished), and dropping it would leave the badge on RUNNING.+ " payload='{}'"+ ]+ : [' exit 0']),'fi','# Keep the payload OFF curl\'s argv. `--data-urlencode "payload=$payload"` puts the full hook','# body (Edit/Write tool_input, the submitted prompt, the last assistant message) into',@@ -279,6 +317,7 @@ export function buildManagedScript(' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',+ ...eventField,' --data-urlencode "payload@${nt_payload_arg}" >/dev/null 2>&1',' elif [ -n "$NODETERM_HOOK_PORT" ]; then',' nt_hook_headers |',@@ -288,6 +327,7 @@ export function buildManagedScript(' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',+ ...eventField,' --data-urlencode "payload@${nt_payload_arg}" >/dev/null 2>&1',' else',' return 1',