Skip to content

Commit f27e4e2

Browse files
Harsh-2002claude
andcommitted
v2.0.1 — Cross-platform Windows compatibility
Add full Windows support for all child_process calls: - New src/utils/shell.ts with cross-platform helpers (execCmd, spawnCmd, spawnAsync, sleepSync) that add shell:true on Windows automatically - Fix ENOENT errors for pm2/npm .cmd shims in daemon.ts and update.ts - Fix OpenCode SDK spawn bug on Windows (shell:true workaround) - Fix path comparisons with normalize() for Windows backslashes - Add Windows graceful shutdown via process message handler - Fix sleep command (timeout on Windows, sleep on Unix) Closes: anomalyco/opencode#8160 Co-Authored-By: Claude Opus 4.6 <[email protected]>
1 parent 5381b76 commit f27e4e2

7 files changed

Lines changed: 195 additions & 33 deletions

File tree

‎package-lock.json‎

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@4via6/relay",
3-
"version": "2.0.0",
3+
"version": "2.0.1",
44
"description": "Telegram bot for AI coding agents — powered by OpenCode",
55
"type": "module",
66
"main": "dist/index.js",

‎src/daemon.ts‎

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
import { execFileSync, spawnSync } from "child_process";
21
import { existsSync } from "fs";
32
import { join, dirname } from "path";
43
import { fileURLToPath } from "url";
4+
import { execCmd, spawnCmd, sleepSync } from "./utils/shell.js";
55

66
const __dirname = dirname(fileURLToPath(import.meta.url));
77
const PROCESS_NAME = "relay";
@@ -35,7 +35,7 @@ function formatMemory(bytes: number): string {
3535

3636
function isPm2Available(): boolean {
3737
try {
38-
execFileSync("pm2", ["--version"], { stdio: "ignore" });
38+
execCmd("pm2", ["--version"], { stdio: "ignore" });
3939
return true;
4040
} catch {
4141
return false;
@@ -47,7 +47,7 @@ function ensurePm2(): void {
4747

4848
console.log(" pm2 not found. Installing globally...\n");
4949
try {
50-
execFileSync("npm", ["install", "-g", "pm2"], { stdio: "inherit" });
50+
execCmd("npm", ["install", "-g", "pm2"], { stdio: "inherit" });
5151
console.log();
5252
} catch {
5353
console.error(
@@ -66,10 +66,10 @@ function ensurePm2(): void {
6666

6767
function getProcessInfo(): Pm2ProcessInfo | null {
6868
try {
69-
const result = execFileSync("pm2", ["jlist"], {
69+
const result = execCmd("pm2", ["jlist"], {
7070
encoding: "utf-8",
7171
stdio: ["pipe", "pipe", "ignore"],
72-
});
72+
}) as string;
7373
const processes = JSON.parse(result);
7474
const proc = processes.find(
7575
(p: { name: string }) => p.name === PROCESS_NAME
@@ -134,7 +134,7 @@ export function daemonStart(): void {
134134
// If there's a stopped/errored process, delete it first
135135
if (info) {
136136
try {
137-
execFileSync("pm2", ["delete", PROCESS_NAME], { stdio: "ignore" });
137+
execCmd("pm2", ["delete", PROCESS_NAME], { stdio: "ignore" });
138138
} catch {
139139
// ignore
140140
}
@@ -158,14 +158,14 @@ export function daemonStart(): void {
158158
}
159159

160160
try {
161-
execFileSync("pm2", pm2Args, { stdio: "inherit" });
161+
execCmd("pm2", pm2Args, { stdio: "inherit" });
162162
} catch {
163163
console.error("\n Failed to start daemon.\n");
164164
process.exit(1);
165165
}
166166

167167
// Brief pause for pm2 to register the process
168-
spawnSync("sleep", ["1"]);
168+
sleepSync(1);
169169

170170
const newInfo = getProcessInfo();
171171
if (newInfo) {
@@ -188,8 +188,8 @@ export function daemonStop(): void {
188188
}
189189

190190
try {
191-
execFileSync("pm2", ["stop", PROCESS_NAME], { stdio: "ignore" });
192-
execFileSync("pm2", ["delete", PROCESS_NAME], { stdio: "ignore" });
191+
execCmd("pm2", ["stop", PROCESS_NAME], { stdio: "ignore" });
192+
execCmd("pm2", ["delete", PROCESS_NAME], { stdio: "ignore" });
193193
} catch {
194194
// ignore — may already be stopped
195195
}
@@ -209,13 +209,13 @@ export function daemonRestart(): void {
209209
}
210210

211211
try {
212-
execFileSync("pm2", ["restart", PROCESS_NAME], { stdio: "inherit" });
212+
execCmd("pm2", ["restart", PROCESS_NAME], { stdio: "inherit" });
213213
} catch {
214214
console.error("\n Failed to restart daemon.\n");
215215
process.exit(1);
216216
}
217217

218-
spawnSync("sleep", ["1"]);
218+
sleepSync(1);
219219

220220
const newInfo = getProcessInfo();
221221
if (newInfo) {
@@ -239,7 +239,7 @@ export function daemonLogs(): void {
239239
process.exit(1);
240240
}
241241

242-
spawnSync("pm2", ["logs", PROCESS_NAME, "--lines", "50"], {
242+
spawnCmd("pm2", ["logs", PROCESS_NAME, "--lines", "50"], {
243243
stdio: "inherit",
244244
});
245245
}

‎src/index.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,12 @@ async function main() {
6363

6464
process.on("SIGINT", () => gracefulShutdown("SIGINT"));
6565
process.on("SIGTERM", () => gracefulShutdown("SIGTERM"));
66+
// Windows: SIGTERM doesn't fire. Use 'message' from pm2 for graceful shutdown.
67+
if (process.platform === "win32") {
68+
process.on("message", (msg) => {
69+
if (msg === "shutdown") gracefulShutdown("shutdown");
70+
});
71+
}
6672

6773
if (botMode === "webhook") {
6874
if (!config.webhookUrl) {

‎src/providers/opencode.ts‎

Lines changed: 77 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import type {
2626
import type { Event as OcEvent } from "@opencode-ai/sdk";
2727
import { getConfig } from "../config/index.js";
2828
import { providerLogger } from "../utils/logger.js";
29+
import { spawnAsync } from "../utils/shell.js";
2930

3031
let client: OpencodeClient;
3132
let serverClose: (() => void) | undefined;
@@ -58,9 +59,19 @@ export class OpenCodeProvider implements Provider {
5859
const hostname = config.opencodeHostname;
5960
const port = config.opencodePort;
6061
providerLogger.info({ mode, hostname, port }, "Initializing provider");
61-
const result = await createOpencode({ hostname, port });
62-
client = result.client;
63-
serverClose = result.server.close;
62+
63+
// On Windows, the SDK's createOpencode() fails with ENOENT because
64+
// spawn("opencode") can't find .cmd shims. We spawn manually with
65+
// shell:true and then connect as a client.
66+
// See: https://github.com/anomalyco/opencode/issues/8160
67+
if (process.platform === "win32") {
68+
const baseUrl = await spawnOpencodeWindows(hostname, port);
69+
client = createOpencodeClient({ baseUrl });
70+
} else {
71+
const result = await createOpencode({ hostname, port });
72+
client = result.client;
73+
serverClose = result.server.close;
74+
}
6475
}
6576
}
6677

@@ -731,6 +742,69 @@ export class OpenCodeProvider implements Provider {
731742
}
732743
}
733744

745+
// --- Windows spawn workaround ---
746+
// SDK's createOpencode() uses spawn("opencode") without shell:true,
747+
// which fails on Windows because npm installs opencode as a .cmd shim.
748+
// We use spawnAsync() which adds shell:true on Windows automatically.
749+
// See: https://github.com/anomalyco/opencode/issues/8160
750+
751+
function spawnOpencodeWindows(hostname: string, port: number): Promise<string> {
752+
const TIMEOUT = 15_000;
753+
const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];
754+
755+
providerLogger.info({ hostname, port }, "Spawning OpenCode server (Windows)");
756+
757+
const proc = spawnAsync("opencode", args, {
758+
env: { ...process.env },
759+
stdio: ["ignore", "pipe", "pipe"],
760+
});
761+
762+
// Store kill function for shutdown
763+
serverClose = () => {
764+
try { proc.kill(); } catch {}
765+
};
766+
767+
return new Promise((resolve, reject) => {
768+
const timer = setTimeout(() => {
769+
proc.kill();
770+
reject(new Error(`OpenCode server did not start within ${TIMEOUT / 1000}s`));
771+
}, TIMEOUT);
772+
773+
let output = "";
774+
775+
proc.stdout?.on("data", (chunk: Buffer) => {
776+
output += chunk.toString();
777+
for (const line of output.split("\n")) {
778+
if (line.includes("opencode server listening")) {
779+
const match = line.match(/on\s+(https?:\/\/[^\s]+)/);
780+
if (match) {
781+
clearTimeout(timer);
782+
providerLogger.info({ url: match[1] }, "OpenCode server started (Windows)");
783+
resolve(match[1]);
784+
return;
785+
}
786+
}
787+
}
788+
});
789+
790+
proc.stderr?.on("data", (chunk: Buffer) => {
791+
output += chunk.toString();
792+
});
793+
794+
proc.on("error", (err) => {
795+
clearTimeout(timer);
796+
reject(new Error(`Failed to spawn OpenCode: ${err.message}`));
797+
});
798+
799+
proc.on("exit", (code) => {
800+
clearTimeout(timer);
801+
let msg = `OpenCode server exited with code ${code}`;
802+
if (output.trim()) msg += `\nOutput: ${output.trim()}`;
803+
reject(new Error(msg));
804+
});
805+
});
806+
}
807+
734808
// --- Helpers ---
735809

736810
function sdkError(error: any): Error {

‎src/update.ts‎

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
import { execFileSync, execSync } from "child_process";
1+
import { execSync } from "child_process";
22
import { readFileSync, existsSync } from "fs";
3-
import { join, dirname } from "path";
3+
import { join, dirname, resolve, normalize } from "path";
44
import { fileURLToPath } from "url";
5+
import { execCmd } from "./utils/shell.js";
56

67
const __dirname = dirname(fileURLToPath(import.meta.url));
78
const PACKAGE_NAME = "@4via6/relay";
@@ -19,10 +20,10 @@ function getLocalVersion(): string {
1920

2021
function getLatestVersion(): string | null {
2122
try {
22-
return execFileSync("npm", ["view", PACKAGE_NAME, "version"], {
23+
return (execCmd("npm", ["view", PACKAGE_NAME, "version"], {
2324
encoding: "utf-8",
2425
stdio: ["pipe", "pipe", "ignore"],
25-
}).trim();
26+
}) as string).trim();
2627
} catch {
2728
return null;
2829
}
@@ -34,12 +35,14 @@ function isGitRepo(): boolean {
3435

3536
function isGlobalNpmInstall(): boolean {
3637
try {
37-
const globalPrefix = execFileSync("npm", ["prefix", "-g"], {
38-
encoding: "utf-8",
39-
stdio: ["pipe", "pipe", "ignore"],
40-
}).trim();
41-
// If our package dir is inside the global prefix, it's a global install
42-
const pkgRoot = join(__dirname, "..");
38+
const globalPrefix = normalize(
39+
(execCmd("npm", ["prefix", "-g"], {
40+
encoding: "utf-8",
41+
stdio: ["pipe", "pipe", "ignore"],
42+
}) as string).trim()
43+
);
44+
// Normalize both paths to handle Windows backslashes and trailing separators
45+
const pkgRoot = normalize(resolve(__dirname, ".."));
4346
return pkgRoot.startsWith(globalPrefix);
4447
} catch {
4548
return false;
@@ -48,10 +51,10 @@ function isGlobalNpmInstall(): boolean {
4851

4952
function isDaemonRunning(): boolean {
5053
try {
51-
const result = execFileSync("pm2", ["jlist"], {
54+
const result = execCmd("pm2", ["jlist"], {
5255
encoding: "utf-8",
5356
stdio: ["pipe", "pipe", "ignore"],
54-
});
57+
}) as string;
5558
const processes = JSON.parse(result);
5659
const proc = processes.find(
5760
(p: { name: string }) => p.name === "relay"
@@ -64,7 +67,7 @@ function isDaemonRunning(): boolean {
6467

6568
function restartDaemon(): void {
6669
try {
67-
execFileSync("pm2", ["restart", "relay"], { stdio: "ignore" });
70+
execCmd("pm2", ["restart", "relay"], { stdio: "ignore" });
6871
console.log(" Daemon restarted.\n");
6972
} catch {
7073
console.log(" Failed to restart daemon. Run `relay restart` manually.\n");
@@ -74,7 +77,7 @@ function restartDaemon(): void {
7477
function updateFromNpm(): boolean {
7578
console.log(` Updating ${PACKAGE_NAME} via npm...\n`);
7679
try {
77-
execFileSync("npm", ["install", "-g", `${PACKAGE_NAME}@latest`], {
80+
execCmd("npm", ["install", "-g", `${PACKAGE_NAME}@latest`], {
7881
stdio: "inherit",
7982
});
8083
return true;

‎src/utils/shell.ts‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/**
2+
* Cross-platform child_process wrappers.
3+
*
4+
* On Windows, npm/pm2/opencode are installed as .cmd shims.
5+
* Node's execFileSync/spawnSync/spawn can't find .cmd files
6+
* without `shell: true`. These helpers add it automatically.
7+
*/
8+
import {
9+
execFileSync,
10+
spawnSync,
11+
spawn,
12+
type ExecFileSyncOptions,
13+
type SpawnSyncOptions,
14+
type SpawnOptions,
15+
type ChildProcess,
16+
type SpawnSyncReturns,
17+
} from "child_process";
18+
19+
const IS_WIN = process.platform === "win32";
20+
21+
/**
22+
* Cross-platform execFileSync.
23+
* Adds `shell: true` on Windows so .cmd shims are found.
24+
*/
25+
export function execCmd(
26+
cmd: string,
27+
args: string[],
28+
options?: ExecFileSyncOptions
29+
): string | Buffer {
30+
return execFileSync(cmd, args, {
31+
...options,
32+
...(IS_WIN && { shell: true }),
33+
});
34+
}
35+
36+
/**
37+
* Cross-platform spawnSync.
38+
* Adds `shell: true` on Windows so .cmd shims are found.
39+
*/
40+
export function spawnCmd(
41+
cmd: string,
42+
args: string[],
43+
options?: SpawnSyncOptions
44+
): SpawnSyncReturns<string | Buffer> {
45+
return spawnSync(cmd, args, {
46+
...options,
47+
...(IS_WIN && { shell: true }),
48+
});
49+
}
50+
51+
/**
52+
* Cross-platform async spawn.
53+
* Adds `shell: true` on Windows so .cmd shims are found.
54+
*/
55+
export function spawnAsync(
56+
cmd: string,
57+
args: string[],
58+
options?: SpawnOptions
59+
): ChildProcess {
60+
return spawn(cmd, args, {
61+
...options,
62+
...(IS_WIN && { shell: true }),
63+
});
64+
}
65+
66+
/**
67+
* Cross-platform sleep (synchronous).
68+
* Uses `timeout` on Windows, `sleep` on Unix.
69+
*/
70+
export function sleepSync(seconds: number): void {
71+
if (IS_WIN) {
72+
spawnSync("timeout", ["/t", String(seconds), "/nobreak"], {
73+
shell: true,
74+
stdio: "ignore",
75+
});
76+
} else {
77+
spawnSync("sleep", [String(seconds)]);
78+
}
79+
}

0 commit comments

Comments
 (0)