Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/box-web-attach.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@e2b/opencode": minor
---

Boxes without leaving OpenCode: `/e2b-attach` opens a box's TUI in the same terminal and comes back when you quit it, and `/e2b-box open` (or `opencode-e2b box open`) signs the browser or the OpenCode app in to a box with a one-time link. `/e2b-box up` shows its progress, copies the link, and starts the box with your default model.
33 changes: 29 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,29 +100,54 @@ Limits: the project must be a git repository; submodule contents and a linked wo

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.

From OpenCode:

```text
/e2b-secrets set anthropic once: stores ANTHROPIC_API_KEY as an E2B secret
/e2b-box up start a box named after the branch; a sign-in link is copied
/e2b-attach open the box's TUI here; quit it (Ctrl+C) to come back, the box keeps working
/e2b-box open open the box in the browser (and copy a second link for the OpenCode app)
/e2b-box pull the box's work, uncommitted files too, as branch e2b/<name>
/e2b-box kill
```

Three ways to work in a box:

| Where | How |
| --- | --- |
| This terminal | `/e2b-attach [name]` pauses your OpenCode and opens the box's TUI in its place. Quit it to come back. |
| Browser | `/e2b-box open [name]` opens the box's web UI, signed in. Works on a phone too: open the link there. |
| OpenCode app | Paste the copied link under Settings > Servers > Add server. The box shows next to your computer, with its own projects. |

A sign-in link works once and expires in 5 minutes. `/e2b-box open` makes a new one any time, and wakes a paused box.

From a shell:

```bash
npm install -g @e2b/opencode # the opencode-e2b command
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 open # open it in the browser instead
opencode-e2b box pull # the box's work, uncommitted files too, as branch e2b/<name>
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 up [name]` | Uploads the project (tracked and uncommitted files, and `.git`) to the same path in a new sandbox, and starts OpenCode there as its background service. Prints a sign-in link. Options: `--template`, `--hours` (default 1), `--model <provider/model>`, `--attach`. |
| `box open [name]` | Wakes the box if it is paused and prints a new sign-in link. In a terminal it also opens the browser. |
| `box attach [name]` | Wakes the box if it is paused, then runs your local `opencode2 --server <box>`. |
| `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/<name>`. 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 <provider>` | 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.
The name defaults to the current branch, or to the project's only box. In OpenCode, `/e2b-box up|open|pull|list|stop|kill`, `/e2b-attach` and `/e2b-secrets` do the same. `/e2b-secrets set` takes the key from OpenCode's environment, never from the prompt. A box started from OpenCode uses the same default model as your sessions, when its provider has a stored key.

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.
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. Sign-in links come from `opencode pair` in the box, so the password itself is never shown.

A box pauses after `--hours`; attach wakes it. E2B plans cap the run time (1 hour on the lower plans).
A box pauses after `--hours`; open or attach wakes it. E2B plans cap the run time (1 hour on the lower plans).

## Development

Expand Down
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@
"./server": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./tui": {
"types": "./dist/v2/tui.d.ts",
"default": "./dist/v2/tui.js"
}
},
"publishConfig": {
Expand Down
2 changes: 1 addition & 1 deletion src/v2/box/attach.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { waitHealthy } from "./server.js"
*/
export async function attachBox(record: BoxRecord, access: E2BAccess): Promise<number> {
await Sandbox.connect(record.sandboxId, access)
await waitHealthy(record.url)
await waitHealthy(record.url, record.password)
const opencode = await localOpencode2()
return new Promise((resolve, reject) => {
const child = spawn(opencode, ["--server", record.url], {
Expand Down
48 changes: 48 additions & 0 deletions src/v2/box/local.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* Hand a box's sign-in link to this machine: the browser, or the clipboard for the
* OpenCode app. Both run where OpenCode's server runs, which is the user's machine.
* Best effort: callers print the link too.
*/

import { spawn } from "node:child_process"

export function openInBrowser(link: string): void {
const opener =
process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open"
const child = spawn(opener, [link], { detached: true, stdio: "ignore" })
child.on("error", () => undefined)
child.unref()
}

/** Resolves true when the text is on the clipboard. */
export async function copyToClipboard(text: string): Promise<boolean> {
for (const [command, ...args] of clipboardCommands()) {
if (await pipeTo(command, args, text)) {
return true
}
}
return false
}

function clipboardCommands(): string[][] {
if (process.platform === "darwin") {
return [["pbcopy"]]
}
if (process.platform === "win32") {
return [["clip"]]
}
return [["wl-copy"], ["xclip", "-selection", "clipboard"], ["xsel", "--clipboard", "--input"]]
}

function pipeTo(command: string, args: string[], input: string): Promise<boolean> {
return new Promise((resolve) => {
const child = spawn(command, args, { stdio: ["pipe", "ignore", "ignore"] })
child.on("error", () => {
resolve(false)
})
child.on("exit", (code) => {
resolve(code === 0)
})
child.stdin.end(input)
})
}
76 changes: 61 additions & 15 deletions src/v2/box/server.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
/** OpenCode 2 serving inside a box, behind a password. */

import type { Sandbox } from "e2b"
import { sh } from "../sync/remote.js"
import { Sandbox } from "e2b"
import type { E2BAccess } from "../sandbox/create.js"
import { quote, sh } from "../sync/remote.js"
import type { BoxRecord } from "./registry.js"

export const PORT = 4096
const HEALTH_TIMEOUT_MS = 90_000
Expand All @@ -20,37 +22,81 @@ export async function ensureOpencode(sandbox: Sandbox): Promise<void> {
}
}

/** Start `opencode2 serve` in `root` and wait until it answers. Resolves with the public URL. */
/**
* Start OpenCode as the box's background service and wait until its API answers.
* Resolves with the public URL. It must be the service, not `opencode serve`:
* `opencode pair` only makes sign-in links for the service.
*/
export async function startServer(
sandbox: Sandbox,
root: string,
password: string,
env: Record<string, string>,
): Promise<string> {
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 settings = [
"hostname 0.0.0.0",
`port ${PORT}`,
'password "$OPENCODE_E2B_PASSWORD"',
...Object.entries(env).map(([key, value]) => `env ${key} ${quote(value)}`),
]
await sh(
sandbox,
[
...settings.map((setting) => `opencode2 service set ${setting} >/dev/null`),
`cd ${quote(root)}`,
"opencode2 service start >/dev/null",
].join(" && "),
{ OPENCODE_E2B_PASSWORD: password },
)
const url = `https://${sandbox.getHost(PORT)}`
await waitHealthy(url)
await waitHealthy(url, password)
await openProject(url, password, root)
return url
}

export async function waitHealthy(url: string): Promise<void> {
/** Wait until the API answers with the password. The web page alone answers before the API is ready. */
export async function waitHealthy(url: string, password: string): Promise<void> {
const deadline = Date.now() + HEALTH_TIMEOUT_MS
while (Date.now() < deadline) {
const response = await fetch(`${url}/global/health`).catch(() => undefined)
const response = await fetch(`${url}/api/info`, { headers: authHeader(password) }).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)`,
`OpenCode in the box did not start within ${HEALTH_TIMEOUT_MS / 1000} s (check with: opencode2 service status)`,
)
}

/**
* A one-time link that signs a browser or the OpenCode app in to the box. It works once
* and expires in 5 minutes. Wakes a paused box first.
*/
export async function webLink(record: BoxRecord, access: E2BAccess): Promise<string> {
const sandbox = await Sandbox.connect(record.sandboxId, access)
await waitHealthy(record.url, record.password)
const link = parsePairLink(await sh(sandbox, `opencode2 pair --url ${quote(record.url)}`))
if (!link) {
throw new Error("OpenCode in the box did not print a sign-in link")
}
return link
}

/** The sign-in link in `opencode pair` output, which also holds a QR code. */
export function parsePairLink(out: string): string | undefined {
return /https:\/\/\S+\/auth\/connect\/\S+/.exec(out)?.[0]
}

/** The web UI lists the folders the server has opened. Open the project once, so it is one click away. */
async function openProject(url: string, password: string, root: string): Promise<void> {
const query = new URLSearchParams({ "location[directory]": root })
const response = await fetch(`${url}/api/location?${query.toString()}`, { headers: authHeader(password) })
if (!response.ok) {
throw new Error(`OpenCode in the box could not open ${root}: HTTP ${response.status}`)
}
}

function authHeader(password: string) {
return { authorization: `Basic ${Buffer.from(`opencode:${password}`).toString("base64")}` }
}
12 changes: 11 additions & 1 deletion src/v2/box/up.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ export interface UpRequest {
template: string
/** How long the box runs before E2B pauses it. Agents work without traffic from here. */
lifetimeMs: number
/** `provider/model` for the box's sessions. Used when that provider has a stored key. */
model?: string
access: E2BAccess
network?: Network
progress: (step: string) => void
Expand Down Expand Up @@ -55,7 +57,10 @@ export async function upBox(request: UpRequest): Promise<BoxRecord> {
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 }),
OPENCODE_CONFIG_CONTENT: JSON.stringify({
enabled_providers: providers,
...(usableModel(request.model, providers) ? { model: request.model } : {}),
}),
})
const record: BoxRecord = {
name,
Expand Down Expand Up @@ -101,3 +106,8 @@ async function headCommit(root: string): Promise<string | undefined> {
() => undefined,
)
}

/** A model the box can run: its provider has a stored key. */
export function usableModel(model: string | undefined, providers: readonly string[]): boolean {
return model !== undefined && providers.includes(model.split("/")[0] ?? "")
}
20 changes: 17 additions & 3 deletions src/v2/cli/box.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@ 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 { openInBrowser } from "../box/local.js"
import { webLink } from "../box/server.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"])
const ACTIONS = new Set(["up", "open", "attach", "pull", "list", "stop", "kill"])

export async function boxCommand(args: string[]): Promise<number> {
const { values, positionals } = parseArgs({
Expand All @@ -20,6 +22,7 @@ export async function boxCommand(args: string[]): Promise<number> {
hours: { type: "string", default: "1" },
domain: { type: "string" },
attach: { type: "boolean", default: false },
model: { type: "string" },
},
})
const [action, given, ...extra] = positionals
Expand Down Expand Up @@ -53,6 +56,7 @@ export async function boxCommand(args: string[]): Promise<number> {
name: await defaultBoxName(root, given),
template: values.template,
lifetimeMs: hours * 3_600_000,
model: values.model,
access,
progress: (step) => {
console.error(`[e2b] ${step}`)
Expand All @@ -62,7 +66,9 @@ export async function boxCommand(args: string[]): Promise<number> {
if (values.attach) {
return attachBox(record, recordAccess(record, access))
}
console.log(`Attach with: opencode-e2b box attach ${record.name}`)
const link = await webLink(record, recordAccess(record, access))
console.log(`Open it in the browser or the OpenCode app (one-time link, 5 minutes):\n ${link}`)
console.log(`Or open the TUI on it: opencode-e2b box attach ${record.name}`)
return 0
}

Expand All @@ -71,13 +77,21 @@ export async function boxCommand(args: string[]): Promise<number> {
if (action === "attach") {
return attachBox(record, boxAccess)
}
if (action === "open") {
const link = await webLink(record, boxAccess)
console.log(`One-time sign-in link for box "${record.name}" (5 minutes):\n ${link}`)
if (process.stdout.isTTY) {
openInBrowser(link)
}
return 0
}
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.`)
console.log(`Box "${record.name}" is paused. Open or attach wakes it.`)
return 0
}
await killBox(record, boxAccess)
Expand Down
7 changes: 4 additions & 3 deletions src/v2/cli/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
/**
* 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 box up|open|attach|pull|list|stop|kill [name]
* opencode-e2b secrets set|list|remove [provider]
*/

Expand All @@ -13,12 +13,13 @@ import { secretsCommand } from "./secrets.js"
import { UsageError } from "./usage-error.js"

const USAGE = `Usage:
opencode-e2b box up [name] [--template <name>] [--hours <n>] [--attach]
opencode-e2b box up [name] [--template <name>] [--hours <n>] [--model <provider/model>] [--attach]
Start a box with this project and OpenCode in it
opencode-e2b box open [name] Open a box in the browser (prints a one-time sign-in link)
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/<name>
opencode-e2b box list The boxes this machine started
opencode-e2b box stop [name] Pause a box. Attach wakes it.
opencode-e2b box stop [name] Pause a box. Open or attach wakes it.
opencode-e2b box kill [name] Delete a box. Pull first.
opencode-e2b secrets set <provider> Store a model key as an E2B secret
opencode-e2b secrets list The providers with a stored key
Expand Down
Loading
Loading