Skip to content

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.

fix(hooks): name the interpreter in the codex Windows hook command

Erik Zwep0d2334b20e09
diff --git a/src/core/agents/hooks/codex-windows-wrapper.ts b/src/core/agents/hooks/codex-windows-wrapper.ts
index 685dedf51..834860187 100644
--- a/src/core/agents/hooks/codex-windows-wrapper.ts
+++ b/src/core/agents/hooks/codex-windows-wrapper.ts
@@ -2,20 +2,31 @@
//
// 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
+// not. The hook runs in the SESSION'S shell, and `codex-rs/shell-command/src/shell_detect.rs`
+// (rust-v0.153.4) prefers PowerShell on Windows:
+//
+// if cfg!(windows) { get_shell(ShellType::PowerShell).unwrap_or_else(ultimate_fallback_shell) }
+//
+// with `codex-rs/hooks/src/engine/command_runner.rs`'s
//
// #[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`:
+// as the fallback. Both are reachable — PowerShell was what the shipped codex-cli 0.153.4 used on a
+// stock Windows 11 install here. NEITHER can parse `if [ -x '...' ]; then ...; fi`:
//
-// -x was unexpected at this time. exit=1
+// cmd.exe -x was unexpected at this time. exit=1
+// PowerShell Missing '(' after 'if' in if statement. 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.
+// line each time (issues #567, #685). `/bin/sh` would not have rescued a parsable variant either:
+// on the machine this was measured on, Git Bash's shell sits at `C:\Program Files\Git\bin\sh.exe`
+// and is not on PATH — hook commands of `& sh '<script>'` and `& sh.exe '<script>'` both came back
+// Failed. Hence the search below is by absolute path, with PATH only as its last resort.
+//
+// WHICH INTERPRETER RUNS THE COMMAND is therefore not something this file may assume. It is pinned
+// in the command itself — `buildManagedCommand` emits `<abs cmd.exe> /d /c call "<this wrapper> "`,
+// measured to run this file under both — so everything below can rely on being run by cmd.exe.
//
// 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,
diff --git a/src/core/agents/hooks/codex.test.ts b/src/core/agents/hooks/codex.test.ts
index 5fcb52ee8..b1f874b9c 100644
--- a/src/core/agents/hooks/codex.test.ts
+++ b/src/core/agents/hooks/codex.test.ts
@@ -1,5 +1,10 @@
-import { describe, expect, it } from 'vitest'
-import { buildCodexHooksAndTrust, buildManagedCommand, CODEX_EVENTS } from './codex'
+import { describe, expect, it, vi } from 'vitest'
+import {
+ buildCodexHooksAndTrust,
+ buildManagedCommand,
+ CODEX_EVENTS,
+ defaultWindowsCmdExe
+} from './codex'
import { computeTrustedHash } from './codex-trust'
import { buildCodexWindowsWrapper, WINDOWS_SH_CANDIDATES } from './codex-windows-wrapper'
@@ -18,22 +23,74 @@ describe('buildManagedCommand', () => {
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')
+ // These assert what the builder CONSTRUCTS. They cannot show that the string executes — that took
+ // running codex on Windows against a throwaway CODEX_HOME, and those results live in the PR for
+ // #685. What a unit test can do is pin the spelling those measurements validated, so a later edit
+ // cannot quietly walk away from it. `cmdExe` is passed explicitly throughout: the default reads
+ // the environment, and these assertions must not depend on the host running them.
+ const CMD = 'C:\\WINDOWS\\System32\\cmd.exe'
+
+ // Issues #567 / #685. The hook runs in the session's shell, and shell_detect.rs prefers PowerShell
+ // on Windows (rust-v0.153.4); command_runner.rs's COMSPEC/`cmd.exe /C` is the fallback. An `sh`
+ // one-liner is a parse error to both — "-x was unexpected at this time." / "Missing '(' after
+ // 'if' in if statement." — exit 1 on EVERY event, for the life of the node.
+ it('win32: constructs a command pointing at the batch wrapper, not an sh one-liner', () => {
+ expect(
+ buildManagedCommand('C:\\Users\\u\\.nodeterm\\agent-hooks\\codex.sh', 'win32', CMD)
+ ).toBe(`${CMD} /d /c call "C:\\Users\\u\\.nodeterm\\agent-hooks\\codex-hook.cmd "`)
+ expect(buildManagedCommand('C:\\a\\codex.sh', 'win32', CMD)).not.toContain('[ -x')
+ expect(buildManagedCommand('C:\\a\\codex.sh', 'win32', CMD)).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 regression #685 reports. A BARE quoted path — what #567 emitted — is a valid PowerShell
+ // expression: a string literal. PowerShell echoes it, exits 0 and runs nothing, so codex reports
+ // the hook `Completed` while no hook ever fired (measured). A silently dark badge is strictly
+ // worse than the exit-1 noise #567 set out to remove, so the command must never START with a
+ // quote — that is the whole defect, in one assertion.
+ it('win32: constructs a command that names an interpreter, never a bare quoted path', () => {
+ const command = buildManagedCommand('C:\\Users\\u\\.nodeterm\\agent-hooks\\codex.sh', 'win32', CMD)
+ expect(command.startsWith('"')).toBe(false)
+ expect(command.startsWith(`${CMD} /d /c call "`)).toBe(true)
+ })
+
+ // Two separate pieces, both load-bearing, both easy to mistake for noise:
+ // `call` stops cmd's /C rule stripping the quote pair around a path holding `&`, `(`
+ // or `)`, which cmd would then re-parse as metacharacters.
+ // trailing space makes PowerShell keep that quoting when it builds cmd's native argument line.
+ // Measured through the shipped codex: with both, profile paths containing `&` and `(` run; with
+ // `call` alone they Fail. A tidy-up that "removes the stray space" would silently reintroduce the
+ // breakage, hence this test.
+ it('win32: keeps the call + trailing-space quoting that survives & and ( in a profile path', () => {
+ const command = buildManagedCommand('C:\\Users\\A&B (x)\\agent-hooks\\codex.sh', 'win32', CMD)
+ expect(command).toBe(`${CMD} /d /c call "C:\\Users\\A&B (x)\\agent-hooks\\codex-hook.cmd "`)
+ expect(command.endsWith(' "')).toBe(true)
+ })
+
+ it('win32: constructs one quoted token — a user profile routinely has a space in it', () => {
+ // The documented `cmd /s /c ""..."" ` doubling was measured Failed — PowerShell collapses the
+ // doubled quotes before cmd sees them — so the quoting stays a single surrounding pair.
+ const command = buildManagedCommand('C:\\Users\\First Last\\agent-hooks\\codex.sh', 'win32', CMD)
+ expect(command).toBe(`${CMD} /d /c call "C:\\Users\\First Last\\agent-hooks\\codex-hook.cmd "`)
+ expect(command).not.toContain('""')
+ })
+
+ // The program name must be usable UNQUOTED, because a quoted leading token is the #685 bug
+ // itself. Anything that could not be written bare falls back to the PATH lookup.
+ it('win32: falls back to bare cmd when the resolved interpreter path needs quoting', () => {
+ vi.stubEnv('SystemRoot', 'C:\\Windows With Space')
+ vi.stubEnv('windir', '')
+ expect(defaultWindowsCmdExe()).toBe('cmd')
+
+ vi.stubEnv('SystemRoot', 'C:\\WINDOWS')
+ expect(defaultWindowsCmdExe()).toBe('C:\\WINDOWS\\System32\\cmd.exe')
+
+ // Neither variable set — the POSIX case, since this function is exported and callable there.
+ vi.stubEnv('SystemRoot', '')
+ expect(defaultWindowsCmdExe()).toBe('cmd')
+ vi.unstubAllEnvs()
+
+ expect(buildManagedCommand('C:\\a\\codex.sh', 'win32', 'cmd').startsWith('cmd /d /c call "'))
+ .toBe(true)
})
// The platform is the machine that will RUN codex. RemoteHooks writes this into an SSH host's
@@ -210,6 +267,31 @@ describe('buildCodexHooksAndTrust', () => {
}
})
+ // Issue #685 repair. A Windows machine on which a #567 build installed successfully carries the
+ // BARE quoted wrapper path — the entry PowerShell reads as a string literal and never runs. It
+ // has to be REPLACED, not appended beside: were the matcher to miss it, the dead entry would
+ // survive every launch while still being reported `Completed`. The matcher keys off the
+ // `agent-hooks/codex-hook.cmd` tail, which both spellings carry, so the strip catches it.
+ it('replaces the pre-#685 bare-quoted wrapper entry with the cmd /c one', () => {
+ const stale = {
+ hooks: [
+ {
+ type: 'command' as const,
+ command: '"C:\\Users\\u\\.nodeterm\\agent-hooks\\codex-hook.cmd"'
+ }
+ ]
+ }
+ 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', () => {
diff --git a/src/core/agents/hooks/codex.ts b/src/core/agents/hooks/codex.ts
index fab6f24b0..820d8bea4 100644
--- a/src/core/agents/hooks/codex.ts
+++ b/src/core/agents/hooks/codex.ts
@@ -140,6 +140,24 @@ function removeManagedFromDefinitions(defs: HookDefinition[]): HookDefinition[]
})
}
+/**
+ * `%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 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
@@ -150,18 +168,70 @@ function removeManagedFromDefinitions(defs: HookDefinition[]): HookDefinition[]
* 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.
+ *
+ * `cmdExe` is likewise a parameter so the BODY stays a pure function of its arguments — it feeds the
+ * trust hash, and a builder that reached for the environment mid-computation would be harder to
+ * pin down. The environment is read only to compute the default, once, at the call. The install
+ * path takes that default; tests pass their own.
*/
export function buildManagedCommand(
script: string,
- platform: NodeJS.Platform | string = process.platform
+ platform: NodeJS.Platform | string = process.platform,
+ cmdExe: string = defaultWindowsCmdExe()
): 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\...`).
+ // Point codex at the batch wrapper written beside the script; the wrapper finds a POSIX shell
+ // and runs the very same `codex.sh` (issue #567).
+ //
+ // NAMING THE INTERPRETER is the fix for #685. #567 emitted the bare quoted wrapper path, which
+ // is what `command_runner.rs`'s COMSPEC/`cmd.exe /C` shape needs. But that is codex's FALLBACK:
+ // the hook runs in the session's shell, and `shell_detect.rs::default_user_shell_from_path`
+ // prefers PowerShell on Windows (`if cfg!(windows) { get_shell(ShellType::PowerShell) ... }`) —
+ // true at the rust-v0.153.4 tag, and measured on the shipped codex-cli 0.153.4 with a stock
+ // config and COMSPEC=cmd.exe. To PowerShell a lone quoted path is a string LITERAL: it echoes
+ // the path, exits 0 and runs nothing, so codex reports the hook `Completed` while no hook ever
+ // fired. A silent no-op is worse than the exit-1 noise #567 removed, because nothing in the UI
+ // says the badge went dark.
+ //
+ // Both interpreters are reachable, so the command must not assume either. Every piece below was
+ // measured, through the shipped codex AND from a cmd.exe parent, with the real wrapper and a
+ // stdin-consuming codex.sh:
+ //
+ // `<abs cmd.exe>` not bare `cmd`. PowerShell resolves a bare name against PATH, and a
+ // `cmd.*` planted in a shared directory earlier on PATH wins — a directory
+ // another principal may be able to write without any access to this user's
+ // profile, so this is NOT the same attacker as one who could edit the
+ // wrapper. Falls back to bare `cmd` only if the resolved path is not safe to
+ // write unquoted (see defaultWindowsCmdExe).
+ // `/d` skips the HKCU/HKLM Command Processor AutoRun entries. Not a security
+ // boundary — HKCU AutoRun and the wrapper are writable by the same user —
+ // but an AutoRun script's stdout would otherwise prefix every hook's output,
+ // and its cwd/env changes would leak into the hook.
+ // `call` needed under a cmd parent: it stops cmd's /C rule stripping the quote pair
+ // around a path holding `&`, `(` or `)`, which would otherwise be re-parsed
+ // as metacharacters.
+ // trailing space INSIDE the quotes, load-bearing, not a typo. It is what makes PowerShell
+ // keep the quoting when it builds cmd's native argument line — without it,
+ // `cmd /d /c call "<path with & or (>"` was measured Failed through the
+ // shipped codex and Completed from a cmd parent; with it, both run. (Direct
+ // check: `powershell -Command 'cmd /d /c echo "paren(x)"'` prints an
+ // unquoted `paren(x)`, while `"paren(x) "` keeps its quotes.)
+ // `cmd /s /c ""..."" `, the documented workaround, is NOT usable — PowerShell
+ // collapses the doubled quotes before cmd sees them (Failed).
+ //
+ // KNOWN LIMITS, all measured, none fixed here, and none of them regressions — the #567 form did
+ // not run at all under PowerShell, for any path:
+ // - `^` in the path fails under both parents.
+ // - `$` and a backtick fail under PowerShell (it interpolates / escapes) and work under cmd.
+ // - `%NAME%` is expanded by both parents when that variable exists.
+ // Each needs the character in the user's own profile name, which Windows permits.
+ //
+ // ALSO MEASURED, and the reason nothing here depends on an exit code: under PowerShell codex
+ // sees the hook's exit status collapsed to 0/1 (a direct cmd parent preserves 0/1/2/37), so the
+ // 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 `"${dir}${CODEX_WINDOWS_WRAPPER_FILE}"`
+ return `${cmdExe} /d /c call "${dir}${CODEX_WINDOWS_WRAPPER_FILE} "`
}
// POSIX single-quote escape so $, `, ", \ in the path are taken literally.
const quoted = `'${script.replaceAll("'", "'\\''")}'`