@nodesandbox-ai/plugin-claude

Claude Code

Register the claude terminal command in one sandbox. The plugin owns lazy downloads, credential restoration, and login/logout events.

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

Run Claude Code

claude.ts
import { Sandbox } from '@nodesandbox-ai/client';
import { claudeCodePlugin } from '@nodesandbox-ai/plugin-claude';

const claude = claudeCodePlugin({
  onReady: () => console.log('Claude Code is prepared'),
  onError: error => console.error(error),
});
const sandbox = await Sandbox.create({
  apiKey: 'ns_live_…',
  source: { type: 'files', files: {} },
  plugins: [claude],
});

const terminal = sandbox.terminals.create({ startCommand: 'claude' });
terminal.onOutput(chunk => console.log(chunk));
await terminal.open();

Opening the terminal launches the CLI and prepares it if needed. Connect keystrokes with terminal.write() and size changes with terminal.resize(). See the terminal API for cleanup.

To prepare without launching, call await sandbox.plugins.get(claude).prepare(). All shared agent options and instance methods are supported.

To use Elements' agent panel, pass claudeCodePlugin(...) to Sandbox.plugins and add a sidenav button for it: { id: 'claude', label: 'Claude Code', icon: <ClaudeCodeIcon />, render: <SandboxTerminal command="claude" /> } in sidenavItems. Each click opens a tab running the claude command, with input, resizing, mobile tabs, and cleanup handled by Elements. See the integration example.

Credentials

credentials is the serialized Claude .credentials.json content, or null. Supply a value or an async loader; onCredentialsChanged reports login, refresh, and logout updates.

credentials.ts
const claude = claudeCodePlugin({
  credentials: async signal => {
    const response = await fetch('/api/agents/claude/credentials', { signal });
    if (!response.ok) throw new Error('Unable to load Claude credentials');
    const { credentials } = await response.json();
    return credentials; // JSON string or null
  },
  onCredentialsChanged: credentials => {
    void fetch('/api/agents/claude/credentials', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ credentials }),
    }).then(response => {
      if (!response.ok) throw new Error('Unable to save Claude credentials');
    }).catch(console.error);
  },
});

These application endpoints are yours to implement and authenticate. Preferences and project-scoped transcripts retain the plugin's local persistence; account credentials are returned to your callback.

Project session history

Set a stable projectId on Sandbox.create() or the React/Elements sandbox. Claude's transcripts are saved in IndexedDB on the runtime origin and restored before launch, isolated from other projects.

sessions.ts
const sandbox = await Sandbox.create({
  ...options,
  projectId: 'my-project',
  plugins: [claudeCodePlugin()],
});

Changes save while the agent is running and when its command exits. Use claude --resume or /resume to reopen a conversation. Deleted transcripts stay deleted, and clearSession() only clears login credentials.

History is browser-local, not synced to Supabase or other devices. Without a project ID it remains only in the current sandbox. Clearing site data removes saved history; an abrupt page close may lose writes that have not finished saving.

session-events.ts
claudeCodePlugin({
  onSessionChange: ({ agent, projectId }) => {
    // Refresh cached history after a successful IndexedDB save.
  },
  onCurrentSessionChange: ({ agent, projectId, sessionId }) => {
    // Update the selected conversation. null means cleared/exited.
  },
});

onSessionChange is a debounced invalidation after persisted changes or deletions, with no transcript payload. It requires a project ID and does not fire on restore or failed saves. onCurrentSessionChange observes Claude's SessionStart/SessionEnd hooks, ignores subagents, and clears on command exit. It works without a project ID. User hooks are preserved; disabling Claude hooks prevents selection notifications.

Callbacks are optional, run in your application, and are not awaited. Errors are reported through onError without interrupting the agent.

Anthropic HTTP proxy

Set anthropicRelay to use your own streaming HTTP endpoint. Omit it to use the runtime host's existing proxy. Claude does not require a WebSocket relay.

proxy.ts
const claude = claudeCodePlugin({
  anthropicRelay: {
    url: 'https://your-app.example/api/anthropic-proxy',
    headers: { 'X-Relay-Authorization': 'Bearer user-session-token' },
  },
});

The proxy receives the original destination in its url query parameter, with the method, body, and provider headers. It must stream responses and support Anthropic API and Claude OAuth endpoints. Your proxy chooses how to authenticate requests; no separate authorization callback is required.

Provider headers take precedence on case-insensitive collisions. Use a dedicated relay header and consume it before forwarding upstream. Cross-origin proxies must allow the runtime origin, headers, methods, and OPTIONS requests. Relay settings apply to Claude and its child processes.

CLI assets

APIBehavior
bundleUrl?: stringURL of a NodeSandbox-compatible Claude JavaScript bundle.
assetsUrl?: stringURL of that build’s matching embedded-assets JSON. Override both URLs when switching builds.
assets.ts
claudeCodePlugin({
  bundleUrl: 'https://cdn.example/claude/release-id/cli.js',
  assetsUrl: 'https://cdn.example/claude/release-id/assets.json',
});

Omitted URLs use the package's pinned artifacts. Compatible CLI updates need no new plugin release; a runtime compatibility change may. New URLs take effect in a new sandbox. The older proxyPath option remains for compatibility; use anthropicRelay for new integrations.

Settings and MCP

Pass raw files to the plugin to inject settings, skills, and MCP configuration after installation and before launch. Project files can also come from your sandbox source.

settings.ts
const claude = claudeCodePlugin({
  files: {
    '/home/user/.claude/settings.json': JSON.stringify(claudeSettings),
    '/.mcp.json': JSON.stringify(mcpConfig),
    '/CLAUDE.md': 'Project instructions',
  },
});

claudeSettings is your configuration object for the selected Claude build. Use the credential API for account secrets. Project files may be included when you save a project.