daemon.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. import { Global } from "@opencode-ai/core/global"
  2. import { InstallationVersion } from "@opencode-ai/core/installation/version"
  3. import { createOpencodeClient } from "@opencode-ai/sdk/v2/client"
  4. import { ServerAuth } from "@opencode-ai/server/auth"
  5. import { Context, Effect, FileSystem, Layer, Option, Schedule, Schema, Scope } from "effect"
  6. import { HttpServer } from "effect/unstable/http"
  7. import { randomBytes, randomUUID } from "crypto"
  8. import path from "path"
  9. export interface Interface {
  10. readonly client: () => Effect.Effect<ReturnType<typeof createOpencodeClient>, unknown>
  11. readonly start: () => Effect.Effect<string, Error>
  12. readonly status: () => Effect.Effect<string | undefined>
  13. readonly stop: () => Effect.Effect<void, unknown>
  14. readonly password: (value?: string) => Effect.Effect<string, unknown>
  15. readonly register: (address: HttpServer.Address) => Effect.Effect<void, unknown, Scope.Scope>
  16. }
  17. export class Service extends Context.Service<Service, Interface>()("@opencode/cli/Daemon") {}
  18. const Registration = Schema.Struct({
  19. id: Schema.optional(Schema.String),
  20. version: Schema.optional(Schema.String),
  21. url: Schema.String,
  22. pid: Schema.Int.check(Schema.isGreaterThan(0)),
  23. })
  24. type Registration = typeof Registration.Type
  25. function sameRegistration(left: Registration, right: Registration) {
  26. return left.id === right.id && left.version === right.version && left.url === right.url && left.pid === right.pid
  27. }
  28. export const layer = Layer.effect(
  29. Service,
  30. Effect.gen(function* () {
  31. const fs = yield* FileSystem.FileSystem
  32. const directory = Global.Path.state
  33. const file = path.join(directory, "server.json")
  34. const passwordFile = path.join(directory, "password")
  35. const decodeRegistration = Schema.decodeUnknownEffect(Schema.fromJsonString(Registration))
  36. const password = Effect.fn("cli.daemon.password")(function* (value?: string) {
  37. const existing = yield* fs.readFileString(passwordFile).pipe(Effect.catch(() => Effect.succeed(undefined)))
  38. if (value === undefined && existing) return existing
  39. // Keep one private credential across server restarts so discovered clients
  40. // can reconnect without exposing a password flag or environment variable.
  41. const generated = value ?? randomBytes(32).toString("base64url")
  42. const temp = passwordFile + ".tmp"
  43. yield* fs.makeDirectory(directory, { recursive: true })
  44. yield* fs.writeFileString(temp, generated, { mode: 0o600 })
  45. yield* fs.rename(temp, passwordFile)
  46. return generated
  47. })
  48. const registration = Effect.fnUntraced(function* () {
  49. return yield* fs.readFileString(file).pipe(Effect.flatMap(decodeRegistration))
  50. })
  51. const createClient = Effect.fnUntraced(function* (url: string) {
  52. return createOpencodeClient({ baseUrl: url, headers: ServerAuth.headers({ password: yield* password() }) })
  53. })
  54. const healthy = Effect.fnUntraced(function* () {
  55. const info = yield* registration()
  56. const client = yield* createClient(info.url)
  57. const response = yield* Effect.tryPromise(() => client.v2.health.get({ signal: AbortSignal.timeout(2_000) }))
  58. if (response.data?.healthy === true) return info
  59. return yield* Effect.fail(new Error("Registered server is not healthy"))
  60. })
  61. const compatible = Effect.fnUntraced(function* () {
  62. const info = yield* healthy()
  63. if (info.version === InstallationVersion) return info
  64. return yield* Effect.fail(new Error("Registered server version does not match the client"))
  65. })
  66. const signal = (pid: number, signal: NodeJS.Signals) =>
  67. Effect.try({ try: () => process.kill(pid, signal), catch: (cause) => cause }).pipe(Effect.ignore)
  68. const awaitStopped = Effect.fnUntraced(function* (pid: number) {
  69. const running = yield* Effect.try({ try: () => process.kill(pid, 0), catch: () => false }).pipe(
  70. Effect.orElseSucceed(() => false),
  71. )
  72. if (!running) return true
  73. return yield* Effect.fail(new Error(`Server process ${pid} is still running`))
  74. })
  75. const stopProcess = Effect.fnUntraced(function* (info: Registration) {
  76. const current = yield* healthy().pipe(Effect.option)
  77. if (Option.isNone(current) || !sameRegistration(current.value, info)) return
  78. yield* signal(info.pid, "SIGTERM")
  79. const stopped = yield* awaitStopped(info.pid).pipe(
  80. Effect.retry(Schedule.spaced("50 millis").pipe(Schedule.both(Schedule.recurs(100)))),
  81. Effect.option,
  82. )
  83. if (Option.isSome(stopped)) return
  84. const latest = yield* healthy().pipe(Effect.option)
  85. if (Option.isNone(latest) || !sameRegistration(latest.value, info)) return
  86. yield* signal(info.pid, "SIGKILL")
  87. yield* awaitStopped(info.pid).pipe(
  88. Effect.retry(Schedule.spaced("50 millis").pipe(Schedule.both(Schedule.recurs(100)))),
  89. )
  90. })
  91. const start = Effect.fn("cli.daemon.start")(function* () {
  92. const existing = yield* healthy().pipe(Effect.option)
  93. const found = Option.getOrUndefined(existing)
  94. if (found?.version === InstallationVersion) return found.url
  95. if (found) yield* stopProcess(found).pipe(Effect.ignore)
  96. yield* Effect.sync(() => {
  97. const compiled = path.basename(process.execPath).replace(/\.exe$/, "") !== "bun"
  98. Bun.spawn([process.execPath, ...(compiled ? [] : [Bun.main]), "serve", "--register"], {
  99. stdin: "ignore",
  100. stdout: "ignore",
  101. stderr: "ignore",
  102. }).unref()
  103. })
  104. return yield* compatible().pipe(
  105. Effect.retry(Schedule.spaced("50 millis").pipe(Schedule.both(Schedule.recurs(100)))),
  106. Effect.map((info) => info.url),
  107. Effect.mapError(() => new Error("Failed to start server")),
  108. )
  109. })
  110. const client = Effect.fn("cli.daemon.client")(function* () {
  111. return yield* createClient(yield* start())
  112. })
  113. const status = Effect.fn("cli.daemon.status")(function* () {
  114. const existing = yield* healthy().pipe(Effect.option)
  115. const found = Option.getOrUndefined(existing)
  116. if (found?.version === InstallationVersion) return found.url
  117. if (found) return undefined
  118. yield* fs.remove(file).pipe(Effect.ignore)
  119. return undefined
  120. })
  121. const stop = Effect.fn("cli.daemon.stop")(function* () {
  122. const existing = yield* healthy().pipe(Effect.option)
  123. // A stale registration may point at a PID that has since been reused by
  124. // another process. Only signal the PID after authenticating the server.
  125. if (Option.isNone(existing)) return yield* fs.remove(file).pipe(Effect.ignore)
  126. yield* stopProcess(existing.value)
  127. yield* fs.remove(file).pipe(Effect.ignore)
  128. })
  129. const register = Effect.fn("cli.daemon.register")(function* (address: HttpServer.Address) {
  130. const id = randomUUID()
  131. const temp = file + "." + id + ".tmp"
  132. yield* fs.makeDirectory(directory, { recursive: true })
  133. yield* fs.writeFileString(
  134. temp,
  135. JSON.stringify({ id, version: InstallationVersion, url: HttpServer.formatAddress(address), pid: process.pid }),
  136. { mode: 0o600 },
  137. )
  138. yield* fs.rename(temp, file)
  139. yield* registration()
  140. .pipe(
  141. Effect.flatMap((info) => (info.id === id ? Effect.void : signal(process.pid, "SIGTERM"))),
  142. Effect.catch(() => signal(process.pid, "SIGTERM")),
  143. Effect.repeat(Schedule.spaced("10 seconds")),
  144. Effect.forkScoped,
  145. )
  146. yield* Effect.addFinalizer(() =>
  147. registration().pipe(
  148. Effect.flatMap((info) => (info.id === id ? fs.remove(file) : Effect.void)),
  149. Effect.ignore,
  150. ),
  151. )
  152. })
  153. return Service.of({ client, start, status, stop, password, register })
  154. }),
  155. )
  156. export const defaultLayer = layer
  157. export * as Daemon from "./daemon"