Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 6b8805bc3b Fix duplicated utility functions and unsafe constructor fallback
- Extract shared command resolution helpers (stripWrappingQuotes,
  resolvePathEnvironmentVariable, resolveWindowsPathExtensions,
  resolveCommandCandidates, isExecutableFile) into a new
  commandResolution.ts module, eliminating duplication between
  processRunner.ts and open.ts.

- Make CodexAppServerManager constructor require services parameter
  instead of using an unsafe cast that erases Effect service
  requirements when services are omitted.

Co-authored-by: Julius Marminge <[email protected]>
2026-03-05 20:52:59 +00:00
Julius Marminge b249442175 Fix Windows process launching for native and batch commands
- add a shared launch-plan resolver to avoid default shell mode on Windows
- resolve executables via PATH/PATHEXT and route `.cmd`/`.bat` through `cmd.exe /d /s /c`
- update runtime/spawn helpers and add focused tests for Windows + WSL behavior
2026-03-05 12:39:09 -08:00
7 changed files with 436 additions and 110 deletions

No files matched your search

+2 -8
View File
@@ -169,15 +169,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
options?: Effect.RunOptions | undefined,
) => Promise<A>;
constructor(services?: ServiceMap.ServiceMap<NodeServices.NodeServices>) {
constructor(services: ServiceMap.ServiceMap<NodeServices.NodeServices>) {
super();
this.runPromise = services
? Effect.runPromiseWith(services)
: ((effect, options) =>
Effect.runPromise(
effect as unknown as Effect.Effect<unknown, never>,
options,
)) as typeof this.runPromise;
this.runPromise = Effect.runPromiseWith(services);
}
async startSession(input: ProviderSessionStartInput): Promise<ProviderSession> {
+71
View File
@@ -0,0 +1,71 @@
import { accessSync, constants, statSync } from "node:fs";
import { extname } from "node:path";
export function stripWrappingQuotes(value: string): string {
return value.replace(/^"+|"+$/g, "");
}
export function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
return env.PATH ?? env.Path ?? env.path ?? "";
}
export function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
const rawValue = env.PATHEXT;
const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
if (!rawValue) return fallback;
const parsed = rawValue
.split(";")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0)
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
}
export function resolveCommandCandidates(
command: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
): ReadonlyArray<string> {
if (platform !== "win32") return [command];
const extension = extname(command);
const normalizedExtension = extension.toUpperCase();
if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
const commandWithoutExtension = command.slice(0, -extension.length);
return Array.from(
new Set([
command,
`${commandWithoutExtension}${normalizedExtension}`,
`${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
]),
);
}
const candidates: string[] = [];
for (const candidateExtension of windowsPathExtensions) {
candidates.push(`${command}${candidateExtension}`);
candidates.push(`${command}${candidateExtension.toLowerCase()}`);
}
return Array.from(new Set(candidates));
}
export function isExecutableFile(
filePath: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
): boolean {
try {
const stat = statSync(filePath);
if (!stat.isFile()) return false;
if (platform === "win32") {
const extension = extname(filePath);
if (extension.length === 0) return false;
return windowsPathExtensions.includes(extension.toUpperCase());
}
accessSync(filePath, constants.X_OK);
return true;
} catch {
return false;
}
}
+8 -71
View File
@@ -6,11 +6,17 @@
*
* @module Open
*/
import { accessSync, constants, statSync } from "node:fs";
import { extname, join } from "node:path";
import { join } from "node:path";
import { EDITORS, type EditorId, type ServerRuntimeEnvironment } from "@t3tools/contracts";
import { ServiceMap, Schema, Effect, Layer } from "effect";
import {
isExecutableFile,
resolveCommandCandidates,
resolvePathEnvironmentVariable,
resolveWindowsPathExtensions,
stripWrappingQuotes,
} from "./commandResolution";
import { spawnDetachedProcess, spawnProcessSync } from "./processRunner";
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
@@ -72,75 +78,6 @@ function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
}
}
function stripWrappingQuotes(value: string): string {
return value.replace(/^"+|"+$/g, "");
}
function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
return env.PATH ?? env.Path ?? env.path ?? "";
}
function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
const rawValue = env.PATHEXT;
const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
if (!rawValue) return fallback;
const parsed = rawValue
.split(";")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0)
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
}
function resolveCommandCandidates(
command: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
): ReadonlyArray<string> {
if (platform !== "win32") return [command];
const extension = extname(command);
const normalizedExtension = extension.toUpperCase();
if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
const commandWithoutExtension = command.slice(0, -extension.length);
return Array.from(
new Set([
command,
`${commandWithoutExtension}${normalizedExtension}`,
`${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
]),
);
}
const candidates: string[] = [];
for (const extension of windowsPathExtensions) {
candidates.push(`${command}${extension}`);
candidates.push(`${command}${extension.toLowerCase()}`);
}
return Array.from(new Set(candidates));
}
function isExecutableFile(
filePath: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
): boolean {
try {
const stat = statSync(filePath);
if (!stat.isFile()) return false;
if (platform === "win32") {
const extension = extname(filePath);
if (extension.length === 0) return false;
return windowsPathExtensions.includes(extension.toUpperCase());
}
accessSync(filePath, constants.X_OK);
return true;
} catch {
return false;
}
}
function resolvePathDelimiter(platform: NodeJS.Platform): string {
return platform === "win32" ? ";" : ":";
}
+135 -1
View File
@@ -1,6 +1,25 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { runProcess, spawnDetachedProcess, spawnProcessSync } from "./processRunner";
import {
makeRuntimeCommand,
resolveProcessLaunchPlan,
runProcess,
spawnDetachedProcess,
spawnProcessSync,
} from "./processRunner";
function withTempDir(run: (dir: string) => void): void {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-process-runner-"));
try {
run(dir);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
}
describe("runProcess", () => {
it("fails when output exceeds max buffer in default mode", async () => {
@@ -37,3 +56,118 @@ describe("runProcess", () => {
).resolves.toBeUndefined();
});
});
describe("resolveProcessLaunchPlan", () => {
it("resolves native windows executables without using a shell", () => {
withTempDir((dir) => {
fs.writeFileSync(path.join(dir, "git.EXE"), "MZ");
const plan = resolveProcessLaunchPlan("git", ["status"], {
env: {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
},
inheritParentEnv: false,
runtimeEnvironment: {
platform: "windows",
pathStyle: "windows",
isWsl: false,
windowsInteropMode: "windows-native",
wslDistroName: null,
},
});
expect(plan.command).toBe(path.join(dir, "git.EXE"));
expect(plan.args).toEqual(["status"]);
expect(plan.shell).toBe(false);
});
});
it("wraps windows batch launchers through cmd.exe without default shell mode", () => {
withTempDir((dir) => {
const wrapperPath = path.join(dir, "code.CMD");
fs.writeFileSync(wrapperPath, "@echo off\r\n");
const plan = resolveProcessLaunchPlan("code", ["C:\\repo\\a&b.ts"], {
env: {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
COMSPEC: "C:\\Windows\\System32\\cmd.exe",
},
inheritParentEnv: false,
runtimeEnvironment: {
platform: "windows",
pathStyle: "windows",
isWsl: false,
windowsInteropMode: "windows-native",
wslDistroName: null,
},
});
expect(plan.command).toBe("C:\\Windows\\System32\\cmd.exe");
expect(plan.args.slice(0, 3)).toEqual(["/d", "/s", "/c"]);
expect(plan.args[3]).toBe(`"${wrapperPath}" "C:\\repo\\a^&b.ts"`);
expect(plan.shell).toBe(false);
});
});
it("keeps wsl-hosted commands on the linux direct exec path", () => {
const plan = resolveProcessLaunchPlan("code", ["/home/julius/repo"], {
runtimeEnvironment: {
platform: "linux",
pathStyle: "posix",
isWsl: true,
windowsInteropMode: "wsl-hosted",
wslDistroName: "Ubuntu",
},
});
expect(plan.command).toBe("code");
expect(plan.args).toEqual(["/home/julius/repo"]);
expect(plan.shell).toBe(false);
});
it("preserves explicit shell configuration", () => {
const plan = resolveProcessLaunchPlan("git", ["status"], {
shell: true,
runtimeEnvironment: {
platform: "windows",
pathStyle: "windows",
isWsl: false,
windowsInteropMode: "windows-native",
wslDistroName: null,
},
});
expect(plan.command).toBe("git");
expect(plan.args).toEqual(["status"]);
expect(plan.shell).toBe(true);
});
});
describe("makeRuntimeCommand", () => {
it("uses the shared launch plan for batch commands on windows", () => {
withTempDir((dir) => {
const wrapperPath = path.join(dir, "code.CMD");
fs.writeFileSync(wrapperPath, "@echo off\r\n");
const command = makeRuntimeCommand("code", ["C:\\repo\\a&b.ts"], {
env: {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
COMSPEC: "C:\\Windows\\System32\\cmd.exe",
},
extendEnv: false,
runtimeEnvironment: {
platform: "windows",
pathStyle: "windows",
isWsl: false,
windowsInteropMode: "windows-native",
wslDistroName: null,
},
});
expect(command.command).toBe("C:\\Windows\\System32\\cmd.exe");
expect(command.args).toEqual(["/d", "/s", "/c", `"${wrapperPath}" "C:\\repo\\a^&b.ts"`]);
expect(command.options.shell).toBe(false);
});
});
});
+210 -23
View File
@@ -5,11 +5,19 @@ import {
spawnSync,
type StdioOptions,
} from "node:child_process";
import { extname, join } from "node:path";
import type { ServerRuntimeEnvironment } from "@t3tools/contracts";
import { Effect, Exit, Scope } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
isExecutableFile,
resolveCommandCandidates,
resolvePathEnvironmentVariable,
resolveWindowsPathExtensions,
stripWrappingQuotes,
} from "./commandResolution";
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
interface ProcessSpawnBaseOptions {
@@ -24,16 +32,21 @@ interface RuntimeShellOptions {
shell?: boolean | string | undefined;
}
interface ProcessSpawnOptions extends ProcessSpawnBaseOptions {
interface ProcessLaunchPlanOptions extends RuntimeShellOptions {
env?: NodeJS.ProcessEnv | Record<string, string | undefined> | undefined;
inheritParentEnv?: boolean | undefined;
}
export interface ProcessSpawnOptions extends ProcessSpawnBaseOptions {
stdio?: StdioOptions | undefined;
detached?: boolean | undefined;
}
interface RuntimeCommandOptions extends ChildProcess.CommandOptions {
export interface RuntimeCommandOptions extends ChildProcess.CommandOptions {
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
}
interface ProcessSpawnSyncOptions extends ProcessSpawnBaseOptions {
export interface ProcessSpawnSyncOptions extends ProcessSpawnBaseOptions {
stdio?: StdioOptions | undefined;
detached?: boolean | undefined;
encoding?: BufferEncoding | undefined;
@@ -62,6 +75,20 @@ export interface ProcessRunResult {
stderrTruncated?: boolean | undefined;
}
export interface ProcessLaunchPlan {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly shell: boolean | string;
readonly runtimeEnvironment: ServerRuntimeEnvironment;
}
interface ResolvedWindowsCommand {
readonly path: string;
readonly kind: "native" | "batch";
}
const WINDOWS_BATCH_EXECUTABLE_EXTENSIONS = new Set([".CMD", ".BAT"]);
function commandLabel(command: string, args: readonly string[]): string {
return [command, ...args].join(" ");
}
@@ -72,31 +99,167 @@ function resolveRuntimeEnvironment(
return runtimeEnvironment ?? detectServerRuntimeEnvironment();
}
function shouldUseShell(options: RuntimeShellOptions): boolean | string {
if (options.shell !== undefined) {
return options.shell;
function resolveEffectiveEnvironment(options: ProcessLaunchPlanOptions): NodeJS.ProcessEnv {
const env = (options.env ?? {}) as NodeJS.ProcessEnv;
if (options.inheritParentEnv === false) {
return { ...env };
}
return resolveRuntimeEnvironment(options.runtimeEnvironment).platform === "windows";
return {
...process.env,
...env,
};
}
function toSpawnOptions(options: ProcessSpawnOptions) {
function resolveWindowsCommand(
command: string,
env: NodeJS.ProcessEnv,
): ResolvedWindowsCommand | null {
const windowsPathExtensions = resolveWindowsPathExtensions(env);
const candidates = resolveCommandCandidates(command, "win32", windowsPathExtensions);
const classify = (filePath: string): ResolvedWindowsCommand => {
const extension = extname(filePath).toUpperCase();
return {
path: filePath,
kind: WINDOWS_BATCH_EXECUTABLE_EXTENSIONS.has(extension) ? "batch" : "native",
};
};
if (command.includes("/") || command.includes("\\")) {
for (const candidate of candidates) {
if (isExecutableFile(candidate, "win32", windowsPathExtensions)) {
return classify(candidate);
}
}
return null;
}
const pathEntries = resolvePathEnvironmentVariable(env)
.split(";")
.map((entry) => stripWrappingQuotes(entry.trim()))
.filter((entry) => entry.length > 0);
for (const pathEntry of pathEntries) {
for (const candidate of candidates) {
const candidatePath = join(pathEntry, candidate);
if (isExecutableFile(candidatePath, "win32", windowsPathExtensions)) {
return classify(candidatePath);
}
}
}
return null;
}
function quoteWindowsBatchArgument(argument: string): string {
if (argument.length === 0) {
return '""';
}
const escaped = argument
.replaceAll("^", "^^")
.replaceAll("%", "%%")
.replaceAll("!", "^!")
.replaceAll("&", "^&")
.replaceAll("|", "^|")
.replaceAll("<", "^<")
.replaceAll(">", "^>")
.replaceAll("(", "^(")
.replaceAll(")", "^)")
.replaceAll('"', '""');
return `"${escaped}"`;
}
function buildWindowsBatchCommandLine(
command: string,
args: ReadonlyArray<string>,
): string {
return [quoteWindowsBatchArgument(command), ...args.map(quoteWindowsBatchArgument)].join(" ");
}
function resolveWindowsCommandShell(env: NodeJS.ProcessEnv): string {
return env.ComSpec ?? env.COMSPEC ?? process.env.ComSpec ?? process.env.COMSPEC ?? "cmd.exe";
}
export function resolveProcessLaunchPlan(
command: string,
args: ReadonlyArray<string>,
options: ProcessLaunchPlanOptions = {},
): ProcessLaunchPlan {
const runtimeEnvironment = resolveRuntimeEnvironment(options.runtimeEnvironment);
if (options.shell !== undefined) {
return {
command,
args: [...args],
shell: options.shell,
runtimeEnvironment,
};
}
if (runtimeEnvironment.platform !== "windows") {
return {
command,
args: [...args],
shell: false,
runtimeEnvironment,
};
}
const env = resolveEffectiveEnvironment(options);
const resolved = resolveWindowsCommand(command, env);
if (!resolved) {
return {
command,
args: [...args],
shell: false,
runtimeEnvironment,
};
}
if (resolved.kind === "batch") {
return {
command: resolveWindowsCommandShell(env),
args: ["/d", "/s", "/c", buildWindowsBatchCommandLine(resolved.path, args)],
shell: false,
runtimeEnvironment,
};
}
return {
command: resolved.path,
args: [...args],
shell: false,
runtimeEnvironment,
};
}
function toSpawnOptions(
options: ProcessSpawnOptions,
launchPlan: ProcessLaunchPlan,
) {
return {
cwd: options.cwd,
env: options.env,
shell: shouldUseShell(options),
shell: launchPlan.shell,
...(options.stdio !== undefined ? { stdio: options.stdio } : {}),
...(options.detached !== undefined ? { detached: options.detached } : {}),
};
}
function toRuntimeCommandOptions(
export function toRuntimeCommandOptions(
options: RuntimeCommandOptions = {},
): ChildProcess.CommandOptions {
const { runtimeEnvironment: _, ...rest } = options;
const launchPlan = resolveProcessLaunchPlan("", [], {
env: options.env,
runtimeEnvironment: options.runtimeEnvironment,
shell: options.shell,
inheritParentEnv: options.extendEnv !== false,
});
return {
...rest,
shell: options.shell ?? shouldUseShell(options),
...options,
shell: launchPlan.shell,
};
}
@@ -105,10 +268,19 @@ export function makeRuntimeCommand(
args: ReadonlyArray<string>,
options: RuntimeCommandOptions = {},
): ChildProcess.StandardCommand {
return ChildProcess.make(command, [...args], toRuntimeCommandOptions(options));
const launchPlan = resolveProcessLaunchPlan(command, args, {
env: options.env,
runtimeEnvironment: options.runtimeEnvironment,
shell: options.shell,
inheritParentEnv: options.extendEnv !== false,
});
return ChildProcess.make(launchPlan.command, launchPlan.args, {
...toRuntimeCommandOptions(options),
shell: launchPlan.shell,
});
}
interface ManagedChildProcess {
export interface ManagedChildProcess {
readonly scope: Scope.Closeable;
readonly handle: ChildProcessSpawner.ChildProcessHandle;
}
@@ -133,10 +305,17 @@ function spawnProcess(
args: readonly string[],
options: ProcessSpawnOptions = {},
): ChildProcessHandle {
return spawn(command, args, toSpawnOptions(options));
const launchPlan = resolveProcessLaunchPlan(command, args, {
env: options.env,
runtimeEnvironment: options.runtimeEnvironment,
shell: options.shell,
inheritParentEnv: options.env === undefined,
});
return spawn(launchPlan.command, launchPlan.args, toSpawnOptions(options, launchPlan));
}
function spawnPipedProcess(
export function spawnPipedProcess(
command: string,
args: readonly string[],
options: Omit<ProcessSpawnOptions, "stdio" | "detached"> = {},
@@ -152,10 +331,17 @@ export function spawnProcessSync(
args: readonly string[],
options: ProcessSpawnSyncOptions = {},
) {
return spawnSync(command, args, {
const launchPlan = resolveProcessLaunchPlan(command, args, {
env: options.env,
runtimeEnvironment: options.runtimeEnvironment,
shell: options.shell,
inheritParentEnv: options.env === undefined,
});
return spawnSync(launchPlan.command, launchPlan.args, {
cwd: options.cwd,
env: options.env,
shell: shouldUseShell(options),
shell: launchPlan.shell,
encoding: options.encoding ?? "utf8",
...(options.stdio !== undefined ? { stdio: options.stdio } : {}),
...(options.detached !== undefined ? { detached: options.detached } : {}),
@@ -249,11 +435,12 @@ function normalizeBufferError(
const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
/**
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
* entire process tree instead.
* On Windows, commands may still execute through a `cmd.exe` wrapper for
* explicit shell usage or `.cmd` / `.bat` launchers. `child.kill()` only
* terminates the wrapper, leaving the actual command running. Use
* `taskkill /T` to kill the entire process tree instead.
*/
function killProcessTree(
export function killProcessTree(
child: ChildProcessHandle,
options: {
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
@@ -15,7 +15,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { afterAll, assert, it, vi } from "@effect/vitest";
import { assertFailure } from "@effect/vitest/utils";
import { Effect, Fiber, Layer, Option, Stream } from "effect";
import { Effect, Fiber, Layer, Option, ServiceMap, Stream } from "effect";
import {
CodexAppServerManager,
@@ -132,7 +132,9 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory
listSessionIds: () => Effect.succeed([]),
});
const validationManager = new FakeCodexManager();
const validationManager = new FakeCodexManager(
ServiceMap.empty() as ServiceMap.ServiceMap<NodeServices.NodeServices>,
);
const validationLayer = it.layer(
makeCodexAdapterLive({ manager: validationManager }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
@@ -164,7 +166,9 @@ validationLayer("CodexAdapterLive validation", (it) => {
);
});
const sessionErrorManager = new FakeCodexManager();
const sessionErrorManager = new FakeCodexManager(
ServiceMap.empty() as ServiceMap.ServiceMap<NodeServices.NodeServices>,
);
sessionErrorManager.sendTurnImpl.mockImplementation(async () => {
throw new Error("Unknown session: sess-missing");
});
@@ -204,7 +208,9 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
);
});
const lifecycleManager = new FakeCodexManager();
const lifecycleManager = new FakeCodexManager(
ServiceMap.empty() as ServiceMap.ServiceMap<NodeServices.NodeServices>,
);
const lifecycleLayer = it.layer(
makeCodexAdapterLive({ manager: lifecycleManager }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
@@ -76,9 +76,6 @@ function detailFromResult(
if (stderr) return stderr;
const stdout = nonEmptyTrimmed(result.stdout);
if (stdout) return stdout;
if (result.code === null) {
return "Command was terminated before reporting an exit code.";
}
if (result.code !== 0) {
return `Command exited with code ${result.code}.`;
}