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(windows): preserve cmd shim argv and stdin

Fabricio Casalifafb9b79b2ca
diff --git a/CLAUDE.md b/CLAUDE.md
index ec2ee7285..222f6d6c3 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -61,12 +61,13 @@ means — and what you may assume when writing a feature — is three tiers, not
follows `PATHEXT`, which means an npm-installed CLI may resolve to `<name>.cmd`; Node's
`execFile`/`spawn` still cannot execute that path directly (`spawn EINVAL`). App-owned
subprocesses must pass their resolved executable and argv through `directExecutableInvocation`
- (`src/core/exec-path.ts`), which maps an npm `.cmd` to its equivalent sibling `.ps1` and invokes
- it with PowerShell `-File`. The argv remains structured all the way through — never replace this
- with `shell:true`, because commit prompts and other user-controlled arguments would then be
- reinterpreted as shell syntax. A `.bat` has no npm sibling contract and fails closed. This helper
- is for subprocess calls; interactive terminal agent launches keep using `agent-launch.ts`'s
- separately tested shell plan.
+ (`src/core/exec-path.ts`), which invokes `.cmd` through a hidden `cmd.exe` with explicit escaping,
+ verbatim arguments and delayed expansion off. Never replace this with `shell:true`: commit prompts
+ and other user-controlled arguments would then be reinterpreted as shell syntax. The helper fails
+ closed for `.bat`/`.ps1`, CR/LF/NUL inside argv, and command lines above cmd's real 8,191-character
+ ceiling. stdin stays a byte stream directly into the shim; routing it through an npm `.ps1` shim's
+ `$input | & node` text pipeline corrupts Unicode and line endings under Windows PowerShell 5.1.
+ Interactive terminal agent launches keep using `agent-launch.ts`'s separately tested shell plan.
## Commands
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index d411791be..ea7fefaac 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -181,10 +181,11 @@ lane unaffected.
- **Finding a Windows executable is not the same as being able to spawn it.** A PATH lookup may
correctly resolve an npm CLI to `<name>.cmd`, but Node's `execFile`/`spawn` cannot execute that
shim directly. For short-lived app-owned subprocesses, pass the resolved path and argv through
- `directExecutableInvocation` (`src/core/exec-path.ts`): it uses npm's sibling `.ps1` shim via
- PowerShell `-File`, preserving the argv boundary. Do not fix this with `shell: true`; prompts and
- other user-controlled arguments would become shell syntax. A `.bat` file has no equivalent safe
- entry point and must fail explicitly.
+ `directExecutableInvocation` (`src/core/exec-path.ts`): it uses hidden `cmd.exe` with explicit
+ escaping, verbatim arguments and delayed expansion off. Do not fix this with `shell: true`;
+ prompts and other user-controlled arguments would become shell syntax. `.bat`/`.ps1`, CR/LF/NUL
+ arguments and lines above cmd's limit fail explicitly. Keep stdin direct: PowerShell's text
+ pipeline changes Unicode and line endings under Windows PowerShell 5.1.
- **Normalize BOTH sides of a path comparison, through one function.** A marker normalized where
it is built and matched raw where it is used is a no-op on the machine you wrote it on and a
diff --git a/src/core/claude-cli.test.ts b/src/core/claude-cli.test.ts
index b0ca949d3..700ac5379 100644
--- a/src/core/claude-cli.test.ts
+++ b/src/core/claude-cli.test.ts
@@ -102,17 +102,18 @@ describe.skipIf(process.platform !== 'win32')('probeClaudeCliAt — Windows npm
fs.rmSync(dir, { recursive: true, force: true })
})
- it('probes a .cmd CLI through its sibling .ps1 entry point', async () => {
+ it('probes a .cmd CLI through cmd.exe', async () => {
const cmd = path.join(dir, 'claude.cmd')
- fs.writeFileSync(cmd, '@echo off\r\nexit /b 91\r\n')
+ const script = path.join(dir, 'claude.js')
fs.writeFileSync(
- path.join(dir, 'claude.ps1'),
+ script,
[
- "if ($args[0] -eq '--version') { Write-Output '2.1.226 (Claude Code)'; exit 0 }",
- "if ($args[0] -eq '--help') { Write-Output ' --session-id <uuid>'; exit 0 }",
- 'exit 92'
- ].join('\r\n')
+ "if (process.argv[2] === '--version') console.log('2.1.226 (Claude Code)')",
+ "else if (process.argv[2] === '--help') console.log(' --session-id <uuid>')",
+ 'else process.exitCode = 92'
+ ].join('\n')
)
+ fs.writeFileSync(cmd, `@echo off\r\n"${process.execPath}" "${script}" %*\r\n`)
expect(await probeClaudeCliAt(cmd)).toEqual({
version: '2.1.226 (Claude Code)',
diff --git a/src/core/claude-cli.ts b/src/core/claude-cli.ts
index b58073c6d..d4be78bab 100644
--- a/src/core/claude-cli.ts
+++ b/src/core/claude-cli.ts
@@ -48,6 +48,7 @@ export async function probeClaudeCliAt(bin: string): Promise<ClaudeCliCaps> {
const versionInvocation = directExecutableInvocation(bin, ['--version'])
if (!versionInvocation) return UNKNOWN_CLAUDE_CLI_CAPS
const { stdout } = await execFileP(versionInvocation.executable, versionInvocation.args, {
+ ...versionInvocation.options,
timeout: PROBE_TIMEOUT_MS
})
// `--help` is a second spawn, paid once per process (this whole probe is memoized). Its
@@ -56,6 +57,7 @@ export async function probeClaudeCliAt(bin: string): Promise<ClaudeCliCaps> {
const helpInvocation = directExecutableInvocation(bin, ['--help'])
const help = helpInvocation
? await execFileP(helpInvocation.executable, helpInvocation.args, {
+ ...helpInvocation.options,
timeout: PROBE_TIMEOUT_MS
})
.then((r) => r.stdout)
diff --git a/src/core/codex-identity-caps.test.ts b/src/core/codex-identity-caps.test.ts
index bc910e08d..4e294706b 100644
--- a/src/core/codex-identity-caps.test.ts
+++ b/src/core/codex-identity-caps.test.ts
@@ -200,17 +200,18 @@ describe('codexCliSupportsRemote', () => {
})
describe.skipIf(process.platform !== 'win32')('probeCodexRemoteFlagAt — Windows npm shim', () => {
- it('uses the sibling PowerShell shim for both help probes', async () => {
+ it('uses cmd.exe for both help probes', async () => {
const cmd = path.join(dir, 'codex.cmd')
- fs.writeFileSync(cmd, '@echo off\r\nexit /b 91\r\n')
+ const script = path.join(dir, 'codex.js')
fs.writeFileSync(
- path.join(dir, 'codex.ps1'),
+ script,
[
- "if ($args.Count -eq 1 -and $args[0] -eq '--help') { Write-Output 'no flag'; exit 0 }",
- "if ($args[0] -eq 'resume' -and $args[1] -eq '--help') { Write-Output ' --remote <URL>'; exit 0 }",
- 'exit 92'
- ].join('\r\n')
+ "if (process.argv[2] === '--help') console.log('no flag')",
+ "else if (process.argv[2] === 'resume' && process.argv[3] === '--help') console.log(' --remote <URL>')",
+ 'else process.exitCode = 92'
+ ].join('\n')
)
+ fs.writeFileSync(cmd, `@echo off\r\n"${process.execPath}" "${script}" %*\r\n`)
await expect(probeCodexRemoteFlagAt(cmd)).resolves.toBe(true)
})
diff --git a/src/core/codex-identity-caps.ts b/src/core/codex-identity-caps.ts
index 429d7805a..a60c8de57 100644
--- a/src/core/codex-identity-caps.ts
+++ b/src/core/codex-identity-caps.ts
@@ -121,6 +121,7 @@ export async function probeCodexRemoteFlagAt(bin: string): Promise<boolean> {
const helpInvocation = directExecutableInvocation(bin, ['--help'])
const help = helpInvocation
? await execFileP(helpInvocation.executable, helpInvocation.args, {
+ ...helpInvocation.options,
timeout: PROBE_TIMEOUT_MS
})
.then((r) => r.stdout)
@@ -132,6 +133,7 @@ export async function probeCodexRemoteFlagAt(bin: string): Promise<boolean> {
const resumeInvocation = directExecutableInvocation(bin, ['resume', '--help'])
const resumeHelp = resumeInvocation
? await execFileP(resumeInvocation.executable, resumeInvocation.args, {
+ ...resumeInvocation.options,
timeout: PROBE_TIMEOUT_MS
})
.then((r) => r.stdout)
diff --git a/src/core/commit-message.test.ts b/src/core/commit-message.test.ts
index c712741f5..594cd705e 100644
--- a/src/core/commit-message.test.ts
+++ b/src/core/commit-message.test.ts
@@ -146,17 +146,15 @@ describe.skipIf(process.platform !== 'win32')('runAgent — Windows npm shim', (
fs.rmSync(dir, { recursive: true, force: true })
})
- it('keeps a hostile prompt as one argument without invoking cmd.exe', async () => {
+ it('keeps a hostile prompt as one argument without interpreting it as cmd syntax', async () => {
const cmd = path.join(dir, 'fake agent.cmd')
+ const script = path.join(dir, 'fake-agent.js')
const touched = path.join(dir, 'should-not-exist.txt')
- fs.writeFileSync(cmd, '@echo off\r\nexit /b 91\r\n')
fs.writeFileSync(
- path.join(dir, 'fake agent.ps1'),
- [
- '$bytes = [Text.Encoding]::UTF8.GetBytes($args[0])',
- '[Console]::Out.Write([Convert]::ToBase64String($bytes))'
- ].join('\r\n')
+ script,
+ "process.stdout.write(Buffer.from(process.argv[2] ?? '', 'utf8').toString('base64'))\n"
)
+ fs.writeFileSync(cmd, `@echo off\r\n"${process.execPath}" "${script}" %*\r\n`)
const prompt = `message & echo pwned > "${touched}"`
vi.resetModules()
@@ -174,4 +172,33 @@ describe.skipIf(process.platform !== 'win32')('runAgent — Windows npm shim', (
})
expect(fs.existsSync(touched)).toBe(false)
})
+
+ it('preserves multiline Unicode stdin as a byte stream through the cmd shim', async () => {
+ const cmd = path.join(dir, 'stdin agent.cmd')
+ const script = path.join(dir, 'stdin-agent.js')
+ fs.writeFileSync(
+ script,
+ [
+ 'const chunks = []',
+ "process.stdin.on('data', (chunk) => chunks.push(chunk))",
+ "process.stdin.on('end', () => process.stdout.write(Buffer.concat(chunks).toString('base64')))"
+ ].join('\n')
+ )
+ fs.writeFileSync(cmd, `@echo off\r\n"${process.execPath}" "${script}" %*\r\n`)
+ const prompt = 'first line\r\nsegunda linha: café 日本語\nlast line'
+
+ vi.resetModules()
+ vi.doUnmock('child_process')
+ const { runAgent } = await import('./commit-message')
+ const result = await runAgent(prompt, dir, {
+ commitAgent: 'custom',
+ commitAgentCommand: `"${cmd}"`,
+ commitExtraPrompt: ''
+ } as never)
+
+ expect(result).toEqual({
+ ok: true,
+ message: Buffer.from(prompt, 'utf8').toString('base64')
+ })
+ })
})
diff --git a/src/core/commit-message.ts b/src/core/commit-message.ts
index ae1448d56..4659349dd 100644
--- a/src/core/commit-message.ts
+++ b/src/core/commit-message.ts
@@ -186,6 +186,7 @@ function spawnAgent(
}
const child = spawn(invocation.executable, invocation.args, {
+ ...invocation.options,
cwd,
env: process.env,
stdio: ['pipe', 'pipe', 'pipe'],
diff --git a/src/core/context-link.ts b/src/core/context-link.ts
index 8104815dc..fbd9349d9 100644
--- a/src/core/context-link.ts
+++ b/src/core/context-link.ts
@@ -212,7 +212,7 @@ export async function opencodeExportAt(bin: string, sessionId: string): Promise<
execFile(
invocation.executable,
invocation.args,
- { encoding: 'utf-8' },
+ { ...invocation.options, encoding: 'utf-8' },
(err, stdout) => resolve(err ? null : stdout)
)
})
diff --git a/src/core/context-link.windows.test.ts b/src/core/context-link.windows.test.ts
index df86db0e4..5dafdf0d7 100644
--- a/src/core/context-link.windows.test.ts
+++ b/src/core/context-link.windows.test.ts
@@ -15,13 +15,11 @@ describe.skipIf(process.platform !== 'win32')('opencodeExportAt - Windows npm sh
fs.rmSync(dir, { recursive: true, force: true })
})
- it('runs the sibling PowerShell shim without interpreting the session id', async () => {
+ it('runs the cmd shim without interpreting the session id', async () => {
const cmd = path.join(dir, 'opencode.cmd')
- fs.writeFileSync(cmd, '@exit /b 99\r\n')
- fs.writeFileSync(
- path.join(dir, 'opencode.ps1'),
- '[Console]::Out.Write(($args | ConvertTo-Json -Compress))\n'
- )
+ const script = path.join(dir, 'opencode.js')
+ fs.writeFileSync(script, 'process.stdout.write(JSON.stringify(process.argv.slice(2)))\n')
+ fs.writeFileSync(cmd, `@echo off\r\n"${process.execPath}" "${script}" %*\r\n`)
const sessionId = 'session & untouched'
const output = await opencodeExportAt(cmd, sessionId)
diff --git a/src/core/exec-path.test.ts b/src/core/exec-path.test.ts
index 42b240fd1..39286e7ba 100644
--- a/src/core/exec-path.test.ts
+++ b/src/core/exec-path.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import fs from 'fs'
import os from 'os'
import path from 'path'
+import { execFileSync } from 'child_process'
import {
directExecutableInvocation,
executableCandidates,
@@ -68,7 +69,7 @@ describe('unquotePathEntry', () => {
describe('directExecutableInvocation', () => {
const systemRoot = 'C:\\Windows'
- const powershell = `${systemRoot}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`
+ const cmd = `${systemRoot}\\System32\\cmd.exe`
it('leaves native and non-Windows executables unchanged', () => {
expect(
@@ -83,36 +84,32 @@ describe('directExecutableInvocation', () => {
).toEqual({ executable: '/usr/bin/agent.cmd', args: ['--version'] })
})
- it('runs a Windows npm cmd shim through its sibling PowerShell shim', () => {
- const existing = new Set([powershell.toLowerCase(), 'c:\\tools\\agent.ps1'])
+ it('runs a Windows cmd shim through hidden cmd.exe with escaped verbatim arguments', () => {
expect(
directExecutableInvocation('C:\\Tools\\agent.CMD', ['--flag', 'value & untouched'], {
platform: 'win32',
systemRoot,
- exists: (candidate) => existing.has(candidate.toLowerCase())
+ exists: (candidate) => candidate.toLowerCase() === cmd.toLowerCase()
})
).toEqual({
- executable: powershell,
+ executable: cmd,
args: [
- '-NoLogo',
- '-NoProfile',
- '-NonInteractive',
- '-ExecutionPolicy',
- 'Bypass',
- '-File',
- 'C:\\Tools\\agent.ps1',
- '--flag',
- 'value & untouched'
- ]
+ '/d',
+ '/s',
+ '/v:off',
+ '/c',
+ '"C:\\Tools\\agent.CMD ^^^"--flag^^^" ^^^"value^^^ ^^^&^^^ untouched^^^""'
+ ],
+ options: { windowsHide: true, windowsVerbatimArguments: true }
})
})
- it('fails closed when a Windows script has no safe direct entry point', () => {
+ it('fails closed without cmd.exe and for unsupported Windows script kinds', () => {
expect(
directExecutableInvocation('C:\\Tools\\agent.cmd', [], {
platform: 'win32',
systemRoot,
- exists: (candidate) => candidate.toLowerCase() === powershell.toLowerCase()
+ exists: () => false
})
).toBeNull()
expect(
@@ -122,6 +119,57 @@ describe('directExecutableInvocation', () => {
exists: () => true
})
).toBeNull()
+ expect(
+ directExecutableInvocation('C:\\Tools\\agent.ps1', [], {
+ platform: 'win32',
+ systemRoot,
+ exists: () => true
+ })
+ ).toBeNull()
+ })
+
+ it('fails closed when cmd.exe cannot preserve argv or the command exceeds its limit', () => {
+ const options = { platform: 'win32' as const, systemRoot, exists: () => true }
+ expect(directExecutableInvocation('C:\\Tools\\agent.cmd', ['line 1\nline 2'], options)).toBeNull()
+ expect(directExecutableInvocation('C:\\Tools\\agent.cmd', ['line 1\rline 2'], options)).toBeNull()
+ expect(directExecutableInvocation('C:\\Tools\\agent.cmd', ['nul\0byte'], options)).toBeNull()
+ expect(directExecutableInvocation('C:\\Tools\\agent.cmd', ['x'.repeat(8100)], options)).toBeNull()
+ })
+})
+
+describe.skipIf(process.platform !== 'win32')('directExecutableInvocation - real cmd shim', () => {
+ it('preserves npm-shim argv boundaries and cmd metacharacters', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-exec-shim-'))
+ try {
+ const shimDir = path.join(dir, 'shims & !tools!')
+ fs.mkdirSync(shimDir)
+ const script = path.join(shimDir, 'capture.js')
+ const cmd = path.join(shimDir, 'capture args.cmd')
+ fs.writeFileSync(script, 'process.stdout.write(JSON.stringify(process.argv.slice(2)))\n')
+ fs.writeFileSync(cmd, `@echo off\r\n"${process.execPath}" "${script}" %*\r\n`)
+ const args = [
+ '',
+ 'plain',
+ 'space value',
+ 'embedded "quote"',
+ 'trailing\\',
+ 'before\\"after',
+ '&|<>()@^',
+ '%PATH%',
+ '!delayed!',
+ 'café 日本語'
+ ]
+ const invocation = directExecutableInvocation(cmd, args)
+ expect(invocation).not.toBeNull()
+
+ const output = execFileSync(invocation!.executable, invocation!.args, {
+ ...invocation!.options,
+ encoding: 'utf8'
+ })
+ expect(JSON.parse(output)).toEqual(args)
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true })
+ }
})
})
diff --git a/src/core/exec-path.ts b/src/core/exec-path.ts
index d5b0b7f09..7c7a2f14a 100644
--- a/src/core/exec-path.ts
+++ b/src/core/exec-path.ts
@@ -192,6 +192,10 @@ export function findInPathString(bin: string, pathStr: string | null | undefined
export interface DirectExecutableInvocation {
executable: string
args: string[]
+ options?: {
+ windowsHide: true
+ windowsVerbatimArguments: true
+ }
}
interface DirectExecutableInvocationOptions {
@@ -200,10 +204,28 @@ interface DirectExecutableInvocationOptions {
exists?: (candidate: string) => boolean
}
+const CMD_LINE_MAX = 8100
+const CMD_META_CHARS = /([()\][%!^"`<>&|;, *?])/g
+
+function escapeCmdCommand(value: string): string {
+ return value.replace(CMD_META_CHARS, '^$1')
+}
+
+// Based on cross-spawn's battle-tested cmd.exe escaping. npm shims forward `%*`, so cmd parses
+// their arguments twice and every metacharacter needs two escape passes.
+function escapeCmdArgument(value: string): string {
+ let escaped = value.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"')
+ escaped = escaped.replace(/(?=(\\+?)?)\1$/, '$1$1')
+ escaped = `"${escaped}"`.replace(CMD_META_CHARS, '^$1')
+ return escaped.replace(CMD_META_CHARS, '^$1')
+}
+
/**
* Builds an argv-safe invocation for a resolved executable. Node cannot execute Windows npm
- * `.cmd` shims directly, and using a shell would reinterpret user-controlled arguments. npm
- * installs an equivalent sibling `.ps1` shim, so run that through PowerShell's `-File` boundary.
+ * `.cmd` shims directly, so run them through cmd.exe with every token escaped and delayed
+ * expansion disabled. CR/LF arguments are refused because cmd treats them as command boundaries
+ * even inside quotes. stdin remains the child's inherited byte stream; PowerShell's text pipeline
+ * must not sit between a staged diff and the agent CLI.
*/
export function directExecutableInvocation(
executable: string,
@@ -214,35 +236,24 @@ export function directExecutableInvocation(
if (platform !== 'win32') return { executable, args }
const ext = path.win32.extname(executable).toLowerCase()
- if (ext === '.bat') return null
- if (ext !== '.cmd' && ext !== '.ps1') return { executable, args }
+ if (ext === '.bat' || ext === '.ps1') return null
+ if (ext !== '.cmd') return { executable, args }
+ if (/\0|\r|\n/u.test(executable) || args.some((arg) => /\0|\r|\n/u.test(arg))) return null
- const script = ext === '.ps1' ? executable : `${executable.slice(0, -ext.length)}.ps1`
const systemRoot = options.systemRoot ?? process.env.SystemRoot
if (!systemRoot) return null
-
- const powershell = path.win32.join(
- systemRoot,
- 'System32',
- 'WindowsPowerShell',
- 'v1.0',
- 'powershell.exe'
- )
+ const cmd = path.win32.join(systemRoot, 'System32', 'cmd.exe')
const exists = options.exists ?? fs.existsSync
- if (!exists(powershell) || !exists(script)) return null
+ if (!exists(cmd)) return null
+
+ const command = [escapeCmdCommand(executable), ...args.map(escapeCmdArgument)].join(' ')
+ const wrapped = `"${command}"`
+ if (wrapped.length > CMD_LINE_MAX) return null
return {
- executable: powershell,
- args: [
- '-NoLogo',
- '-NoProfile',
- '-NonInteractive',
- '-ExecutionPolicy',
- 'Bypass',
- '-File',
- script,
- ...args
- ]
+ executable: cmd,
+ args: ['/d', '/s', '/v:off', '/c', wrapped],
+ options: { windowsHide: true, windowsVerbatimArguments: true }
}
}
diff --git a/src/core/git-service.ts b/src/core/git-service.ts
index ff1e85be3..c711fabf7 100644
--- a/src/core/git-service.ts
+++ b/src/core/git-service.ts
@@ -59,7 +59,11 @@ async function ghAuthed(): Promise<boolean> {
ghAuthedInFlight = (async () => {
let value = false
try {
- await run(invocation.executable, invocation.args, { env: GIT_ENV, maxBuffer: 1024 * 1024 })
+ await run(invocation.executable, invocation.args, {
+ ...invocation.options,
+ env: GIT_ENV,
+ maxBuffer: 1024 * 1024
+ })
value = true
} catch {
value = false
@@ -813,7 +817,12 @@ export class GitService {
env.GH_TOKEN = token
}
try {
- await run(invocation.executable, invocation.args, { cwd, env, maxBuffer: 10 * 1024 * 1024 })
+ await run(invocation.executable, invocation.args, {
+ ...invocation.options,
+ cwd,
+ env,
+ maxBuffer: 10 * 1024 * 1024
+ })
return { ok: true, message: 'Published to GitHub.' }
} catch (e) {
const err = e as { stderr?: string; message?: string }
diff --git a/src/core/git-service.windows.test.ts b/src/core/git-service.windows.test.ts
index 1086d99c7..f60812926 100644
--- a/src/core/git-service.windows.test.ts
+++ b/src/core/git-service.windows.test.ts
@@ -27,18 +27,17 @@ describe.skipIf(process.platform !== 'win32')('GitService - Windows npm gh shim'
vi.resetModules()
})
- it('publishes through the PowerShell sibling with the original Windows PATH', async () => {
+ it('publishes through the cmd shim with the original Windows PATH', async () => {
const capture = path.join(dir, 'gh-call.json')
- fs.writeFileSync(path.join(dir, 'gh.cmd'), '@exit /b 99\r\n')
+ const script = path.join(dir, 'gh.js')
fs.writeFileSync(
- path.join(dir, 'gh.ps1'),
+ script,
[
- "if ($args[0] -eq 'repo') {",
- " [IO.File]::WriteAllText($env:NT_GH_CAPTURE, (@{ args = @($args); path = $env:PATH } | ConvertTo-Json -Compress))",
- '}',
- 'exit 0'
- ].join('\r\n')
+ "const fs = require('fs')",
+ "fs.writeFileSync(process.env.NT_GH_CAPTURE, JSON.stringify({ args: process.argv.slice(2), path: process.env.PATH }))"
+ ].join('\n')
)
+ fs.writeFileSync(path.join(dir, 'gh.cmd'), `@echo off\r\n"${process.execPath}" "${script}" %*\r\n`)
const expectedPath = `${dir};${originalPath ?? ''}`
process.env.PATH = expectedPath
process.env.PATHEXT = '.EXE;.CMD'
diff --git a/src/core/grok-cli.test.ts b/src/core/grok-cli.test.ts
index 66357fa68..59d5631ec 100644
--- a/src/core/grok-cli.test.ts
+++ b/src/core/grok-cli.test.ts
@@ -95,15 +95,16 @@ describe('grokCapsFromRunner — both subcommands are actually asked', () => {
})
describe.skipIf(process.platform !== 'win32')('probeGrokCliAt — Windows npm shim', () => {
- it('probes through the sibling PowerShell shim', async () => {
+ it('probes through cmd.exe', async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-grok-shim-'))
try {
const cmd = path.join(dir, 'grok.cmd')
- fs.writeFileSync(cmd, '@echo off\r\nexit /b 91\r\n')
+ const script = path.join(dir, 'grok.js')
fs.writeFileSync(
- path.join(dir, 'grok.ps1'),
- "if ($args[0] -eq '--help') { Write-Output ' --session-id <uuid>'; exit 0 }\r\nexit 92\r\n"
+ script,
+ "if (process.argv[2] === '--help') console.log(' --session-id <uuid>')\nelse process.exitCode = 92\n"
)
+ fs.writeFileSync(cmd, `@echo off\r\n"${process.execPath}" "${script}" %*\r\n`)
// `models` exits 92 in the fake shim: the help answer survives, the model list is empty.
await expect(probeGrokCliAt(cmd)).resolves.toEqual({ sessionIdFlag: true, models: [] })
diff --git a/src/core/grok-cli.ts b/src/core/grok-cli.ts
index 7fe22fe1e..d48a43532 100644
--- a/src/core/grok-cli.ts
+++ b/src/core/grok-cli.ts
@@ -68,6 +68,7 @@ export function probeGrokCliAt(bin: string): Promise<GrokCliCaps> {
const invocation = directExecutableInvocation(bin, args)
if (!invocation) return null
const { stdout } = await execFileP(invocation.executable, invocation.args, {
+ ...invocation.options,
timeout: PROBE_TIMEOUT_MS
})
return stdout
diff --git a/src/core/usage/codex-usage.ts b/src/core/usage/codex-usage.ts
index 60ea508a7..20bb7e4b4 100644
--- a/src/core/usage/codex-usage.ts
+++ b/src/core/usage/codex-usage.ts
@@ -167,6 +167,7 @@ export async function fetchCodexUsageViaAppServerAt(
let child: ReturnType<typeof spawn>
try {
child = spawn(invocation.executable, invocation.args, {
+ ...invocation.options,
env: { ...process.env, CODEX_HOME: home },
stdio: ['pipe', 'pipe', 'ignore']
})
diff --git a/src/core/usage/codex-usage.windows.test.ts b/src/core/usage/codex-usage.windows.test.ts
index 88b58f6de..138d2f25a 100644
--- a/src/core/usage/codex-usage.windows.test.ts
+++ b/src/core/usage/codex-usage.windows.test.ts
@@ -17,21 +17,22 @@ describe.skipIf(process.platform !== 'win32')(
fs.rmSync(dir, { recursive: true, force: true })
})
- it('completes the JSON-RPC fallback through the sibling PowerShell shim', async () => {
+ it('completes the JSON-RPC fallback through the cmd shim', async () => {
const cmd = path.join(dir, 'codex.cmd')
- fs.writeFileSync(cmd, '@exit /b 99\r\n')
+ const script = path.join(dir, 'codex.js')
fs.writeFileSync(
- path.join(dir, 'codex.ps1'),
+ script,
[
- 'while (($line = [Console]::In.ReadLine()) -ne $null) {',
- " if ($line -match '\"id\":1') {",
- " [Console]::Out.WriteLine('{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{}}')",
- " } elseif ($line -match '\"id\":2') {",
- " [Console]::Out.WriteLine('{\"jsonrpc\":\"2.0\",\"id\":2,\"result\":{\"rateLimits\":{\"primary\":{\"usedPercent\":42,\"limitWindowSeconds\":18000}}}}')",
- ' }',
- '}'
+ "const readline = require('readline')",
+ "const input = readline.createInterface({ input: process.stdin })",
+ "input.on('line', (line) => {",
+ " const request = JSON.parse(line)",
+ " if (request.id === 1) console.log(JSON.stringify({ jsonrpc: '2.0', id: 1, result: {} }))",
+ " if (request.id === 2) console.log(JSON.stringify({ jsonrpc: '2.0', id: 2, result: { rateLimits: { primary: { usedPercent: 42, limitWindowSeconds: 18000 } } } }))",
+ '})'
].join('\n')
)
+ fs.writeFileSync(cmd, `@echo off\r\n"${process.execPath}" "${script}" %*\r\n`)
const usage = await fetchCodexUsageViaAppServerAt(cmd, dir)
expect(usage?.status).toBe('ok')
diff --git a/src/main/codex-accounts.ts b/src/main/codex-accounts.ts
index 1764db126..4b052fbfc 100644
--- a/src/main/codex-accounts.ts
+++ b/src/main/codex-accounts.ts
@@ -113,6 +113,7 @@ export async function ensureCodexAccountDaemon(accountId?: string): Promise<void
const invocation = directExecutableInvocation(codex, ['app-server', 'daemon', 'start'])
if (!invocation) throw new Error('Codex CLI has no safe Windows entry point')
await execFileP(invocation.executable, invocation.args, {
+ ...invocation.options,
cwd: os.homedir(),
env: { ...process.env, ...codexSessionEnv(platform().userDataDir, accountId) },
timeout: 15_000,
@@ -273,6 +274,7 @@ export function initCodexAccounts(getSshManager?: () => SshProjectManager | unde
const invocation = directExecutableInvocation(codex, ['app-server', 'daemon', 'stop'])
if (!invocation) throw new Error('Codex CLI has no safe Windows entry point')
await execFileP(invocation.executable, invocation.args, {
+ ...invocation.options,
cwd: os.homedir(),
env: { ...process.env, CODEX_HOME: localCodexAccountHome(id) },
timeout: 10_000,