@nodesandbox-ai/plugin-opencode
OpenCode
Register the opencode terminal command, restore its provider credentials, and load its CLI pack on demand.
npm i @nodesandbox-ai/client @nodesandbox-ai/plugin-opencodeRun OpenCode
import { Sandbox } from '@nodesandbox-ai/client';
import { opencodePlugin } from '@nodesandbox-ai/plugin-opencode';
const opencode = opencodePlugin({
onReady: () => console.log('OpenCode is prepared'),
onError: error => console.error(error),
});
const sandbox = await Sandbox.create({
apiKey: 'ns_live_…',
source: { type: 'files', files: {} },
plugins: [opencode],
});
const terminal = sandbox.terminals.create({ startCommand: 'opencode' });
terminal.onOutput(chunk => console.log(chunk));
await terminal.open();The command downloads the pack on first use. preload: true prepares it alongside project dependency installation; it never starts OpenCode or blocks npm installation. See the terminal API to attach input and resize events.
For a ready-made terminal UI, pass opencodePlugin(...) to Sandbox.plugins and add a { id: 'opencode', label: 'OpenCode', icon: <OpenCodeIcon />, render: <SandboxTerminal command="opencode" /> } button to sidenavItems. Elements gives it a persistent agent panel and mobile tabs. Follow the Elements integration guide.
Credentials and lifecycle
Credentials are OpenCode's logins as opencode auth export prints them (a JSON list, secrets included), or null. OpenCode 1's auth.json format is still accepted and converted. Before a command, OpenCode's logins are made to match yours; a login made inside OpenCode (/connect, a token refresh, a logout) returns to your app through onCredentialsChanged. The sync runs only when you pass credentials or onCredentialsChanged. Model and TUI preferences are persisted locally.
const opencode = opencodePlugin({
credentials: async signal => {
const response = await fetch('/api/agents/opencode/credentials', { signal });
if (!response.ok) throw new Error('Unable to load OpenCode credentials');
const { credentials } = await response.json();
return credentials; // the `opencode auth export` JSON string, or null
},
onCredentialsChanged: credentials => {
// Save through your authenticated account-storage API.
void saveOpenCodeCredentials(credentials).catch(console.error);
},
});Implement the endpoint and saveOpenCodeCredentials in your application. Use sandbox.plugins.get(opencode) for prepare(), setCredentials(), and clearSession(). See shared agent options for callback signatures.
Project session history
Set a stable projectId on Sandbox.create() or the React/Elements sandbox. Project sources already supply it. OpenCode opens project-scoped databases directly with SQLite WASM in the browser's Origin Private File System (OPFS) on the runtime origin. Each commit writes changed pages and a rollback journal; there are no database snapshots or copies through the sandbox filesystem.
const sandbox = await Sandbox.create({
...options,
projectId: 'my-project',
plugins: [opencodePlugin()],
});Custom packs must include the current SQLite OPFS shim and assets. Existing IndexedDB history is not migrated. Use /sessions or opencode --session <id> to resume. Model/TUI preferences use localStorage; credentials remain separate.
History is browser-local, not synced to Supabase or other devices. Without a project ID, databases remain in memory for the current process. Clearing site data removes persisted history. OPFS and a cross-origin-isolated runtime worker are required; unavailable storage produces a startup error. The runtime host already supplies the necessary isolation headers. clearSession() only clears login credentials.
opencodePlugin({
onSessionChange: ({ agent, projectId }) => {
// Refresh cached history after a successful SQLite commit.
},
onCurrentSessionChange: ({ agent, projectId, sessionId }) => {
// Update the selected conversation. null means home/exited.
},
});onSessionChange is a debounced invalidation after persisted changes or deletions, with no database payload. It requires a project ID and does not fire on reads, rollbacks, or failed commits. onCurrentSessionChange works without a project ID and observes the TUI's selected conversation, including resume without sending a message. It clears on home/exit. The headless opencode run command reports the top-level session it starts. Both come from a small OpenCode plugin the package enables in opencode.json.
Callbacks are optional, run in your application, and are not awaited. Errors are reported through onError without interrupting the agent. Existing settings/plugins are preserved; custom packs must support OpenCode's 1.x TUI/server plugin APIs. Disabling the injected TUI/server hook disables current-session notifications; history notifications come from SQLite commits.
Provider HTTP proxy
opencodePlugin({
opencodeRelay: {
url: 'https://your-app.example/api/model-proxy',
headers: { 'X-Relay-Authorization': 'Bearer user-session-token' },
},
});The endpoint receives the original destination in the url query parameter and forwards the method, body, and provider headers. It must stream responses and support the providers you enable, including their login endpoints. Omit opencodeRelay to retain the runtime's networking.
Your proxy decides how to authenticate the optional headers. Provider headers take precedence on collisions, so use a dedicated relay header and consume it before forwarding upstream. Cross-origin proxies must allow the runtime origin, methods, headers, and OPTIONS requests. The pack download still uses bundleUrl.
CLI bundle
bundleUrl?: stringURL of a NodeSandbox-compatible pack JSON containing the CLI and its dependencies. Omit to use the pinned pack.opencodePlugin({
bundleUrl: 'https://cdn.example/opencode/release-id/opencode.pack.json',
});The bundle is a pack JSON, not a native executable. A compatible build can be selected without republishing the plugin. Create a new sandbox to load the new pack.
Settings and themes
Use files for raw configuration written after installation and before launch. MCP and theme configuration follow the schema of your chosen OpenCode build. Project files can also come from your sandbox source.
const opencode = opencodePlugin({
files: {
'/opencode.json': JSON.stringify(opencodeConfig),
'/AGENTS.md': 'Project instructions',
},
});opencodeConfig is your OpenCode configuration object. Configure OpenCode's TUI appearance through its files; configure the surrounding terminal with your terminal component. The plugin has no separate theme or settings option.
OpenCode's TUI settings default to the nodesandbox-neutral theme, which matches Elements (#0a0a0a in dark mode, #ffffff in light mode), with the session sidebar and the tab strip hidden. They are written to OpenCode's settings file, ~/.config/opencode/cli.json, unless the sandbox already has one or you supply your own. To customize an instance, supply its own theme file and select it in cli.json; your file replaces all the defaults:
const opencode = opencodePlugin({
files: {
'/home/user/.config/opencode/themes/my-app.json': async signal => {
const response = await fetch('/api/agents/opencode/theme', { signal });
if (!response.ok) throw new Error('Unable to load theme');
return response.text();
},
'/home/user/.config/opencode/cli.json': JSON.stringify({
$schema: 'https://opencode.ai/v2/cli.json',
theme: { name: 'my-app' },
session: { sidebar: 'hide' },
tabs: { mode: 'off' },
}),
},
});Your endpoint should return a complete OpenCode theme JSON object with light and dark variants. You can also pass JSON.stringify(myTheme) directly. Merge any other TUI settings you need into the supplied cli.json; leave out session.sidebar or tabs.mode to get OpenCode's own auto.
Pass your current color mode to Sandbox.theme or the Elements provider. OpenCode follows live mode changes without restarting, unless its mode is locked inside the CLI. These files are applied during preparation; they do not need to be rewritten when switching modes.