| 116 | } catch (error) { |
| 117 | done({ code: -1, error }) |
| 118 | return |
| 119 | } |
| 120 | |
| 121 | child.stdout?.on("data", (chunk) => stdout.push(Buffer.from(chunk))) |
| 122 | child.stderr?.on("data", (chunk) => stderr.push(Buffer.from(chunk))) |
| 123 | if (Number(options.timeoutMs) > 0) { |
| 124 | timer = setTimeout(() => { |
| 125 | timedOut = true |
| 126 | terminateChild(child) |
| 127 | }, Number(options.timeoutMs)) |
| 128 | timer.unref?.() |
| 129 | } |
| 130 | child.on("error", (error) => done({ code: -1, error })) |
| 131 | child.on("exit", (code, signal) => done({ code: timedOut ? 124 : (code ?? (signal ? 1 : 0)), signal })) |
| 132 | }) |
| 133 | } |
| 134 | |
| 135 | function quoteWindowsArg(value) { |
| 136 | const text = String(value ?? "") |
| 137 | return `"${text.replace(/(\\*)"/g, '$1$1\\"').replace(/\\+$/g, "$&$&")}"` |
| 138 | } |
| 139 | |
| 140 | function stripBom(text) { |
| 141 | return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text |
| 142 | } |
| 143 | |
| 144 | async function run(command, commandArgs, cwd, options = {}) { |
| 145 | const direct = await spawnOnce(command, commandArgs, cwd, options) |
| 146 | if (direct.code !== -1 || process.platform !== "win32" || !["ENOENT", "EINVAL"].includes(direct.error?.code)) return direct |
| 147 | |
| 148 | const fallback = await spawnOnce("cmd.exe", ["/d", "/s", "/c", command, ...commandArgs], cwd, options) |
| 149 | if (fallback.code === -1) { |
| 150 | console.error(`[opencode-loopd] failed to start ${command}: ${fallback.error?.message || direct.error?.message || "unknown error"}`) |
| 151 | } |
| 152 | return fallback |
| 153 | } |
| 154 | |
| 155 | async function resolveLatestSessionID(opencodeBin, project, preferredTitle) { |
| 156 | const result = await run(opencodeBin, ["session", "list", "--format", "json", "-n", "20"], project, { capture: true, timeoutMs: 15_000 }) |