|
| 1 | +import type { Daytona, Sandbox } from "@daytonaio/sdk" |
| 2 | +import type { Plugin } from "@opencode-ai/plugin" |
| 3 | +import { join } from "node:path" |
| 4 | +import { fileURLToPath } from "node:url" |
| 5 | +import { tmpdir } from "node:os" |
| 6 | +import { access, copyFile, mkdir } from "node:fs/promises" |
| 7 | + |
| 8 | +let client: Promise<Daytona> | undefined |
| 9 | + |
| 10 | +let daytona = function daytona(): Promise<Daytona> { |
| 11 | + if (client == null) { |
| 12 | + client = import("@daytonaio/sdk").then( |
| 13 | + ({ Daytona }) => |
| 14 | + new Daytona({ |
| 15 | + apiKey: "dtn_d63c206564ef49d4104ec2cd755e561bb3665beed8fd7d7ab2c5f7a2186965f0", |
| 16 | + }), |
| 17 | + ) |
| 18 | + } |
| 19 | + return client |
| 20 | +} |
| 21 | + |
| 22 | + |
| 23 | + |
| 24 | +const preview = new Map<string, { url: string; token: string }>() |
| 25 | +const repo = "/home/daytona/workspace/repo" |
| 26 | +const root = "/home/daytona/workspace" |
| 27 | +const localbin = "/home/daytona/opencode" |
| 28 | +const installbin = "/home/daytona/.opencode/bin/opencode" |
| 29 | +const health = "http://127.0.0.1:3096/global/health" |
| 30 | + |
| 31 | +const local = fileURLToPath( |
| 32 | + new URL("./packages/opencode/dist/opencode-linux-x64-baseline/bin/opencode", import.meta.url), |
| 33 | +) |
| 34 | + |
| 35 | +async function exists(file: string) { |
| 36 | + return access(file) |
| 37 | + .then(() => true) |
| 38 | + .catch(() => false) |
| 39 | +} |
| 40 | + |
| 41 | +function sh(value: string) { |
| 42 | + return `'${value.replace(/'/g, `"'"'"`)}'` |
| 43 | +} |
| 44 | + |
| 45 | +// Internally Daytona uses axios, which tries to overwrite stack |
| 46 | +// traces when a failure happens. That path fails in Bun, however, so |
| 47 | +// when something goes wrong you only see a very obscure error. |
| 48 | +async function withSandbox<T>(name: string, fn: (sandbox: Sandbox) => Promise<T>) { |
| 49 | + const stack = Error.captureStackTrace |
| 50 | + // @ts-expect-error temporary compatibility hack for Daytona's axios stack handling in Bun |
| 51 | + Error.captureStackTrace = undefined |
| 52 | + try { |
| 53 | + return await fn(await (await daytona()).get(name)) |
| 54 | + } finally { |
| 55 | + Error.captureStackTrace = stack |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +export const DaytonaWorkspacePlugin: Plugin = async ({ experimental_workspace, worktree, project }) => { |
| 60 | + experimental_workspace.register("daytona", { |
| 61 | + name: "Daytona", |
| 62 | + description: "Create a remote Daytona workspace", |
| 63 | + configure(config) { |
| 64 | + return config |
| 65 | + }, |
| 66 | + async create(config, env) { |
| 67 | + const temp = join(tmpdir(), `opencode-daytona-${Date.now()}`) |
| 68 | + |
| 69 | + console.log("creating sandbox...") |
| 70 | + |
| 71 | + const sandbox = await ( |
| 72 | + await daytona() |
| 73 | + ).create({ |
| 74 | + name: config.name, |
| 75 | + snapshot: "daytona-large", |
| 76 | + envVars: env, |
| 77 | + }) |
| 78 | + |
| 79 | + console.log("creating ssh...") |
| 80 | + |
| 81 | + const ssh = await withSandbox(config.name, (sandbox) => sandbox.createSshAccess()) |
| 82 | + console.log("daytona:", ssh.sshCommand) |
| 83 | + |
| 84 | + const run = async (command: string) => { |
| 85 | + console.log("sandbox:", command) |
| 86 | + const result = await sandbox.process.executeCommand(command) |
| 87 | + if (result.result) process.stdout.write(result.result) |
| 88 | + if (result.exitCode === 0) return result |
| 89 | + throw new Error(result.result || `sandbox command failed: ${command}`) |
| 90 | + } |
| 91 | + |
| 92 | + const wait = async () => { |
| 93 | + for (let i = 0; i < 60; i++) { |
| 94 | + const result = await sandbox.process.executeCommand(`curl -fsS ${sh(health)}`) |
| 95 | + if (result.exitCode === 0) { |
| 96 | + if (result.result) process.stdout.write(result.result) |
| 97 | + return |
| 98 | + } |
| 99 | + console.log(`waiting for server (${i + 1}/60)`) |
| 100 | + await Bun.sleep(1000) |
| 101 | + } |
| 102 | + |
| 103 | + const log = await sandbox.process.executeCommand(`test -f /tmp/opencode.log && cat /tmp/opencode.log || true`) |
| 104 | + throw new Error(log.result || "daytona workspace server did not become ready in time") |
| 105 | + } |
| 106 | + |
| 107 | + const dir = join(temp, "repo") |
| 108 | + const tar = join(temp, "repo.tgz") |
| 109 | + const source = `file://${worktree}` |
| 110 | + await mkdir(temp, { recursive: true }) |
| 111 | + const args = ["clone", "--depth", "1", "--no-local"] |
| 112 | + if (config.branch) args.push("--branch", config.branch) |
| 113 | + args.push(source, dir) |
| 114 | + |
| 115 | + console.log("git cloning...") |
| 116 | + |
| 117 | + const clone = Bun.spawn(["git", ...args], { |
| 118 | + cwd: tmpdir(), |
| 119 | + stdout: "pipe", |
| 120 | + stderr: "pipe", |
| 121 | + }) |
| 122 | + const code = await clone.exited |
| 123 | + if (code !== 0) throw new Error(await new Response(clone.stderr).text()) |
| 124 | + |
| 125 | + const configPackage = join(worktree, ".opencode", "package.json") |
| 126 | + // if (await exists(configPackage)) { |
| 127 | + // console.log("copying config package...") |
| 128 | + // await mkdir(join(dir, ".opencode"), { recursive: true }) |
| 129 | + // await copyFile(configPackage, join(dir, ".opencode", "package.json")) |
| 130 | + // } |
| 131 | + |
| 132 | + console.log("tarring...") |
| 133 | + |
| 134 | + const packed = Bun.spawn(["tar", "-czf", tar, "-C", temp, "repo"], { |
| 135 | + stdout: "ignore", |
| 136 | + stderr: "pipe", |
| 137 | + }) |
| 138 | + if ((await packed.exited) !== 0) throw new Error(await new Response(packed.stderr).text()) |
| 139 | + |
| 140 | + console.log("uploading files...") |
| 141 | + |
| 142 | + await sandbox.fs.uploadFile(tar, "repo.tgz") |
| 143 | + |
| 144 | + const have = await exists(local) |
| 145 | + console.log("local", local) |
| 146 | + if (have) { |
| 147 | + console.log("uploading local binary...") |
| 148 | + await sandbox.fs.uploadFile(local, "opencode") |
| 149 | + } |
| 150 | + |
| 151 | + console.log("bootstrapping workspace...") |
| 152 | + await run(`rm -rf ${sh(repo)} && mkdir -p ${sh(root)} && tar -xzf \"$HOME/repo.tgz\" -C \"$HOME/workspace\"`) |
| 153 | + |
| 154 | + if (have) { |
| 155 | + await run(`chmod +x ${sh(localbin)}`) |
| 156 | + } else { |
| 157 | + await run( |
| 158 | + `mkdir -p \"$HOME/.opencode/bin\" && OPENCODE_INSTALL_DIR=\"$HOME/.opencode/bin\" curl -fsSL https://opencode.ai/install | bash`, |
| 159 | + ) |
| 160 | + } |
| 161 | + |
| 162 | + await run(`printf \"%s\\n\" ${sh(project.id)} > ${sh(`${repo}/.git/opencode`)}`) |
| 163 | + |
| 164 | + console.log("starting server...") |
| 165 | + await run( |
| 166 | + `cd ${sh(repo)} && exe=${sh(localbin)} && if [ ! -x \"$exe\" ]; then exe=${sh(installbin)}; fi && nohup env \"$exe\" serve --hostname 0.0.0.0 --port 3096 >/tmp/opencode.log 2>&1 </dev/null &`, |
| 167 | + ) |
| 168 | + |
| 169 | + console.log("waiting for server...") |
| 170 | + await wait() |
| 171 | + }, |
| 172 | + async remove(config) { |
| 173 | + const sandbox = await (await daytona()).get(config.name).catch(() => undefined) |
| 174 | + if (!sandbox) return |
| 175 | + await (await daytona()).delete(sandbox) |
| 176 | + preview.delete(config.name) |
| 177 | + }, |
| 178 | + async target(config) { |
| 179 | + let link = preview.get(config.name) |
| 180 | + if (!link) { |
| 181 | + link = await withSandbox(config.name, (sandbox) => sandbox.getPreviewLink(3096)) |
| 182 | + preview.set(config.name, link) |
| 183 | + } |
| 184 | + return { |
| 185 | + type: "remote", |
| 186 | + url: link.url, |
| 187 | + headers: { |
| 188 | + "x-daytona-preview-token": link.token, |
| 189 | + "x-daytona-skip-preview-warning": "true", |
| 190 | + "x-opencode-directory": repo, |
| 191 | + }, |
| 192 | + } |
| 193 | + }, |
| 194 | + }) |
| 195 | + |
| 196 | + return {} |
| 197 | +} |
| 198 | + |
| 199 | +export default DaytonaWorkspacePlugin |
0 commit comments