TypeScript
fix(opencode): OpenCode servers stop with a killed server on Windows (#21103)
Dara Adedejib6629dcd68dd
diff --git a/packages/provider-opencode/src/server/OpenCodeRuntime.ts b/packages/provider-opencode/src/server/OpenCodeRuntime.tsindex 1f73d9cb02b..bff49126ce4 100644--- a/packages/provider-opencode/src/server/OpenCodeRuntime.ts+++ b/packages/provider-opencode/src/server/OpenCodeRuntime.ts@@ -598,8 +598,11 @@ const makeOpenCodeRuntime = Effect.gen(function* () {const hostPlatform = yield* HostProcess.Platform;const serverLedger = yield* OpenCodeServerLedger.OpenCodeServerLedger;const agentScope = yield* AgentScope;+ // npm installs OpenCode as `opencode.CMD`, which `cmd.exe` runs. The+ // `opencode.exe` it starts escapes libuv's kill-on-close job and outlives a+ // server that is killed, so the shim's executable runs directly instead.const resolveCommand = (command: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>- resolveSpawnCommand(command, args, env ? { env } : {});+ resolveSpawnCommand(command, args, { ...(env ? { env } : {}), bypassNpmShim: true });const runOpenCodeCommand: OpenCodeRuntime["Service"]["runOpenCodeCommand"] = (input) =>Effect.gen(function* () {diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.tsindex 8634ebc3966..38c305ac116 100644--- a/packages/shared/src/shell.test.ts+++ b/packages/shared/src/shell.test.ts@@ -18,6 +18,7 @@ import {listLoginShellCandidates,mergePathEntries,mergePathValues,+ npmShimExecutable,preferGitForWindowsBinary,readEnvironmentFromLoginShell,readEnvironmentFromWindowsShell,@@ -654,6 +655,111 @@ describe("preferGitForWindowsBinary", () => {});});+// Byte for byte what `npm install -g opencode-ai` writes as `opencode.cmd`.+const NPM_OPENCODE_SHIM = [+ "@ECHO off",+ "GOTO start",+ ":find_dp0",+ "SET dp0=%~dp0",+ "EXIT /b",+ ":start",+ "SETLOCAL",+ "CALL :find_dp0",+ '"%dp0%\\node_modules\\opencode-ai\\bin\\opencode.exe" %*',+ "",+].join("\r\n");++describe("npmShimExecutable", () => {+ const shimPath = "C:\\Users\\me\\AppData\\Roaming\\npm\\opencode.cmd";+ const executable =+ "C:\\Users\\me\\AppData\\Roaming\\npm\\node_modules\\opencode-ai\\bin\\opencode.exe";+ const exists = (filePath: string) => filePath === executable;++ it("finds the executable npm's shim runs", () => {+ expect(npmShimExecutable(shimPath, () => NPM_OPENCODE_SHIM, exists)).toBe(executable);+ expect(+ npmShimExecutable(shimPath.replace(".cmd", ".CMD"), () => NPM_OPENCODE_SHIM, exists),+ ).toBe(executable);+ });++ it("keeps a shim that does more than run the executable", () => {+ const withSetting = NPM_OPENCODE_SHIM.replace(+ "SETLOCAL",+ "SETLOCAL\r\nSET OPENCODE_CONFIG=C:\\x",+ );+ expect(npmShimExecutable(shimPath, () => withSetting, exists)).toBeUndefined();+ const nodeScript = NPM_OPENCODE_SHIM.replace(+ '"%dp0%\\node_modules\\opencode-ai\\bin\\opencode.exe" %*',+ '"%_prog%" "%dp0%\\node_modules\\opencode-ai\\bin\\opencode.js" %*',+ );+ expect(+ npmShimExecutable(+ shimPath,+ () => nodeScript,+ () => true,+ ),+ ).toBeUndefined();+ });++ it("keeps a shim CMD would read differently", () => {+ // CMD keeps trailing characters in an unquoted `SET` value, so these point+ // `dp0`, and with it the executable, somewhere else.+ for (const suffix of ["\u00a0", "\t", " "]) {+ const altered = NPM_OPENCODE_SHIM.replace("SET dp0=%~dp0", `SET dp0=%~dp0${suffix}`);+ expect(+ npmShimExecutable(+ shimPath,+ () => altered,+ () => true,+ ),+ ).toBeUndefined();+ }+ const nonBreakingSeparator = NPM_OPENCODE_SHIM.replace(+ 'opencode.exe" %*',+ 'opencode.exe"\u00a0%*',+ );+ expect(+ npmShimExecutable(+ shimPath,+ () => nonBreakingSeparator,+ () => true,+ ),+ ).toBeUndefined();+ const indented = NPM_OPENCODE_SHIM.replace("SETLOCAL", " SETLOCAL");+ expect(+ npmShimExecutable(+ shimPath,+ () => indented,+ () => true,+ ),+ ).toBeUndefined();+ });++ it("keeps the shim when its executable is missing or it is not a .cmd", () => {+ expect(+ npmShimExecutable(+ shimPath,+ () => NPM_OPENCODE_SHIM,+ () => false,+ ),+ ).toBeUndefined();+ expect(+ npmShimExecutable(+ shimPath,+ () => undefined,+ () => true,+ ),+ ).toBeUndefined();+ expect(+ npmShimExecutable(+ shimPath.replace(".cmd", ".bat"),+ () => NPM_OPENCODE_SHIM,+ () => true,+ ),+ ).toBeUndefined();+ });+});+effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => {it.effect("runs Windows executables directly without a shell", () =>Effect.gen(function* () {@@ -672,6 +778,45 @@ effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => {}),);+ it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")(+ "runs the executable behind an npm shim directly when asked",+ () =>+ Effect.scoped(+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const prefix = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-shim-" });+ const shim = path.join(prefix, "opencode.cmd");+ const executable = path.join(+ prefix,+ "node_modules",+ "opencode-ai",+ "bin",+ "opencode.exe",+ );+ yield* fs.makeDirectory(path.dirname(executable), { recursive: true });+ yield* fs.writeFileString(executable, "");+ yield* fs.writeFileString(shim, NPM_OPENCODE_SHIM);+ const resolve = (bypassNpmShim: boolean) =>+ resolveSpawnCommand("opencode", ["serve", "--port=4096"], {+ env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },+ bypassNpmShim,+ }).pipe(+ Effect.provideService(HostProcess.Platform, "win32"),+ Effect.provideService(CommandResolutionCache, new Map()),+ Effect.provideService(SpawnExecutableResolution, () => shim),+ );++ expect(yield* resolve(true)).toEqual({+ command: executable,+ args: ["serve", "--port=4096"],+ shell: false,+ });+ expect((yield* resolve(false)).shell).toBe(true);+ }),+ ),+ );+it.effect("builds one escaped cmd.exe line for Windows command shims", () =>Effect.gen(function* () {const command = yield* resolveSpawnCommand(diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.tsindex e8a9cc2ba77..1e0a1fecf2f 100644--- a/packages/shared/src/shell.ts+++ b/packages/shared/src/shell.ts@@ -679,10 +679,64 @@ export function preferGitForWindowsBinary(return executable;}+// What npm's cmd-shim writes for a package whose bin is a native executable.+const NPM_EXECUTABLE_SHIM_PREFIX = [+ "@ECHO off",+ "GOTO start",+ ":find_dp0",+ "SET dp0=%~dp0",+ "EXIT /b",+ ":start",+ "SETLOCAL",+ "CALL :find_dp0",+];+const NPM_EXECUTABLE_SHIM_RUN = /^"%dp0%\\([^"%]+\.exe)" +%\*$/;++function readFileSyncOrUndefined(filePath: string): string | undefined {+ try {+ return NodeFS.readFileSync(filePath, "utf8");+ } catch {+ return undefined;+ }+}++/**+ * The executable an npm cmd-shim runs, when the shim does nothing else.+ * Started through the shim, the executable is a child of `cmd.exe` and so+ * escapes the kill-on-close job libuv puts every child in: it keeps running+ * after this process is killed. Started directly it is in the job.+ */+export function npmShimExecutable(+ shimPath: string,+ readFile: (filePath: string) => string | undefined = readFileSyncOrUndefined,+ isFile: (filePath: string) => boolean = isFileSync,+): string | undefined {+ const path = NodePath.win32;+ if (path.extname(shimPath).toLowerCase() !== ".cmd") return undefined;+ // Compared exactly: whitespace CMD keeps, such as after `SET dp0=`, would+ // make it run a different file than the one found here.+ const lines = readFile(shimPath)+ ?.split(/\r?\n/)+ .filter((line) => line.length > 0);+ if (lines?.length !== NPM_EXECUTABLE_SHIM_PREFIX.length + 1) return undefined;+ if (NPM_EXECUTABLE_SHIM_PREFIX.some((expected, index) => lines[index] !== expected)) {+ return undefined;+ }+ const target = NPM_EXECUTABLE_SHIM_RUN.exec(lines.at(-1)!)?.[1];+ if (target === undefined) return undefined;+ const executable = path.join(path.dirname(shimPath), target);+ return isFile(executable) ? executable : undefined;+}++export interface SpawnCommandOptions extends CommandAvailabilityOptions {+ /** Run the executable behind an npm cmd-shim directly (see `npmShimExecutable`). */+ readonly bypassNpmShim?: boolean;+}+export const resolveSpawnCommand = Effect.fnUntraced(function* (command: string,args: ReadonlyArray<string>,- options: CommandAvailabilityOptions = {},+ options: SpawnCommandOptions = {},): Effect.fn.Return<ResolvedSpawnCommand> {const platform = yield* HostProcess.Platform;if (platform !== "win32") {@@ -729,6 +783,10 @@ export const resolveSpawnCommand = Effect.fnUntraced(function* (if (extension !== ".cmd" && extension !== ".bat") {return { command: resolvedCommand, args: [...args], shell: false };}+ const shimExecutable = options.bypassNpmShim ? npmShimExecutable(resolvedCommand) : undefined;+ if (shimExecutable !== undefined) {+ return { command: shimExecutable, args: [...args], shell: false };+ }// Node runs a shell spawn as `cmd.exe /d /s /c "<command> <args...>"`, but// passing args with `shell: true` prints DEP0190. Build the same escaped line