server.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. import { spawn } from "node:child_process"
  2. import { type Config } from "./gen/types.gen.js"
  3. export type ServerOptions = {
  4. hostname?: string
  5. port?: number
  6. signal?: AbortSignal
  7. timeout?: number
  8. config?: Config
  9. }
  10. export type TuiOptions = {
  11. project?: string
  12. model?: string
  13. session?: string
  14. agent?: string
  15. signal?: AbortSignal
  16. config?: Config
  17. }
  18. export async function createOpencodeServer(options?: ServerOptions) {
  19. options = Object.assign(
  20. {
  21. hostname: "127.0.0.1",
  22. port: 4096,
  23. timeout: 5000,
  24. },
  25. options ?? {},
  26. )
  27. const proc = spawn(
  28. `opencode`,
  29. [`serve`, `--hostname=${options.hostname}`, `--port=${options.port}`],
  30. {
  31. signal: options.signal,
  32. env: {
  33. ...process.env,
  34. OPENCODE_CONFIG_CONTENT: JSON.stringify(options.config ?? {}),
  35. },
  36. },
  37. )
  38. const url = await new Promise<string>((resolve, reject) => {
  39. const id = setTimeout(() => {
  40. reject(new Error(`Timeout waiting for server to start after ${options.timeout}ms`))
  41. }, options.timeout)
  42. let output = ""
  43. proc.stdout?.on("data", (chunk) => {
  44. output += chunk.toString()
  45. const lines = output.split("\n")
  46. for (const line of lines) {
  47. if (line.startsWith("opencode server listening")) {
  48. const match = line.match(/on\s+(https?:\/\/[^\s]+)/)
  49. if (!match) {
  50. throw new Error(`Failed to parse server url from output: ${line}`)
  51. }
  52. clearTimeout(id)
  53. resolve(match[1]!)
  54. return
  55. }
  56. }
  57. })
  58. proc.stderr?.on("data", (chunk) => {
  59. output += chunk.toString()
  60. })
  61. proc.on("exit", (code) => {
  62. clearTimeout(id)
  63. let msg = `Server exited with code ${code}`
  64. if (output.trim()) {
  65. msg += `\nServer output: ${output}`
  66. }
  67. reject(new Error(msg))
  68. })
  69. proc.on("error", (error) => {
  70. clearTimeout(id)
  71. reject(error)
  72. })
  73. if (options.signal) {
  74. options.signal.addEventListener("abort", () => {
  75. clearTimeout(id)
  76. reject(new Error("Aborted"))
  77. })
  78. }
  79. })
  80. return {
  81. url,
  82. close() {
  83. proc.kill()
  84. },
  85. }
  86. }
  87. export function createOpencodeTui(options?: TuiOptions) {
  88. const args = []
  89. if (options?.project) {
  90. args.push(`--project=${options.project}`)
  91. }
  92. if (options?.model) {
  93. args.push(`--model=${options.model}`)
  94. }
  95. if (options?.session) {
  96. args.push(`--session=${options.session}`)
  97. }
  98. if (options?.agent) {
  99. args.push(`--agent=${options.agent}`)
  100. }
  101. const proc = spawn(`opencode`, args, {
  102. signal: options?.signal,
  103. stdio: "inherit",
  104. env: {
  105. ...process.env,
  106. OPENCODE_CONFIG_CONTENT: JSON.stringify(options?.config ?? {}),
  107. },
  108. })
  109. return {
  110. close() {
  111. proc.kill()
  112. },
  113. }
  114. }