@kaiz11/sandbox-client
v0.0.3
Published
Client for sandbox-api - container orchestration for AI agents
Readme
@kaiz11/sandbox-client
Type-safe client for sandbox-api - container orchestration for AI agents (Claude Code, OpenCode).
Installation
pnpm add @kaiz11/sandbox-clientFor stream parsing (optional):
pnpm add @hikari/utilsUsage
Public API (Authenticated)
The public API requires JWT authentication via Stack platform.
import { createSandboxClient } from "@kaiz11/sandbox-client";
const client = createSandboxClient({
baseUrl: "https://sandbox-api.zenku.app/trpc",
tenantId: "my-tenant",
accessToken: "eyJ...", // JWT from Stack
});
// Create a container
const { containerId } = await client.container.create.mutate({
type: "standard",
});
// Run a command synchronously
const result = await client.exec.run.mutate({
containerId,
command: "echo hello world",
});
console.log(result.stdout); // "hello world\n"
// Clean up
await client.container.remove.mutate({ containerId });Admin API (Internal Only)
The admin API has no authentication - access is controlled via network isolation (Tailscale).
import { createAdminClient } from "@kaiz11/sandbox-client";
const admin = createAdminClient({
baseUrl: "http://container-platform-standalone:3101/trpc", // Tailscale
});
// Create container (requires accountId/userId)
const { containerId } = await admin.container.create.mutate({
accountId: "test-account",
userId: "test-user",
type: "standard",
});
// Run command (no ownership check)
const result = await admin.exec.run.mutate({
containerId,
command: "whoami",
});
// List all containers
const containers = await admin.container.list.query();Streaming (Simple API)
High-level streaming with automatic Centrifugo connection and optional parsing.
import { createSandboxClient, streamClaude } from "@kaiz11/sandbox-client";
import { ClaudeStreamParser } from "@hikari/utils";
import { WebSocket } from "ws"; // Required for Node.js
const client = createSandboxClient({ baseUrl, tenantId, accessToken });
// Stream with parsed output
for await (const chunk of streamClaude(
client,
{ containerId, prompt: "Create hello.py" },
{ websocket: WebSocket, parser: new ClaudeStreamParser() }
)) {
process.stdout.write(chunk.text); // Formatted output
}
// Or collect everything at once
import { runClaudeStream } from "@kaiz11/sandbox-client";
const result = await runClaudeStream(
client,
{ containerId, prompt: "Explain this code" },
{
websocket: WebSocket,
parser: new ClaudeStreamParser(),
onOutput: (chunk) => process.stdout.write(chunk.text),
}
);
console.log(`Exit: ${result.exitCode}`);
console.log(`Cost: $${result.metadata?.total_cost_usd}`);OpenCode Streaming
import { streamOpenCode, runOpenCodeStream } from "@kaiz11/sandbox-client";
import { OpenCodeStreamParser } from "@hikari/utils";
// Stream
for await (const chunk of streamOpenCode(
client,
{ containerId, prompt: "List files", model: "opencode/glm-4.7-free" },
{ websocket: WebSocket, parser: new OpenCodeStreamParser() }
)) {
process.stdout.write(chunk.text);
}
// Or collect
const result = await runOpenCodeStream(client, { containerId, prompt }, options);Shell Command Streaming
import { streamExec, runExecStream } from "@kaiz11/sandbox-client";
// Stream raw output
for await (const chunk of streamExec(
client,
{ containerId, command: "for i in 1 2 3; do echo $i; sleep 1; done" },
{ websocket: WebSocket }
)) {
process.stdout.write(chunk.raw);
}
// Or collect
const { raw, exitCode } = await runExecStream(client, { containerId, command }, options);Low-Level Centrifugo Access
For advanced use cases, use the low-level connectCentrifugo directly:
import { connectCentrifugo, extractOutput } from "@kaiz11/sandbox-client";
// Manual stream setup
const stream = await client.claude.start.mutate({ containerId, prompt });
for await (const event of connectCentrifugo({
url: stream.centrifugoUrl!,
token: stream.centrifugoToken!,
channel: stream.channel,
websocket: WebSocket,
})) {
// Raw StreamEvent: { type, streamId, containerId, data?, exitCode?, error?, timestamp }
if (event.type === "output") process.stdout.write(event.data ?? "");
if (event.type === "exit") console.log(`Exit: ${event.exitCode}`);
}Session Management
Download and upload Claude Code sessions to persist/restore conversations.
import { downloadSession, uploadSession } from "@kaiz11/sandbox-client";
// Download session from container
const session = await downloadSession(
{ baseUrl: "https://sandbox-api.zenku.app", tenantId, accessToken },
{ containerId, sessionId: "my-session-id" }
);
// Save to file (Node.js)
import fs from "fs";
fs.writeFileSync(`${session.sessionId}.jsonl.gz`, Buffer.from(session.data));
// Upload session to different container (resume conversation)
await uploadSession(
{ baseUrl: "https://sandbox-api.zenku.app", tenantId, accessToken },
{
containerId: newContainerId,
sessionId: session.sessionId,
data: session.data,
}
);
// Then use claude.start with resumeSessionId
await client.claude.start.mutate({
containerId: newContainerId,
prompt: "Continue where we left off",
resumeSessionId: session.sessionId,
});API Reference
Clients
| Factory | Description |
| ------------------------------ | ------------------------------------------ |
| createSandboxClient(options) | Public API client (requires auth) |
| createAdminClient(options) | Admin API client (no auth, Tailscale only) |
Streaming Helpers (Recommended)
| Function | Description |
| --------------------- | --------------------------------------------- |
| streamClaude() | AsyncGenerator for Claude with auto-connect |
| runClaudeStream() | Collect Claude output into result object |
| streamOpenCode() | AsyncGenerator for OpenCode with auto-connect |
| runOpenCodeStream() | Collect OpenCode output into result object |
| streamExec() | AsyncGenerator for shell commands |
| runExecStream() | Collect shell output into result object |
Low-Level Centrifugo
| Function | Description |
| ------------------------------ | ---------------------------------------- |
| connectCentrifugo(options) | AsyncGenerator yielding raw StreamEvents |
| collectStreamEvents(options) | Collect all events into array |
| extractOutput(events) | Extract stdout and exitCode from events |
Session Helpers
| Function | Description |
| ----------------------- | ---------------------------------------------- |
| downloadSession(opts) | Download session.jsonl.gz from container |
| uploadSession(opts) | Upload session.jsonl.gz to container (restore) |
Container Types
standard- Basic sandbox with Claude Codeopencode- OpenCode AI agentopencode-ohmyoc-*- OpenCode with Oh-My-OpenCodeopencode-serve-*- OpenCode with serve mode
Stream Events
interface StreamEvent {
type: "start" | "output" | "exit" | "error";
streamId: string;
containerId: string;
data?: string; // For "output"
exitCode?: number; // For "exit"
error?: string; // For "error"
timestamp: number;
}Stream Parsers
Use parsers from @hikari/utils to format raw JSONL output:
| Parser | Description |
| ---------------------- | ---------------------------------- |
| ClaudeStreamParser | Parse Claude Code streaming output |
| OpenCodeStreamParser | Parse OpenCode streaming output |
Both parsers extend BufferedJsonParser and handle partial chunks, tool calls, and metadata extraction.
Shared Types
This package exports Zod schemas that are shared between sandbox-client and sandbox-api. This ensures type consistency across the API boundary.
// Import types
import type { ContainerInfo, StreamEvent, ExecResult } from "@kaiz11/sandbox-client";
// Import Zod schemas (for validation or building on top of)
import {
ContainerInfoSchema,
StreamEventSchema,
CreateContainerInputSchema,
} from "@kaiz11/sandbox-client/types";Available schemas:
| Schema | Description |
| --------------------------------- | ------------------------------- |
| ContainerTypeSchema | Container type enum |
| ContainerInfoSchema | Container info response |
| CreateContainerInputSchema | Create container input (public) |
| AdminCreateContainerInputSchema | Create container input (admin) |
| CreateContainerResponseSchema | Create container response |
| ExecResultSchema | Command execution result |
| StreamStartResponseSchema | Stream start response |
| StreamEventSchema | Centrifugo stream event |
| StartClaudeInputSchema | Claude start input |
| StartOpenCodeInputSchema | OpenCode start input |
Environment
| Environment | Public URL | Admin URL |
| ----------- | ------------------------------------ | ------------------------------------------------ |
| Production | https://sandbox-api.zenku.app/trpc | http://container-platform-standalone:3101/trpc |
| Development | https://sandbox-api.zenku.dev/trpc | http://container-platform-standalone:3102/trpc |
License
Copyright © 2026 Kai Zhao. All rights reserved.
This software is proprietary and confidential. Unauthorized copying, distribution, modification, or use of this software, via any medium, is strictly prohibited without prior written permission from the copyright holder.
