@usesandbox/sdk
v0.0.15
Published
TypeScript SDK for interacting with the Sandbox API.
Downloads
64
Readme
@usesandbox/sdk
TypeScript SDK for interacting with the Sandbox API.
Installation
bun add @usesandbox/sdkUsage
Initialize the client
import { Sandbox } from "@usesandbox/sdk";
// Using environment variable SANDBOX_API_KEY
const client = Sandbox();
// Or provide API key explicitly
const client = Sandbox({
apiKey: "your-api-key",
baseUrl: "https://api.usesandbox.dev/api/v1", // optional
});Note: You can also use
createSandboxClient()if you prefer a more explicit function name.
Create a sandbox
const sandbox = await client.sandboxes.create({
template: "node-app",
});
console.log(sandbox.id); // Access sandbox ID
console.log(sandbox.data); // Access full sandbox dataList sandboxes
const sandboxes = await client.sandboxes.list();
for (const sandbox of sandboxes) {
console.log(sandbox.id, sandbox.data.name);
}Get sandbox by ID
const sandbox = await client.sandboxes.get("sandbox-id");
console.log(sandbox.data);Execute commands
const result = await sandbox.exec(["npm", "test"]);
console.log(result.stdout);
console.log(result.exitCode);Refresh sandbox info
const updatedData = await sandbox.refresh();
// or
const info = await sandbox.info(); // alias for refreshKill sandbox
await sandbox.kill();File Operations
Write files
// Write text file
await sandbox.files.write("/app/config.json", '{"key": "value"}');
// Write binary file
const imageData = new Uint8Array([0x89, 0x50, 0x4e, 0x47, ...]);
const result = await sandbox.files.write("/app/image.png", imageData);
console.log(`Wrote ${result.bytesWritten} bytes`);Read files
// Read text file (default UTF-8)
const config = await sandbox.files.read("/app/config.json");
console.log(JSON.parse(config));
// Read binary file
const imageBuffer = await sandbox.files.read("/app/image.png", {
encoding: "binary"
});
console.log(`Read ${imageBuffer.byteLength} bytes`);Complete Example
import { Sandbox } from "@usesandbox/sdk";
async function main() {
const client = Sandbox();
// Create a new sandbox
const sandbox = await client.sandboxes.create({
template: "node-app",
});
console.log(`Created sandbox: ${sandbox.id}`);
// Execute a command
const result = await sandbox.exec(["echo", "Hello from sandbox!"]);
console.log(result.stdout);
// Get updated info
const info = await sandbox.info();
console.log(`Sandbox state: ${info.state}`);
// Clean up
await sandbox.kill();
console.log("Sandbox destroyed");
}
main().catch(console.error);Error Handling
import { SandboxApiError } from "@usesandbox/sdk";
try {
const sandbox = await client.sandboxes.get("invalid-id");
} catch (error) {
if (error instanceof SandboxApiError) {
console.error(`API Error ${error.status}: ${error.response.message}`);
}
}Daemon CLI
The SDK includes a CLI daemon that starts a supervised process and exposes an HTTP API on port 64832 (configurable via PORT). This is useful for managing background processes and streaming logs.
Start the daemon
npx -y @usesandbox/sdk daemon "npm start"- The daemon spawns the provided command as a supervised child.
- Listens on
http://localhost:64832(override withPORT). - Optional auth: set
SANDBOX_AGENT_TOKENto requireAuthorization: Bearer <token>.
API endpoints
GET /healthz
{ "status": "ok" }POST /exec
Execute additional commands with optional SSE log streaming.
- Request body:
{ "command": "string", "timeoutMs": number } timeoutMsdefaults to 300,000 ms; max 600,000 ms (10 minutes).
Non‑streaming response (JSON):
{
"stdout": "...",
"stderr": "...",
"exitCode": 0,
"success": true
}Streaming response (SSE):
curl -N -H "Accept: text/event-stream" -X POST http://localhost:64832/exec -d '{"command":"echo hello && sleep 2 && echo done"}'SSE events:
event: startwith metadata (pid, startedAt, timeoutMs)event: logwith{ "stream": "stdout"|"stderr", "line": "..." }event: timeoutwhen enforcedevent: exitwith{ "code", "signal", "durationMs" }event: pingevery 15 seconds (keep‑alive)
Example usage
# Start daemon with a simple loop as the initial command
npx -y @usesandbox/sdk daemon "while true; do echo 'alive'; sleep 5; done"
# In another terminal, run a command and stream logs
curl -N -H "Accept: text/event-stream" -X POST http://localhost:64832/exec -d '{"command":"echo hello && ls -la"}'
# Run a command without streaming (JSON response)
curl -X POST http://localhost:64832/exec -H "Content-Type: application/json" -d '{"command":"sleep 2 && echo done"}'Development
# Install dependencies
bun install
# Build
bun run build
# Run tests
bun test
# Watch mode
bun run devLicense
MIT
