@nodesandbox-ai/plugin
Develop a plugin
A compute plugin combines a just-bash command with optional files and terminal metadata. Its callback stays in your application and uses generic SDK capabilities to work with the sandbox.
npm i @nodesandbox-ai/client @nodesandbox-ai/pluginThe command contract
Return { command, files?, interactive? } from your package and pass it to Sandbox.create({ plugins: [...] }). Plain just-bash commands also work as shorthand. The helper exported by @nodesandbox-ai/plugin creates the same command shape without pulling the shell interpreter into your application.
command: CommandRequired just-bash command. command.name identifies the plugin and must be unique within the sandbox.files?: PluginFilesAbsolute VFS paths mapped to text, Uint8Array, or a lazy function returning either value. Written once before the first command invocation.interactive?: booleanDefault false. Marks a program that can take over terminal input and resizing.import { defineCommand, decodeBytesToUtf8 } from '@nodesandbox-ai/plugin';
export function upperPlugin() {
return {
command: defineCommand('upper', async (args, ctx) => ({
stdout: decodeBytesToUtf8(ctx.stdin).toUpperCase(),
stderr: '',
exitCode: 0,
})),
};
}import { Sandbox } from '@nodesandbox-ai/client';
import { upperPlugin } from './upper';
const sandbox = await Sandbox.create({ apiKey, plugins: [upperPlugin()] });
const result = await sandbox.runShell('echo "hello world" | upper');
console.log(result.stdout); // HELLO WORLDEach name must be unique within a sandbox. Command callbacks return a promise of { stdout, stderr, exitCode }. Keep plugin options in the factory closure; keep mutable state scoped to the sandbox.
Inject files
import { defineCommand, type SandboxPlugin } from '@nodesandbox-ai/plugin';
const hello = {
files: { '/opt/hello/message.txt': 'Hello world\n' },
command: defineCommand('hello', async (args, ctx) => ({
stdout: await ctx.fs.readFile('/opt/hello/message.txt'),
stderr: '',
exitCode: 0,
})),
} satisfies SandboxPlugin;const files = {
'/data/remote.txt': async () => (await fetch('https://example.com')).text(),
'/data/config.json': async (signal: AbortSignal) => {
const response = await fetch('/api/config', { signal });
if (!response.ok) throw new Error('Config download failed');
return response.text();
},
};The SDK snapshots literal contents and loader references when the sandbox is created. Loaders run lazily in the application, in parallel; they can return text or bytes, directly or through a promise. The optional signal argument cancels on sandbox disposal or a failure in the file batch. Pass it to fetch or other cancellable work.
All loader results must resolve and validate before the SDK creates parent directories and writes files. Concurrent invocations share the same load and write; cancelling one command stops only its wait. A failed batch is retried on the next invocation. A successful injection runs once per sandbox; subsequent commands preserve edits and deletions.
Generic files run before your command's installation code. If configuration must be written after installation, write it inside cached preparation with getPluginContext(ctx).writeFiles(...). The official agents' factory files options already use that ordering. Loading and finalization stay inside the command; sandbox disposal uses onDispose.
Commands and subcommands
One root command can dispatch subcommands such as supabase functions deploy and supabase db query. Pipes, redirects, working directories, environment variables, byte-string stdin, and exit codes follow just-bash conventions.
import { defineCommand, type ExecResult } from '@nodesandbox-ai/plugin';
type Options = {
execute(args: string[], signal?: AbortSignal): Promise<ExecResult>;
};
export function supabasePlugin(options: Options) {
return defineCommand('supabase', async (args, ctx) => {
if (!['functions', 'db'].includes(args[0])) {
return { stdout: '', stderr: 'Expected functions or db\n', exitCode: 2 };
}
return options.execute(args, ctx.signal);
});
}Application callbacks
The handler runs in the embedding application, so it can call your authenticated backend directly. No callback registration or code serialization is required.
const supabase = supabasePlugin({
async execute(args, signal) {
const response = await fetch('/api/supabase/execute', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ args }),
signal,
});
if (!response.ok) throw new Error('Supabase command failed');
return response.json();
},
});
const sandbox = await Sandbox.create({ apiKey, plugins: [supabase] });Your backend validates and authorizes the operation. ctx.signal is cancelled when the command or sandbox stops.
Terminal programs
Install inside the command handler, then await execution. Use cachePerSandbox to share in-flight and successful preparation without sharing state across sandboxes. Rejected preparations are removed from the cache so the next invocation can retry.
import {
defineCommand, cachePerSandbox, getPluginContext, runNode, awaitCommand,
} from '@nodesandbox-ai/plugin';
export function myCliPlugin(options: { bundleUrl: string }) {
const entry = '/opt/mycli/cli.js';
const install = cachePerSandbox(async sandbox => {
const response = await fetch(options.bundleUrl, {
signal: AbortSignal.any([sandbox.signal, AbortSignal.timeout(60_000)]),
});
if (!response.ok) throw new Error('CLI download failed');
const source = await response.text();
sandbox.signal.throwIfAborted();
await sandbox.writeFiles({ [entry]: source });
});
return {
interactive: true,
command: defineCommand('mycli', async (args, ctx) => {
await awaitCommand(ctx, install(getPluginContext(ctx)));
return await runNode(ctx, entry, args);
}),
};
}The installation uses the sandbox lifetime signal; cancelling one invocation stops its wait without cancelling another command's shared installation. Put command-finalization work in finally, and use sandbox.onDispose(cleanup) for persistent resources. Handle finalization failures separately so they do not replace the command's original result.
runNode connects the terminal directly to the Node process inside the host. For an application-owned engine, use runProcess(ctx, async size => process). The process supplies readable stdout/stderr, optional writable stdin, wait(), kill(), and optional resize(). The helper streams I/O and returns the standard command result on exit.
Sandbox capabilities
ctx.fsAsynchronous operations on the authoritative sandbox filesystem, including generated and private files. Use readdir for enumeration; synchronous getAllPaths is unavailable across the bridge.ctx.cwd / ctx.env / ctx.stdinWorking directory, environment Map, and just-bash byte-string stdin.ctx.exec(command, options)Execute a nested shell command. Include cwd and pass args separately for safe argument forwarding.getPluginContext(ctx)Access this sandbox’s stable identity, lifetime signal, projectId, and capabilities.sandbox.writeFiles(files)Resolve file loaders and batch-write strings or Uint8Arrays at absolute VFS paths, creating parent directories.sandbox.watch(path, callback)Subscribe to recursive filesystem changes; resolves to an unsubscribe function.sandbox.onDispose(cleanup)Register cleanup scoped to this sandbox.cachePerSandbox(factory)Cache a promise by sandbox identity; evict failures and release the entry on disposal.Definitions can be reused across sandboxes. Avoid global installation flags or shared credential variables. If callers can reset installed files, validate an installation marker and invalidate your cached state when it no longer matches the bundle.
Custom commands are also available from Elements' shell terminal when registered through Sandbox.plugins. To put one in the sidenav, add a sidenavItems button that renders it, render: <SandboxTerminal command="mycli" />; each click opens a tab with its own session. Setting interactive: true does not add a button by itself.
MCP servers
A plugin can offer the sandbox's coding agents an MCP server that runs as one of its commands over stdio. Declare it in mcpServers:
import { defineCommand, type SandboxPlugin } from '@nodesandbox-ai/plugin';
export const docsSearch = {
command: defineCommand('docs-search', run), // `docs-search mcp` serves MCP over stdio
mcpServers: {
'docs-search': {
command: 'docs-search',
args: ['mcp'],
description: 'Search this project\'s documentation',
timeout: 30_000,
},
},
} satisfies SandboxPlugin;command: stringThe command the agent starts, usually your plugin's own.args?: string[]Its arguments.env?: Record<string, string>Extra environment variables for it.description?: stringWhat it is for. Pi shows it to its model.timeout?: numberPer request, in milliseconds. Set it when a call can take longer than an agent's default, which is 5s in OpenCode.Names are letters, digits, _ and -, and must be unique across the sandbox's plugins; a duplicate fails Sandbox.create(). The official Claude Code, OpenCode and Pi plugins add every declared server to their agent's configuration before each run, and remove the ones they wrote once no plugin declares them. A user's own server of the same name is left alone. Codex is not configured. Every plugin can read the sandbox's servers from getPluginContext(ctx).mcpServers; an agent plugin of your own can write them with syncMcpServers() and MCP_SERVER_MARKER from @nodesandbox-ai/plugin. The Playwright plugin works this way.
Publish a package
Export your factory from an ordinary npm package and build it with your normal TypeScript tooling. Include its JavaScript and declarations in the published package. Consumers install it, import the factory, and add its returned plugin to plugins. The SandboxPlugin, SandboxPluginInput (wrapper or plain command), PluginFile, and PluginFiles types are exported from @nodesandbox-ai/plugin.
Large CLI artifacts can be downloaded from a configurable bundleUrl. The npm package owns preparation, credentials, settings, and cleanup. The runtime host provides generic capabilities and does not import individual plugins. There is no separate runtime adapter bundle, module URL, or custom packaging step.
The client and host both need the command callback bridge. Existing deployments using runtime-module descriptors must update together. See Plugins for the official agent options and instance methods.