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
fix(windows): run gemini, grok and copilot status hooks through a .cmd wrapper
review298cbaf0e2f1
diff --git a/src/core/agent-integrations.ts b/src/core/agent-integrations.tsindex 75590adae..cf3eb598c 100644--- a/src/core/agent-integrations.ts+++ b/src/core/agent-integrations.ts@@ -188,12 +188,15 @@ export function legacyInstructionFiles(agent: IntegrationAgentId, home: string =}}+// Every file a declined agent loses, Windows wrappers included (`windowsHookWrapperFile`: the+// `.cmd` that PowerShell-run hooks call). A wrapper left behind would outlive its script harmlessly+// (it drains and exits 0), but "remove exactly what we wrote" means all of it.const HOOK_SCRIPTS: Partial<Record<IntegrationAgentId, string[]>> = {claude: ['claude.sh'],codex: ['codex.sh', 'codex-hook.cmd'],- gemini: ['gemini.sh'],- grok: ['grok.sh'],- copilot: ['copilot.sh'],+ gemini: ['gemini.sh', 'gemini-hook.cmd'],+ grok: ['grok.sh', 'grok-hook.cmd'],+ copilot: ['copilot.sh', 'copilot-hook.cmd'],antigravity: ['antigravity.sh', 'antigravity-hook.cmd']}diff --git a/src/core/agents/hooks/antigravity-windows-wrapper.ts b/src/core/agents/hooks/antigravity-windows-wrapper.tsindex 0fa6ba61d..335c9f306 100644--- a/src/core/agents/hooks/antigravity-windows-wrapper.ts+++ b/src/core/agents/hooks/antigravity-windows-wrapper.ts@@ -17,7 +17,7 @@// `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'+import { windowsShProbeBatch } from './windows-hook-wrapper'/** The wrapper's file name, beside the managed script it runs. */export const ANTIGRAVITY_WINDOWS_WRAPPER_FILE = 'antigravity-hook.cmd'diff --git a/src/core/agents/hooks/codex-windows-wrapper.ts b/src/core/agents/hooks/codex-windows-wrapper.tsindex 554b183cd..d022a2987 100644--- a/src/core/agents/hooks/codex-windows-wrapper.ts+++ b/src/core/agents/hooks/codex-windows-wrapper.ts@@ -43,72 +43,17 @@// 3. **Exit 0 when there is no shell and no script.** "nodeterm is not installed here" must look// like nothing happening, not like a broken hook — same contract the POSIX `else` branch has.//-// The shell search order is Git for Windows' real layouts first (both `bin` and `usr\bin`, 64-bit-// and 32-bit program dirs, and the per-user install under LOCALAPPDATA, which is what `winget-// install Git.Git` produces without admin), then whatever `sh.exe` is on PATH. PATH is last on-// purpose: it is the least predictable, and a WSL `sh` shim there cannot run a Windows-path script.+// The shell search, the wrapper template and the cmd.exe invocation live in+// `windows-hook-wrapper.ts`, shared with gemini, grok, copilot and antigravity. This file keeps the+// codex-specific names and the measurements above; the codex wrapper's bytes are pinned by a test.+import { buildWindowsHookWrapper } from './windows-hook-wrapper'-/** Where the wrapper looks for a POSIX shell, in order. cmd.exe expands these itself. */-export const WINDOWS_SH_CANDIDATES = [- '%ProgramFiles%\\Git\\bin\\sh.exe',- '%ProgramFiles%\\Git\\usr\\bin\\sh.exe',- '%ProgramFiles(x86)%\\Git\\bin\\sh.exe',- '%ProgramFiles(x86)%\\Git\\usr\\bin\\sh.exe',- '%LOCALAPPDATA%\\Programs\\Git\\bin\\sh.exe',- '%LOCALAPPDATA%\\Programs\\Git\\usr\\bin\\sh.exe'-] as const+export { WINDOWS_SH_CANDIDATES, windowsShProbeBatch } from './windows-hook-wrapper'/** The wrapper's file name, beside the managed script it runs. */export const CODEX_WINDOWS_WRAPPER_FILE = 'codex-hook.cmd'-/**- * The batch wrapper's content.- *- * `%~dp0` is the wrapper's own directory (with a trailing backslash), so the wrapper carries NO- * absolute path of its own — it finds `codex.sh` beside itself. That matters because- * `managedHookScriptPath`'s whole point is one stable machine-wide location, and baking the path- * in would give us a second copy of it to keep in sync.- *- * The script path is handed to sh with forward slashes (`%VAR:\=/%`): MSYS converts a- * `C:\...`-shaped argument in most cases, but `C:/...` needs no conversion at all and cannot be- * mistaken for an option or an escape.- *- * CRLF: batch files are line-oriented and cmd.exe is not reliably tolerant of LF, so this is- * 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"'- ]-}-+/** The batch wrapper's content: `codex.sh`, found beside the wrapper, run by the first POSIX shell. */export function buildCodexWindowsWrapper(): string {- const lines = [- '@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="',- ...windowsShProbeBatch(),- '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',- ''- ]- return lines.join('\r\n')+ return buildWindowsHookWrapper('codex.sh', 'codex')}diff --git a/src/core/agents/hooks/codex.ts b/src/core/agents/hooks/codex.tsindex 4a6dae70e..7bb133b38 100644--- a/src/core/agents/hooks/codex.ts+++ b/src/core/agents/hooks/codex.ts@@ -29,6 +29,7 @@ import { renameAtomicSync } from '../../fs-atomic'import { buildManagedScript } from './managed-script'import { normalizeHookCommand } from './install-helper'import { buildCodexWindowsWrapper, CODEX_WINDOWS_WRAPPER_FILE } from './codex-windows-wrapper'+import { buildWindowsHookInvocation, defaultWindowsCmdExe } from './windows-hook-wrapper'import {computeTrustedHash,getCodexCanonicalTrustPath,@@ -156,23 +157,9 @@ export function stripCodexManagedHooks(config: HooksConfig): HooksConfig | nullreturn removed ? { ...config, hooks: next } : null}-/**- * `%SystemRoot%\System32\cmd.exe`, or bare `cmd` when that cannot be spelled unquoted.- *- * Unquoted is the whole constraint: quoting the program name is exactly what breaks under- * PowerShell (a quoted leading token is a string literal, which is #685), so a resolved path- * carrying a space or a shell metacharacter is unusable and the PATH lookup is the lesser evil.- * `windir` is the fallback name for the same value on older installs.- */-export function defaultWindowsCmdExe(): string {- const root = process.env.SystemRoot || process.env.windir || ''- if (!root) return 'cmd'- const abs = `${root}\\System32\\cmd.exe`- // Deliberately a strict allow-list, not a metacharacter deny-list: anything outside a plain- // drive-letter path is not worth guessing at. The fallback then attempts a PATH lookup, which is- // what this function exists to avoid — but an unusable absolute path would run nothing at all.- return /^[A-Za-z]:\\[A-Za-z0-9\\._-]*$/.test(abs) ? abs : 'cmd'-}+// `defaultWindowsCmdExe` moved to windows-hook-wrapper.ts (shared by every wrapped agent); re-exported+// here because callers and tests import it from codex.+export { defaultWindowsCmdExe }/*** The hook command, formed the SAME way for hooks.json AND the trust entry — the trust hash is@@ -247,7 +234,7 @@ export function buildManagedCommand(// exit-2 "block the prompt" convention does not survive this path. The managed script exits 0// on every branch, including its bails, so no behaviour in this repo relies on the distinction.const dir = script.slice(0, Math.max(script.lastIndexOf('\\'), script.lastIndexOf('/')) + 1)- return `${cmdExe} /d /c call "${dir}${CODEX_WINDOWS_WRAPPER_FILE} "`+ return buildWindowsHookInvocation(`${dir}${CODEX_WINDOWS_WRAPPER_FILE}`, cmdExe)}// POSIX single-quote escape so $, `, ", \ in the path are taken literally.const quoted = `'${script.replaceAll("'", "'\\''")}'`diff --git a/src/core/agents/hooks/copilot.test.ts b/src/core/agents/hooks/copilot.test.tsindex 16d262cd4..ee55b6474 100644--- a/src/core/agents/hooks/copilot.test.ts+++ b/src/core/agents/hooks/copilot.test.ts@@ -30,7 +30,9 @@ describe('copilot hook installer', () => {it("writes Copilot's native hook-file shape and the shared managed script", async () => {const { copilotHookConfigPath, installCopilotHooks } =await import('./copilot')- installCopilotHooks()+ // Explicit platform: the exact entry below is the POSIX one, and the Windows CI runner would+ // otherwise (correctly) add a `powershell` key.+ installCopilotHooks('linux')expect(copilotHookConfigPath()).toBe(path.join(home, '.copilot', 'hooks', 'nodeterm-status.json'))@@ -98,4 +100,26 @@ describe('copilot hook installer', () => {hooks: {}})})++ it('win32: adds the powershell key (the one Copilot runs there) beside bash, wrapper first', async () => {+ const { copilotHookConfigPath, installCopilotHooks } = await import('./copilot')+ const CMD = 'C:\\WINDOWS\\System32\\cmd.exe'+ installCopilotHooks('win32', CMD)+ const wrapper = path.join(home, '.nodeterm', 'agent-hooks', 'copilot-hook.cmd')+ expect(readFileSync(wrapper, 'utf8')).toContain('set "NT_SCRIPT=%~dp0copilot.sh"')+ const cfg = JSON.parse(readFileSync(copilotHookConfigPath(), 'utf8'))+ for (const [event, entries] of Object.entries(cfg.hooks) as [string, Record<string, unknown>[]][]) {+ expect(entries, event).toHaveLength(1)+ expect(entries[0].bash, event).toMatch(/^if \[ -r /)+ expect(entries[0].powershell, event).toBe(`${CMD} /d /c call "${wrapper} "`)+ }+ expect(cfg.hooks.Notification[0].matcher).toBe('permission_prompt|elicitation_dialog')+ })++ it('buildCopilotHookConfig: no windows command (the SSH installer) means no powershell key', async () => {+ const { buildCopilotHookConfig } = await import('./copilot')+ const cfg = buildCopilotHookConfig('POSIX')+ for (const entries of Object.values(cfg.hooks)) expect(entries[0]).not.toHaveProperty('powershell')+ expect(buildCopilotHookConfig('POSIX', 'WIN').hooks.Stop?.[0]).toMatchObject({ bash: 'POSIX', powershell: 'WIN' })+ })})diff --git a/src/core/agents/hooks/copilot.ts b/src/core/agents/hooks/copilot.tsindex 15059ee15..395f20863 100644--- a/src/core/agents/hooks/copilot.ts+++ b/src/core/agents/hooks/copilot.ts@@ -10,6 +10,7 @@ import { COPILOT_HOOK_EVENTS } from '@shared/agents/hook-events'import {buildManagedHookCommand,installManagedHookScript,+ installWindowsHookWrapper,writeManagedHookFileAtomic} from './install-helper'@@ -22,6 +23,8 @@ const REMOTE_HOME_MAX = 4096export interface CopilotHookCommand {type: 'command'bash: string+ /** What Copilot runs on Windows instead of `bash`. Present only in a Windows install. */+ powershell?: stringtimeoutSec: numbermatcher?: string}@@ -60,14 +63,22 @@ export function copilotHookConfigPath(): string {return path.join(copilotHomeDir(), 'hooks', COPILOT_HOOK_FILE)}-/** Pure config builder shared with the SSH installer, which supplies a remote script path. */-export function buildCopilotHookConfig(command: string): CopilotHookConfig {+/**+ * Pure config builder shared with the SSH installer, which supplies a remote script path.+ *+ * `windowsCommand` adds Copilot's `powershell` key — the one it runs on Windows, where the `bash`+ * line is never consulted. `bash` stays in either case (Copilot requires a command for the+ * platform it runs on, and keeping the POSIX line means a config copied off a Windows box still+ * works elsewhere). The SSH installer passes none, so a host's file is byte-identical.+ */+export function buildCopilotHookConfig(command: string, windowsCommand?: string): CopilotHookConfig {const hooks: Record<string, CopilotHookCommand[]> = {}for (const event of COPILOT_HOOK_EVENTS) {hooks[event] = [{type: 'command',bash: command,+ ...(windowsCommand !== undefined ? { powershell: windowsCommand } : {}),timeoutSec: 5,// Copilot's notification matcher is a regex on notification_type. These are the only two// notifications that change nodeterm state; filtering at source avoids one process per@@ -81,17 +92,22 @@ export function buildCopilotHookConfig(command: string): CopilotHookConfig {return { version: 1, hooks }}-export function installCopilotHooks(): void {+export function installCopilotHooks(platform: NodeJS.Platform | string = process.platform, cmdExe?: string): void {const script = installManagedHookScript('copilot', SCRIPT_FILE_NAME)if (!script) return+ // On Windows Copilot runs the `powershell` key, so its wrapper must exist before the config+ // names it (same order rule as installHooksInto).+ const windows = platform === 'win32'+ if (windows && !installWindowsHookWrapper('copilot', script)) returnconst configPath = copilotHookConfigPath()try {fs.mkdirSync(path.dirname(configPath), { recursive: true })- // Our own file, published by rename so copilot never reads it half written.- writeManagedHookFileAtomic(- configPath,- `${JSON.stringify(buildCopilotHookConfig(buildManagedHookCommand(script)), null, 2)}\n`+ const config = buildCopilotHookConfig(+ buildManagedHookCommand(script),+ windows ? buildManagedHookCommand(script, {}, 'win32', cmdExe) : undefined)+ // Our own file, published by rename so copilot never reads it half written.+ writeManagedHookFileAtomic(configPath, `${JSON.stringify(config, null, 2)}\n`)} catch (e) {console.warn('[agent-hooks] copilot install failed', e)}diff --git a/src/core/agents/hooks/gemini.ts b/src/core/agents/hooks/gemini.tsindex 3fc416e3b..aed24f772 100644--- a/src/core/agents/hooks/gemini.ts+++ b/src/core/agents/hooks/gemini.ts@@ -17,7 +17,10 @@ export function installGeminiHooks(): void {agentId: 'gemini',scriptFileName: SCRIPT_FILE_NAME,configPath: configPath(),- events: GEMINI_HOOK_EVENTS+ events: GEMINI_HOOK_EVENTS,+ // Gemini runs a hook through PowerShell on Windows (`getShellConfiguration`: ComSpec when it is+ // powershell/pwsh, else pwsh.exe, else powershell.exe), which cannot parse the POSIX line.+ windowsWrapper: true})}diff --git a/src/core/agents/hooks/grok.ts b/src/core/agents/hooks/grok.tsindex 6a93f1198..e37f44814 100644--- a/src/core/agents/hooks/grok.ts+++ b/src/core/agents/hooks/grok.ts@@ -52,7 +52,11 @@ export function installGrokHooks(): void {scriptFileName: SCRIPT_FILE_NAME,configPath: grokHookConfigPath(),events: GROK_EVENTS,- atomicConfig: true+ atomicConfig: true,+ // Grok's hook docs (user-guide/10-hooks.md) say commands run under PowerShell on Windows; its+ // binary names powershell.exe and cmd.exe. The wrapper invocation runs under either. NOT yet+ // measured on a device — see docs/grok-agent.md's checklist.+ windowsWrapper: true})}diff --git a/src/core/agents/hooks/install-helper.fs.test.ts b/src/core/agents/hooks/install-helper.fs.test.tsindex 90c56144f..e8d60d8fa 100644--- a/src/core/agents/hooks/install-helper.fs.test.ts+++ b/src/core/agents/hooks/install-helper.fs.test.ts@@ -1,7 +1,7 @@// The repair issue #558 actually owes the user: their settings.json ON DISK must come back to one// managed entry per event at the next launch, not just a fresh install. `installManagedAgentHooks`// runs `installHooksInto` for every agent at boot, so proving it here proves the repair.-import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'fs'+import { existsSync, mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'fs'import { tmpdir } from 'os'import path from 'path'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'@@ -100,3 +100,55 @@ describe('owned Grok config repair', () => {expect(readConfig().hooks.Stop[0].hooks[0].command).toContain('grok.sh')})})++describe('installHooksInto — Windows wrapper for PowerShell-run hooks (gemini, grok)', () => {+ const CMD = 'C:\\WINDOWS\\System32\\cmd.exe'+ const geminiInstall = (platform: string) =>+ installHooksInto({+ agentId: 'gemini',+ scriptFileName: 'gemini.sh',+ configPath: configPath(),+ events: ['AfterTool', 'Notification'],+ windowsWrapper: true,+ platform,+ cmdExe: CMD+ })+ const wrapperPath = () => path.join(dir, '.nodeterm', 'agent-hooks', 'gemini-hook.cmd')++ it('win32: writes the CRLF wrapper beside the script and points every event at it', () => {+ geminiInstall('win32')+ const wrapper = readFileSync(wrapperPath(), 'utf8')+ expect(wrapper).toContain('set "NT_SCRIPT=%~dp0gemini.sh"')+ expect(wrapper).toContain('\r\n')+ const command = readConfig().hooks.AfterTool[0].hooks[0].command+ expect(command).toBe(`${CMD} /d /c call "${wrapperPath()} "`)+ expect(readConfig().hooks.Notification[0].hooks[0].command).toBe(command)+ })++ it('win32: replaces the POSIX entry an older build left (no duplicate per event)', () => {+ geminiInstall('linux')+ geminiInstall('win32')+ expect(readConfig().hooks.AfterTool).toHaveLength(1)+ expect(readConfig().hooks.AfterTool[0].hooks[0].command).toContain('gemini-hook.cmd')+ })++ it('win32: a wrapper that cannot be written leaves the config untouched (wrapper BEFORE config)', () => {+ // A directory where the wrapper file must go makes the atomic publish fail.+ mkdirSync(wrapperPath(), { recursive: true })+ writeFileSync(configPath(), '{"model":"keep"}')+ geminiInstall('win32')+ expect(readFileSync(configPath(), 'utf8')).toBe('{"model":"keep"}')+ })++ it('other platforms: no wrapper, and the command is the POSIX guard', () => {+ geminiInstall('darwin')+ expect(existsSync(wrapperPath())).toBe(false)+ expect(readConfig().hooks.AfterTool[0].hooks[0].command).toMatch(/^if \[ -r /)+ })++ it('claude never gets a wrapper, even on win32 (its hooks run in Git Bash)', () => {+ installHooksInto({ agentId: 'claude', scriptFileName: 'claude.sh', configPath: configPath(), events: ['Stop'], platform: 'win32' })+ expect(existsSync(path.join(dir, '.nodeterm', 'agent-hooks', 'claude-hook.cmd'))).toBe(false)+ expect(readConfig().hooks.Stop[0].hooks[0].command).toMatch(/^if \[ -r /)+ })+})diff --git a/src/core/agents/hooks/install-helper.test.ts b/src/core/agents/hooks/install-helper.test.tsindex f0e28ac98..3143a7200 100644--- a/src/core/agents/hooks/install-helper.test.ts+++ b/src/core/agents/hooks/install-helper.test.ts@@ -6,6 +6,7 @@ import { join } from 'node:path'import {buildManagedHookCommand,mergeManagedHook,+ stripManagedHook,writeManagedHookConfig,writeManagedHookFileAtomic,type HookSettings@@ -257,3 +258,60 @@ describe('mergeManagedHook — only OUR handler is removed from a shared definitexpect(mergeManagedHook(before, cmd, ['Stop']).hooks!.SubagentStop).toBe('nonsense')})})++describe('buildManagedHookCommand — Windows wrapper (gemini / grok / copilot)', () => {+ const CMD = 'C:\\WINDOWS\\System32\\cmd.exe'+ const winScript = 'C:\\Users\\u\\.nodeterm\\agent-hooks\\gemini.sh'++ it('win32: runs the agent wrapper through the measured cmd.exe invocation', () => {+ expect(buildManagedHookCommand(winScript, {}, 'win32', CMD)).toBe(+ `${CMD} /d /c call "C:\\Users\\u\\.nodeterm\\agent-hooks\\gemini-hook.cmd "`+ )+ })++ it('the default and every non-win32 platform stay byte-identical to the POSIX line', () => {+ const posix =+ "if [ -r '/h/.nodeterm/agent-hooks/gemini.sh' ]; then sh '/h/.nodeterm/agent-hooks/gemini.sh'; else cat >/dev/null 2>&1 || :; fi"+ expect(buildManagedHookCommand('/h/.nodeterm/agent-hooks/gemini.sh')).toBe(posix)+ expect(buildManagedHookCommand('/h/.nodeterm/agent-hooks/gemini.sh', {}, 'linux', CMD)).toBe(posix)+ expect(buildManagedHookCommand('/h/.nodeterm/agent-hooks/gemini.sh', {}, 'darwin', CMD)).toBe(posix)+ })++ it('refuses antigravity-only options on win32 instead of dropping them', () => {+ expect(() => buildManagedHookCommand(winScript, { env: { A: 'b' } }, 'win32', CMD)).toThrow()+ expect(() => buildManagedHookCommand(winScript, { fallbackStdout: '{}' }, 'win32', CMD)).toThrow()+ })++ it('an upgrade REPLACES the POSIX entry with the .cmd one (one handler per event, not two)', () => {+ const posixCmd = buildManagedHookCommand(winScript)+ const winCmd = buildManagedHookCommand(winScript, {}, 'win32', CMD)+ const foreign = { hooks: [{ type: 'command', command: 'echo mine' }] }+ const before = { hooks: { AfterTool: [foreign, { hooks: [{ type: 'command', command: posixCmd }] }] } }+ const out = mergeManagedHook(before, winCmd, ['AfterTool'])+ expect(out.hooks!.AfterTool).toEqual([foreign, { hooks: [{ type: 'command', command: winCmd }] }])+ // Both spellings present at once (a half-upgraded file) still collapse to one.+ const both = { hooks: { AfterTool: [{ hooks: [{ type: 'command', command: posixCmd }] }, { hooks: [{ type: 'command', command: winCmd }] }] } }+ expect(mergeManagedHook(both, winCmd, ['AfterTool']).hooks!.AfterTool).toEqual([+ { hooks: [{ type: 'command', command: winCmd }] }+ ])+ })++ it('uninstall strips both spellings and no other agent\'s entry', () => {+ const posixCmd = buildManagedHookCommand(winScript)+ const winCmd = buildManagedHookCommand(winScript, {}, 'win32', CMD)+ const claudeWin = buildManagedHookCommand('C:\\Users\\u\\.nodeterm\\agent-hooks\\claude.sh')+ const cfg = {+ hooks: {+ Stop: [+ { hooks: [{ type: 'command', command: posixCmd }] },+ { hooks: [{ type: 'command', command: winCmd }] },+ { hooks: [{ type: 'command', command: claudeWin }] }+ ]+ }+ }+ expect(stripManagedHook(cfg, 'gemini.sh', ['Stop']).hooks!.Stop).toEqual([+ { hooks: [{ type: 'command', command: claudeWin }] }+ ])+ })+})+diff --git a/src/core/agents/hooks/install-helper.ts b/src/core/agents/hooks/install-helper.tsindex d21183356..d3e060b04 100644--- a/src/core/agents/hooks/install-helper.ts+++ b/src/core/agents/hooks/install-helper.ts@@ -19,6 +19,7 @@ import { readFileSync, writeFileSync, mkdirSync, chmodSync, rmSync } from 'fs'import { managedEventName, type ManagedHookEvent } from '@shared/agents/hook-events'import { renameAtomicSync, tempNameFor } from '../../fs-atomic'import { buildManagedScript } from './managed-script'+import { buildWindowsHookInvocation, buildWindowsHookWrapper, windowsHookWrapperFile } from './windows-hook-wrapper'type HookDef = { matcher?: string; hooks?: { type: string; command: string; timeout?: number }[] }type Settings = { hooks?: Record<string, HookDef[]>; [k: string]: unknown }@@ -121,7 +122,31 @@ export interface ManagedHookCommandOptions {const shQuote = (s: string): string => `'${s.replaceAll("'", "'\\''")}'`-export function buildManagedHookCommand(scriptPath: string, opts: ManagedHookCommandOptions = {}): string {+/**+ * `platform` is the platform of the machine that will RUN the agent, and it is POSIX unless a+ * caller says otherwise — deliberately NOT `process.platform`: the SSH installers+ * (`RemoteHooks`) call this for a POSIX host whatever the desktop is, and a default that followed+ * the desktop would hand a Linux server a `cmd.exe` line. Only the LOCAL installers pass their own+ * platform. On `win32` the command runs the agent's `.cmd` wrapper beside the script+ * (`windowsHookWrapperFile`) through `buildWindowsHookInvocation` — the codex form, measured to run+ * under PowerShell and cmd.exe alike.+ */+export function buildManagedHookCommand(+ scriptPath: string,+ opts: ManagedHookCommandOptions = {},+ platform: NodeJS.Platform | string = 'posix',+ cmdExe?: string+): string {+ if (platform === 'win32') {+ // Only antigravity uses these, and it has its own wrapper + command (it reads stdout as a+ // decision). Refuse rather than silently drop them on the Windows line.+ if (opts.env || opts.fallbackStdout !== undefined) {+ throw new Error('env / fallbackStdout are not supported by the Windows hook wrapper')+ }+ const dir = scriptPath.slice(0, Math.max(scriptPath.lastIndexOf('\\'), scriptPath.lastIndexOf('/')) + 1)+ const leaf = scriptPath.slice(dir.length)+ return buildWindowsHookInvocation(`${dir}${windowsHookWrapperFile(leaf)}`, cmdExe)+ }// POSIX single-quote escape so $, `, " and \ in the path are taken literally.const q = shQuote(scriptPath)const prefix = Object.entries(opts.env ?? {})@@ -173,6 +198,24 @@ function managedMarkerFor(command: string): string {return m ? m[0] : 'agent-hooks'}+/**+ * BOTH spellings of one agent's managed entry, whichever one we were handed: the POSIX+ * `agent-hooks/<agent>.sh` and the Windows wrapper `agent-hooks/<agent>-hook.cmd`.+ *+ * Matching only the spelling THIS install writes is #558 again: a Windows settings.json that+ * already carries the POSIX entry (every Windows gemini install before the wrapper existed) would+ * keep it and gain the `.cmd` one beside it — two hooks per event, one of which can never run. With+ * the pair, the next launch REPLACES it, and an uninstall strips both. Same rule codex's own matcher+ * follows (`isManagedCommand` in codex.ts). On POSIX this only ever widens the sweep to a `.cmd`+ * entry of ours, which nothing on POSIX writes.+ */+function managedMarkersFor(marker: string): string[] {+ const m = marker.match(/^agent-hooks\/(.+?)(?:-hook\.cmd|\.sh)$/)+ if (!m) return [marker]+ const script = `${m[1]}.sh`+ return [`agent-hooks/${script}`, `agent-hooks/${windowsHookWrapperFile(script)}`]+}+/*** Does one handler's command belong to us? `legacy` also accepts the pre-hook-server* `claude-signals` marker (the install path sweeps it; the uninstall path deliberately does not,@@ -182,10 +225,11 @@ function managedMarkerFor(command: string): string {* rather than throwing, or one malformed entry skips the whole agent's install.*/function managedCommandMatcher(marker: string, legacy: boolean): (command?: string) => boolean {+ const markers = managedMarkersFor(marker)return (command?: string) => {if (typeof command !== 'string') return falseconst c = normalizeHookCommand(command)- return c.includes(marker) || (legacy && c.includes('claude-signals'))+ return markers.some((m) => c.includes(m)) || (legacy && c.includes('claude-signals'))}}@@ -293,15 +337,45 @@ export interface InstallHooksOptions {events: readonly ManagedHookEvent[]/** Atomic replacement is safe only when nodeterm owns the config file outright (Grok). */atomicConfig?: boolean+ /**+ * Does this agent run its hooks through PowerShell / cmd.exe on Windows? Then a Windows install+ * writes the `.cmd` wrapper beside the script and points the config at it (gemini, grok). Claude+ * leaves it off: Claude Code runs hooks through Git Bash, where the POSIX command is correct.+ */+ windowsWrapper?: boolean+ /** The platform the agent runs on. Test seam; the local installers run where the agent does. */+ platform?: NodeJS.Platform | string+ /** Test seam for the Windows invocation's interpreter (default: `defaultWindowsCmdExe()`). */+ cmdExe?: string+}++/**+ * Write the agent's `.cmd` wrapper beside its managed script. Returns false when it could not be+ * written — the caller must then leave the config alone, because a command pointing at a missing+ * wrapper is exactly the dead entry the wrapper exists to replace.+ */+export function installWindowsHookWrapper(agentId: string, scriptPath: string): boolean {+ const leaf = path.basename(scriptPath)+ try {+ writeManagedHookFileAtomic(path.join(path.dirname(scriptPath), windowsHookWrapperFile(leaf)), buildWindowsHookWrapper(leaf, agentId))+ return true+ } catch (e) {+ console.warn(`[agent-hooks] ${agentId} Windows wrapper write failed`, e)+ return false+ }}export function installHooksInto(opts: InstallHooksOptions): void {const { agentId, scriptFileName, configPath, events, atomicConfig = false } = opts+ const platform = opts.platform ?? process.platform+ const wrapped = platform === 'win32' && !!opts.windowsWrapperconst sp = installManagedHookScript(agentId, scriptFileName)if (!sp) return+ // Order matters: the wrapper must exist before the config points the agent at it.+ if (wrapped && !installWindowsHookWrapper(agentId, sp)) return- const command = buildManagedHookCommand(sp)+ const command = wrapped ? buildManagedHookCommand(sp, {}, 'win32', opts.cmdExe) : buildManagedHookCommand(sp)if (!atomicConfig) {updateSettingsFile(configPath, (config) => mergeManagedHook(config, command, events))returndiff --git a/src/core/agents/hooks/windows-hook-wrapper.test.ts b/src/core/agents/hooks/windows-hook-wrapper.test.tsnew file mode 100644index 000000000..645ea16c6--- /dev/null+++ b/src/core/agents/hooks/windows-hook-wrapper.test.ts@@ -0,0 +1,95 @@+import { describe, expect, it } from 'vitest'+import {+ buildWindowsHookInvocation,+ buildWindowsHookWrapper,+ buildWindowsShLauncher,+ WINDOWS_SH_CANDIDATES,+ WINDOWS_SH_REQUIRED_MESSAGE,+ windowsHookWrapperFile+} from './windows-hook-wrapper'+import { buildCodexWindowsWrapper } from './codex-windows-wrapper'++// These pin what the generators CONSTRUCT. Whether cmd.exe runs them is a device fact (the codex+// wrapper's was measured for #567/#685; the new agents' rows are in the docs' device checklists).+const CMD = 'C:\\WINDOWS\\System32\\cmd.exe'++describe('windowsHookWrapperFile', () => {+ it('names the wrapper after the script, matching codex-hook.cmd', () => {+ expect(windowsHookWrapperFile('gemini.sh')).toBe('gemini-hook.cmd')+ expect(windowsHookWrapperFile('grok.sh')).toBe('grok-hook.cmd')+ expect(windowsHookWrapperFile('copilot.sh')).toBe('copilot-hook.cmd')+ expect(windowsHookWrapperFile('codex.sh')).toBe('codex-hook.cmd')+ })+})++describe('buildWindowsHookWrapper', () => {+ const w = buildWindowsHookWrapper('gemini.sh', 'gemini')++ it('runs the named script found beside itself, with no absolute path baked in', () => {+ expect(w).toContain('set "NT_SCRIPT=%~dp0gemini.sh"')+ expect(w).not.toMatch(/[A-Za-z]:\\Users/)+ expect(w).not.toContain('curl')+ })++ it('is CRLF throughout', () => {+ expect(w.split('\n').slice(0, -1).every((l) => l.endsWith('\r'))).toBe(true)+ })++ it('drains stdin and exits 0 when there is no shell or no script', () => {+ expect(w).toContain('if not exist "%NT_SCRIPT%" goto :nt_drain')+ expect(w).toContain('if not defined NT_SH goto :nt_drain')+ expect(w.slice(w.indexOf(':nt_drain'))).toContain('findstr /r ".*" >nul 2>&1')+ expect(w.trimEnd().endsWith('exit /b 0')).toBe(true)+ })++ it('keeps the codex wrapper byte-identical (it is the same template)', () => {+ expect(buildWindowsHookWrapper('codex.sh', 'codex')).toBe(buildCodexWindowsWrapper())+ })+})++describe('buildWindowsHookInvocation', () => {+ it('is the measured codex form: absolute cmd.exe, /d, call, trailing space inside the quotes', () => {+ expect(buildWindowsHookInvocation('C:\\Users\\u\\.nodeterm\\agent-hooks\\gemini-hook.cmd', CMD)).toBe(+ `${CMD} /d /c call "C:\\Users\\u\\.nodeterm\\agent-hooks\\gemini-hook.cmd "`+ )+ })+})++describe('buildWindowsShLauncher', () => {+ const l = buildWindowsShLauncher('nodeterm.sh')++ it('passes every argument through %* untouched, after the script path', () => {+ expect(l).toContain('set "NT_SCRIPT=%~dp0nodeterm.sh"')+ expect(l).toContain('"%NT_SH%" "%NT_ARG%" %*')+ // No re-quoting layer of its own: `--cmd=--version` and a quoted value with spaces reach sh as+ // the caller's shell tokenized them.+ expect(l).not.toMatch(/%~?[1-9]/)+ expect(l).toContain('exit /b %ERRORLEVEL%')+ })++ it('searches the same Git for Windows layouts, PATH last', () => {+ for (const c of WINDOWS_SH_CANDIDATES) expect(l).toContain(c)+ const last = Math.max(...WINDOWS_SH_CANDIDATES.map((c) => l.indexOf(c)))+ expect(l.indexOf('%%~$PATH:I')).toBeGreaterThan(last)+ })++ it('fails LOUDLY with exit 1 when no shell exists — an agent ran it on purpose', () => {+ expect(l).toContain('if not defined NT_SH goto :nt_nosh')+ const bail = l.slice(l.indexOf('\r\n:nt_nosh') + 2)+ expect(bail.split('\r\n')[0]).toBe(':nt_nosh')+ expect(bail).toContain(`>&2 echo ${WINDOWS_SH_REQUIRED_MESSAGE}`)+ expect(bail.split('\r\n')[2]).toBe('exit /b 1')+ expect(WINDOWS_SH_REQUIRED_MESSAGE).toContain('Git for Windows (sh.exe) is required')+ // Never a silent drain: that is the hook wrapper's contract, not a CLI's.+ expect(l).not.toContain('findstr')+ })++ it('never puts the message inside a parenthesized block (its `)` would close it early)', () => {+ expect(l).not.toMatch(/^if .*\(echo/m)+ })++ it('keeps `!` literal and is CRLF', () => {+ expect(l).toContain('DisableDelayedExpansion')+ expect(l.split('\n').slice(0, -1).every((x) => x.endsWith('\r'))).toBe(true)+ })+})diff --git a/src/core/agents/hooks/windows-hook-wrapper.ts b/src/core/agents/hooks/windows-hook-wrapper.tsnew file mode 100644index 000000000..75a743e76--- /dev/null+++ b/src/core/agents/hooks/windows-hook-wrapper.ts@@ -0,0 +1,157 @@+// The Windows entry points shared by every agent whose hooks (or tool calls) are NOT run by a+// POSIX shell: a batch file that finds Git for Windows' `sh.exe` and hands it the one POSIX script.+//+// Codex was the first (`codex-windows-wrapper.ts` carries the measurements: PowerShell and cmd.exe+// both reject `if [ -r ... ]`, and `sh.exe` is not on PATH on a stock Git install). Gemini, grok and+// copilot run their hooks through PowerShell on Windows too (gemini's `getShellConfiguration`, grok's+// own hook docs, copilot's `powershell` key), so they use the same wrapper, built here from one+// template. Claude is the exception: Claude Code runs its hooks through Git Bash, where the POSIX+// command is already correct.+//+// Two shapes, deliberately different on the bail path:+// - the HOOK wrapper (`buildWindowsHookWrapper`) drains stdin and exits 0 when there is no shell+// or no script — "nodeterm is not installed here" must look like nothing happening, and a bail+// that never reads the payload can EPIPE the agent mid-write (#186/#187);+// - the CLI launcher (`buildWindowsShLauncher`) is something an agent RUNS on purpose, so it+// fails loudly with a message saying what is missing and exits 1.++/**+ * Where a wrapper looks for a POSIX shell, in order. cmd.exe expands these itself.+ *+ * Git for Windows' real layouts first (both `bin` and `usr\bin`, 64-bit and 32-bit program dirs,+ * and the per-user install under LOCALAPPDATA, which is what `winget install Git.Git` produces+ * without admin), then whatever `sh.exe` is on PATH. PATH is last on purpose: it is the least+ * predictable, and a WSL `sh` shim there cannot run a Windows-path script.+ */+export const WINDOWS_SH_CANDIDATES = [+ '%ProgramFiles%\\Git\\bin\\sh.exe',+ '%ProgramFiles%\\Git\\usr\\bin\\sh.exe',+ '%ProgramFiles(x86)%\\Git\\bin\\sh.exe',+ '%ProgramFiles(x86)%\\Git\\usr\\bin\\sh.exe',+ '%LOCALAPPDATA%\\Programs\\Git\\bin\\sh.exe',+ '%LOCALAPPDATA%\\Programs\\Git\\usr\\bin\\sh.exe'+] as const++/**+ * The batch lines that leave `NT_SH` naming a POSIX shell (or undefined): the candidates above in+ * order, then PATH. Shared by every wrapper so they 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"'+ ]+}++/** The wrapper's file name for a managed script: `gemini.sh` → `gemini-hook.cmd`. Codex's+ * `codex-hook.cmd` follows the same rule, which is what lets the managed-entry matcher pair the+ * two spellings of one agent's entry (see install-helper's `managedMarkersFor`). */+export function windowsHookWrapperFile(scriptFileName: string): string {+ return `${scriptFileName.replace(/\.sh$/, '')}-hook.cmd`+}++/**+ * A hook wrapper's content: run `<scriptFileName>` (found beside the wrapper through `%~dp0`, so the+ * wrapper bakes in no absolute path) with the first POSIX shell found, passing stdin through.+ *+ * The script path is handed to sh with forward slashes (`%VAR:\=/%`): MSYS converts a+ * `C:\...`-shaped argument in most cases, but `C:/...` needs no conversion at all.+ *+ * CRLF: batch files are line-oriented and cmd.exe is not reliably tolerant of LF, so this is CRLF+ * regardless of the host that generated it. `writer` names the agent in the bail comment only; the+ * codex wrapper's bytes are pinned by a test and must not move.+ */+export function buildWindowsHookWrapper(scriptFileName: string, writer = 'the agent'): string {+ const lines = [+ '@echo off',+ 'rem Managed by nodeterm (agent-hooks). Regenerated on every app launch; edits are lost.',+ 'setlocal EnableExtensions',+ `set "NT_SCRIPT=%~dp0${scriptFileName}"`,+ 'if not exist "%NT_SCRIPT%" goto :nt_drain',+ 'set "NT_SH="',+ ...windowsShProbeBatch(),+ '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 ${writer} 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',+ ''+ ]+ return lines.join('\r\n')+}++/**+ * `%SystemRoot%\System32\cmd.exe`, or bare `cmd` when that cannot be spelled unquoted.+ *+ * Unquoted is the whole constraint: quoting the program name is exactly what breaks under+ * PowerShell (a quoted leading token is a string literal, which is #685), so a resolved path+ * carrying a space or a shell metacharacter is unusable and the PATH lookup is the lesser evil.+ * `windir` is the fallback name for the same value on older installs.+ */+export function defaultWindowsCmdExe(): string {+ const root = process.env.SystemRoot || process.env.windir || ''+ if (!root) return 'cmd'+ const abs = `${root}\\System32\\cmd.exe`+ // Deliberately a strict allow-list, not a metacharacter deny-list: anything outside a plain+ // drive-letter path is not worth guessing at. The fallback then attempts a PATH lookup, which is+ // what this function exists to avoid — but an unusable absolute path would run nothing at all.+ return /^[A-Za-z]:\\[A-Za-z0-9\\._-]*$/.test(abs) ? abs : 'cmd'+}++/**+ * The hook-config command that runs a wrapper under EITHER PowerShell or cmd.exe:+ * `<abs cmd.exe> /d /c call "<wrapper> "`. Every piece (the absolute interpreter, `/d`, `call`, the+ * trailing space INSIDE the quotes) was measured through the shipped codex — see the long note in+ * codex.ts `buildManagedCommand`, which this was extracted from byte-for-byte (the codex trust hash+ * is computed over the result, so it must not drift).+ */+export function buildWindowsHookInvocation(wrapperPath: string, cmdExe: string = defaultWindowsCmdExe()): string {+ return `${cmdExe} /d /c call "${wrapperPath} "`+}++/** What the CLI launcher prints when no POSIX shell exists. Exported for the test and the docs. */+export const WINDOWS_SH_REQUIRED_MESSAGE =+ 'nodeterm: Git for Windows (sh.exe) is required to run this command. Install it from https://git-scm.com and retry.'++/**+ * A `.cmd` launcher for a user-invoked POSIX CLI shim (`nodeterm.sh`, `context.sh`) so an agent+ * whose tool shell is PowerShell or cmd.exe can run it: `& "<dir>\nodeterm.cmd" list`.+ *+ * Arguments pass through `%*` untouched — never re-quoted here, because a second quoting layer is+ * exactly what would split `--prompt "two words"` or eat a leading `--` value. Stdin is inherited.+ * Batch still re-parses `%*`, so `%`, and `&`/`|`/`<`/`>`/`^` outside quotes, are not safe inline+ * (the skill text says so and points at the file-based flags).+ *+ * `DisableDelayedExpansion` keeps a `!` in an argument or a profile path literal.+ */+export function buildWindowsShLauncher(scriptFileName: string): string {+ const lines = [+ '@echo off',+ 'rem Managed by nodeterm. Regenerated on every app launch; edits are lost.',+ 'setlocal EnableExtensions DisableDelayedExpansion',+ `set "NT_SCRIPT=%~dp0${scriptFileName}"`,+ 'set "NT_SH="',+ ...windowsShProbeBatch(),+ 'if not defined NT_SH goto :nt_nosh',+ 'if not exist "%NT_SCRIPT%" goto :nt_noscript',+ 'set "NT_ARG=%NT_SCRIPT:\\=/%"',+ '"%NT_SH%" "%NT_ARG%" %*',+ 'exit /b %ERRORLEVEL%',+ // Labels, not parenthesized blocks: the message holds `(sh.exe)`, and a `)` inside a block+ // closes it early. `>&2` leads so echo prints no trailing space.+ ':nt_nosh',+ `>&2 echo ${WINDOWS_SH_REQUIRED_MESSAGE}`,+ 'exit /b 1',+ ':nt_noscript',+ '>&2 echo nodeterm: "%NT_SCRIPT%" is missing. Restart nodeterm to reinstall it.',+ 'exit /b 1',+ ''+ ]+ return lines.join('\r\n')+}