@devries-cameron20 / t3code-1 / commits / b6629dcd68
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(opencode): OpenCode servers stop with a killed server on Windows (#21103)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Dara Adedeji committed Oct 18, 2026 at 15:54 UTC b6629dcd68dd26a98250e34087c594592ea55a46
3 files changed +208 -2
packages/provider-opencode/src/server/OpenCodeRuntime.ts
+4 -1
@@ -598,8 +598,11 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
598 const hostPlatform = yield* HostProcess.Platform;
599 const serverLedger = yield* OpenCodeServerLedger.OpenCodeServerLedger;
600 const agentScope = yield* AgentScope;
601 + // npm installs OpenCode as `opencode.CMD`, which `cmd.exe` runs. The
602 + // `opencode.exe` it starts escapes libuv's kill-on-close job and outlives a
603 + // server that is killed, so the shim's executable runs directly instead.
604 const resolveCommand = (command: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>
602 - resolveSpawnCommand(command, args, env ? { env } : {});
605 + resolveSpawnCommand(command, args, { ...(env ? { env } : {}), bypassNpmShim: true });
606
607 const runOpenCodeCommand: OpenCodeRuntime["Service"]["runOpenCodeCommand"] = (input) =>
608 Effect.gen(function* () {
packages/shared/src/shell.test.ts
+145
@@ -18,6 +18,7 @@ import {
18 listLoginShellCandidates,
19 mergePathEntries,
20 mergePathValues,
21 + npmShimExecutable,
22 preferGitForWindowsBinary,
23 readEnvironmentFromLoginShell,
24 readEnvironmentFromWindowsShell,
@@ -654,6 +655,111 @@ describe("preferGitForWindowsBinary", () => {
655 });
656 });
657
658 +// Byte for byte what `npm install -g opencode-ai` writes as `opencode.cmd`.
659 +const NPM_OPENCODE_SHIM = [
660 + "@ECHO off",
661 + "GOTO start",
662 + ":find_dp0",
663 + "SET dp0=%~dp0",
664 + "EXIT /b",
665 + ":start",
666 + "SETLOCAL",
667 + "CALL :find_dp0",
668 + '"%dp0%\\node_modules\\opencode-ai\\bin\\opencode.exe" %*',
669 + "",
670 +].join("\r\n");
671 +
672 +describe("npmShimExecutable", () => {
673 + const shimPath = "C:\\Users\\me\\AppData\\Roaming\\npm\\opencode.cmd";
674 + const executable =
675 + "C:\\Users\\me\\AppData\\Roaming\\npm\\node_modules\\opencode-ai\\bin\\opencode.exe";
676 + const exists = (filePath: string) => filePath === executable;
677 +
678 + it("finds the executable npm's shim runs", () => {
679 + expect(npmShimExecutable(shimPath, () => NPM_OPENCODE_SHIM, exists)).toBe(executable);
680 + expect(
681 + npmShimExecutable(shimPath.replace(".cmd", ".CMD"), () => NPM_OPENCODE_SHIM, exists),
682 + ).toBe(executable);
683 + });
684 +
685 + it("keeps a shim that does more than run the executable", () => {
686 + const withSetting = NPM_OPENCODE_SHIM.replace(
687 + "SETLOCAL",
688 + "SETLOCAL\r\nSET OPENCODE_CONFIG=C:\\x",
689 + );
690 + expect(npmShimExecutable(shimPath, () => withSetting, exists)).toBeUndefined();
691 + const nodeScript = NPM_OPENCODE_SHIM.replace(
692 + '"%dp0%\\node_modules\\opencode-ai\\bin\\opencode.exe" %*',
693 + '"%_prog%" "%dp0%\\node_modules\\opencode-ai\\bin\\opencode.js" %*',
694 + );
695 + expect(
696 + npmShimExecutable(
697 + shimPath,
698 + () => nodeScript,
699 + () => true,
700 + ),
701 + ).toBeUndefined();
702 + });
703 +
704 + it("keeps a shim CMD would read differently", () => {
705 + // CMD keeps trailing characters in an unquoted `SET` value, so these point
706 + // `dp0`, and with it the executable, somewhere else.
707 + for (const suffix of ["\u00a0", "\t", " "]) {
708 + const altered = NPM_OPENCODE_SHIM.replace("SET dp0=%~dp0", `SET dp0=%~dp0${suffix}`);
709 + expect(
710 + npmShimExecutable(
711 + shimPath,
712 + () => altered,
713 + () => true,
714 + ),
715 + ).toBeUndefined();
716 + }
717 + const nonBreakingSeparator = NPM_OPENCODE_SHIM.replace(
718 + 'opencode.exe" %*',
719 + 'opencode.exe"\u00a0%*',
720 + );
721 + expect(
722 + npmShimExecutable(
723 + shimPath,
724 + () => nonBreakingSeparator,
725 + () => true,
726 + ),
727 + ).toBeUndefined();
728 + const indented = NPM_OPENCODE_SHIM.replace("SETLOCAL", " SETLOCAL");
729 + expect(
730 + npmShimExecutable(
731 + shimPath,
732 + () => indented,
733 + () => true,
734 + ),
735 + ).toBeUndefined();
736 + });
737 +
738 + it("keeps the shim when its executable is missing or it is not a .cmd", () => {
739 + expect(
740 + npmShimExecutable(
741 + shimPath,
742 + () => NPM_OPENCODE_SHIM,
743 + () => false,
744 + ),
745 + ).toBeUndefined();
746 + expect(
747 + npmShimExecutable(
748 + shimPath,
749 + () => undefined,
750 + () => true,
751 + ),
752 + ).toBeUndefined();
753 + expect(
754 + npmShimExecutable(
755 + shimPath.replace(".cmd", ".bat"),
756 + () => NPM_OPENCODE_SHIM,
757 + () => true,
758 + ),
759 + ).toBeUndefined();
760 + });
761 +});
762 +
763 effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => {
764 it.effect("runs Windows executables directly without a shell", () =>
765 Effect.gen(function* () {
@@ -672,6 +778,45 @@ effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => {
778 }),
779 );
780
781 + it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")(
782 + "runs the executable behind an npm shim directly when asked",
783 + () =>
784 + Effect.scoped(
785 + Effect.gen(function* () {
786 + const fs = yield* FileSystem.FileSystem;
787 + const path = yield* Path.Path;
788 + const prefix = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-shim-" });
789 + const shim = path.join(prefix, "opencode.cmd");
790 + const executable = path.join(
791 + prefix,
792 + "node_modules",
793 + "opencode-ai",
794 + "bin",
795 + "opencode.exe",
796 + );
797 + yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
798 + yield* fs.writeFileString(executable, "");
799 + yield* fs.writeFileString(shim, NPM_OPENCODE_SHIM);
800 + const resolve = (bypassNpmShim: boolean) =>
801 + resolveSpawnCommand("opencode", ["serve", "--port=4096"], {
802 + env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
803 + bypassNpmShim,
804 + }).pipe(
805 + Effect.provideService(HostProcess.Platform, "win32"),
806 + Effect.provideService(CommandResolutionCache, new Map()),
807 + Effect.provideService(SpawnExecutableResolution, () => shim),
808 + );
809 +
810 + expect(yield* resolve(true)).toEqual({
811 + command: executable,
812 + args: ["serve", "--port=4096"],
813 + shell: false,
814 + });
815 + expect((yield* resolve(false)).shell).toBe(true);
816 + }),
817 + ),
818 + );
819 +
820 it.effect("builds one escaped cmd.exe line for Windows command shims", () =>
821 Effect.gen(function* () {
822 const command = yield* resolveSpawnCommand(
packages/shared/src/shell.ts
+59 -1
@@ -679,10 +679,64 @@ export function preferGitForWindowsBinary(
679 return executable;
680 }
681
682 +// What npm's cmd-shim writes for a package whose bin is a native executable.
683 +const NPM_EXECUTABLE_SHIM_PREFIX = [
684 + "@ECHO off",
685 + "GOTO start",
686 + ":find_dp0",
687 + "SET dp0=%~dp0",
688 + "EXIT /b",
689 + ":start",
690 + "SETLOCAL",
691 + "CALL :find_dp0",
692 +];
693 +const NPM_EXECUTABLE_SHIM_RUN = /^"%dp0%\\([^"%]+\.exe)" +%\*$/;
694 +
695 +function readFileSyncOrUndefined(filePath: string): string | undefined {
696 + try {
697 + return NodeFS.readFileSync(filePath, "utf8");
698 + } catch {
699 + return undefined;
700 + }
701 +}
702 +
703 +/**
704 + * The executable an npm cmd-shim runs, when the shim does nothing else.
705 + * Started through the shim, the executable is a child of `cmd.exe` and so
706 + * escapes the kill-on-close job libuv puts every child in: it keeps running
707 + * after this process is killed. Started directly it is in the job.
708 + */
709 +export function npmShimExecutable(
710 + shimPath: string,
711 + readFile: (filePath: string) => string | undefined = readFileSyncOrUndefined,
712 + isFile: (filePath: string) => boolean = isFileSync,
713 +): string | undefined {
714 + const path = NodePath.win32;
715 + if (path.extname(shimPath).toLowerCase() !== ".cmd") return undefined;
716 + // Compared exactly: whitespace CMD keeps, such as after `SET dp0=`, would
717 + // make it run a different file than the one found here.
718 + const lines = readFile(shimPath)
719 + ?.split(/\r?\n/)
720 + .filter((line) => line.length > 0);
721 + if (lines?.length !== NPM_EXECUTABLE_SHIM_PREFIX.length + 1) return undefined;
722 + if (NPM_EXECUTABLE_SHIM_PREFIX.some((expected, index) => lines[index] !== expected)) {
723 + return undefined;
724 + }
725 + const target = NPM_EXECUTABLE_SHIM_RUN.exec(lines.at(-1)!)?.[1];
726 + if (target === undefined) return undefined;
727 + const executable = path.join(path.dirname(shimPath), target);
728 + return isFile(executable) ? executable : undefined;
729 +}
730 +
731 +export interface SpawnCommandOptions extends CommandAvailabilityOptions {
732 + /** Run the executable behind an npm cmd-shim directly (see `npmShimExecutable`). */
733 + readonly bypassNpmShim?: boolean;
734 +}
735 +
736 export const resolveSpawnCommand = Effect.fnUntraced(function* (
737 command: string,
738 args: ReadonlyArray<string>,
685 - options: CommandAvailabilityOptions = {},
739 + options: SpawnCommandOptions = {},
740 ): Effect.fn.Return<ResolvedSpawnCommand> {
741 const platform = yield* HostProcess.Platform;
742 if (platform !== "win32") {
@@ -729,6 +783,10 @@ export const resolveSpawnCommand = Effect.fnUntraced(function* (
783 if (extension !== ".cmd" && extension !== ".bat") {
784 return { command: resolvedCommand, args: [...args], shell: false };
785 }
786 + const shimExecutable = options.bypassNpmShim ? npmShimExecutable(resolvedCommand) : undefined;
787 + if (shimExecutable !== undefined) {
788 + return { command: shimExecutable, args: [...args], shell: false };
789 + }
790
791 // Node runs a shell spawn as `cmd.exe /d /s /c "<command> <args...>"`, but
792 // passing args with `shell: true` prints DEP0190. Build the same escaped line