Optional capabilities

Plugins

Keep the sandbox focused on files, shell commands, Node/npm, and previews. Add agents, custom commands, or other runtime capabilities to each instance through plugins.

$npm i @nodesandbox-ai/client @nodesandbox-ai/plugin-opencode

Add a plugin

Sandbox.create() accepts a plugins array, which defaults to empty. Installing a plugin registers its commands; running a command downloads and prepares its assets on demand.

sandbox.ts
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],
});

// Dependencies are installed. Opening this terminal launches OpenCode.
const terminal = sandbox.terminals.create({ startCommand: 'opencode' });
const output = terminal.onOutput(chunk => console.log(chunk));
await terminal.open();
// Connect your terminal UI's input to terminal.write(data).
// When closing the panel: output.dispose(); await terminal.kill();
APIBehavior
@nodesandbox-ai/plugin-opencodeopencodePlugin(options?) registers opencode.
@nodesandbox-ai/plugin-claudeclaudeCodePlugin(options?) registers claude.
@nodesandbox-ai/plugin-codexcodexPlugin(options) registers codex; configure its relay host and authorization callback.
@nodesandbox-ai/plugin-pipiPlugin(options?) registers pi and lazily installs its pinned npm release.
@nodesandbox-ai/plugin-playwrightplaywrightPlugin(options?) registers playwright and playwright-cli, and offers playwright mcp to Claude Code, OpenCode and Pi.

The generic plugin shape is { command, files?, interactive?, mcpServers? }, with plain just-bash commands accepted as shorthand. The agent factories return interactive wrappers. See Develop a plugin for custom commands, static files, and an interactive CLI example.

Add agents to Elements

Elements can manage the terminal UI for registered agents. Pass the same definitions to Sandbox.plugins and add a sidenav button whose command launches each agent. You do not need to open terminals manually.

agent-workspace.tsx
'use client';
import { useMemo } from 'react';
import '@nodesandbox-ai/elements/styles.css';
import { OpenCodeIcon, Sandbox, SandboxTerminal, type SandboxProps } from '@nodesandbox-ai/elements';
import { opencodePlugin } from '@nodesandbox-ai/plugin-opencode';

const sidenavItems = [
  { id: 'opencode', label: 'OpenCode', icon: <OpenCodeIcon />, render: <SandboxTerminal command="opencode" /> },
];

export function Workspace({ apiKey, source }: Pick<SandboxProps, 'apiKey' | 'source'>) {
  const plugins = useMemo(() => [opencodePlugin()], []);
  return (
    <Sandbox
      apiKey={apiKey}
      source={source}
      plugins={plugins}
      sidenavItems={sidenavItems}
      style={{ height: 640 }}
    />
  );
}

On desktop, the buttons appear in a sidenav beside a resizable panel; registering a plugin adds no button by itself. Below 720px of embed width, tabs slide between the selected agent and Preview, and a menu switches agents. Each click opens a tab with its own session, and sessions remain mounted while hidden.

The Elements agent guide includes installation and the agent plugins, plus composing your own shell and themes. If you use the workbench IDE, register compute plugins through runtimePlugins; see the prop mapping.

Loading and readiness

APIBehavior
Sandbox onReady(sandbox)The filesystem, commands, and terminals are usable. Project dependencies may still be installing. The callback is not awaited.
Sandbox.create() resolvesDependency installation and framework setup have finished. Start project-dependent commands here.
Plugin onReady()That plugin has finished preparing its assets and credentials. It has not launched a program.
sandbox.start() resolvesThe preview HTTP listener is available. This is separate from plugin readiness.

Agent plugins are lazy by default. The first command or an explicit prepare() loads them. Set preload: true to download and restore credentials after shell readiness, alongside dependency installation.

preload.ts
const opencode = opencodePlugin({ preload: true });
const sandbox = await Sandbox.create({
  apiKey,
  source,
  plugins: [opencode],
});
// Preloading never launches the agent and does not hold up npm install.
// Launch after create() when the agent needs installed project dependencies.
const terminal = sandbox.terminals.create({ startCommand: 'opencode' });
await terminal.open();

A project dependency installation failure rejects create() and disposes the early sandbox handle. Disposing a sandbox aborts plugin work and closes its processes and watchers.

Shared agent options

Claude Code, OpenCode, Codex, and Pi all accept these options. Their package guides cover relay configuration and asset formats.

APIBehavior
preload?: booleanDefault false. Prepare in parallel with installation without launching the CLI.
credentials?A JSON string, null, or an async (signal: AbortSignal) => Promise<string | null> loader. Read lazily during preparation.
onReady?: () => voidCalled when preparation completes.
onCredentialsChanged?Receives the new credential JSON string, or null on logout. Persist it through your application.
onError?: (error: Error) => voidReceives preparation errors and errors emitted by the plugin.
files?: PluginFilesText, Uint8Array, or lazy functions returning either value. Resolved and written at absolute sandbox paths after installation and before the first command.
bundleUrl?: stringOverride the pinned CLI artifact. The required artifact format differs by agent.

Claude Code and OpenCode additionally support onSessionChange and onCurrentSessionChange. These callbacks are separate from credentials and are not yet implemented by Codex or Pi.

APIBehavior
onSessionChange({ agent, projectId })Debounced history invalidation after successful persistence: Claude files in IndexedDB, OpenCode commits in OPFS. Requires a project ID; no transcript payload and no event on restore or failed saves.
onCurrentSessionChange({ agent, projectId, sessionId })Selected conversation changed. sessionId is null on clear/exit; projectId is optional. Repeated IDs are deduplicated.

Plugin instances

Keep the plugin definition to retrieve a typed instance. Definitions are reusable; every sandbox owns independent runtime state. The plugin set is supplied when creating the sandbox.

plugin-instance.ts
const agent = sandbox.plugins.get(opencode);
await agent.prepare(); // Download and restore without launching.
await agent.setCredentials(credentialsJson); // string | null
await agent.clearSession(); // Clear credentials and emit logout.

console.log(sandbox.plugins.has('opencode'));

get(definition) preserves the instance type; get(id) returns unknown. Looking up an uninstalled plugin throws. setCredentials(null) clears the runtime credential; clearSession() also emits onCredentialsChanged(null).

Credentials and settings

Each agent owns its credential format and lifecycle. Supply credentials through the plugin and save changes in your app's account storage. Credential files live outside saved project files. Browser-visible relay headers should contain user/session credentials; keep server secrets on your backend.

Project configuration, skills, and MCP settings remain ordinary files. Inject agent-specific configuration through the factory's files option. Project files can also come from source or sandbox.requestFileSystem(). Use the format expected by the selected CLI build. Codex project files use the same sandbox filesystem, while its guest configuration is managed by the plugin; see Codex runtime requirements.

agent-files.ts
const opencode = opencodePlugin({
  files: {
    '/AGENTS.md': 'Run the project tests after changing code.',
    '/opencode.json': async signal => {
      const response = await fetch('/api/agents/opencode/config', { signal });
      if (!response.ok) throw new Error('Unable to load OpenCode settings');
      return response.text();
    },
  },
});

The configuration endpoint in this example belongs to your application. File loaders run in the embedding app during preparation and receive an abort signal for cancellation.

Use files to inject raw configuration, skills, or themes before the first command. Files are written once per prepared sandbox and may overwrite the supplied paths. There is no separate settings or theme schema. Terminal appearance belongs to your terminal UI; an agent's own TUI theme belongs to its configuration. Agent download URLs can change independently of the npm plugin version when the build is compatible.

Execution model

Plugin callbacks and lifecycle state live in the embedding application. The runtime host supplies generic filesystem, shell, and process capabilities. Claude, OpenCode, and Pi execute Node inside the host; Codex owns its Wasmer process in the application.

Install plugins as ordinary npm packages. The client and host must both support the command callback bridge; no plugin-specific host build is needed. See React integration and Elements integration for provider and agent UI examples.