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(hooks): give codex a Windows entry point — cmd.exe cannot run an sh one-liner
enes92ddd393b352
diff --git a/CLAUDE.md b/CLAUDE.mdindex 588ebeaec..72c2d90f8 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1211,7 +1211,24 @@ else, and its context links must keep classifying across restarts).*healed*, not preserved, on both the local and the SSH path). The per-event **`matcher`** the grokinstaller needs is why events are typed `ManagedHookEvent` (`string | {event, matcher}`): grok'stool matcher is a REGEX and must be `.*` — a bare `*` is invalid and silently stops tool events- firing. Plain-string events keep their byte-identical output for every other agent. **Both+ firing. Plain-string events keep their byte-identical output for every other agent.+ **Codex is the one agent whose hook command is NOT a POSIX one-liner on Windows** (issue #567):+ it builds the command as `cmd.exe /C <string>` (`codex-rs/hooks/src/engine/command_runner.rs`,+ rust-v0.151.0) unless the session has a shell configured, which a default Windows install has+ not — so `if [ -x '…' ]; then …; fi` answered `-x was unexpected at this time.` and **exit 1 on+ every event**, for the life of the node. Claude is fine there only because Claude Code runs its+ hooks through Git Bash. The fix is a batch entry point (`codex-hook.cmd`,+ `codex-windows-wrapper.ts`) written beside `codex.sh` and named by `buildManagedCommand`'s win32+ branch; it **locates a POSIX shell and runs the same script** — deliberately not a second+ implementation of the hook protocol, which would be two copies of the POST/failover/token/+ permission-poll to drift. Three rules it must keep: pass stdin through, DRAIN stdin on every bail+ (codex writes the payload there; #186/#187), and exit 0 when there is no shell or no script.+ Two traps around it: `buildManagedCommand`'s `platform` is the platform of the machine that will+ RUN codex, so `RemoteHooks.installCodexRemote` passes POSIX explicitly (a Windows desktop must not+ put a `.cmd` command on a Linux host); and `isManagedCommand` matches **both** leaves+ (`codex.sh` AND `codex-hook.cmd`) on every platform — matching only the local one would leave a+ pre-fix entry unrecognized, so the fresh one is appended beside it, which is #558 on a second+ file. Matching both is what REPAIRS an existing Windows install at the next launch. **Bothsides of the managed-entry match go through `normalizeHookCommand`** — the marker used to befolded to `/` while the stored command was compared raw, so on Windows nodeterm never recognizedits OWN entry and appended a fresh set every launch (#558: nine copies of nine events, ninediff --git a/src/core/agents/hooks/codex-windows-wrapper.ts b/src/core/agents/hooks/codex-windows-wrapper.tsnew file mode 100644index 000000000..685dedf51--- /dev/null+++ b/src/core/agents/hooks/codex-windows-wrapper.ts@@ -0,0 +1,95 @@+// The Windows entry point for the codex managed hook.+//+// WHY THIS EXISTS. Every managed hook command in this repo is a POSIX `sh` one-liner, and for+// claude that is fine on Windows because Claude Code runs its hooks through Git Bash. Codex does+// not: `codex-rs/hooks/src/engine/command_runner.rs` (rust-v0.151.0) builds the hook command as+//+// #[cfg(windows)] ("COMSPEC", "cmd.exe", "/C")+//+// and only substitutes a different shell when the session has one configured — which a default+// Windows install does not. So the string we write is handed to `cmd.exe /C`, which cannot parse+// `if [ -x '...' ]; then ...; fi`:+//+// -x was unexpected at this time. exit=1+//+// That is exit 1 on EVERY event, for the whole life of a codex node: no status badge, no+// PermissionRequest forwarding, no Stop to clear RUNNING, and a visible "hook exited with code 1"+// line each time (issue #567). `/bin/sh` would not have rescued a cmd-parsable variant either —+// Git Bash's shell is at `C:\Program Files\Git\bin\sh.exe` and is not on PATH.+//+// WHAT THIS IS NOT. It is deliberately **not** a second implementation of the hook protocol. The+// managed script (`managed-script.ts`) stays the one POSIX source of truth for POSTing the payload,+// the endpoint failover, the node token and the permission-answer poll; a `.cmd`/PowerShell port of+// all that is two copies of one protocol, which is the drift this codebase pays for repeatedly.+// This file only finds a POSIX shell and hands it the script.+//+// THREE THINGS THE WRAPPER OWES, and each is a real failure if dropped:+// 1. **Pass stdin through untouched.** Codex writes the hook payload to the child's stdin; the+// script reads it. `cmd.exe` does not buffer or consume it, so the plain call inherits it.+// 2. **Drain stdin on every bail.** A wrapper that exits without reading can EPIPE the writer+// mid-payload — the exact reason the claude/gemini command carries `else cat >/dev/null 2>&1`+// (#186/#187), and the one thing the codex POSIX command was missing.+// 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.++/** 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++/** 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).+ */+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.',+ 'setlocal EnableExtensions',+ '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"',+ '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')+}diff --git a/src/core/agents/hooks/codex.test.ts b/src/core/agents/hooks/codex.test.tsindex 653736231..aef1d791e 100644--- a/src/core/agents/hooks/codex.test.ts+++ b/src/core/agents/hooks/codex.test.ts@@ -1,18 +1,91 @@import { describe, expect, it } from 'vitest'import { buildCodexHooksAndTrust, buildManagedCommand, CODEX_EVENTS } from './codex'import { computeTrustedHash } from './codex-trust'+import { buildCodexWindowsWrapper, WINDOWS_SH_CANDIDATES } from './codex-windows-wrapper'-// The command form a codex hook carries: `if [ -x '<script>' ]; then /bin/sh '<script>'; fi`.-// The trust hash is computed over THIS exact byte string, so the hooks.json command and the-// config.toml trust entry must always come from the same builder.+// The command form a codex hook carries. The trust hash is computed over THIS exact byte string, so+// the hooks.json command and the config.toml trust entry must always come from the same builder.describe('buildManagedCommand', () => {- it('wraps the script path in the [ -x ] guard with POSIX single-quoting', () => {- expect(buildManagedCommand('/a/b/codex.sh')).toBe(- "if [ -x '/a/b/codex.sh' ]; then /bin/sh '/a/b/codex.sh'; fi"+ it('POSIX: wraps the script path in the [ -x ] guard with POSIX single-quoting', () => {+ expect(buildManagedCommand('/a/b/codex.sh', 'linux')).toBe(+ "if [ -x '/a/b/codex.sh' ]; then /bin/sh '/a/b/codex.sh'; else cat >/dev/null 2>&1 || :; fi"+ )+ })++ it('POSIX: drains stdin when it bails — codex writes the payload there (#186/#187)', () => {+ // Without this, a bail that never reads can EPIPE the writer mid-payload. It is the same+ // `else` branch install-helper's command has always carried; codex's was the one without it.+ expect(buildManagedCommand('/a/b/codex.sh', 'darwin')).toContain('else cat >/dev/null 2>&1')+ })++ // Issue #567: codex runs a hook command through `cmd.exe /C` on Windows+ // (codex-rs/hooks/src/engine/command_runner.rs, rust-v0.151.0), which answers+ // "-x was unexpected at this time." and exit 1 to an `sh` one-liner — on EVERY event, for the+ // life of the node.+ it('win32: points cmd.exe at the batch wrapper beside the script, not at an sh one-liner', () => {+ expect(buildManagedCommand('C:\\Users\\u\\.nodeterm\\agent-hooks\\codex.sh', 'win32')).toBe(+ '"C:\\Users\\u\\.nodeterm\\agent-hooks\\codex-hook.cmd"'+ )+ expect(buildManagedCommand('C:\\a\\codex.sh', 'win32')).not.toContain('[ -x')+ expect(buildManagedCommand('C:\\a\\codex.sh', 'win32')).not.toContain('/bin/sh')+ })++ it('win32: the path stays one quoted token — a user profile routinely has a space in it', () => {+ expect(buildManagedCommand('C:\\Users\\First Last\\agent-hooks\\codex.sh', 'win32')).toBe(+ '"C:\\Users\\First Last\\agent-hooks\\codex-hook.cmd"'+ )+ })++ // The platform is the machine that will RUN codex. RemoteHooks writes this into an SSH host's+ // hooks.json, and that host is POSIX whatever the desktop is — so a Windows desktop must not put+ // a `.cmd` command on a Linux server.+ it('the platform argument decides, not the host generating the string', () => {+ expect(buildManagedCommand('/home/u/.nodeterm/agent-hooks/codex.sh', 'linux')).toContain(+ '/bin/sh')})})+describe('buildCodexWindowsWrapper', () => {+ const wrapper = buildCodexWindowsWrapper()++ it('runs the SAME codex.sh, found beside itself — no second copy of the protocol', () => {+ // The wrapper only locates a shell. Everything about the hook protocol (the POST, the endpoint+ // failover, the node token, the permission-answer poll) stays in the one POSIX script.+ expect(wrapper).toContain('set "NT_SCRIPT=%~dp0codex.sh"')+ expect(wrapper).not.toContain('curl')+ })++ it('searches Git for Windows layouts before PATH', () => {+ for (const candidate of WINDOWS_SH_CANDIDATES) expect(wrapper).toContain(candidate)+ const lastCandidate = Math.max(...WINDOWS_SH_CANDIDATES.map((c) => wrapper.indexOf(c)))+ expect(wrapper.indexOf('%%~$PATH:I')).toBeGreaterThan(lastCandidate)+ })++ it('hands sh a forward-slash path, which needs no MSYS conversion', () => {+ expect(wrapper).toContain('set "NT_ARG=%NT_SCRIPT:\\=/%"')+ expect(wrapper).toContain('"%NT_SH%" "%NT_ARG%"')+ })++ it('drains stdin and exits 0 on every bail — no shell, no script', () => {+ // "nodeterm is not installed here" must look like nothing happening, not a broken hook; and a+ // bail that never reads codex's payload can EPIPE the writer.+ expect(wrapper).toContain('if not exist "%NT_SCRIPT%" goto :nt_drain')+ expect(wrapper).toContain('if not defined NT_SH goto :nt_drain')+ expect(wrapper.slice(wrapper.indexOf(':nt_drain'))).toContain('findstr /r ".*" >nul 2>&1')+ expect(wrapper.trimEnd().endsWith('exit /b 0')).toBe(true)+ })++ it('propagates the script exit code on the happy path', () => {+ expect(wrapper).toContain('exit /b %ERRORLEVEL%')+ })++ it('is CRLF — cmd.exe is not reliably tolerant of LF in a batch file', () => {+ expect(wrapper).toContain('\r\n')+ expect(wrapper.replace(/\r\n/g, '')).not.toContain('\n')+ })+})+describe('buildCodexHooksAndTrust', () => {it('returns null for an unparseable (null) hooks.json so the caller never clobbers it', () => {expect(buildCodexHooksAndTrust(null, 'cmd', '/h/hooks.json')).toBeNull()@@ -86,7 +159,13 @@ describe('buildCodexHooksAndTrust', () => {// hooks fire correctly (codex-cli 0.114.0). Locking them guards the exact JSON canonicalization// codex hashes against — any drift here silently breaks every codex status badge.it('matches the byte-exact trust hashes codex accepts in the field', () => {- const command = buildManagedCommand('/root/.nodeterm-server/agent-hooks/codex.sh')+ // The command is a FROZEN LITERAL, not `buildManagedCommand(...)`. These hashes are evidence+ // about codex's CANONICALIZATION, captured from a live config.toml — regenerating them from+ // whatever the builder currently emits would silently destroy the only external check we have+ // on it. Change the command string here only if you have re-captured the hashes from a host+ // where the hooks demonstrably fire.+ const command =+ "if [ -x '/root/.nodeterm-server/agent-hooks/codex.sh' ]; then /bin/sh '/root/.nodeterm-server/agent-hooks/codex.sh'; fi"const built = buildCodexHooksAndTrust({}, command, '/root/.codex/hooks.json')!const byLabel = Object.fromEntries(built.trustEntries.map((e) => [e.eventLabel, computeTrustedHash(e)]))expect(byLabel).toMatchObject({@@ -105,6 +184,43 @@ describe('buildCodexHooksAndTrust', () => {})})+ // Issue #567 repair. A Windows machine already carries the unrunnable POSIX command in its+ // hooks.json. If the managed-entry matcher only recognized the leaf THIS platform writes, that+ // entry would survive the strip and the fresh `.cmd` entry would be APPENDED beside it — #558's+ // duplicate-per-launch, on the same file. Both leaves are matched, always, so the next app launch+ // collapses the file to exactly one runnable entry.+ it('replaces a pre-fix POSIX entry with the Windows one instead of appending beside it', () => {+ const stale = {+ hooks: [+ {+ type: 'command',+ command:+ "if [ -x 'C:\\Users\\u\\.nodeterm\\agent-hooks\\codex.sh' ]; then /bin/sh 'C:\\Users\\u\\.nodeterm\\agent-hooks\\codex.sh'; fi"+ }+ ]+ }+ const command = buildManagedCommand('C:\\Users\\u\\.nodeterm\\agent-hooks\\codex.sh', 'win32')+ const built = buildCodexHooksAndTrust(+ { hooks: { Stop: [stale], SessionStart: [stale] } },+ command,+ 'C:\\Users\\u\\.codex\\hooks.json'+ )!+ for (const ev of ['Stop', 'SessionStart']) {+ expect(built.config.hooks![ev]).toEqual([{ hooks: [{ type: 'command', command }] }])+ }+ })++ // The mirror of the above: a POSIX host that somehow carries a `.cmd` entry (a settings file+ // copied between machines) is repaired the same way rather than accumulating both.+ it('replaces a stray Windows entry on a POSIX install', () => {+ const stale = {+ hooks: [{ type: 'command', command: '"/home/u/.nodeterm/agent-hooks/codex-hook.cmd"' }]+ }+ const command = buildManagedCommand('/home/u/.nodeterm/agent-hooks/codex.sh', 'linux')+ const built = buildCodexHooksAndTrust({ hooks: { Stop: [stale] } }, command, '/h/hooks.json')!+ expect(built.config.hooks!.Stop).toEqual([{ hooks: [{ type: 'command', command }] }])+ })+it('subscribes the subagent pair (spawn_agent fan-out) with snake_case labels', () => {expect(CODEX_EVENTS).toContain('SubagentStart')expect(CODEX_EVENTS).toContain('SubagentStop')diff --git a/src/core/agents/hooks/codex.ts b/src/core/agents/hooks/codex.tsindex 8bb87d050..fab6f24b0 100644--- a/src/core/agents/hooks/codex.ts+++ b/src/core/agents/hooks/codex.ts@@ -28,6 +28,7 @@ import { randomUUID } from 'crypto'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 {computeTrustedHash,getCodexCanonicalTrustPath,@@ -105,7 +106,18 @@ function isManagedCommand(command: string | undefined): boolean {// Separator folding comes from install-helper so the two installers can never disagree about// what makes an entry ours — the drift that made the JSON-settings agents duplicate on Windows// (#558). Only the normalizer is shared; codex's merge stays its own (the trust hash).- return normalizeHookCommand(command).includes(`agent-hooks/${SCRIPT_FILE_NAME}`)+ //+ // BOTH leaves, always, on every platform. The Windows command names `codex-hook.cmd` while every+ // pre-#567 Windows install (and every POSIX one) names `codex.sh`, so matching only the leaf THIS+ // platform writes would fail to recognize an entry we ourselves put there — and `mergeManagedHook`+ // logic here would keep it and append a second one, which is #558 all over again. Matching both is+ // also what REPAIRS a Windows hooks.json that already carries the unrunnable POSIX command: it is+ // stripped before the fresh one is pushed, so the next app launch heals the file.+ const c = normalizeHookCommand(command)+ return (+ c.includes(`agent-hooks/${SCRIPT_FILE_NAME}`) ||+ c.includes(`agent-hooks/${CODEX_WINDOWS_WRAPPER_FILE}`)+ )}function definitionHasManagedCommand(def: HookDefinition): boolean {@@ -128,15 +140,35 @@ function removeManagedFromDefinitions(defs: HookDefinition[]): HookDefinition[]})}-// Why: form the POSIX command the SAME way for hooks.json AND the trust entry —-// the trust hash is computed over this exact byte string, so any divergence-// makes Codex reject the hook. The POSIX wrapper's-// `[ -x ... ]` guard makes a missing/non-executable script a silent no-op so a-// broken install never poisons the session with exit-127 noise.-export function buildManagedCommand(script: string): string {+/**+ * The hook command, formed the SAME way for hooks.json AND the trust entry — the trust hash is+ * computed over this exact byte string, so any divergence makes Codex reject the hook. The POSIX+ * form's `[ -x ... ]` guard makes a missing/non-executable script a silent no-op, so a broken+ * install never poisons the session with exit-127 noise.+ *+ * `platform` is the platform of the machine that will RUN codex, not the one generating the string,+ * and it is a parameter for exactly that reason: `RemoteHooks.installCodexRemote` writes this into+ * an SSH host's `~/.codex/hooks.json`, and that host is POSIX whatever the desktop is. A default of+ * `process.platform` would make a Windows desktop install a `.cmd` command on a Linux server.+ */+export function buildManagedCommand(+ script: string,+ platform: NodeJS.Platform | string = process.platform+): string {+ if (platform === 'win32') {+ // Codex hands this to `cmd.exe /C`, which cannot parse an `sh` one-liner (issue #567). Point it+ // at the batch wrapper written beside the script; the wrapper finds a POSIX shell and runs the+ // very same `codex.sh`. Quoted as one token: cmd strips a single surrounding pair, and the path+ // routinely contains spaces (`C:\Users\First Last\...`).+ const dir = script.slice(0, Math.max(script.lastIndexOf('\\'), script.lastIndexOf('/')) + 1)+ return `"${dir}${CODEX_WINDOWS_WRAPPER_FILE}"`+ }// POSIX single-quote escape so $, `, ", \ in the path are taken literally.const quoted = `'${script.replaceAll("'", "'\\''")}'`- return `if [ -x ${quoted} ]; then /bin/sh ${quoted}; fi`+ // The `else` branch DRAINS stdin. Codex writes the hook payload there, so a bail that never reads+ // it can EPIPE the writer mid-payload — the same reason install-helper's command carries it+ // (#186/#187). This was the one managed command missing it.+ return `if [ -x ${quoted} ]; then /bin/sh ${quoted}; else cat >/dev/null 2>&1 || :; fi`}// Pure core of the codex install: given the CURRENT parsed hooks.json (or {} for@@ -258,10 +290,35 @@ function writeManagedScript(file: string): void {}}+/** The batch entry point beside the script — Windows only; nothing else ever reads it. */+function writeWindowsWrapper(script: string): void {+ const dir = path.dirname(script)+ const file = path.join(dir, CODEX_WINDOWS_WRAPPER_FILE)+ mkdirSync(dir, { recursive: true })+ const tmp = path.join(dir, `.${Date.now()}-${randomUUID()}.tmp`)+ let renamed = false+ try {+ writeFileSync(tmp, buildCodexWindowsWrapper(), 'utf8')+ renameAtomicSync(tmp, file)+ renamed = true+ } finally {+ if (!renamed && existsSync(tmp)) {+ try {+ unlinkSync(tmp)+ } catch {+ /* best effort */+ }+ }+ }+}+export function installCodexHooks(): void {const script = scriptPath()try {writeManagedScript(script)+ // Order matters: the wrapper must exist before hooks.json points codex at it, or the first+ // events after an install land on a missing file.+ if (process.platform === 'win32') writeWindowsWrapper(script)} catch (e) {console.warn('[agent-hooks] codex script write failed', e)returndiff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.tsindex 80d58d34f..1ed718f27 100644--- a/src/main/remote-ssh/remote-hooks.ts+++ b/src/main/remote-ssh/remote-hooks.ts@@ -382,7 +382,9 @@ export class RemoteHooks {),buildManagedScript('codex', REMOTE_IDENTITY_ROOT))- const command = buildCodexManagedCommand(script)+ // POSIX explicitly: the platform argument is the HOST's, never this desktop's. A Windows+ // desktop writes a `.cmd` command locally (issue #567) and must not put one on a Linux server.+ const command = buildCodexManagedCommand(script, 'linux')const codexHome = `${home}/.codex`const hooksFile = `${codexHome}/hooks.json`const configToml = `${codexHome}/config.toml`