From 1d17dc6869b58787ec627ea2c3544478b6d1df71 Mon Sep 17 00:00:00 2001 From: NubsCarson <192162056+NubsCarson@users.noreply.github.com> Date: Mon, 14 Sep 2026 12:04:33 -0400 Subject: [PATCH 1/4] core: launch Windows engine shims through cross-spawn --- .github/workflows/windows-engine.yml | 28 +++++++ packages/core/package.json | 2 + packages/core/src/account/claudeAuth.ts | 2 +- packages/core/src/account/codexAuth.ts | 2 +- packages/core/src/runtime/claudeModels.ts | 2 + .../core/src/runtime/codex-approvals.spec.ts | 8 +- .../src/runtime/codex-resume-fallback.spec.ts | 8 +- packages/core/src/runtime/codexModels.ts | 2 +- packages/core/src/runtime/detect.ts | 2 +- packages/core/src/runtime/engineBin.ts | 11 ++- .../core/src/runtime/engineProcess.spec.ts | 82 +++++++++++++++++++ packages/core/src/runtime/engineProcess.ts | 13 +++ packages/core/src/runtime/engineVersions.ts | 2 +- packages/core/src/runtime/spawn.ts | 3 +- pnpm-lock.yaml | 13 +++ 15 files changed, 162 insertions(+), 18 deletions(-) create mode 100644 .github/workflows/windows-engine.yml create mode 100644 packages/core/src/runtime/engineProcess.spec.ts create mode 100644 packages/core/src/runtime/engineProcess.ts diff --git a/.github/workflows/windows-engine.yml b/.github/workflows/windows-engine.yml new file mode 100644 index 00000000..cf47cbd5 --- /dev/null +++ b/.github/workflows/windows-engine.yml @@ -0,0 +1,28 @@ +name: Windows engine launch +on: + workflow_dispatch: + push: + paths: + - 'packages/core/src/runtime/**' + - 'packages/core/src/account/**' + - 'packages/core/package.json' + - 'pnpm-lock.yaml' + - '.github/workflows/windows-engine.yml' + pull_request: + paths: + - 'packages/core/src/runtime/**' + - 'packages/core/src/account/**' + - 'packages/core/package.json' + - 'pnpm-lock.yaml' + - '.github/workflows/windows-engine.yml' +jobs: + launch: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + with: { version: 9 } + - uses: actions/setup-node@v4 + with: { node-version: 22, cache: pnpm } + - run: pnpm install --frozen-lockfile + - run: pnpm --filter @iqlabs-official/agent-sdk exec vitest run src/runtime/engineProcess.spec.ts diff --git a/packages/core/package.json b/packages/core/package.json index d7d8fdaf..17b2677d 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -24,6 +24,7 @@ "@solana/web3.js": "^1.98.0" }, "devDependencies": { + "@types/cross-spawn": "^6.0.6", "@iqlabs-official/solana-sdk": "^0.1.28", "@solana/web3.js": "^1.98.0", "@types/jsdom": "^30.0.0", @@ -36,6 +37,7 @@ "vitest": "^4.1.8" }, "dependencies": { + "cross-spawn": "^7.0.6", "@anthropic-ai/claude-agent-sdk": "^0.3.170", "@modelcontextprotocol/sdk": "^1.29.0", "@openai/codex-sdk": "^0.139.0", diff --git a/packages/core/src/account/claudeAuth.ts b/packages/core/src/account/claudeAuth.ts index 7a487c0e..ec9e6792 100644 --- a/packages/core/src/account/claudeAuth.ts +++ b/packages/core/src/account/claudeAuth.ts @@ -16,7 +16,7 @@ // the user's OAuth token off-device.) The only thing we persist is a tiny marker so the // onboarding can skip the login screen on next launch; the real auth lives in the CLI. -import { spawn } from "node:child_process"; +import { spawnEngine as spawn } from "../runtime/engineProcess.js"; import { readFile, rm, writeFile } from "node:fs/promises"; import { tokenFile, tokensDir, ensureDir } from "../core/paths.js"; import { resolveEngineBin } from "../runtime/engineBin.js"; diff --git a/packages/core/src/account/codexAuth.ts b/packages/core/src/account/codexAuth.ts index c7b237dd..4f277f60 100644 --- a/packages/core/src/account/codexAuth.ts +++ b/packages/core/src/account/codexAuth.ts @@ -12,7 +12,7 @@ // Exit 0 = success. We never see or store the session token — codex CLI owns it // in ~/.codex/auth.json, device-local. -import { spawn } from "node:child_process"; +import { spawnEngine as spawn } from "../runtime/engineProcess.js"; import { readFile, writeFile, rm } from "node:fs/promises"; import { tokenFile, tokensDir, ensureDir } from "../core/paths.js"; import { resolveEngineBin } from "../runtime/engineBin.js"; diff --git a/packages/core/src/runtime/claudeModels.ts b/packages/core/src/runtime/claudeModels.ts index a5177013..47fc65d7 100644 --- a/packages/core/src/runtime/claudeModels.ts +++ b/packages/core/src/runtime/claudeModels.ts @@ -2,6 +2,7 @@ import { query } from "@anthropic-ai/claude-agent-sdk"; import type { ModelInfo } from "@anthropic-ai/claude-agent-sdk"; import type { ChatModelOption } from "../chat/modelOptions.js"; import { resolveEngineBin } from "./engineBin.js"; +import { spawnClaudeProcess } from "./engineProcess.js"; // Live model catalog for the "claude" engine, pulled from the Claude Code CLI the user // already runs. The agent SDK's query() exposes supportedModels() over its control @@ -75,6 +76,7 @@ export async function listClaudeModelOptions(cwd?: string): Promise ({ - ...await importOriginal(), - spawn: vi.fn(), +vi.mock("./engineProcess.js", async (importOriginal) => ({ + ...await importOriginal(), + spawnEngine: vi.fn(), })); afterEach(() => { diff --git a/packages/core/src/runtime/codex-resume-fallback.spec.ts b/packages/core/src/runtime/codex-resume-fallback.spec.ts index 3ab5a025..3e33b952 100644 --- a/packages/core/src/runtime/codex-resume-fallback.spec.ts +++ b/packages/core/src/runtime/codex-resume-fallback.spec.ts @@ -5,7 +5,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { PassThrough, Writable } from "node:stream"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { spawn } from "node:child_process"; +import { spawnEngine as spawn } from "./engineProcess.js"; import { spawnCli } from "./spawn.js"; import { createRuntime } from "./index.js"; import { getNativeId } from "./inject/idmap.js"; @@ -16,9 +16,9 @@ import { codexSessionsDir } from "../core/paths.js"; import type { ApprovalRequest } from "./approval/channel.js"; import type { ChatMessage } from "./contract.js"; -vi.mock("node:child_process", async (importOriginal) => ({ - ...await importOriginal(), - spawn: vi.fn(), +vi.mock("./engineProcess.js", async (importOriginal) => ({ + ...await importOriginal(), + spawnEngine: vi.fn(), })); afterEach(() => { diff --git a/packages/core/src/runtime/codexModels.ts b/packages/core/src/runtime/codexModels.ts index a6438a73..ae2f5e2c 100644 --- a/packages/core/src/runtime/codexModels.ts +++ b/packages/core/src/runtime/codexModels.ts @@ -1,4 +1,4 @@ -import { spawn } from "node:child_process"; +import { spawnEngine as spawn } from "./engineProcess.js"; import readline from "node:readline"; import type { ChatModelOption } from "../chat/modelOptions.js"; import type { Model } from "./codex_bindings/v2/Model.js"; diff --git a/packages/core/src/runtime/detect.ts b/packages/core/src/runtime/detect.ts index 0c98ab19..0921d67e 100644 --- a/packages/core/src/runtime/detect.ts +++ b/packages/core/src/runtime/detect.ts @@ -1,7 +1,7 @@ // CLI availability check for onboarding. Standalone (no wallet/storage) — // answers "is codex/claude installed, and logged in?" so the UI can guide setup. -import { spawn } from "node:child_process"; +import { spawnEngine as spawn } from "./engineProcess.js"; import { isClaudeLoggedIn } from "../account/claudeAuth.js"; import { isCodexLoggedIn } from "../account/codexAuth.js"; import { resolveEngineBin } from "./engineBin.js"; diff --git a/packages/core/src/runtime/engineBin.ts b/packages/core/src/runtime/engineBin.ts index fedf4b23..79f9208f 100644 --- a/packages/core/src/runtime/engineBin.ts +++ b/packages/core/src/runtime/engineBin.ts @@ -40,13 +40,15 @@ let nodeBin: string | undefined; function fromPath(name: string): string | undefined { try { const cmd = process.platform === "win32" ? "where" : "which"; - const hit = execFileSync(cmd, [name], { + const hits = execFileSync(cmd, [name], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], }) - .split("\n")[0] - ?.trim(); - return hit && existsSync(hit) ? hit : undefined; + .split("\n").map((hit) => hit.trim()).filter((hit) => hit && existsSync(hit)); + // `where` may list npm's extensionless POSIX shim before its Windows launcher. + return process.platform === "win32" + ? hits.find((hit) => /\.(exe|com|cmd|bat)$/i.test(hit)) + : hits[0]; } catch { return undefined; } @@ -83,6 +85,7 @@ function candidates(name: EngineName | "node"): string[] { return [ // the official native installer: ~/.local/bin/claude is a symlink to // ~/.local/share/claude/versions/ + ...(win && name !== "node" ? [join(home, ".local", "bin", `${name}.exe`)] : []), join(home, ".local", "bin", exe), // node version managers: one global-bin dir per runtime version, newest first ...versionedBins(join(home, ".nvm", "versions", "node"), ["bin"], exe), diff --git a/packages/core/src/runtime/engineProcess.spec.ts b/packages/core/src/runtime/engineProcess.spec.ts new file mode 100644 index 00000000..f39bd05f --- /dev/null +++ b/packages/core/src/runtime/engineProcess.spec.ts @@ -0,0 +1,82 @@ +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterAll, describe, expect, it, vi } from "vitest"; +import { spawnEngine, spawnClaudeProcess } from "./engineProcess.js"; + +const home = mkdtempSync(join(tmpdir(), "agentnet-launch-")); +const binDir = join(home, "engine install (226)"); +mkdirSync(binDir); +const entry = join(binDir, "probe.cjs"); +writeFileSync(entry, ` +const args = process.argv.slice(2); +if (args[0] === '--version') console.log('codex 0.154.0'); +else if (args[0] === 'login') console.log('Logged in using ChatGPT'); +else if (args[0] === 'auth') console.log(JSON.stringify({ loggedIn: true })); +else if (args[0] === 'wait') process.stdin.resume(); +else console.log(JSON.stringify(args)); +`); +const cmd = join(binDir, "codex.cmd"); +writeFileSync(cmd, `@echo off\r\n"${process.execPath}" "%~dp0probe.cjs" %*\r\n`); +afterAll(() => { vi.unstubAllEnvs(); rmSync(home, { recursive: true, force: true }); }); + +describe("engine process launch", () => { + it("preserves argument boundaries through the shared launcher", async () => { + const args = ['two words', 'a"b', '(paren)', 'x&y', '%PATH%', 'semi;colon']; + const child = spawnEngine(process.execPath, [entry, ...args], { stdio: ["ignore", "pipe", "pipe"] }); + let output = ""; + child.stdout.on("data", (data) => { output += data; }); + const code = await new Promise((resolve, reject) => { child.on("error", reject); child.on("close", resolve); }); + expect(code).toBe(0); + expect(JSON.parse(output)).toEqual(args); + }); + + it("forwards the Claude SDK abort signal to a piped child", async () => { + const ctl = new AbortController(); + const child = spawnClaudeProcess({ command: process.execPath, args: [entry, 'wait'], env: process.env, signal: ctl.signal }); + const error = new Promise((resolve) => child.once("error", resolve)); + const closed = new Promise((resolve) => child.once("close", resolve)); + await new Promise((resolve) => child.once("spawn", resolve)); + ctl.abort(); + expect((await error).name).toBe("AbortError"); + await closed; + }); +}); + +describe.skipIf(process.platform !== "win32")("Windows npm launcher", () => { + it("runs a cmd shim in a spaced path with quoted and shell-special arguments", async () => { + const args = ['two words', 'a"b', '(paren)', 'x&y', '%PATH%', 'semi;colon']; + const child = spawnEngine(cmd, args, { stdio: ["ignore", "pipe", "pipe"] }); + let output = ""; + child.stdout.on("data", (data) => { output += data; }); + const code = await new Promise((resolve, reject) => { child.on("error", reject); child.on("close", resolve); }); + expect(code).toBe(0); + expect(JSON.parse(output)).toEqual(args); + }); + + it("detects and authenticates engines launched through cmd files", async () => { + vi.stubEnv("AGENTNET_CODEX_PATH", cmd); + vi.stubEnv("AGENTNET_CLAUDE_PATH", cmd); + const { detectCli } = await import("./detect.js"); + expect(await detectCli()).toEqual({ claude: "ok", codex: "ok" }); + }); + + it("launches the Claude SDK process through the same cmd adapter", async () => { + const child = spawnClaudeProcess({ command: cmd, args: ['SDK round trip'], env: process.env, signal: new AbortController().signal }); + let output = ""; + child.stdout.on("data", (data) => { output += data; }); + const code = await new Promise((resolve, reject) => { child.on("error", reject); child.on("close", resolve); }); + expect(code).toBe(0); + expect(JSON.parse(output)).toEqual(['SDK round trip']); + }); + + it("prefers the Windows shim when where also finds an extensionless launcher", async () => { + vi.unstubAllEnvs(); + vi.stubEnv("PATH", `${binDir};${process.env.PATH}`); + vi.stubEnv("AGENTNET_CODEX_PATH", ""); + writeFileSync(join(binDir, "codex"), "#!/bin/sh\nexit 1\n"); + vi.resetModules(); + const { resolveEngineBin } = await import("./engineBin.js"); + expect(resolveEngineBin("codex")).toBe(cmd); + }); +}); diff --git a/packages/core/src/runtime/engineProcess.ts b/packages/core/src/runtime/engineProcess.ts new file mode 100644 index 00000000..e85ae518 --- /dev/null +++ b/packages/core/src/runtime/engineProcess.ts @@ -0,0 +1,13 @@ +import crossSpawn from "cross-spawn"; +import type { SpawnOptions } from "@anthropic-ai/claude-agent-sdk"; + +// cross-spawn preserves Node's stdio behavior but its typings omit the overloads +// that narrow piped streams. Keep that contract at the shared import boundary. +export const spawnEngine = crossSpawn as typeof import("node:child_process").spawn; + +// Adapt the SDK process contract to the same Windows-aware launcher used by the +// login, version and Codex paths. Forward the SDK's delayed abort signal so its +// graceful stdin shutdown still gets a chance to finish. +export function spawnClaudeProcess({ command, args, cwd, env, signal }: SpawnOptions) { + return spawnEngine(command, args, { cwd, env, signal, stdio: "pipe", windowsHide: true }); +} diff --git a/packages/core/src/runtime/engineVersions.ts b/packages/core/src/runtime/engineVersions.ts index 4065f4c4..55d87de8 100644 --- a/packages/core/src/runtime/engineVersions.ts +++ b/packages/core/src/runtime/engineVersions.ts @@ -5,7 +5,7 @@ // engine's own updater, or the official npm command when the engine is missing. All // host-side, on an explicit user tap. -import { spawn } from "node:child_process"; +import { spawnEngine as spawn } from "./engineProcess.js"; import { basename } from "node:path"; import { ENGINE_UPDATE_COMMAND } from "./engineInstall.js"; import { resolveEngineBin, type EngineName } from "./engineBin.js"; diff --git a/packages/core/src/runtime/spawn.ts b/packages/core/src/runtime/spawn.ts index 224c1982..aaf18b52 100644 --- a/packages/core/src/runtime/spawn.ts +++ b/packages/core/src/runtime/spawn.ts @@ -13,7 +13,6 @@ // and never imports an SDK type. Output is delivered as already-mapped ChatMessages // (convert/* map the SDK events); the runtime just appends + paints. -import { spawn } from "node:child_process"; import readline from "node:readline"; import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs"; import { mkdir, writeFile, unlink } from "node:fs/promises"; @@ -34,6 +33,7 @@ import type { } from "./approval/channel.js"; import { autoApprove } from "./approval/channel.js"; import { resolveEngineBin } from "./engineBin.js"; +import { spawnEngine as spawn, spawnClaudeProcess } from "./engineProcess.js"; // Loosely-typed view of AskUserQuestion's raw input (the SDK hands us `unknown`-ish data). type ApprovalQuestionInput = { @@ -442,6 +442,7 @@ function claudeEngine(opts: SpawnOpts): Engine { // use the user's installed claude (logged in) so the bundled extension doesn't // need the SDK's own native binary on its (unresolvable) bundle-relative path. pathToClaudeCodeExecutable: claudeBin, + spawnClaudeCodeProcess: spawnClaudeProcess, stderr: (d: string) => { if (d.trim()) cb.emitErr(`[claude] ${d.trim()}`); }, // Passive skill-shopping wiring (issue #21): the MCP marketplace server + its // allowed tools, when the toggle is ON. The "which skills you have" directive is diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f57ff507..a190e1e3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -28,6 +28,9 @@ importers: '@solana/spl-token-metadata': specifier: ^0.1.6 version: 0.1.6(@solana/web3.js@1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6))(fastestsmallesttextencoderdecoder@1.0.22)(typescript@5.9.3) + cross-spawn: + specifier: ^7.0.6 + version: 7.0.6 dompurify: specifier: ^3.4.9 version: 3.4.9 @@ -44,6 +47,9 @@ importers: '@solana/web3.js': specifier: ^1.98.0 version: 1.98.4(bufferutil@4.1.0)(typescript@5.9.3)(utf-8-validate@6.0.6) + '@types/cross-spawn': + specifier: ^6.0.6 + version: 6.0.6 '@types/jsdom': specifier: ^30.0.0 version: 30.0.0 @@ -1181,6 +1187,9 @@ packages: '@types/connect@3.4.38': resolution: {integrity: sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==} + '@types/cross-spawn@6.0.6': + resolution: {integrity: sha512-fXRhhUkG4H3TQk5dBhQ7m/JDdSNHKwR2BBia62lhwEIq9xGiQKLxd6LymNhn47SjXhsUEPmxi+PKw2OkW4LLjA==} + '@types/deep-eql@4.0.2': resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} @@ -3643,6 +3652,10 @@ snapshots: dependencies: '@types/node': 20.19.42 + '@types/cross-spawn@6.0.6': + dependencies: + '@types/node': 20.19.42 + '@types/deep-eql@4.0.2': {} '@types/estree@1.0.9': {} From 1815b4322c2c8a1126fc7494a6466c5af5079a26 Mon Sep 17 00:00:00 2001 From: NubsCarson <192162056+NubsCarson@users.noreply.github.com> Date: Mon, 14 Sep 2026 12:09:36 -0400 Subject: [PATCH 2/4] test: exercise npm batch dispatch and canonical Windows paths --- .../core/src/runtime/engineProcess.spec.ts | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/packages/core/src/runtime/engineProcess.spec.ts b/packages/core/src/runtime/engineProcess.spec.ts index f39bd05f..af9435a6 100644 --- a/packages/core/src/runtime/engineProcess.spec.ts +++ b/packages/core/src/runtime/engineProcess.spec.ts @@ -1,4 +1,4 @@ -import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync, realpathSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterAll, describe, expect, it, vi } from "vitest"; @@ -17,7 +17,15 @@ else if (args[0] === 'wait') process.stdin.resume(); else console.log(JSON.stringify(args)); `); const cmd = join(binDir, "codex.cmd"); -writeFileSync(cmd, `@echo off\r\n"${process.execPath}" "%~dp0probe.cjs" %*\r\n`); +// Match npm/cmd-shim's dispatch: its goto/endLocal sequence avoids a second +// batch context interpreting forwarded arguments. A plain `%*` wrapper does not. +writeFileSync(cmd, [ + '@ECHO off', 'GOTO start', ':find_dp0', 'SET dp0=%~dp0', 'EXIT /b', + ':start', 'SETLOCAL', 'CALL :find_dp0', + `SET "_prog=${process.execPath}"`, + 'endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%probe.cjs" %*', + '', +].join('\r\n')); afterAll(() => { vi.unstubAllEnvs(); rmSync(home, { recursive: true, force: true }); }); describe("engine process launch", () => { @@ -48,9 +56,11 @@ describe.skipIf(process.platform !== "win32")("Windows npm launcher", () => { const args = ['two words', 'a"b', '(paren)', 'x&y', '%PATH%', 'semi;colon']; const child = spawnEngine(cmd, args, { stdio: ["ignore", "pipe", "pipe"] }); let output = ""; + let stderr = ""; child.stdout.on("data", (data) => { output += data; }); + child.stderr.on("data", (data) => { stderr += data; }); const code = await new Promise((resolve, reject) => { child.on("error", reject); child.on("close", resolve); }); - expect(code).toBe(0); + expect(code, stderr).toBe(0); expect(JSON.parse(output)).toEqual(args); }); @@ -77,6 +87,6 @@ describe.skipIf(process.platform !== "win32")("Windows npm launcher", () => { writeFileSync(join(binDir, "codex"), "#!/bin/sh\nexit 1\n"); vi.resetModules(); const { resolveEngineBin } = await import("./engineBin.js"); - expect(resolveEngineBin("codex")).toBe(cmd); + expect(realpathSync(resolveEngineBin("codex"))).toBe(realpathSync(cmd)); }); }); From 44e3434ffb3e989d8f47ad5ca95a29b46a208348 Mon Sep 17 00:00:00 2001 From: NubsCarson <192162056+NubsCarson@users.noreply.github.com> Date: Mon, 14 Sep 2026 12:15:20 -0400 Subject: [PATCH 3/4] core: resolve npm shim targets before passing engine arguments --- packages/core/package.json | 1 + packages/core/src/runtime/engineProcess.spec.ts | 9 ++++----- packages/core/src/runtime/engineProcess.ts | 13 ++++++++++++- packages/core/src/runtime/read-cmd-shim.d.ts | 4 ++++ pnpm-lock.yaml | 9 +++++++++ 5 files changed, 30 insertions(+), 6 deletions(-) create mode 100644 packages/core/src/runtime/read-cmd-shim.d.ts diff --git a/packages/core/package.json b/packages/core/package.json index 17b2677d..5f65a3cf 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -37,6 +37,7 @@ "vitest": "^4.1.8" }, "dependencies": { + "read-cmd-shim": "^5.0.0", "cross-spawn": "^7.0.6", "@anthropic-ai/claude-agent-sdk": "^0.3.170", "@modelcontextprotocol/sdk": "^1.29.0", diff --git a/packages/core/src/runtime/engineProcess.spec.ts b/packages/core/src/runtime/engineProcess.spec.ts index af9435a6..30dcdcf9 100644 --- a/packages/core/src/runtime/engineProcess.spec.ts +++ b/packages/core/src/runtime/engineProcess.spec.ts @@ -8,7 +8,7 @@ const home = mkdtempSync(join(tmpdir(), "agentnet-launch-")); const binDir = join(home, "engine install (226)"); mkdirSync(binDir); const entry = join(binDir, "probe.cjs"); -writeFileSync(entry, ` +writeFileSync(entry, `#!/usr/bin/env node const args = process.argv.slice(2); if (args[0] === '--version') console.log('codex 0.154.0'); else if (args[0] === 'login') console.log('Logged in using ChatGPT'); @@ -17,13 +17,12 @@ else if (args[0] === 'wait') process.stdin.resume(); else console.log(JSON.stringify(args)); `); const cmd = join(binDir, "codex.cmd"); -// Match npm/cmd-shim's dispatch: its goto/endLocal sequence avoids a second -// batch context interpreting forwarded arguments. A plain `%*` wrapper does not. +// Match npm/cmd-shim's dispatch instead of a hand-written batch wrapper. writeFileSync(cmd, [ '@ECHO off', 'GOTO start', ':find_dp0', 'SET dp0=%~dp0', 'EXIT /b', ':start', 'SETLOCAL', 'CALL :find_dp0', `SET "_prog=${process.execPath}"`, - 'endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%probe.cjs" %*', + 'endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\probe.cjs" %*', '', ].join('\r\n')); afterAll(() => { vi.unstubAllEnvs(); rmSync(home, { recursive: true, force: true }); }); @@ -87,6 +86,6 @@ describe.skipIf(process.platform !== "win32")("Windows npm launcher", () => { writeFileSync(join(binDir, "codex"), "#!/bin/sh\nexit 1\n"); vi.resetModules(); const { resolveEngineBin } = await import("./engineBin.js"); - expect(realpathSync(resolveEngineBin("codex"))).toBe(realpathSync(cmd)); + expect(realpathSync.native(resolveEngineBin("codex"))).toBe(realpathSync.native(cmd)); }); }); diff --git a/packages/core/src/runtime/engineProcess.ts b/packages/core/src/runtime/engineProcess.ts index e85ae518..10e8f215 100644 --- a/packages/core/src/runtime/engineProcess.ts +++ b/packages/core/src/runtime/engineProcess.ts @@ -1,9 +1,20 @@ +/// import crossSpawn from "cross-spawn"; +import readCmdShim from "read-cmd-shim"; +import { dirname, resolve } from "node:path"; import type { SpawnOptions } from "@anthropic-ai/claude-agent-sdk"; // cross-spawn preserves Node's stdio behavior but its typings omit the overloads // that narrow piped streams. Keep that contract at the shared import boundary. -export const spawnEngine = crossSpawn as typeof import("node:child_process").spawn; +export const spawnEngine = ((command, args, options) => { + // Global npm shims require another cmd parsing pass, which can reinterpret + // quoted arguments. Resolve their target as npm does for a symlink instead. + // cross-spawn then follows the target's shebang without passing through cmd. + if (process.platform === "win32" && /\.cmd$/i.test(command)) { + command = resolve(dirname(command), readCmdShim.sync(command)); + } + return crossSpawn(command, args, options); +}) as typeof import("node:child_process").spawn; // Adapt the SDK process contract to the same Windows-aware launcher used by the // login, version and Codex paths. Forward the SDK's delayed abort signal so its diff --git a/packages/core/src/runtime/read-cmd-shim.d.ts b/packages/core/src/runtime/read-cmd-shim.d.ts new file mode 100644 index 00000000..ca5cfdb4 --- /dev/null +++ b/packages/core/src/runtime/read-cmd-shim.d.ts @@ -0,0 +1,4 @@ +declare module "read-cmd-shim" { + const readCmdShim: { sync(path: string): string }; + export default readCmdShim; +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a190e1e3..6d86f991 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -37,6 +37,9 @@ importers: marked: specifier: ^18.0.5 version: 18.0.5 + read-cmd-shim: + specifier: ^5.0.0 + version: 5.0.0 zod: specifier: ^4.4.3 version: 4.4.3 @@ -2295,6 +2298,10 @@ packages: resolution: {integrity: sha512-HNe9WslTbXmFK8o8cmwgAeJFSBvt1bPdHCVKtaaV+WlAN36mpT4hcRpwbf3fY56ar2oIXzsBpOAiIRHAdY0OlQ==} engines: {node: '>=0.10.0'} + read-cmd-shim@5.0.0: + resolution: {integrity: sha512-SEbJV7tohp3DAAILbEMPXavBjAnMN0tVnh4+9G8ihV4Pq3HYF9h8QNez9zkJ1ILkv9G2BjdzwctznGZXgu/HGw==} + engines: {node: ^18.17.0 || >=20.5.0} + readdirp@4.1.2: resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==} engines: {node: '>= 14.18.0'} @@ -4727,6 +4734,8 @@ snapshots: react@19.2.7: {} + read-cmd-shim@5.0.0: {} + readdirp@4.1.2: {} require-directory@2.1.1: {} From 3dbe5183253c2d2fabab0b287d7e705b98a74037 Mon Sep 17 00:00:00 2001 From: NubsCarson <192162056+NubsCarson@users.noreply.github.com> Date: Mon, 14 Sep 2026 12:16:38 -0400 Subject: [PATCH 4/4] test: keep unknown batch wrappers out of the shell fallback --- packages/core/src/runtime/engineProcess.spec.ts | 8 ++++++++ packages/core/src/runtime/engineProcess.ts | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/core/src/runtime/engineProcess.spec.ts b/packages/core/src/runtime/engineProcess.spec.ts index 30dcdcf9..823516f8 100644 --- a/packages/core/src/runtime/engineProcess.spec.ts +++ b/packages/core/src/runtime/engineProcess.spec.ts @@ -51,6 +51,14 @@ describe("engine process launch", () => { }); describe.skipIf(process.platform !== "win32")("Windows npm launcher", () => { + it("rejects unknown batch wrappers instead of forwarding arguments through a shell", () => { + for (const ext of ['cmd', 'bat']) { + const wrapper = join(binDir, `unknown.${ext}`); + writeFileSync(wrapper, '@echo off\r\necho %*\r\n'); + expect(() => spawnEngine(wrapper, ['a"b&c'], { stdio: 'pipe' })).toThrow(/doesn't appear to be a cmd-shim/); + } + }); + it("runs a cmd shim in a spaced path with quoted and shell-special arguments", async () => { const args = ['two words', 'a"b', '(paren)', 'x&y', '%PATH%', 'semi;colon']; const child = spawnEngine(cmd, args, { stdio: ["ignore", "pipe", "pipe"] }); diff --git a/packages/core/src/runtime/engineProcess.ts b/packages/core/src/runtime/engineProcess.ts index 10e8f215..79434082 100644 --- a/packages/core/src/runtime/engineProcess.ts +++ b/packages/core/src/runtime/engineProcess.ts @@ -10,7 +10,7 @@ export const spawnEngine = ((command, args, options) => { // Global npm shims require another cmd parsing pass, which can reinterpret // quoted arguments. Resolve their target as npm does for a symlink instead. // cross-spawn then follows the target's shebang without passing through cmd. - if (process.platform === "win32" && /\.cmd$/i.test(command)) { + if (process.platform === "win32" && /\.(?:cmd|bat)$/i.test(command)) { command = resolve(dirname(command), readCmdShim.sync(command)); } return crossSpawn(command, args, options);