/** * Parent-side handle for the local-ONNX embedding subprocess (#518). * * Spawns a Node (preferred) or Bun child that runs `embedding-worker` so * `onnxruntime-node` never loads in the OpenCode/Bun host. Dispose uses * SIGKILL so ORT's NAPI finalizer cannot crash the host on Windows. */ import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"; import { createInterface } from "node:readline"; import { fileURLToPath } from "node:url"; import { existsSync } from "node:fs"; import { homedir } from "node:os"; import { basename, dirname, join } from "node:path"; import { log, safeLog } from "./logger.js"; import { parseWorkerResponse, type EmbeddingWorkerRequest, type EmbeddingWorkerResponse, } from "./embedding-worker-protocol.js"; export type EmbeddingSubprocessWarmup = { model: string; cacheDir: string; pooling: string; dtype?: string; }; type Pending = { resolve: (value: EmbeddingWorkerResponse) => void; reject: (error: Error) => void; timer: ReturnType; }; type PluginImportMeta = ImportMeta & { path?: string; dirname?: string; dir?: string; }; const DEFAULT_REQUEST_TIMEOUT_MS = 60_000; function which(cmd: string): string | null { const pathEnv = process.env.PATH ?? process.env.Path ?? ""; const ext = process.platform === "win32" ? (process.env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";").filter(Boolean) : [""]; const sep = process.platform === "win32" ? ";" : ":"; for (const dir of pathEnv.split(sep)) { if (!dir) continue; for (const e of ext) { const candidate = join(dir, `${cmd}${e}`); if (existsSync(candidate)) return candidate; } } return null; } /** PATH plus well-known install locations (OpenCode sandboxes often omit PATH entries). */ export function resolveRuntimeCandidates(cmd: "node" | "bun"): string[] { const found: string[] = []; const seen = new Set(); const add = (path: string | null | undefined) => { if (!path || seen.has(path) || !existsSync(path)) return; seen.add(path); found.push(path); }; add(which(cmd)); const home = homedir(); const local = process.env.LOCALAPPDATA; const pf = process.env.ProgramFiles ?? "C:\\Program Files"; const pf86 = process.env["ProgramFiles(x86)"] ?? "C:\\Program Files (x86)"; if (cmd === "node") { if (process.platform === "win32") { add(join(pf, "nodejs", "node.exe")); add(join(pf86, "nodejs", "node.exe")); if (local) add(join(local, "Programs", "nodejs", "node.exe")); } else { add("/usr/local/bin/node"); add("/usr/bin/node"); add(join(home, ".nvm", "current", "bin", "node")); } } else { if (process.platform === "win32") { add(join(home, ".bun", "bin", "bun.exe")); if (local) add(join(local, "bun", "bin", "bun.exe")); } else { add(join(home, ".bun", "bin", "bun")); add("/usr/local/bin/bun"); } } return found; } function isBunOrNodeExecutable(path: string): boolean { const name = basename(path).toLowerCase(); return name === "bun" || name === "bun.exe" || name === "node" || name === "node.exe"; } export type EmbeddingWorkerRuntime = { /** Executable to spawn (node, bun, or a bun --compile host such as opencode.exe). */ command: string; /** Extra argv before the worker script path. */ args: string[]; /** Extra env for the child (merged over process.env). */ env: Record; }; /** * Prefer Node so ORT runs outside Bun's NAPI host (#518). Fall back to a Bun * *subprocess* (still isolated from the OpenCode host) when Node is missing — * a child segfault kills only the worker, not `opencode serve`. * * When only a Bun `--compile` host is available (typical OpenCode standalone * install with no Node/Bun on PATH), re-exec `process.execPath` with * `BUN_BE_BUN=1` so the child acts as the Bun CLI and can run our worker * script (Bun ≥ 1.2.16; OpenCode 2.3.x ships Bun 1.4.x). */ export function resolveEmbeddingWorkerRuntime(): EmbeddingWorkerRuntime | null { const node = resolveRuntimeCandidates("node")[0]; if (node) return { command: node, args: [], env: {} }; const bun = resolveRuntimeCandidates("bun")[0]; if (bun) return { command: bun, args: [], env: {} }; if (typeof process.versions.bun === "string" && process.execPath) { // OpenCode.exe / other bun --compile hosts: ignore the bundled entrypoint // and run our worker as plain `bun