diff --git a/README.md b/README.md index 628d946..4ba2283 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ E2B sandboxes for OpenCode. One package supports both OpenCode releases: - **OpenCode 1** (`opencode-ai`): the plugin registers an `e2b` type for OpenCode's experimental workspace API. A workspace runs OpenCode itself in an E2B sandbox. The sections from [Install](#install) on describe this mode. -- **OpenCode 2** (`@opencode/cli`): OpenCode 2 has no workspace API for plugins. The plugin runs every shell command of your local OpenCode in an E2B sandbox instead, and keeps your files on your machine. See [OpenCode 2](#opencode-2). +- **OpenCode 2** (`@opencode/cli`): OpenCode 2 has no workspace API for plugins. The plugin runs every shell command of your local OpenCode in an E2B sandbox instead, and keeps your files on your machine. For long tasks, a box runs OpenCode itself in a sandbox. See [OpenCode 2](#opencode-2). The package's default export carries both entry points: OpenCode 1 calls `server`, OpenCode 2 calls `setup`, and each loads only its own code. @@ -39,6 +39,18 @@ E2B_API_KEY=... OPENCODE_EXPERIMENTAL_WORKSPACES=true opencode ## OpenCode 2 +Two ways to use E2B with OpenCode 2: + +- **Shell mode** (the plugin): OpenCode stays on your machine, and its shell commands run in a sandbox. +- **Boxes** (`opencode-e2b box`): OpenCode itself runs in a sandbox, for a task that runs on without your machine. You attach to it with your TUI and pull the work home as a branch. + +### Shell mode + + + + Shell mode: OpenCode on your machine sends each shell command to the project sandbox, with your changes first, and gets the output and changed files back + + OpenCode runs on your machine. Every shell command that it runs (the agent's and your `!` commands) runs in an E2B sandbox, at the same path as on your machine. Reading and editing files stays local, so diffs, undo and the file picker work as usual. ```jsonc @@ -66,6 +78,7 @@ Git: a plain git command (`git add .`, `git commit -m "..."`, `git checkout -b x | `domain` | `E2B_DOMAIN` or `e2b.app` | E2B region: `e2b.app` (US), `e2b-juliett.dev` (EU), `e2b-tango.dev` (APAC). The API key must belong to that region. | | `template` | `opencode` | Template for new sandboxes | | `idleMinutes` | `15` | Idle time before the sandbox pauses | +| `boxHours` | `1` | How long a box from `/e2b-box up` runs before it pauses. The E2B plan caps this. | | `env` | `[]` | Names of environment variables to pass to commands. Nothing else from your environment goes to the sandbox. | | `git` | `"auto"` | Send `.git` to the sandbox: `"auto"` up to 200 MB, `true` always, `false` never | | `network` | none | `{ "allowOut": [...], "denyOut": [...] }` | @@ -77,6 +90,38 @@ Commands: `/e2b-status`, `/e2b-pull ` (copy sandbox-only files such as `di Limits: the project must be a git repository; submodule contents and a linked worktree's history are not synced; gitignored build output stays in the sandbox (use `e2b_read` or `/e2b-pull`). +### Boxes + + + + Box mode: box up sends the project with its git history to a box running the OpenCode server; your TUI attaches to it; the box reaches the model API with a key that E2B adds; box pull brings the work home as branch e2b/name + + +A box is a sandbox with your project and an OpenCode 2 server in it. The agent keeps working when your laptop sleeps. Each box is one task. + +```bash +opencode-e2b secrets set anthropic # once: stores ANTHROPIC_API_KEY (or stdin) as an E2B secret +opencode-e2b box up --attach # start a box named after the branch, open the TUI on it +opencode-e2b box pull # the box's work, uncommitted files too, as branch e2b/ +opencode-e2b box kill +``` + +| Command | What it does | +| --- | --- | +| `box up [name]` | Uploads the project (tracked and uncommitted files, and `.git`) to the same path in a new sandbox, and starts `opencode2 serve` there. Options: `--template`, `--hours` (default 1), `--attach`. | +| `box attach [name]` | Wakes the box if it is paused, then runs your local `opencode2 --server `. | +| `box pull [name]` | Commits the box's work in progress on a scratch ref (the agent's branch and index stay as they are) and fetches it as a git bundle into `e2b/`. No credentials go to the box. | +| `box list`, `box stop`, `box kill` | List the boxes this machine started, pause one, delete one. | +| `secrets set\|list\|remove ` | Model keys for boxes: `anthropic`, `openai`, `openrouter`. | + +The name defaults to the current branch, or to the project's only box. In OpenCode, `/e2b-box up|pull|list|stop|kill` and `/e2b-secrets` do the same. `/e2b-secrets set` takes the key from OpenCode's environment, never from the prompt. + +Model keys: a box gets a placeholder, and E2B's egress proxy puts the stored secret into requests to the provider's API. No process in the box holds the key. The box offers only the providers with a stored key, and commits with your git `user.name` and `user.email`. + +Each box has a random server password. It is stored with the box record in `~/.local/state/opencode-e2b/boxes/` (readable only by you), and never sent to E2B as metadata. + +A box pauses after `--hours`; attach wakes it. E2B plans cap the run time (1 hour on the lower plans). + ## Development ```bash @@ -86,7 +131,7 @@ bun run format:check # oxfmt bun run test ``` -`bun run check` runs all four. Lint rules are errors in `src/v2` and `src/index.ts`, and warnings in older code until each rule is cleaned up there. The anti-slop rules are vendored in `tools/oxlint/anti-slop` (see its `VENDOR.md`). +`bun run check` runs all four. The diagrams are built from `assets/diagrams/*.html` with `assets/diagrams/build.sh`. Lint rules are errors in `src/v2` and `src/index.ts`, and warnings in older code until each rule is cleaned up there. The anti-slop rules are vendored in `tools/oxlint/anti-slop` (see its `VENDOR.md`). The plugin is loaded by OpenCode's Bun runtime and uses Bun as its development runtime. `bun run test` builds `dist/` first, then runs the Bun test runner against `test/*.test.ts`. @@ -96,7 +141,7 @@ Layout: | -------------- | ----------------------------------------------------------------------------------------- | ------------------------------- | | `src/core/` | Shared E2B code: SDK setup and attribution, sandboxes, templates, cleanup, upload, config | No OpenCode packages | | `src/v1/` | OpenCode 1: workspace adapter, bootstrap, compatibility checks | `@opencode-ai/plugin` | -| `src/v2/` | OpenCode 2: shell hook, sync, sandbox per project, tools and commands | `@opencode/plugin` (types only) | +| `src/v2/` | OpenCode 2: shell hook, sync, sandbox per project, tools and commands; boxes and the CLI | `@opencode/plugin` (types only) | | `src/index.ts` | The default export with both entry points, each loaded on first use | type imports only | ## Runtime Behavior diff --git a/assets/box-dark.png b/assets/box-dark.png new file mode 100644 index 0000000..96502a9 Binary files /dev/null and b/assets/box-dark.png differ diff --git a/assets/box.png b/assets/box.png new file mode 100644 index 0000000..7ecd69b Binary files /dev/null and b/assets/box.png differ diff --git a/assets/diagrams/box-dark.html b/assets/diagrams/box-dark.html new file mode 100644 index 0000000..d760b1f --- /dev/null +++ b/assets/diagrams/box-dark.html @@ -0,0 +1,381 @@ + + + + + Box mode + + + + + + Box mode + + opencode-e2b box up uploads the project with its git history to an E2B box running OpenCode. Your TUI + attaches to it. The model key is an E2B secret, added to model API requests by the E2B egress proxy. + box pull brings the work home as branch e2b/name. + + + + + + + + + + + + + + + + + E2B CLOUD + + + + + + + + + + + + box up + + + + PROJECT + .GIT + + + + box attach (your TUI) + + + + box pull -> branch e2b/<name> + + + + E2B SECRET + + + + VIA PROXY + + + + + + + LOCAL + + + Your branch + + + tracked + uncommitted + + + OpenCode TUI + + + + + + + BOX + + + OpenCode server + + + same path as yours + + + one per task + + + + + + + MODEL + + + Model API + + + Anthropic, OpenAI + + + box holds no key + + + + diff --git a/assets/diagrams/box.html b/assets/diagrams/box.html new file mode 100644 index 0000000..8e6dbba --- /dev/null +++ b/assets/diagrams/box.html @@ -0,0 +1,381 @@ + + + + + Box mode + + + + + + Box mode + + opencode-e2b box up uploads the project with its git history to an E2B box running OpenCode. Your TUI + attaches to it. The model key is an E2B secret, added to model API requests by the E2B egress proxy. + box pull brings the work home as branch e2b/name. + + + + + + + + + + + + + + + + + E2B CLOUD + + + + + + + + + + + + box up + + + + PROJECT + .GIT + + + + box attach (your TUI) + + + + box pull -> branch e2b/<name> + + + + E2B SECRET + + + + VIA PROXY + + + + + + + LOCAL + + + Your branch + + + tracked + uncommitted + + + OpenCode TUI + + + + + + + BOX + + + OpenCode server + + + same path as yours + + + one per task + + + + + + + MODEL + + + Model API + + + Anthropic, OpenAI + + + box holds no key + + + + diff --git a/assets/diagrams/build.sh b/assets/diagrams/build.sh new file mode 100755 index 0000000..bafd7ba --- /dev/null +++ b/assets/diagrams/build.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +# Rebuild the README diagrams. The two light HTML files are the SOURCE; the dark +# variants and all four PNGs are generated — edit `shell.html` / `box.html` +# and re-run this, never the outputs. +# +# assets/diagrams/shell.html ──▶ assets/shell.png + assets/shell-dark.png +# assets/diagrams/box.html ──▶ assets/box.png + assets/box-dark.png +# +# The dark variant is a token swap, not a second drawing: the light/dark pairs +# below are diagram-design's own skin tokens, so a colour that isn't in this +# table is a colour the light file should not have used either. +# +# Needs Google Chrome (headless). Run from anywhere. +set -euo pipefail + +DIR="$(CDPATH= cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +OUT="$(dirname "$DIR")" +CHROME="${CHROME:-/Applications/Google Chrome.app/Contents/MacOS/Google Chrome}" +[ -x "$CHROME" ] || { echo "no Chrome at $CHROME — set CHROME=..." >&2; exit 1; } + +# slug:viewport-height — the height is the HTML's own svg height, so a diagram +# that grows needs its number changed here too. +DIAGRAMS=(shell:296 box:328) + +for d in "${DIAGRAMS[@]}"; do + slug="${d%%:*}"; height="${d##*:}" + + python3 - "$DIR/$slug.html" "$DIR/$slug-dark.html" "$slug" <<'PY' +import sys +src, dst, slug = sys.argv[1], sys.argv[2], sys.argv[3] +PAIRS = [ + ("#f5f5f5", "#0c1117"), # paper — GitHub's dark canvas + ("#2d3142", "#f5f5f5"), # ink + ("#ffffff", "#151b23"), # paper-2 — one step up from canvas + ("#4f5d75", "#bfc0c0"), # muted + ("#7a8399", "#8e98ac"), # soft + ("#eb6c36", "#f08a59"), # accent + ("rgba(235,108,54,0.08)", "rgba(240,138,89,0.10)"), + ("rgba(235,108,54,0.40)", "rgba(240,138,89,0.50)"), + ("rgba(45,49,66,0.02)", "rgba(245,245,245,0.03)"), + ("rgba(45,49,66,0.05)", "rgba(245,245,245,0.05)"), + ("rgba(45,49,66,0.10)", "rgba(245,245,245,0.10)"), + ("rgba(45,49,66,0.40)", "rgba(245,245,245,0.40)"), + ("rgba(45,49,66,0.80)", "rgba(245,245,245,0.80)"), + ("rgba(79,93,117,0.10)", "rgba(191,192,192,0.10)"), + ("rgba(122,131,153,0.40)", "rgba(142,152,172,0.40)"), +] +s = open(src).read() +# Two passes through placeholders: ink→paper and paper→ink would otherwise +# chase each other and land every colour on the same value. +for i, (light, _) in enumerate(PAIRS): + s = s.replace(light, f"@@{i}@@") +for i, (_, dark) in enumerate(PAIRS): + s = s.replace(f"@@{i}@@", dark) +# Per-variant accessible IDs: two SVGs inlined in one page must never share them. +s = s.replace(f"{slug}-title", f"{slug}-dark-title").replace(f"{slug}-desc", f"{slug}-dark-desc") +open(dst, "w").write(s) +PY + + for variant in "$slug" "$slug-dark"; do + "$CHROME" --headless --disable-gpu --hide-scrollbars \ + --force-device-scale-factor=2 --window-size="1000,$height" \ + --screenshot="$OUT/$variant.png" "file://$DIR/$variant.html" 2>/dev/null + echo " wrote assets/$variant.png" + done +done diff --git a/assets/diagrams/shell-dark.html b/assets/diagrams/shell-dark.html new file mode 100644 index 0000000..642a66e --- /dev/null +++ b/assets/diagrams/shell-dark.html @@ -0,0 +1,331 @@ + + + + + Shell mode + + + + + + Shell mode + + OpenCode runs on your machine and edits your files there. Each shell command runs in one E2B sandbox + per project: changed files are sent before the command, and files the command changed come back after + it. + + + + + + + + + + + + + + + + E2B CLOUD + + + + + + + + every shell command + + + + YOUR CHANGES FIRST + + + + output + changed files + + + + + + + LOCAL + + + OpenCode + + + edits your files here + + + model key stays here + + + + + + + SANDBOX + + + Project sandbox + + + same files, git-synced + + + paused when idle + + + + + + + RUNS + + + Commands + + + tests, builds, servers + + + preview URLs + + + + diff --git a/assets/diagrams/shell.html b/assets/diagrams/shell.html new file mode 100644 index 0000000..99aa7e7 --- /dev/null +++ b/assets/diagrams/shell.html @@ -0,0 +1,331 @@ + + + + + Shell mode + + + + + + Shell mode + + OpenCode runs on your machine and edits your files there. Each shell command runs in one E2B sandbox + per project: changed files are sent before the command, and files the command changed come back after + it. + + + + + + + + + + + + + + + + E2B CLOUD + + + + + + + + every shell command + + + + YOUR CHANGES FIRST + + + + output + changed files + + + + + + + LOCAL + + + OpenCode + + + edits your files here + + + model key stays here + + + + + + + SANDBOX + + + Project sandbox + + + same files, git-synced + + + paused when idle + + + + + + + RUNS + + + Commands + + + tests, builds, servers + + + preview URLs + + + + diff --git a/assets/shell-dark.png b/assets/shell-dark.png new file mode 100644 index 0000000..a2298cc Binary files /dev/null and b/assets/shell-dark.png differ diff --git a/assets/shell.png b/assets/shell.png new file mode 100644 index 0000000..0796fb2 Binary files /dev/null and b/assets/shell.png differ diff --git a/package.json b/package.json index ff20aa2..4906b9b 100644 --- a/package.json +++ b/package.json @@ -3,6 +3,9 @@ "version": "0.2.0", "private": true, "description": "E2B sandboxes for OpenCode: workspaces for OpenCode 1, sandboxed shell commands for OpenCode 2", + "bin": { + "opencode-e2b": "dist/v2/cli/main.js" + }, "files": [ "dist", "bin", diff --git a/src/v2/box/attach.ts b/src/v2/box/attach.ts new file mode 100644 index 0000000..c8a0d16 --- /dev/null +++ b/src/v2/box/attach.ts @@ -0,0 +1,43 @@ +/** Open this machine's OpenCode TUI on a box. */ + +import { spawn } from "node:child_process" +import { Sandbox } from "e2b" +import type { E2BAccess } from "../sandbox/create.js" +import { run } from "../sync/files.js" +import type { BoxRecord } from "./registry.js" +import { waitHealthy } from "./server.js" + +/** + * Wake the box first: traffic alone wakes a paused box, but the request that woke it + * hangs. Then run the local TUI against the box's server. Resolves with its exit code. + */ +export async function attachBox(record: BoxRecord, access: E2BAccess): Promise { + await Sandbox.connect(record.sandboxId, access) + await waitHealthy(record.url) + const opencode = await localOpencode2() + return new Promise((resolve, reject) => { + const child = spawn(opencode, ["--server", record.url], { + cwd: record.root, + stdio: "inherit", + env: { ...process.env, OPENCODE_SERVER_PASSWORD: record.password }, + }) + child.on("error", reject) + child.on("exit", (code) => { + resolve(code ?? 0) + }) + }) +} + +/** `opencode2` if installed, else `opencode` when it is OpenCode 2. */ +async function localOpencode2(): Promise { + for (const bin of ["opencode2", "opencode"]) { + const version = await run(bin, ["--version"], { cwd: process.cwd() }).then( + (out) => out.toString(), + () => "", + ) + if (/\bv?2\.\d+/.test(version)) { + return bin + } + } + throw new Error("OpenCode 2 is not installed here. Install it with: npm install -g @opencode/cli") +} diff --git a/src/v2/box/manage.ts b/src/v2/box/manage.ts new file mode 100644 index 0000000..1b070e7 --- /dev/null +++ b/src/v2/box/manage.ts @@ -0,0 +1,82 @@ +/** Box actions shared by the CLI and the OpenCode slash commands. */ + +import { Sandbox } from "e2b" +import type { E2BAccess } from "../sandbox/create.js" +import { run } from "../sync/files.js" +import { + type BoxRecord, + type BoxState, + boxName, + boxState, + listBoxes, + readBox, + removeBox, +} from "./registry.js" + +/** `given`, or the current branch of `root`, as a box name. */ +export async function defaultBoxName(root: string, given: string | undefined): Promise { + if (given) { + return boxName(given) + } + const branch = await run("git", ["branch", "--show-current"], { cwd: root }).then( + (out) => out.toString().trim(), + () => "", + ) + return boxName(branch || "main") +} + +/** + * The box to act on: the one named `given`, else the one named after the current branch, + * else the only box of this project. Fails with a clear message otherwise. + */ +export async function findBox(root: string | undefined, given: string | undefined): Promise { + if (given !== undefined || root === undefined) { + const name = boxName(given ?? "") + const record = await readBox(name) + if (!record) { + throw new Error(`no box named "${name}" on this machine. See the list with: opencode-e2b box list`) + } + return record + } + const byBranch = await readBox(await defaultBoxName(root, undefined)) + if (byBranch) { + return byBranch + } + const mine = (await listBoxes()).filter((record) => record.root === root) + if (mine.length === 1) { + return mine[0] + } + throw new Error( + mine.length === 0 + ? "this project has no box. Start one with: opencode-e2b box up" + : `this project has several boxes, so name one: ${mine.map((record) => record.name).join(", ")}`, + ) +} + +export async function listWithState(access: E2BAccess): Promise<{ record: BoxRecord; state: BoxState }[]> { + const records = await listBoxes() + return Promise.all(records.map(async (record) => ({ record, state: await boxState(record, access) }))) +} + +/** Pause a box. Its files, installed tools and the OpenCode session stay; attach wakes it. */ +export async function stopBox(record: BoxRecord, access: E2BAccess): Promise { + await Sandbox.pause(record.sandboxId, access) +} + +/** Delete a box and its record. Pull first: work that is only in the box is lost. */ +export async function killBox(record: BoxRecord, access: E2BAccess): Promise { + await Sandbox.kill(record.sandboxId, access) + await removeBox(record.name) +} + +export function describeBoxes(boxes: { record: BoxRecord; state: BoxState }[]): string { + if (boxes.length === 0) { + return "No boxes yet. Start one with: opencode-e2b box up (or /e2b-box up in OpenCode)." + } + return boxes + .map( + ({ record, state }) => + `${record.name} ${state} ${record.root} (started ${record.createdAt.slice(0, 16)})`, + ) + .join("\n") +} diff --git a/src/v2/box/pull.ts b/src/v2/box/pull.ts new file mode 100644 index 0000000..90b3d8c --- /dev/null +++ b/src/v2/box/pull.ts @@ -0,0 +1,81 @@ +/** + * Bring a box's work home as a local branch, e2b/. In the box, the work in + * progress (uncommitted files too) is committed on a scratch ref, without touching the + * agent's own branch or index, and packed as a git bundle with only the commits since + * the box started. Locally, git fetches the bundle. No credentials are involved. + */ + +import { randomUUID } from "node:crypto" +import { rm, writeFile } from "node:fs/promises" +import os from "node:os" +import path from "node:path" +import { Sandbox } from "e2b" +import type { E2BAccess } from "../sandbox/create.js" +import { run } from "../sync/files.js" +import { quote, sh } from "../sync/remote.js" +import type { BoxRecord } from "./registry.js" + +export const PULL_REF = "refs/opencode-e2b/pull" +const NOTHING = "OPENCODE_E2B_NOTHING_NEW" + +/** The script that runs in the box. It prints the bundle path, or NOTHING when there is no new work. */ +export function bundleScript(root: string, name: string, base: string | undefined, bundle: string): string { + const author = "-c user.name=opencode-e2b -c user.email=opencode-e2b@localhost" + return ` +set -e -o pipefail +cd ${quote(root)} +export GIT_INDEX_FILE=$(mktemp) +if git rev-parse -q --verify HEAD >/dev/null; then git read-tree HEAD; parent="-p HEAD"; else parent=""; fi +git add -A >/dev/null +tree=$(git write-tree) +rm -f "$GIT_INDEX_FILE" +unset GIT_INDEX_FILE +if [ -n "$parent" ] && [ "$tree" = "$(git rev-parse 'HEAD^{tree}')" ]; then + commit=$(git rev-parse HEAD) +else + commit=$(git ${author} commit-tree "$tree" $parent -m ${quote(`Work in progress from box ${name}`)}) +fi +${base ? `if [ "$commit" = ${quote(base)} ]; then echo ${NOTHING}; exit 0; fi` : ""} +git update-ref ${PULL_REF} "$commit" +git bundle create ${quote(bundle)} ${PULL_REF}${base ? ` ^${base}` : ""} 2>/dev/null +echo ${quote(bundle)} +` +} + +export interface Pulled { + /** The local branch with the box's work, or undefined when there was nothing new. */ + branch?: string + /** `git log --oneline` of the new commits. */ + log: string +} + +/** What a pull brought home, for the CLI and the slash command. */ +export function pullSummary(name: string, pulled: Pulled): string { + if (!pulled.branch) { + return `Box "${name}" has no new work.` + } + const count = pulled.log.split("\n").length + return `Branch ${pulled.branch} has the box's work (${count} ${count === 1 ? "commit" : "commits"}):\n${pulled.log}` +} + +export async function pullBox(record: BoxRecord, access: E2BAccess): Promise { + const sandbox = await Sandbox.connect(record.sandboxId, access) + const remoteBundle = `/tmp/opencode-e2b-pull-${randomUUID()}.bundle` + const out = (await sh(sandbox, bundleScript(record.root, record.name, record.base, remoteBundle))).trim() + if (out.endsWith(NOTHING)) { + return { log: "" } + } + const bytes = await sandbox.files.read(remoteBundle, { format: "bytes" }) + sandbox.files.remove(remoteBundle).catch(() => undefined) + const localBundle = path.join(os.tmpdir(), `opencode-e2b-pull-${randomUUID()}.bundle`) + const branch = `e2b/${record.name}` + try { + await writeFile(localBundle, Buffer.from(bytes)) + await run("git", ["fetch", "-q", localBundle, `+${PULL_REF}:refs/heads/${branch}`], { cwd: record.root }) + } finally { + await rm(localBundle, { force: true }) + } + const range = record.base ? `${record.base}..${branch}` : branch + const log = (await run("git", ["log", "--oneline", range], { cwd: record.root })).toString().trim() + return { branch, log } +} diff --git a/src/v2/box/registry.ts b/src/v2/box/registry.ts new file mode 100644 index 0000000..d2c5136 --- /dev/null +++ b/src/v2/box/registry.ts @@ -0,0 +1,94 @@ +/** + * The boxes this machine started. Each box has a local record with its server URL and + * password; the password never goes to E2B. Records live in the user's state directory, + * one file per box, readable only by the user. + */ + +import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises" +import os from "node:os" +import path from "node:path" +import { Sandbox, SandboxNotFoundError } from "e2b" +import * as z from "zod" +import type { E2BAccess } from "../sandbox/create.js" + +const BoxRecord = z.object({ + name: z.string(), + sandboxId: z.string(), + url: z.string(), + password: z.string(), + /** The project folder: on this machine, and at the same path in the box. */ + root: z.string(), + /** The commit the box started from. Pull sends only the work after it. */ + base: z.string().optional(), + domain: z.string().optional(), + template: z.string(), + createdAt: z.string(), +}) +export type BoxRecord = z.infer + +export type BoxState = "running" | "paused" | "gone" + +function boxesDir(): string { + const state = process.env.XDG_STATE_HOME ?? path.join(os.homedir(), ".local", "state") + return path.join(state, "opencode-e2b", "boxes") +} + +/** A box name that is safe as a file name, a git branch and E2B metadata. */ +export function boxName(raw: string): string { + return raw + .toLowerCase() + .replaceAll(/[^a-z0-9._-]+/g, "-") + .replaceAll(/^[-.]+|[-.]+$/g, "") +} + +export async function saveBox(record: BoxRecord): Promise { + await mkdir(boxesDir(), { recursive: true, mode: 0o700 }) + await writeFile(path.join(boxesDir(), `${record.name}.json`), JSON.stringify(record, null, 2), { + mode: 0o600, + }) +} + +export async function readBox(name: string): Promise { + const raw = await readFile(path.join(boxesDir(), `${name}.json`), "utf8").catch( + (err: NodeJS.ErrnoException) => { + if (err.code === "ENOENT") { + return undefined + } + throw err + }, + ) + if (raw === undefined) { + return undefined + } + const parsed = BoxRecord.safeParse(JSON.parse(raw)) + return parsed.success ? parsed.data : undefined +} + +export async function listBoxes(): Promise { + const files = await readdir(boxesDir()).catch((err: NodeJS.ErrnoException) => { + if (err.code === "ENOENT") { + return [] + } + throw err + }) + const records = await Promise.all( + files.filter((file) => file.endsWith(".json")).map((file) => readBox(file.slice(0, -".json".length))), + ) + return records.filter((record) => record !== undefined) +} + +export async function removeBox(name: string): Promise { + await rm(path.join(boxesDir(), `${name}.json`), { force: true }) +} + +export async function boxState(record: BoxRecord, access: E2BAccess): Promise { + try { + const info = await Sandbox.getInfo(record.sandboxId, access) + return info.state === "paused" ? "paused" : "running" + } catch (err) { + if (err instanceof SandboxNotFoundError) { + return "gone" + } + throw err + } +} diff --git a/src/v2/box/server.ts b/src/v2/box/server.ts new file mode 100644 index 0000000..2a21dcf --- /dev/null +++ b/src/v2/box/server.ts @@ -0,0 +1,56 @@ +/** OpenCode 2 serving inside a box, behind a password. */ + +import type { Sandbox } from "e2b" +import { sh } from "../sync/remote.js" + +export const PORT = 4096 +const HEALTH_TIMEOUT_MS = 90_000 + +/** + * Make sure the box has OpenCode 2. The public opencode template gets it as `opencode2`; + * until then it is installed next to OpenCode 1, the same way the template does it. + */ +export async function ensureOpencode(sandbox: Sandbox): Promise { + const present = (await sh(sandbox, "command -v opencode2 || true")).trim() + if (present === "") { + await sh( + sandbox, + "sudo npm install -g --prefix /opt/opencode2 @opencode/cli >/dev/null && sudo ln -sf /opt/opencode2/bin/opencode2 /usr/local/bin/opencode2", + ) + } +} + +/** Start `opencode2 serve` in `root` and wait until it answers. Resolves with the public URL. */ +export async function startServer( + sandbox: Sandbox, + root: string, + password: string, + env: Record, +): Promise { + await sandbox.commands.run( + `opencode2 serve --hostname 0.0.0.0 --port ${PORT} >/tmp/opencode-e2b-box.log 2>&1`, + { + background: true, + cwd: root, + envs: { ...env, OPENCODE_SERVER_PASSWORD: password }, + timeoutMs: 0, + }, + ) + const url = `https://${sandbox.getHost(PORT)}` + await waitHealthy(url) + return url +} + +export async function waitHealthy(url: string): Promise { + const deadline = Date.now() + HEALTH_TIMEOUT_MS + while (Date.now() < deadline) { + const response = await fetch(`${url}/global/health`).catch(() => undefined) + if (response?.ok) { + return + } + await new Promise((resolve) => setTimeout(resolve, 1000)) + } + throw new Error( + `OpenCode in the box did not start within ${HEALTH_TIMEOUT_MS / 1000} s (log: /tmp/opencode-e2b-box.log)`, + ) +} diff --git a/src/v2/box/up.ts b/src/v2/box/up.ts new file mode 100644 index 0000000..5dbaf95 --- /dev/null +++ b/src/v2/box/up.ts @@ -0,0 +1,103 @@ +/** + * Start a box: a sandbox with the project at the same path (tracked and uncommitted + * files, and .git), and OpenCode 2 serving there. The model key comes from E2B secrets. + */ + +import { randomUUID } from "node:crypto" +import type { Sandbox } from "e2b" +import { placeholderEnv, providerNetwork, storedProviders } from "../providers.js" +import { type E2BAccess, type Network, createSandbox, mergeNetwork } from "../sandbox/create.js" +import { run } from "../sync/files.js" +import { push } from "../sync/push-pull.js" +import { applySpool, init, quote, sh } from "../sync/remote.js" +import { type BoxRecord, boxState, readBox, saveBox } from "./registry.js" +import { ensureOpencode, startServer } from "./server.js" + +export interface UpRequest { + root: string + name: string + template: string + /** How long the box runs before E2B pauses it. Agents work without traffic from here. */ + lifetimeMs: number + access: E2BAccess + network?: Network + progress: (step: string) => void +} + +export async function upBox(request: UpRequest): Promise { + const { root, name, access } = request + const existing = await readBox(name) + if (existing && (await boxState(existing, access)) !== "gone") { + throw new Error(`box "${name}" already exists. Attach to it, pull it, or kill it first.`) + } + const providers = await storedProviders(access) + if (providers.length === 0) { + throw new Error( + "no model key is stored yet. Store one as an E2B secret first: opencode-e2b secrets set anthropic (or /e2b-secrets set anthropic in OpenCode).", + ) + } + + request.progress("creating the sandbox") + const sandbox = await createSandbox(request.template, access, { + metadata: { app: "opencode-e2b-box", box: name }, + idleMs: request.lifetimeMs, + network: mergeNetwork(request.network, providerNetwork(providers)), + }) + try { + await init(sandbox, root) + request.progress("uploading the project, with uncommitted files and .git") + await push(sandbox, root, { files: new Map() }, true) + await applySpool(sandbox, root) + await copyGitIdentity(sandbox, root) + request.progress("starting OpenCode in the box") + await ensureOpencode(sandbox) + const password = randomUUID() + const url = await startServer(sandbox, root, password, { + ...placeholderEnv(providers), + // Only the providers with a stored key. Otherwise OpenCode may pick a free default model instead. + OPENCODE_CONFIG_CONTENT: JSON.stringify({ enabled_providers: providers }), + }) + const record: BoxRecord = { + name, + sandboxId: sandbox.sandboxId, + url, + password, + root, + base: await headCommit(root), + domain: access.domain, + template: request.template, + createdAt: new Date().toISOString(), + } + await saveBox(record) + return record + } catch (err) { + // A box that did not come up is deleted, so it does not keep billing. + await sandbox.kill().catch(() => undefined) + throw err + } +} + +/** The agent commits in the box as the user, as it would on the user's machine. */ +async function copyGitIdentity(sandbox: Sandbox, root: string): Promise { + const settings = await Promise.all( + ["user.name", "user.email"].map(async (key) => { + const value = await run("git", ["config", key], { cwd: root }).then( + (out) => out.toString().trim(), + () => "", + ) + return value ? `git config --global ${key} ${quote(value)}` : undefined + }), + ) + const commands = settings.filter((command) => command !== undefined) + if (commands.length > 0) { + await sh(sandbox, commands.join(" && ")) + } +} + +/** The commit the project is on, or undefined in a repository without commits. */ +async function headCommit(root: string): Promise { + return run("git", ["rev-parse", "--verify", "-q", "HEAD"], { cwd: root }).then( + (out) => out.toString().trim(), + () => undefined, + ) +} diff --git a/src/v2/cli/box.ts b/src/v2/cli/box.ts new file mode 100644 index 0000000..84bb173 --- /dev/null +++ b/src/v2/cli/box.ts @@ -0,0 +1,91 @@ +/** opencode-e2b box [name] */ + +import { parseArgs } from "node:util" +import { attachBox } from "../box/attach.js" +import { defaultBoxName, describeBoxes, findBox, killBox, listWithState, stopBox } from "../box/manage.js" +import { pullBox, pullSummary } from "../box/pull.js" +import { upBox } from "../box/up.js" +import type { E2BAccess } from "../sandbox/create.js" +import { gitRoot } from "../sync/files.js" +import { UsageError } from "./usage-error.js" + +const ACTIONS = new Set(["up", "attach", "pull", "list", "stop", "kill"]) + +export async function boxCommand(args: string[]): Promise { + const { values, positionals } = parseArgs({ + args, + allowPositionals: true, + options: { + template: { type: "string", default: "opencode" }, + hours: { type: "string", default: "1" }, + domain: { type: "string" }, + attach: { type: "boolean", default: false }, + }, + }) + const [action, given, ...extra] = positionals + if (action === undefined || !ACTIONS.has(action)) { + throw new UsageError(action ? `unknown box action "${action}"` : "say what to do with the box") + } + if (extra.length > 0) { + throw new UsageError(`unexpected arguments: ${extra.join(" ")}`) + } + const access: E2BAccess = { + apiKey: process.env.E2B_API_KEY, + domain: values.domain ?? process.env.E2B_DOMAIN, + } + + if (action === "list") { + console.log(describeBoxes(await listWithState(access))) + return 0 + } + + const root = await gitRoot(process.cwd()) + if (action === "up") { + if (!root) { + throw new Error("a box starts from a git repository, and this folder is not in one") + } + const hours = Number(values.hours) + if (!(hours > 0)) { + throw new UsageError("--hours must be a positive number") + } + const record = await upBox({ + root, + name: await defaultBoxName(root, given), + template: values.template, + lifetimeMs: hours * 3_600_000, + access, + progress: (step) => { + console.error(`[e2b] ${step}`) + }, + }) + console.error(`[e2b] box "${record.name}" is up`) + if (values.attach) { + return attachBox(record, recordAccess(record, access)) + } + console.log(`Attach with: opencode-e2b box attach ${record.name}`) + return 0 + } + + const record = await findBox(root, given) + const boxAccess = recordAccess(record, access) + if (action === "attach") { + return attachBox(record, boxAccess) + } + if (action === "pull") { + console.log(pullSummary(record.name, await pullBox(record, boxAccess))) + return 0 + } + if (action === "stop") { + await stopBox(record, boxAccess) + console.log(`Box "${record.name}" is paused. Attach wakes it.`) + return 0 + } + await killBox(record, boxAccess) + console.log(`Box "${record.name}" is deleted.`) + return 0 +} + +/** A box lives in the region it was started in. */ +function recordAccess(record: { domain?: string }, access: E2BAccess): E2BAccess { + return { ...access, domain: record.domain ?? access.domain } +} diff --git a/src/v2/cli/main.ts b/src/v2/cli/main.ts new file mode 100644 index 0000000..1c12db3 --- /dev/null +++ b/src/v2/cli/main.ts @@ -0,0 +1,59 @@ +#!/usr/bin/env node +/** + * opencode-e2b: boxes (OpenCode running in an E2B sandbox) and the model keys they use. + * + * opencode-e2b box up|attach|pull|list|stop|kill [name] + * opencode-e2b secrets set|list|remove [provider] + */ + +import "../../core/e2b-sdk.js" +import { errorText } from "../shell/runner.js" +import { boxCommand } from "./box.js" +import { secretsCommand } from "./secrets.js" +import { UsageError } from "./usage-error.js" + +const USAGE = `Usage: + opencode-e2b box up [name] [--template ] [--hours ] [--attach] + Start a box with this project and OpenCode in it + opencode-e2b box attach [name] Open the OpenCode TUI on a box + opencode-e2b box pull [name] Bring the box's work home as branch e2b/ + opencode-e2b box list The boxes this machine started + opencode-e2b box stop [name] Pause a box. Attach wakes it. + opencode-e2b box kill [name] Delete a box. Pull first. + opencode-e2b secrets set Store a model key as an E2B secret + opencode-e2b secrets list The providers with a stored key + opencode-e2b secrets remove Delete a stored key + +The box name defaults to the current git branch, or to the project's only box. Providers: anthropic, openai, openrouter. +The key for "secrets set" comes from the provider's variable (ANTHROPIC_API_KEY, ...) or stdin. +E2B_API_KEY selects the account, and E2B_DOMAIN or --domain the region.` + +async function main(args: string[]): Promise { + const [group, ...rest] = args + if (group === "box") { + return boxCommand(rest) + } + if (group === "secrets") { + return secretsCommand(rest) + } + if (group === undefined || group === "help" || group === "--help" || group === "-h") { + console.log(USAGE) + return 0 + } + throw new UsageError(`unknown command "${group}"`) +} + +let code = 0 +try { + code = await main(process.argv.slice(2)) +} catch (err) { + if (err instanceof UsageError) { + console.error(`opencode-e2b: ${err.message}\n\n${USAGE}`) + code = 2 + } else { + console.error(errorText(err)) + code = 1 + } +} +// The E2B SDK keeps its HTTP/2 connections open, which would keep the process alive. +process.exit(code) diff --git a/src/v2/cli/secrets.ts b/src/v2/cli/secrets.ts new file mode 100644 index 0000000..4f5ef09 --- /dev/null +++ b/src/v2/cli/secrets.ts @@ -0,0 +1,76 @@ +/** opencode-e2b secrets set|list|remove [provider] */ + +import { text } from "node:stream/consumers" +import { parseArgs } from "node:util" +import { + PROVIDERS, + PROVIDER_IDS, + type ProviderId, + isProvider, + removeProviderKey, + secretName, + setProviderKey, + storedProviders, +} from "../providers.js" +import type { E2BAccess } from "../sandbox/create.js" +import { UsageError } from "./usage-error.js" + +export async function secretsCommand(args: string[]): Promise { + const { values, positionals } = parseArgs({ + args, + allowPositionals: true, + options: { domain: { type: "string" } }, + }) + const [action, provider] = positionals + const access: E2BAccess = { + apiKey: process.env.E2B_API_KEY, + domain: values.domain ?? process.env.E2B_DOMAIN, + } + + if (action === "list") { + const stored = await storedProviders(access) + console.log( + stored.length > 0 + ? stored.map((id) => `${id} (E2B secret ${secretName(id)})`).join("\n") + : "No model keys stored yet.", + ) + return 0 + } + if (action !== "set" && action !== "remove") { + throw new UsageError(action ? `unknown secrets action "${action}"` : "say what to do with the secrets") + } + const id = parseProvider(provider) + if (action === "set") { + await setProviderKey(id, await readKey(id), access) + console.log( + `Stored the ${id} key as E2B secret ${secretName(id)}. Boxes get it through the egress proxy only.`, + ) + return 0 + } + const removed = await removeProviderKey(id, access) + console.log(removed ? `Deleted the stored ${id} key.` : `No ${id} key was stored.`) + return 0 +} + +function parseProvider(raw: string | undefined): ProviderId { + if (raw === undefined || !isProvider(raw)) { + throw new UsageError(`name a provider: ${PROVIDER_IDS.join(", ")}`) + } + return raw +} + +/** The key from the provider's environment variable, else from piped stdin. Never from an argument: shells keep history. */ +async function readKey(id: ProviderId): Promise { + const fromEnv = process.env[PROVIDERS[id].env] + if (fromEnv) { + return fromEnv + } + if (process.stdin.isTTY) { + throw new UsageError(`set ${PROVIDERS[id].env}, or pipe the key in`) + } + const fromStdin = (await text(process.stdin)).trim() + if (fromStdin === "") { + throw new UsageError("the key on stdin is empty") + } + return fromStdin +} diff --git a/src/v2/cli/usage-error.ts b/src/v2/cli/usage-error.ts new file mode 100644 index 0000000..5b7ad6b --- /dev/null +++ b/src/v2/cli/usage-error.ts @@ -0,0 +1,2 @@ +/** A mistake in the command line. The CLI shows the message with the usage. */ +export class UsageError extends Error {} diff --git a/src/v2/index.ts b/src/v2/index.ts index 1452bfc..c7b95fd 100644 --- a/src/v2/index.ts +++ b/src/v2/index.ts @@ -10,6 +10,8 @@ * shell/ the shell redirect: shim, the socket it talks to, the runner, git routing * sync/ keeping the sandbox copy equal to the host copy around each command * sandbox/ one E2B sandbox per project + * box/ boxes: OpenCode itself running in a sandbox, for long tasks + * cli/ the opencode-e2b command for boxes and their model keys */ import { createHash } from "node:crypto" @@ -17,7 +19,8 @@ import os from "node:os" import path from "node:path" import type { Plugin } from "@opencode/plugin" import "../core/e2b-sdk.js" -import { createBox } from "./sandbox/box.js" +import { createProjectSandbox } from "./sandbox/project-sandbox.js" +import { registerBoxCommands } from "./opencode/box-commands.js" import { registerCommands } from "./opencode/commands.js" import { createSandboxSwitch } from "./opencode/context.js" import { gitRoot } from "./sync/files.js" @@ -35,24 +38,25 @@ const plugin: Plugin.Plugin = { const project = root ?? opencode.location.directory const key = createHash("sha256").update(project).digest("hex").slice(0, 16) - const box = createBox(opencode.storage, project, key, { + const projectSandbox = createProjectSandbox(opencode.storage, project, key, { apiKey: process.env.E2B_API_KEY, domain: opts.domain, template: opts.template, idleMs: opts.idleMs, network: networkFor(opts), }) - const runner = createRunner(root, box, opts.git) + const runner = createRunner(root, projectSandbox, opts.git) const server = await startServer( path.join(os.tmpdir(), `opencode-e2b-${process.pid}-${key}.sock`), runner, ) const sandboxSwitch = await createSandboxSwitch(opencode.storage, `off:${key}`) - const context = { opencode, opts, root, project, box, runner, sandboxSwitch } + const context = { opencode, opts, root, project, projectSandbox, runner, sandboxSwitch } await registerHooks(context, server.socket) await registerTools(context) await registerCommands(context) + await registerBoxCommands(context) return () => { runner.close() diff --git a/src/v2/opencode/box-commands.ts b/src/v2/opencode/box-commands.ts new file mode 100644 index 0000000..87c47e5 --- /dev/null +++ b/src/v2/opencode/box-commands.ts @@ -0,0 +1,124 @@ +/** + * Slash commands for boxes: /e2b-box and /e2b-secrets. They do what the CLI does, + * except attach, which needs its own terminal. Replies never show a box password or a key. + */ + +import type { Plugin } from "@opencode/plugin" +import { defaultBoxName, describeBoxes, findBox, killBox, listWithState, stopBox } from "../box/manage.js" +import { pullBox, pullSummary } from "../box/pull.js" +import { upBox } from "../box/up.js" +import { networkFor } from "../options.js" +import { + PROVIDERS, + PROVIDER_IDS, + isProvider, + removeProviderKey, + secretName, + setProviderKey, + storedProviders, +} from "../providers.js" +import type { E2BAccess } from "../sandbox/create.js" +import type { PluginContext } from "./context.js" + +type SessionID = Parameters[0]["sessionID"] + +const BOX_USAGE = + "Usage: /e2b-box up|pull|list|stop|kill [name]. The name defaults to the current branch, or the project's only box." +const BOX_ACTIONS = new Set(["up", "pull", "list", "stop", "kill"]) +const SECRETS_USAGE = `Usage: /e2b-secrets set|remove , or /e2b-secrets list. Providers: ${PROVIDER_IDS.join(", ")}.` + +export async function registerBoxCommands(plugin: PluginContext): Promise { + const { opencode, opts, root } = plugin + const access: E2BAccess = { apiKey: process.env.E2B_API_KEY, domain: opts.domain } + + const reply = async (sessionID: SessionID, text: string, summary = text) => { + await opencode.session.synthetic({ + sessionID, + text: `[e2b] ${text}`, + description: `e2b · ${summary}`, + resume: false, + }) + } + + /** The text of the reply to `/e2b-box [name]`. */ + const box = async (action: string | undefined, given: string | undefined): Promise => { + if (action === undefined || !BOX_ACTIONS.has(action)) { + return BOX_USAGE + } + if (action === "list") { + return describeBoxes(await listWithState(access)) + } + if (!root) { + return "Boxes need a git repository, and this folder is not in one." + } + if (action === "up") { + const record = await upBox({ + root, + name: await defaultBoxName(root, given), + template: opts.template, + lifetimeMs: opts.boxLifetimeMs, + access, + network: networkFor(opts), + progress: () => undefined, + }) + return `Box "${record.name}" is up with this project and OpenCode in it. Open it in a terminal with: opencode-e2b box attach ${record.name}` + } + const record = await findBox(root, given) + const boxAccess = { ...access, domain: record.domain ?? access.domain } + if (action === "pull") { + return pullSummary(record.name, await pullBox(record, boxAccess)) + } + if (action === "stop") { + await stopBox(record, boxAccess) + return `Box "${record.name}" is paused. Attach wakes it.` + } + await killBox(record, boxAccess) + return `Box "${record.name}" is deleted.` + } + + /** The text of the reply to `/e2b-secrets [provider]`. */ + const secrets = async (action: string | undefined, provider: string | undefined): Promise => { + if (action === "list") { + const stored = await storedProviders(access) + return stored.length > 0 ? `Model keys stored for: ${stored.join(", ")}` : "No model keys stored yet." + } + if ((action !== "set" && action !== "remove") || provider === undefined || !isProvider(provider)) { + return SECRETS_USAGE + } + if (action === "remove") { + return (await removeProviderKey(provider, access)) + ? `Deleted the stored ${provider} key.` + : `No ${provider} key was stored.` + } + // The key comes from OpenCode's own environment, never from the prompt: prompts are kept in the session. + const value = process.env[PROVIDERS[provider].env] + if (!value) { + return `${PROVIDERS[provider].env} is not set where OpenCode runs. Set it, or run: opencode-e2b secrets set ${provider}` + } + await setProviderKey(provider, value, access) + return `Stored ${PROVIDERS[provider].env} as E2B secret ${secretName(provider)}. Boxes get it through the egress proxy only.` + } + + const words = (text: string | undefined) => (text ?? "").trim().split(/\s+/).filter(Boolean) + + await opencode.command.transform((commands) => { + commands.add({ + name: "e2b-box", + description: "Run OpenCode in an E2B box: /e2b-box up|pull|list|stop|kill [name]", + execute: async ({ sessionID, prompt }) => { + const [action, name] = words(prompt.text) + const text = await box(action, name) + await reply(sessionID, text, text.split("\n")[0]) + }, + }) + + commands.add({ + name: "e2b-secrets", + description: "Store model keys for boxes as E2B secrets: /e2b-secrets set|list|remove [provider]", + execute: async ({ sessionID, prompt }) => { + const [action, provider] = words(prompt.text) + await reply(sessionID, await secrets(action, provider)) + }, + }) + }) +} diff --git a/src/v2/opencode/commands.ts b/src/v2/opencode/commands.ts index ec232a5..1890214 100644 --- a/src/v2/opencode/commands.ts +++ b/src/v2/opencode/commands.ts @@ -8,7 +8,7 @@ import { fetchPaths } from "../sync/transfer.js" type SessionID = Parameters[0]["sessionID"] export async function registerCommands(plugin: PluginContext): Promise { - const { opencode, opts, root, box, sandboxSwitch } = plugin + const { opencode, opts, root, projectSandbox, sandboxSwitch } = plugin // A command's result goes to the session as a synthetic message. The TUI shows only // its description, so that carries the answer; the text is the full version for the model. @@ -45,7 +45,7 @@ export async function registerCommands(plugin: PluginContext): Promise { await reply(sessionID, "Usage: /e2b-pull [more paths]") return } - await fetchPaths(await box.get(), root, paths) + await fetchPaths(await projectSandbox.get(), root, paths) await reply(sessionID, `Copied from the sandbox: ${paths.join(", ")}`) }, }) @@ -54,7 +54,7 @@ export async function registerCommands(plugin: PluginContext): Promise { name: "e2b-reset", description: "Delete the sandbox. The next command starts a fresh one.", execute: async ({ sessionID }) => { - const killed = await box.kill() + const killed = await projectSandbox.kill() await reply( sessionID, killed @@ -70,7 +70,7 @@ export async function registerCommands(plugin: PluginContext): Promise { "Save the sandbox (installed dependencies, tools) as the start for new ones. /e2b-snapshot clear stops that.", execute: async ({ sessionID, prompt }) => { if ((prompt.text ?? "").trim() === "clear") { - const cleared = await box.clearSnapshot() + const cleared = await projectSandbox.clearSnapshot() await reply( sessionID, cleared @@ -79,7 +79,7 @@ export async function registerCommands(plugin: PluginContext): Promise { ) return } - const saved = await box.snapshot() + const saved = await projectSandbox.snapshot() await reply( sessionID, `Saved snapshot ${saved.snapshotId}. New sandboxes for this project start from it, with what is installed now. Your files still sync from your machine.`, diff --git a/src/v2/opencode/context.ts b/src/v2/opencode/context.ts index e105be7..23dc3de 100644 --- a/src/v2/opencode/context.ts +++ b/src/v2/opencode/context.ts @@ -1,7 +1,7 @@ /** What the plugin's hooks, tools and commands share. */ import type { Plugin } from "@opencode/plugin" -import type { Box } from "../sandbox/box.js" +import type { ProjectSandbox } from "../sandbox/project-sandbox.js" import type { Options } from "../options.js" import type { Runner } from "../shell/runner.js" @@ -18,7 +18,7 @@ export interface PluginContext { root: string | undefined /** `root`, or the opened folder outside a git checkout. */ project: string - box: Box + projectSandbox: ProjectSandbox runner: Runner sandboxSwitch: SandboxSwitch } diff --git a/src/v2/opencode/status.ts b/src/v2/opencode/status.ts index 113752d..3331264 100644 --- a/src/v2/opencode/status.ts +++ b/src/v2/opencode/status.ts @@ -5,11 +5,11 @@ import { describeNetwork } from "../options.js" import type { GitHistory } from "../shell/runner.js" export async function readStatus(plugin: PluginContext): Promise<{ text: string; line: string }> { - const { opts, root, project, box, runner, sandboxSwitch } = plugin - const sandbox = box.peek() + const { opts, root, project, projectSandbox, runner, sandboxSwitch } = plugin + const sandbox = projectSandbox.peek() const sync = runner.lastSync() const error = runner.lastError() - const [metrics, saved] = await Promise.all([box.metrics(), box.savedSnapshot()]) + const [metrics, saved] = await Promise.all([projectSandbox.metrics(), projectSandbox.savedSnapshot()]) const mb = (bytes: number) => `${Math.round(bytes / 1024 / 1024)} MB` const usage = metrics ? `CPU ${Math.round(metrics.cpuUsedPct)}% of ${metrics.cpuCount}, memory ${mb(metrics.memUsed)} of ${mb(metrics.memTotal)}, disk ${mb(metrics.diskUsed)} of ${mb(metrics.diskTotal)}` diff --git a/src/v2/opencode/tools.ts b/src/v2/opencode/tools.ts index 20841b6..a9c9e69 100644 --- a/src/v2/opencode/tools.ts +++ b/src/v2/opencode/tools.ts @@ -8,7 +8,7 @@ import { readStatus } from "./status.js" const READ_LIMIT = 50_000 export async function registerTools(plugin: PluginContext): Promise { - const { opencode, project, box } = plugin + const { opencode, project, projectSandbox } = plugin await opencode.tool.transform((tools) => { tools.add({ name: "e2b_preview_url", @@ -17,7 +17,7 @@ export async function registerTools(plugin: PluginContext): Promise { options: { codemode: false }, input: z.object({ port: z.int().min(1).max(65535) }), async execute({ port }) { - const sandbox = await box.get() + const sandbox = await projectSandbox.get() return { content: `https://${sandbox.getHost(port)}` } }, }) @@ -28,7 +28,7 @@ export async function registerTools(plugin: PluginContext): Promise { options: { codemode: false }, input: z.object({ path: z.string().min(1), offset: z.int().min(0).default(0) }), async execute({ path: file, offset }) { - const sandbox = await box.get() + const sandbox = await projectSandbox.get() const bytes = await sandbox.files.read(path.resolve(project, file), { format: "bytes" }) const slice = Buffer.from(bytes).subarray(offset, offset + READ_LIMIT) const rest = bytes.length - offset - slice.length diff --git a/src/v2/options.ts b/src/v2/options.ts index 5e3d95f..a4b0485 100644 --- a/src/v2/options.ts +++ b/src/v2/options.ts @@ -7,8 +7,9 @@ */ import type { Plugin } from "@opencode/plugin" -import { Secret, type SandboxNetworkOpts } from "e2b" +import { Secret } from "e2b" import * as z from "zod" +import type { Network } from "./sandbox/create.js" const name = z.string().min(1) @@ -31,6 +32,8 @@ const OptionsSchema = z domain: name.optional(), template: name.default("opencode"), idleMinutes: z.number().positive().default(15), + /** How long a box runs before E2B pauses it. E2B plans cap this (1 hour on the lower plans). */ + boxHours: z.number().positive().default(1), /** Names of host environment variables to pass to commands. */ env: z.array(name).default([]), /** Send .git to the sandbox: always, never, or "auto" (only when it is small enough). */ @@ -39,9 +42,10 @@ const OptionsSchema = z /** Host -> how to inject a stored secret into requests to that host. */ secrets: z.record(z.string(), SecretRule).default({}), }) - .transform(({ idleMinutes, network, ...rest }) => ({ + .transform(({ idleMinutes, boxHours, network, ...rest }) => ({ ...rest, idleMs: idleMinutes * 60_000, + boxLifetimeMs: boxHours * 3_600_000, allowOut: network.allowOut, denyOut: network.denyOut, })) @@ -58,7 +62,7 @@ export function parseOptions(input: Plugin.Context["options"] | undefined): Opti } /** The sandbox network config, or undefined to leave E2B's default (all egress allowed). */ -export function networkFor(opts: Options): SandboxNetworkOpts | undefined { +export function networkFor(opts: Options): Network | undefined { const hosts = Object.keys(opts.secrets) if (hosts.length === 0 && !opts.allowOut && !opts.denyOut) { return undefined diff --git a/src/v2/providers.ts b/src/v2/providers.ts new file mode 100644 index 0000000..bd5fbdc --- /dev/null +++ b/src/v2/providers.ts @@ -0,0 +1,74 @@ +/** + * Model providers for boxes. A box runs OpenCode itself, so it needs a model key. The + * key is stored once as an E2B secret; the box gets only a placeholder, and E2B's egress + * proxy puts the real key into each HTTPS request to the provider. The box never holds it. + */ + +import { Secret } from "e2b" +import type { E2BAccess, Network } from "./sandbox/create.js" + +export const PROVIDER_IDS = ["anthropic", "openai", "openrouter"] as const + +export type ProviderId = (typeof PROVIDER_IDS)[number] + +export const PROVIDERS: Record = { + anthropic: { env: "ANTHROPIC_API_KEY", host: "api.anthropic.com", header: "x-api-key", prefix: "" }, + openai: { env: "OPENAI_API_KEY", host: "api.openai.com", header: "Authorization", prefix: "Bearer " }, + openrouter: { + env: "OPENROUTER_API_KEY", + host: "openrouter.ai", + header: "Authorization", + prefix: "Bearer ", + }, +} + +/** The value OpenCode sees in the box. The egress proxy replaces it on the wire. */ +const PLACEHOLDER = "set-by-the-e2b-egress-proxy" + +export function isProvider(id: string): id is ProviderId { + return PROVIDER_IDS.some((known) => known === id) +} + +export function secretName(id: ProviderId): string { + return `opencode-e2b-${id}` +} + +/** Store or replace the key for `id`. */ +export async function setProviderKey(id: ProviderId, value: string, access: E2BAccess): Promise { + const name = secretName(id) + if (await Secret.exists(name, access)) { + await Secret.update(name, value, access) + } else { + await Secret.create(name, value, access) + } +} + +/** Resolves true if a key was stored. */ +export function removeProviderKey(id: ProviderId, access: E2BAccess): Promise { + return Secret.destroy(secretName(id), access) +} + +/** Providers whose key is stored as an E2B secret. */ +export async function storedProviders(access: E2BAccess): Promise { + const stored = await Promise.all(PROVIDER_IDS.map((id) => Secret.exists(secretName(id), access))) + return PROVIDER_IDS.filter((_, i) => stored[i]) +} + +/** Egress rules that put each provider's stored key into requests to its API. */ +export function providerNetwork(ids: ProviderId[]): Network | undefined { + if (ids.length === 0) { + return undefined + } + const rules = Object.fromEntries( + ids.map((id) => { + const { host, header, prefix } = PROVIDERS[id] + return [host, [{ transform: { headers: { [header]: `${prefix}${Secret.fill(secretName(id))}` } } }]] + }), + ) + return { rules } +} + +/** The environment OpenCode in the box needs to offer these providers: placeholders, never keys. */ +export function placeholderEnv(ids: ProviderId[]): Record { + return Object.fromEntries(ids.map((id) => [PROVIDERS[id].env, PLACEHOLDER])) +} diff --git a/src/v2/sandbox/create.ts b/src/v2/sandbox/create.ts new file mode 100644 index 0000000..54a64aa --- /dev/null +++ b/src/v2/sandbox/create.ts @@ -0,0 +1,51 @@ +/** Creating sandboxes the same way in both modes: paused when idle, woken by traffic, with network rules. */ + +import { Sandbox, type SandboxNetworkRule } from "e2b" + +/** Which E2B account and region to use. */ +export interface E2BAccess { + apiKey?: string + /** E2B region domain, for example e2b-juliett.dev for the EU. Defaults to E2B_DOMAIN or e2b.app. */ + domain?: string +} + +/** The part of E2B's network config this plugin sets: plain lists and a rule per host. */ +export interface Network { + allowOut?: string[] + denyOut?: string[] + rules?: Record +} + +export interface CreateSettings { + metadata: Record + /** Idle time before E2B pauses the sandbox. */ + idleMs: number + network?: Network +} + +/** `from` is a template name or a snapshot id. */ +export function createSandbox(from: string, access: E2BAccess, settings: CreateSettings): Promise { + return Sandbox.create(from, { + ...access, + metadata: settings.metadata, + timeoutMs: settings.idleMs, + lifecycle: { onTimeout: "pause", autoResume: true }, + network: settings.network, + }) +} + +/** Combine two network configs. Allow and deny lists add up; for the same host, `extra`'s rules win. */ +export function mergeNetwork(base: Network | undefined, extra: Network | undefined): Network | undefined { + if (!base || !extra) { + return base ?? extra + } + const list = (a: string[] = [], b: string[] = []) => { + const items = [...a, ...b] + return items.length > 0 ? [...new Set(items)] : undefined + } + return { + allowOut: list(base.allowOut, extra.allowOut), + denyOut: list(base.denyOut, extra.denyOut), + rules: { ...base.rules, ...extra.rules }, + } +} diff --git a/src/v2/sandbox/box.ts b/src/v2/sandbox/project-sandbox.ts similarity index 92% rename from src/v2/sandbox/box.ts rename to src/v2/sandbox/project-sandbox.ts index dad4f5b..f2c2ed9 100644 --- a/src/v2/sandbox/box.ts +++ b/src/v2/sandbox/project-sandbox.ts @@ -10,18 +10,13 @@ * project's sandbox, if any, is the starting point for new ones. */ -import { - NotFoundError, - Sandbox, - type SandboxMetrics, - type SandboxNetworkOpts, - SandboxNotFoundError, -} from "e2b" +import { NotFoundError, Sandbox, type SandboxMetrics, SandboxNotFoundError } from "e2b" import * as z from "zod" import type { Plugin } from "@opencode/plugin" import { init } from "../sync/remote.js" +import { type Network, createSandbox } from "./create.js" -export interface BoxOptions { +export interface ProjectSandboxOptions { apiKey?: string /** E2B region domain, for example e2b-juliett.dev for the EU. Defaults to E2B_DOMAIN or e2b.app. */ domain?: string @@ -29,7 +24,7 @@ export interface BoxOptions { /** Idle time before E2B pauses the sandbox. Every command restarts it. */ idleMs: number /** Egress rules: allow and deny lists, and per-host request transforms that inject stored secrets. */ - network?: SandboxNetworkOpts + network?: Network } type Storage = Plugin.Context["storage"] @@ -39,7 +34,7 @@ const CachedBox = z.object({ sandboxId: z.string(), template: z.string() }) const SavedSnapshot = z.object({ snapshotId: z.string(), template: z.string(), at: z.string() }) export type SavedSnapshot = z.infer -export interface Box { +export interface ProjectSandbox { /** The sandbox, created on first use. `onCreate` runs before a new sandbox starts. */ get(onCreate?: () => void): Promise /** The sandbox if one is connected now. Never creates one. */ @@ -55,9 +50,14 @@ export interface Box { metrics(): Promise } -export function createBox(storage: Storage, root: string, key: string, opts: BoxOptions): Box { +export function createProjectSandbox( + storage: Storage, + root: string, + key: string, + opts: ProjectSandboxOptions, +): ProjectSandbox { const region = opts.domain ?? process.env.E2B_DOMAIN ?? "e2b.app" - const cacheKey = `box:${region}:${key}` + const cacheKey = `projectSandbox:${region}:${key}` const snapshotKey = `snapshot:${region}:${key}` const api = { apiKey: opts.apiKey, domain: opts.domain } const metadata = { app: "opencode-e2b", project: key, template: opts.template } @@ -101,13 +101,7 @@ export function createBox(storage: Storage, root: string, key: string, opts: Box async function create(): Promise { const create = (from: string) => - Sandbox.create(from, { - ...api, - metadata, - timeoutMs: opts.idleMs, - lifecycle: { onTimeout: "pause", autoResume: true }, - network: opts.network, - }) + createSandbox(from, api, { metadata, idleMs: opts.idleMs, network: opts.network }) const saved = await read(snapshotKey, SavedSnapshot) if (saved?.template === opts.template) { try { diff --git a/src/v2/shell/runner.ts b/src/v2/shell/runner.ts index ac36c31..814cae9 100644 --- a/src/v2/shell/runner.ts +++ b/src/v2/shell/runner.ts @@ -4,7 +4,7 @@ */ import { type Sandbox, SandboxNotFoundError } from "e2b" -import type { Box } from "../sandbox/box.js" +import type { ProjectSandbox } from "../sandbox/project-sandbox.js" import type { RunRequest } from "./protocol.js" import { APPLY_FAILED_EXIT, @@ -55,7 +55,11 @@ const NOTHING_PULLED: Pulled = { written: [], removed: [], conflicts: [] } const NOT_A_REPO = "opencode-e2b runs commands in a sandbox copy of your git repository, and this folder is not in one. Run `git init`, or turn the sandbox off with /e2b-off." -export function createRunner(root: string | undefined, box: Box, shipGit: boolean | "auto"): Runner { +export function createRunner( + root: string | undefined, + projectSandbox: ProjectSandbox, + shipGit: boolean | "auto", +): Runner { /** The agreed file state, valid for the sandbox with this id. */ let state: { sandboxId: string; value: State } | undefined let last: SyncInfo | undefined @@ -87,7 +91,7 @@ export function createRunner(root: string | undefined, box: Box, shipGit: boolea /** Connect (or create) the sandbox and send what changed. A sandbox that is gone is replaced once. */ async function connectAndPrepare(project: string, output: Output) { const attempt = async () => { - const sandbox = await box.get(() => { + const sandbox = await projectSandbox.get(() => { output.note("starting a sandbox for this project and uploading it (first command only)") }) return { sandbox, sent: await prepare(sandbox, project) } @@ -98,7 +102,7 @@ export function createRunner(root: string | undefined, box: Box, shipGit: boolea if (!(err instanceof SandboxNotFoundError)) { throw err } - box.forget() + projectSandbox.forget() return attempt() } } @@ -135,7 +139,7 @@ export function createRunner(root: string | undefined, box: Box, shipGit: boolea }, killed, () => { - box.keepAlive() + projectSandbox.keepAlive() }, ) for (const warning of syncWarnings(stderr)) { @@ -187,17 +191,17 @@ export function createRunner(root: string | undefined, box: Box, shipGit: boolea } }, warm() { - if (!root || box.peek() || warming) { + if (!root || projectSandbox.peek() || warming) { return } - warming = background(async () => syncNow(await box.get(), root)).finally(() => { + warming = background(async () => syncNow(await projectSandbox.get(), root)).finally(() => { warming = undefined }) }, syncSoon() { clearTimeout(soon) soon = setTimeout(() => { - const sandbox = box.peek() + const sandbox = projectSandbox.peek() if (root && sandbox) { void background(() => syncNow(sandbox, root)) } diff --git a/test/v2-box.test.ts b/test/v2-box.test.ts new file mode 100644 index 0000000..c731f3c --- /dev/null +++ b/test/v2-box.test.ts @@ -0,0 +1,95 @@ +import assert from "node:assert/strict" +import { execFileSync } from "node:child_process" +import { mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs" +import os from "node:os" +import path from "node:path" +import { afterAll, test } from "bun:test" +import { PULL_REF, bundleScript, pullSummary } from "../dist/v2/box/pull.js" +import { boxName, listBoxes, readBox, removeBox, saveBox } from "../dist/v2/box/registry.js" + +const temp = mkdtempSync(path.join(os.tmpdir(), "opencode-e2b-box-")) +afterAll(() => { + rmSync(temp, { recursive: true, force: true }) +}) + +const git = (cwd: string, ...args: string[]) => + execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@t", ...args], { cwd }) + .toString() + .trim() + +function repo(name: string): string { + const dir = path.join(temp, name) + execFileSync("git", ["init", "-q", "-b", "main", dir]) + writeFileSync(path.join(dir, "a.txt"), "one\n") + git(dir, "add", "a.txt") + git(dir, "commit", "-qm", "base") + return dir +} + +const runScript = (dir: string, base: string | undefined, bundle: string) => + execFileSync("bash", ["-c", bundleScript(dir, "task", base, bundle)]) + .toString() + .trim() + +test("box names are safe as file names and branches", () => { + assert.equal(boxName("Feature/Login Page"), "feature-login-page") + assert.equal(boxName("..hidden.."), "hidden") + assert.equal(boxName("fix_1.2"), "fix_1.2") +}) + +test("pull bundles commits and uncommitted work, and leaves the agent's index alone", () => { + const box = repo("box") + const base = git(box, "rev-parse", "HEAD") + writeFileSync(path.join(box, "a.txt"), "two\n") + git(box, "commit", "-qam", "agent commit") + writeFileSync(path.join(box, "a.txt"), "three\n") + writeFileSync(path.join(box, "new.txt"), "untracked\n") + const statusBefore = git(box, "status", "--porcelain") + + const bundle = path.join(temp, "work.bundle") + assert.equal(runScript(box, base, bundle), bundle) + assert.equal(git(box, "status", "--porcelain"), statusBefore) + + const home = repo("home") + git(home, "fetch", "-q", bundle, `+${PULL_REF}:refs/heads/e2b/task`) + assert.deepEqual(git(home, "log", "--format=%s", `${base}..e2b/task`).split("\n"), [ + "Work in progress from box task", + "agent commit", + ]) + assert.equal(git(home, "show", "e2b/task:a.txt"), "three") + assert.equal(git(home, "show", "e2b/task:new.txt"), "untracked") +}) + +test("pull reports nothing new when the box has no work", () => { + const box = repo("idle") + const base = git(box, "rev-parse", "HEAD") + assert.equal(runScript(box, base, path.join(temp, "idle.bundle")), "OPENCODE_E2B_NOTHING_NEW") +}) + +test("the pull summary counts commits", () => { + assert.equal(pullSummary("b", { log: "" }), 'Box "b" has no new work.') + assert.equal( + pullSummary("b", { branch: "e2b/b", log: "abc one" }), + "Branch e2b/b has the box's work (1 commit):\nabc one", + ) + assert.match(pullSummary("b", { branch: "e2b/b", log: "abc one\ndef two" }), /\(2 commits\)/) +}) + +test("records are private to the user and round-trip", async () => { + process.env.XDG_STATE_HOME = path.join(temp, "state") + const record = { + name: "task", + sandboxId: "sbx", + url: "https://4096-sbx.e2b.app", + password: "secret", + root: "/work/project", + template: "opencode", + createdAt: new Date().toISOString(), + } + await saveBox(record) + assert.equal(statSync(path.join(temp, "state", "opencode-e2b", "boxes", "task.json")).mode & 0o777, 0o600) + assert.deepEqual(await readBox("task"), record) + assert.deepEqual(await listBoxes(), [record]) + await removeBox("task") + assert.equal(await readBox("task"), undefined) +}) diff --git a/test/v2-cli.test.ts b/test/v2-cli.test.ts new file mode 100644 index 0000000..5faa146 --- /dev/null +++ b/test/v2-cli.test.ts @@ -0,0 +1,45 @@ +import assert from "node:assert/strict" +import { spawnSync } from "node:child_process" +import { mkdtempSync, rmSync } from "node:fs" +import os from "node:os" +import path from "node:path" +import { afterAll, test } from "bun:test" + +const state = mkdtempSync(path.join(os.tmpdir(), "opencode-e2b-cli-")) +afterAll(() => { + rmSync(state, { recursive: true, force: true }) +}) + +const cli = (...args: string[]) => { + const result = spawnSync("node", [path.resolve("dist/v2/cli/main.js"), ...args], { + env: { ...process.env, XDG_STATE_HOME: state, ANTHROPIC_API_KEY: "" }, + input: "", + }) + return { code: result.status, out: result.stdout.toString(), err: result.stderr.toString() } +} + +test("help prints the usage", () => { + const { code, out } = cli() + assert.equal(code, 0) + assert.match(out, /opencode-e2b box up/) +}) + +test("mistakes exit 2 with the usage", () => { + for (const args of [["nope"], ["box", "dance", "x"], ["secrets", "set", "acme"], ["box", "up", "a", "b"]]) { + const { code, err } = cli(...args) + assert.equal(code, 2, args.join(" ")) + assert.match(err, /Usage:/) + } +}) + +test("an empty key is refused before E2B is called", () => { + const { code, err } = cli("secrets", "set", "anthropic") + assert.equal(code, 2) + assert.match(err, /empty/) +}) + +test("box list works without any boxes", () => { + const { code, out } = cli("box", "list") + assert.equal(code, 0) + assert.match(out, /No boxes yet/) +}) diff --git a/test/v2-providers.test.ts b/test/v2-providers.test.ts new file mode 100644 index 0000000..17a8d50 --- /dev/null +++ b/test/v2-providers.test.ts @@ -0,0 +1,46 @@ +import assert from "node:assert/strict" +import { test } from "bun:test" +import { isProvider, placeholderEnv, providerNetwork, secretName } from "../dist/v2/providers.js" +import { mergeNetwork } from "../dist/v2/sandbox/create.js" + +test("a provider key reaches the box only as an egress rule", () => { + assert.deepEqual(providerNetwork(["anthropic", "openai"]), { + rules: { + "api.anthropic.com": [ + { transform: { headers: { "x-api-key": "${e2b.secrets.opencode-e2b-anthropic}" } } }, + ], + "api.openai.com": [ + { transform: { headers: { Authorization: "Bearer ${e2b.secrets.opencode-e2b-openai}" } } }, + ], + }, + }) + assert.equal(providerNetwork([]), undefined) +}) + +test("the box environment holds placeholders, not keys", () => { + const env = placeholderEnv(["anthropic"]) + assert.deepEqual(Object.keys(env), ["ANTHROPIC_API_KEY"]) + assert.doesNotMatch(env.ANTHROPIC_API_KEY, /^sk-/) +}) + +test("provider names", () => { + assert.equal(isProvider("anthropic"), true) + assert.equal(isProvider("toString"), false) + assert.equal(secretName("openrouter"), "opencode-e2b-openrouter") +}) + +test("network configs merge: lists add up, the second config's rule wins for a host", () => { + const rule = (header: string) => [{ transform: { headers: { [header]: "x" } } }] + assert.deepEqual( + mergeNetwork( + { allowOut: ["github.com"], rules: { "api.anthropic.com": rule("a"), "api.github.com": rule("b") } }, + { allowOut: ["github.com", "api.anthropic.com"], rules: { "api.anthropic.com": rule("c") } }, + ), + { + allowOut: ["github.com", "api.anthropic.com"], + denyOut: undefined, + rules: { "api.anthropic.com": rule("c"), "api.github.com": rule("b") }, + }, + ) + assert.equal(mergeNetwork(undefined, undefined), undefined) +})