process.ts 1.0 KB

12345678910111213141516171819202122232425262728293031
  1. import { type ChildProcess, spawnSync } from "node:child_process"
  2. // Duplicated from `packages/opencode/src/util/process.ts` because the SDK cannot
  3. // import `opencode` without creating a cycle (`opencode` depends on `@opencode-ai/sdk`).
  4. export function stop(proc: ChildProcess) {
  5. if (proc.exitCode !== null || proc.signalCode !== null) return
  6. if (process.platform === "win32" && proc.pid) {
  7. const out = spawnSync("taskkill", ["/pid", String(proc.pid), "/T", "/F"], { windowsHide: true })
  8. if (!out.error && out.status === 0) return
  9. }
  10. proc.kill()
  11. }
  12. export function bindAbort(proc: ChildProcess, signal?: AbortSignal, onAbort?: () => void) {
  13. if (!signal) return () => {}
  14. const abort = () => {
  15. clear()
  16. stop(proc)
  17. onAbort?.()
  18. }
  19. const clear = () => {
  20. signal.removeEventListener("abort", abort)
  21. proc.off("exit", clear)
  22. proc.off("error", clear)
  23. }
  24. signal.addEventListener("abort", abort, { once: true })
  25. proc.on("exit", clear)
  26. proc.on("error", clear)
  27. if (signal.aborted) abort()
  28. return clear
  29. }