attach.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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
  12. .positional("server", {
  13. type: "string",
  14. describe: "http://localhost:4096",
  15. })
  16. .option("session", {
  17. alias: ["s"],
  18. describe: "session id to continue",
  19. type: "string",
  20. }),
  21. handler: async (args) => {
  22. let cmd = [] as string[]
  23. const tui = Bun.embeddedFiles.find((item) => (item as File).name.includes("tui")) as File
  24. if (tui) {
  25. let binaryName = tui.name
  26. if (process.platform === "win32" && !binaryName.endsWith(".exe")) {
  27. binaryName += ".exe"
  28. }
  29. const binary = path.join(Global.Path.cache, "tui", binaryName)
  30. const file = Bun.file(binary)
  31. if (!(await file.exists())) {
  32. await Bun.write(file, tui, { mode: 0o755 })
  33. if (process.platform !== "win32") await fs.chmod(binary, 0o755)
  34. }
  35. cmd = [binary]
  36. }
  37. if (!tui) {
  38. const dir = Bun.fileURLToPath(new URL("../../../../tui/cmd/opencode", import.meta.url))
  39. let binaryName = `./dist/tui${process.platform === "win32" ? ".exe" : ""}`
  40. await $`go build -o ${binaryName} ./main.go`.cwd(dir)
  41. cmd = [path.join(dir, binaryName)]
  42. }
  43. if (args.session) {
  44. cmd.push("--session", args.session)
  45. }
  46. Log.Default.info("tui", {
  47. cmd,
  48. })
  49. const proc = Bun.spawn({
  50. cmd,
  51. stdout: "inherit",
  52. stderr: "inherit",
  53. stdin: "inherit",
  54. env: {
  55. ...process.env,
  56. CGO_ENABLED: "0",
  57. OPENCODE_SERVER: args.server,
  58. },
  59. })
  60. await proc.exited
  61. },
  62. })