import { Sandbox } from 'e2b'
import { createOpencodeClient } from '@opencode-ai/sdk'
const sandbox = await Sandbox.betaCreate('opencode', {
envs: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY },
autoPause: true,
timeoutMs: 10 * 60 * 1000,
})
// Start the OpenCode server
sandbox.commands.run('opencode serve --hostname 0.0.0.0 --port 4096', {
background: true,
})
// Wait for the server to be ready
const host = sandbox.getHost(4096)
const baseUrl = `https://${host}`
while (true) {
try {
await fetch(`${baseUrl}/global/health`)
break
} catch {
await new Promise((r) => setTimeout(r, 500))
}
}
// Connect to the server
const client = createOpencodeClient({
baseUrl,
})
// Create a session and send a prompt
const { data: session } = await client.session.create({
body: { title: 'E2B Session' },
})
const { data: result } = await client.session.prompt({
path: { id: session.id },
body: {
parts: [{ type: 'text', text: 'Create a hello world HTTP server in Go' }],
},
})
console.log(result)