attach.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { Global } from "../../global"
  2. import { cmd } from "./cmd"
  3. import path from "path"
  4. import fs from "fs/promises"
  5. import { Log } from "../../util/log"
  6. import { $ } from "bun"
  7. export const AttachCommand = cmd({
  8. command: "attach <server>",
  9. describe: "attach to a running opencode server",
  10. builder: (yargs) =>
  11. yargs.positional("server", {
  12. type: "string",
  13. describe: "http://localhost:4096",
  14. }),
  15. handler: async (args) => {
  16. let cmd = [] as string[]
  17. const tui = Bun.embeddedFiles.find((item) => (item as File).name.includes("tui")) as File
  18. if (tui) {
  19. let binaryName = tui.name
  20. if (process.platform === "win32" && !binaryName.endsWith(".exe")) {
  21. binaryName += ".exe"
  22. }
  23. const binary = path.join(Global.Path.cache, "tui", binaryName)
  24. const file = Bun.file(binary)
  25. if (!(await file.exists())) {
  26. await Bun.write(file, tui, { mode: 0o755 })
  27. if (process.platform !== "win32") await fs.chmod(binary, 0o755)
  28. }
  29. cmd = [binary]
  30. }
  31. if (!tui) {
  32. const dir = Bun.fileURLToPath(new URL("../../../../tui/cmd/opencode", import.meta.url))
  33. let binaryName = `./dist/tui${process.platform === "win32" ? ".exe" : ""}`
  34. await $`go build -o ${binaryName} ./main.go`.cwd(dir)
  35. cmd = [path.join(dir, binaryName)]
  36. }
  37. Log.Default.info("tui", {
  38. cmd,
  39. })
  40. const proc = Bun.spawn({
  41. cmd,
  42. stdout: "inherit",
  43. stderr: "inherit",
  44. stdin: "inherit",
  45. env: {
  46. ...process.env,
  47. CGO_ENABLED: "0",
  48. OPENCODE_SERVER: args.server,
  49. },
  50. })
  51. await proc.exited
  52. },
  53. })