index.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. import { BusEvent } from "@/bus/bus-event"
  2. import path from "path"
  3. import { $ } from "bun"
  4. import z from "zod"
  5. import { NamedError } from "@opencode-ai/util/error"
  6. import { Log } from "../util/log"
  7. import { iife } from "@/util/iife"
  8. import { Flag } from "../flag/flag"
  9. declare global {
  10. const OPENCODE_VERSION: string
  11. const OPENCODE_CHANNEL: string
  12. }
  13. export namespace Installation {
  14. const log = Log.create({ service: "installation" })
  15. export type Method = Awaited<ReturnType<typeof method>>
  16. export const Event = {
  17. Updated: BusEvent.define(
  18. "installation.updated",
  19. z.object({
  20. version: z.string(),
  21. }),
  22. ),
  23. UpdateAvailable: BusEvent.define(
  24. "installation.update-available",
  25. z.object({
  26. version: z.string(),
  27. }),
  28. ),
  29. }
  30. export const Info = z
  31. .object({
  32. version: z.string(),
  33. latest: z.string(),
  34. })
  35. .meta({
  36. ref: "InstallationInfo",
  37. })
  38. export type Info = z.infer<typeof Info>
  39. export async function info() {
  40. return {
  41. version: VERSION,
  42. latest: await latest(),
  43. }
  44. }
  45. export function isPreview() {
  46. return CHANNEL !== "latest"
  47. }
  48. export function isLocal() {
  49. return CHANNEL === "local"
  50. }
  51. export async function method() {
  52. if (process.execPath.includes(path.join(".opencode", "bin"))) return "curl"
  53. if (process.execPath.includes(path.join(".local", "bin"))) return "curl"
  54. const exec = process.execPath.toLowerCase()
  55. const checks = [
  56. {
  57. name: "npm" as const,
  58. command: () => $`npm list -g --depth=0`.throws(false).quiet().text(),
  59. },
  60. {
  61. name: "yarn" as const,
  62. command: () => $`yarn global list`.throws(false).quiet().text(),
  63. },
  64. {
  65. name: "pnpm" as const,
  66. command: () => $`pnpm list -g --depth=0`.throws(false).quiet().text(),
  67. },
  68. {
  69. name: "bun" as const,
  70. command: () => $`bun pm ls -g`.throws(false).quiet().text(),
  71. },
  72. {
  73. name: "brew" as const,
  74. command: () => $`brew list --formula opencode`.throws(false).quiet().text(),
  75. },
  76. ]
  77. checks.sort((a, b) => {
  78. const aMatches = exec.includes(a.name)
  79. const bMatches = exec.includes(b.name)
  80. if (aMatches && !bMatches) return -1
  81. if (!aMatches && bMatches) return 1
  82. return 0
  83. })
  84. for (const check of checks) {
  85. const output = await check.command()
  86. if (output.includes(check.name === "brew" ? "opencode" : "opencode-ai")) {
  87. return check.name
  88. }
  89. }
  90. return "unknown"
  91. }
  92. export const UpgradeFailedError = NamedError.create(
  93. "UpgradeFailedError",
  94. z.object({
  95. stderr: z.string(),
  96. }),
  97. )
  98. async function getBrewFormula() {
  99. const tapFormula = await $`brew list --formula anomalyco/tap/opencode`.throws(false).quiet().text()
  100. if (tapFormula.includes("opencode")) return "anomalyco/tap/opencode"
  101. const coreFormula = await $`brew list --formula opencode`.throws(false).quiet().text()
  102. if (coreFormula.includes("opencode")) return "opencode"
  103. return "opencode"
  104. }
  105. export async function upgrade(method: Method, target: string) {
  106. let cmd
  107. switch (method) {
  108. case "curl":
  109. cmd = $`curl -fsSL https://opencode.ai/install | bash`.env({
  110. ...process.env,
  111. VERSION: target,
  112. })
  113. break
  114. case "npm":
  115. cmd = $`npm install -g opencode-ai@${target}`
  116. break
  117. case "pnpm":
  118. cmd = $`pnpm install -g opencode-ai@${target}`
  119. break
  120. case "bun":
  121. cmd = $`bun install -g opencode-ai@${target}`
  122. break
  123. case "brew": {
  124. const formula = await getBrewFormula()
  125. cmd = $`brew install ${formula}`.env({
  126. HOMEBREW_NO_AUTO_UPDATE: "1",
  127. ...process.env,
  128. })
  129. break
  130. }
  131. default:
  132. throw new Error(`Unknown method: ${method}`)
  133. }
  134. const result = await cmd.quiet().throws(false)
  135. log.info("upgraded", {
  136. method,
  137. target,
  138. stdout: result.stdout.toString(),
  139. stderr: result.stderr.toString(),
  140. })
  141. if (result.exitCode !== 0)
  142. throw new UpgradeFailedError({
  143. stderr: result.stderr.toString("utf8"),
  144. })
  145. await $`${process.execPath} --version`.nothrow().quiet().text()
  146. }
  147. export const VERSION = typeof OPENCODE_VERSION === "string" ? OPENCODE_VERSION : "local"
  148. export const CHANNEL = typeof OPENCODE_CHANNEL === "string" ? OPENCODE_CHANNEL : "local"
  149. export const USER_AGENT = `opencode/${CHANNEL}/${VERSION}/${Flag.OPENCODE_CLIENT}`
  150. export async function latest(installMethod?: Method) {
  151. const detectedMethod = installMethod || (await method())
  152. if (detectedMethod === "brew") {
  153. const formula = await getBrewFormula()
  154. if (formula === "opencode") {
  155. return fetch("https://formulae.brew.sh/api/formula/opencode.json")
  156. .then((res) => {
  157. if (!res.ok) throw new Error(res.statusText)
  158. return res.json()
  159. })
  160. .then((data: any) => data.versions.stable)
  161. }
  162. }
  163. if (detectedMethod === "npm" || detectedMethod === "bun" || detectedMethod === "pnpm") {
  164. const registry = await iife(async () => {
  165. const r = (await $`npm config get registry`.quiet().nothrow().text()).trim()
  166. const reg = r || "https://registry.npmjs.org"
  167. return reg.endsWith("/") ? reg.slice(0, -1) : reg
  168. })
  169. const channel = CHANNEL
  170. return fetch(`${registry}/opencode-ai/${channel}`)
  171. .then((res) => {
  172. if (!res.ok) throw new Error(res.statusText)
  173. return res.json()
  174. })
  175. .then((data: any) => data.version)
  176. }
  177. return fetch("https://api.github.com/repos/anomalyco/opencode/releases/latest")
  178. .then((res) => {
  179. if (!res.ok) throw new Error(res.statusText)
  180. return res.json()
  181. })
  182. .then((data: any) => data.tag_name.replace(/^v/, ""))
  183. }
  184. }