Skip to content

An open-source, faster Devin alternative

TypeScript

sdk 3.0.0: remove the sandbox client, keep @opencomputer/sdk/agents (097 step 7.2, U1)

Mohamed Habib via Computer06affcf07315
diff --git a/docs/reference/typescript-sdk/agents.mdx b/docs/reference/typescript-sdk/agents.mdx
index 3d637f66..940c252d 100644
--- a/docs/reference/typescript-sdk/agents.mdx
+++ b/docs/reference/typescript-sdk/agents.mdx
@@ -11,8 +11,9 @@ use [`@opencomputer/react`](/agents/react) in the browser and
[`@opencomputer/agent`](/agents/hooks) to define agent behavior.
The client uses web-standard APIs and runs on Cloudflare Workers without
-Node compatibility, Vercel functions, Deno and Node. The package root,
-`@opencomputer/sdk`, provides the separate sandbox client.
+Node compatibility, Vercel functions, Deno and Node. It is the package's
+only entry point: SDK 3.0 removed the sandbox client from the package root,
+`@opencomputer/sdk`.
```bash
npm install @opencomputer/sdk
diff --git a/sdks/typescript/CHANGELOG.md b/sdks/typescript/CHANGELOG.md
index 2780992e..d5d79707 100644
--- a/sdks/typescript/CHANGELOG.md
+++ b/sdks/typescript/CHANGELOG.md
@@ -1,5 +1,25 @@
# Changelog
+## 3.0.0
+
+Breaking. The sandbox client is removed; the package keeps only the
+Serverless Agents management client at `@opencomputer/sdk/agents`, which is
+unchanged from 2.3.1.
+
+- The package root (`@opencomputer/sdk`) and `@opencomputer/sdk/node` are no
+ longer exports; importing either fails to resolve. Removed with them:
+ `Sandbox`, `ScalingLockedError`, `PlanLimitError`,
+ `SandboxFamilyLimitError`, `Browser`, `BrowserProfile`,
+ `BrowserProfileAuthCheck`, `SandboxAgent`, `Filesystem`, `Exec`,
+ `ExecTimeoutError`, `Mounts`, `Shell` (`ShellBusyError`,
+ `ShellClosedError`), `Pty`, `Templates`, `Image`, `Snapshots`, the sandbox
+ `Webhooks` and `WebhookDeliveries`, `verifyWebhook` and
+ `WebhookVerificationError`, `SecretStore`, `Usage`, `Tags`,
+ `prewarmConnections`, `SDK_VERSION`, `SDK_VERSION_HEADER`, and their types.
+- The `undici` dependency is dropped; the package has no runtime
+ dependencies.
+- Code that still uses the sandbox client pins `@opencomputer/sdk@2`.
+
## 2.3.0
- `@opencomputer/sdk/agents`: questions. `Session.question` is the question
diff --git a/sdks/typescript/README.md b/sdks/typescript/README.md
index 9ccf2f2d..a849d77c 100644
--- a/sdks/typescript/README.md
+++ b/sdks/typescript/README.md
@@ -1,8 +1,8 @@
# @opencomputer/sdk
-The official TypeScript SDK for [OpenComputer](https://github.com/diggerhq/opencomputer): the **cloud sandbox** client at the package root, and the **Serverless Agents** management client on the portable `@opencomputer/sdk/agents` subpath.
+The official TypeScript client for the [OpenComputer](https://github.com/diggerhq/opencomputer) **Serverless Agents** management API. It has one entry point, `@opencomputer/sdk/agents`.
-> Versions before 2.0.0 also carried a client for the retired Durable Agent Sessions API; see [CHANGELOG](./CHANGELOG.md).
+> **3.0.0 removed the sandbox client.** `Sandbox`, `Browser`, `SandboxAgent`, `Templates`, `Image`, `Snapshots`, sandbox `Webhooks`, `verifyWebhook`, `SecretStore`, `Usage`/`Tags` and everything else that was exported from the package root (`@opencomputer/sdk`) and `@opencomputer/sdk/node` are gone, because the OpenComputer sandbox platform is shut down. Importing the package root now fails to resolve. Code that still needs the sandbox client pins `@opencomputer/sdk@2`; `@opencomputer/sdk/agents` is unchanged from 2.3.1. Versions before 2.0.0 also carried a client for the retired Durable Agent Sessions API. See the [CHANGELOG](./CHANGELOG.md).
## Install
@@ -10,28 +10,9 @@ The official TypeScript SDK for [OpenComputer](https://github.com/diggerhq/openc
npm install @opencomputer/sdk
```
-## Quick Start
+## Usage
-```typescript
-import { Sandbox } from "@opencomputer/sdk";
-
-const sandbox = await Sandbox.create({ template: "base" });
-
-// Execute commands
-const result = await sandbox.commands.run("echo hello");
-console.log(result.stdout); // "hello\n"
-
-// Read and write files
-await sandbox.files.write("/tmp/test.txt", "Hello, world!");
-const content = await sandbox.files.read("/tmp/test.txt");
-
-// Clean up
-await sandbox.kill();
-```
-
-## Serverless Agents management client
-
-Serverless Agents (`opencomputer deploy`) are managed over the [management API](https://opencomputer.dev/agents/api). The client for it is a separate subpath export whose module graph has no Node dependency and runs nothing at import, so the same code serves a Cloudflare Worker without Node compatibility, Vercel, Deno and Node. Use it from trusted server code; the API key must not reach a browser.
+Serverless Agents (`opencomputer deploy`) are managed over the [management API](https://opencomputer.dev/agents/api). The client is the `@opencomputer/sdk/agents` subpath export, whose module graph has no Node dependency and runs nothing at import, so the same code serves a Cloudflare Worker without Node compatibility, Vercel, Deno and Node. Use it from trusted server code; the API key must not reach a browser.
```typescript
import { OpenComputer, OpenComputerError } from "@opencomputer/sdk/agents";
@@ -78,47 +59,14 @@ const { document, session } = await oc.sessions.startOnDocument({
`startSessionOnDocument({ apiKey, ...params })` from the same subpath is the standalone form of the call.
-## Sandbox webhooks (Preview)
-
-Subscribe to sandbox lifecycle events (`sandbox.ready`, `sandbox.stopped`, …) — signed, retried, and redeliverable. `verifyWebhook` checks a delivery's signature and returns its envelope. **Preview: newly available; the surface may change.**
-
-```typescript
-import { Webhooks, verifyWebhook, type SandboxLifecycleEvent } from "@opencomputer/sdk";
-
-const webhooks = new Webhooks({ apiKey: process.env.OPENCOMPUTER_API_KEY! });
-
-// `secret` (whsec_…) is returned ONCE on create — store it; you need it to verify.
-const { secret } = await webhooks.create({
- url: "https://app.example.com/oc-webhook",
- eventTypes: ["sandbox.stopped"],
-});
-
-// In your handler — verify against the RAW body, then route:
-const delivery = await verifyWebhook<SandboxLifecycleEvent>(rawBody, request.headers, secret);
-if (delivery.type === "sandbox.stopped") {
- console.log(delivery.sandboxId, delivery.event.data.reason);
-}
-```
-
## Configuration
-**Sandboxes** (`Sandbox`):
-
-| Option | Env Variable | Default |
-|----------|------------------------|----------------------------------|
-| `apiUrl` | `OPENCOMPUTER_API_URL` | `https://app.opencomputer.dev` |
-| `apiKey` | `OPENCOMPUTER_API_KEY` | (none) |
-
-**Serverless Agents** (`OpenComputer` from `@opencomputer/sdk/agents`):
-
| Option | Default |
|-----------|----------------------------------------------------|
| `baseUrl` | `https://app.opencomputer.dev/api/managed-agents` |
| `apiKey` | required |
| `fetch` | the global `fetch` |
-Importing the package root installs nothing globally and opens no connection. The sandbox client keeps its own HTTP/2 pool, created on the first request and warmed on the first `Sandbox.create`; call `prewarmConnections()` earlier to pay that cost before a timing loop.
-
## Releasing
**Bump the `version` in `package.json` (and `package-lock.json`) in any PR that changes the SDK.** Publishing only fires on a version change — a change merged without a bump silently won't release. One bump per PR is enough.
diff --git a/sdks/typescript/examples/bench-checkpoints.ts b/sdks/typescript/examples/bench-checkpoints.ts
deleted file mode 100644
index c05f20b0..00000000
--- a/sdks/typescript/examples/bench-checkpoints.ts
+++ /dev/null
@@ -1,246 +0,0 @@
-/**
- * Checkpoint Benchmark
- *
- * Measures wall-clock timing of each checkpoint operation:
- * 1. Create checkpoint (pause + drive copy + resume + S3 upload)
- * 2. List checkpoints
- * 3. Restore checkpoint (kill VM + copy drives + cold boot)
- * 4. Fork from checkpoint (new sandbox from checkpoint drives)
- * 5. Delete checkpoint
- *
- * Each operation is run multiple times and min/avg/max are reported.
- *
- * Usage:
- * npx tsx examples/bench-checkpoints.ts
- */
-
-import { Sandbox } from "../src/index";
-
-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-function red(msg: string) { console.log(`\x1b[31m${msg}\x1b[0m`); }
-
-async function sleep(ms: number) {
- return new Promise((r) => globalThis.setTimeout(r, ms));
-}
-
-interface Timing {
- label: string;
- samples: number[];
-}
-
-function stats(t: Timing) {
- const sorted = [...t.samples].sort((a, b) => a - b);
- const min = sorted[0];
- const max = sorted[sorted.length - 1];
- const avg = Math.round(t.samples.reduce((s, v) => s + v, 0) / t.samples.length);
- const median = sorted[Math.floor(sorted.length / 2)];
- return { min, max, avg, median };
-}
-
-function formatMs(ms: number): string {
- if (ms < 1000) return `${ms}ms`;
- return `${(ms / 1000).toFixed(2)}s`;
-}
-
-function printTable(timings: Timing[]) {
- const labelWidth = Math.max(...timings.map((t) => t.label.length), 9);
- const header = `${"Operation".padEnd(labelWidth)} ${"Runs".padStart(4)} ${"Min".padStart(8)} ${"Avg".padStart(8)} ${"Median".padStart(8)} ${"Max".padStart(8)}`;
- const sep = "─".repeat(header.length);
-
- console.log();
- bold(sep);
- bold(header);
- bold(sep);
-
- for (const t of timings) {
- const s = stats(t);
- const row = `${t.label.padEnd(labelWidth)} ${String(t.samples.length).padStart(4)} ${formatMs(s.min).padStart(8)} ${formatMs(s.avg).padStart(8)} ${formatMs(s.median).padStart(8)} ${formatMs(s.max).padStart(8)}`;
- console.log(row);
- }
- bold(sep);
- console.log();
-}
-
-async function timed<T>(fn: () => Promise<T>): Promise<{ result: T; ms: number }> {
- const start = Date.now();
- const result = await fn();
- return { result, ms: Date.now() - start };
-}
-
-async function waitForReady(sandbox: Sandbox, checkpointId: string, timeoutMs = 120000): Promise<boolean> {
- const start = Date.now();
- while (Date.now() - start < timeoutMs) {
- const list = await sandbox.listCheckpoints();
- const cp = list.find((c) => c.id === checkpointId);
- if (cp && cp.status === "ready") return true;
- if (cp && cp.status !== "processing") return false;
- await sleep(1000);
- }
- return false;
-}
-
-const ITERATIONS = 3;
-
-async function main() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Checkpoint Benchmark ║");
- bold("╚══════════════════════════════════════════════════╝\n");
-
- dim(`Iterations per operation: ${ITERATIONS}`);
- console.log();
-
- const timings: Timing[] = [];
- const createSbTiming: Timing = { label: "Create sandbox", samples: [] };
- const createTiming: Timing = { label: "Create checkpoint", samples: [] };
- const listTiming: Timing = { label: "List checkpoints", samples: [] };
- const restoreTiming: Timing = { label: "Restore (in-place)", samples: [] };
- const forkTiming: Timing = { label: "Fork from checkpoint", samples: [] };
- const deleteTiming: Timing = { label: "Delete checkpoint", samples: [] };
- const firstCmdTiming: Timing = { label: "First cmd after restore", samples: [] };
-
- timings.push(createSbTiming, createTiming, listTiming, restoreTiming, firstCmdTiming, forkTiming, deleteTiming);
-
- const sandboxes: Sandbox[] = [];
-
- try {
- // ── Benchmark: Create sandbox ─────────────────────────────────
- bold("━━━ Create sandbox ━━━\n");
-
- let sandbox!: Sandbox;
- for (let i = 0; i < ITERATIONS; i++) {
- const { result: sb, ms } = await timed(() =>
- Sandbox.create({ template: "base", timeout: 300 }),
- );
- createSbTiming.samples.push(ms);
- sandboxes.push(sb);
- dim(`#${i + 1}: ${formatMs(ms)} (sandbox=${sb.sandboxId})`);
- if (i === 0) sandbox = sb;
- // Kill extra sandboxes — we only need the first for remaining benchmarks
- if (i > 0) sb.kill().catch(() => {});
- }
- console.log();
-
- // ── Setup ──────────────────────────────────────────────────────
- bold("━━━ Setup ━━━\n");
- dim(`Using sandbox ${sandbox.sandboxId} for checkpoint benchmarks`);
-
- // Write payload data to workspace
- const payloadMB = parseInt(process.env.BENCH_PAYLOAD_MB || "10240", 10);
- const payloadGB = payloadMB / 1024;
- dim(`Writing ${payloadMB >= 1024 ? payloadGB + " GB" : payloadMB + " MB"} payload...`);
- const { ms: writeMs } = await timed(async () => {
- if (payloadMB >= 1024) {
- // Write in 1GB chunks for large payloads
- const chunks = Math.ceil(payloadMB / 1024);
- for (let i = 0; i < chunks; i++) {
- await sandbox.commands.run(`dd if=/dev/zero of=/workspace/payload-${i}.bin bs=1M count=1024 2>/dev/null`, { timeout: 300 });
- dim(` chunk ${i + 1}/${chunks} written`);
- }
- } else {
- await sandbox.commands.run(`dd if=/dev/zero of=/workspace/payload.bin bs=1M count=${payloadMB} 2>/dev/null`, { timeout: 300 });
- }
- });
- await sandbox.commands.run("echo bench-state > /workspace/marker.txt");
- dim(`Wrote ${payloadMB >= 1024 ? payloadGB + " GB" : payloadMB + " MB"} payload + marker file (${formatMs(writeMs)})`);
- console.log();
-
- // ── Benchmark: Create checkpoint ───────────────────────────────
- bold("━━━ Create checkpoint ━━━\n");
-
- const checkpointIds: string[] = [];
- for (let i = 0; i < ITERATIONS; i++) {
- const name = `bench-cp-${i}`;
- const { result: cp, ms } = await timed(() => sandbox.createCheckpoint(name));
- createTiming.samples.push(ms);
- checkpointIds.push(cp.id);
- dim(`#${i + 1}: ${formatMs(ms)} (id=${cp.id.slice(0, 8)}…, status=${cp.status})`);
-
- // Wait for ready before next iteration (so S3 upload doesn't compete)
- await waitForReady(sandbox, cp.id);
- }
- console.log();
-
- // ── Benchmark: List checkpoints ────────────────────────────────
- bold("━━━ List checkpoints ━━━\n");
-
- for (let i = 0; i < ITERATIONS; i++) {
- const { result: list, ms } = await timed(() => sandbox.listCheckpoints());
- listTiming.samples.push(ms);
- dim(`#${i + 1}: ${formatMs(ms)} (${list.length} checkpoints)`);
- }
- console.log();
-
- // ── Benchmark: Restore (in-place revert) ───────────────────────
- bold("━━━ Restore (in-place revert) ━━━\n");
-
- for (let i = 0; i < ITERATIONS; i++) {
- // Modify state before each restore so we can verify it works
- await sandbox.commands.run(`echo pre-restore-${i} > /workspace/marker.txt`);
-
- const cpId = checkpointIds[0]; // always restore to the first checkpoint
- const { ms: restoreMs } = await timed(() => sandbox.restoreCheckpoint(cpId));
- restoreTiming.samples.push(restoreMs);
-
- // Measure time to first command after restore
- const { result: cmd, ms: cmdMs } = await timed(() =>
- sandbox.commands.run("cat /workspace/marker.txt"),
- );
- firstCmdTiming.samples.push(cmdMs);
-
- const marker = cmd.stdout.trim();
- const ok = marker === "bench-state" ? "✓" : `✗ (got: ${marker})`;
- dim(`#${i + 1}: restore=${formatMs(restoreMs)}, first_cmd=${formatMs(cmdMs)} ${ok}`);
- }
- console.log();
-
- // ── Benchmark: Fork from checkpoint ────────────────────────────
- bold("━━━ Fork from checkpoint ━━━\n");
-
- for (let i = 0; i < ITERATIONS; i++) {
- const cpId = checkpointIds[0];
- const { result: forked, ms } = await timed(() => Sandbox.createFromCheckpoint(cpId));
- forkTiming.samples.push(ms);
- sandboxes.push(forked);
-
- // Verify the fork has correct state
- const cmd = await forked.commands.run("cat /workspace/marker.txt");
- const marker = cmd.stdout.trim();
- const ok = marker === "bench-state" ? "✓" : `✗ (got: ${marker})`;
- dim(`#${i + 1}: ${formatMs(ms)} (sandbox=${forked.sandboxId}) ${ok}`);
- }
- console.log();
-
- // ── Benchmark: Delete checkpoint ───────────────────────────────
- bold("━━━ Delete checkpoint ━━━\n");
-
- for (let i = 0; i < ITERATIONS; i++) {
- const cpId = checkpointIds[i];
- const { ms } = await timed(() => sandbox.deleteCheckpoint(cpId));
- deleteTiming.samples.push(ms);
- dim(`#${i + 1}: ${formatMs(ms)}`);
- }
- console.log();
-
- // ── Results ────────────────────────────────────────────────────
- bold("━━━ Results ━━━");
- printTable(timings);
-
- } catch (err: any) {
- red(`Fatal: ${err.message}`);
- if (err.stack) dim(err.stack);
- } finally {
- bold("━━━ Cleanup ━━━\n");
- for (const sb of sandboxes) {
- try {
- await sb.kill();
- dim(`Killed ${sb.sandboxId}`);
- } catch { /* best effort */ }
- }
- }
-}
-
-main().catch((err) => {
- console.error("Fatal:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/lifecycle-test.ts b/sdks/typescript/examples/lifecycle-test.ts
deleted file mode 100644
index 8fe068a0..00000000
--- a/sdks/typescript/examples/lifecycle-test.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-/**
- * OpenSandbox SDK Lifecycle Test
- *
- * Tests: create → commands → files → domain → kill
- *
- * Usage:
- * npx tsx examples/lifecycle-test.ts
- *
- * Environment:
- * OPENCOMPUTER_API_URL (default: http://localhost:8080)
- * OPENCOMPUTER_API_KEY (default: test-key)
- */
-
-import { Sandbox } from "../src/index";
-
-const API_URL = process.env.OPENCOMPUTER_API_URL ?? "http://localhost:8080";
-const API_KEY = process.env.OPENCOMPUTER_API_KEY ?? "test-key";
-
-function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }
-function red(msg: string) { console.log(`\x1b[31m✗ ${msg}\x1b[0m`); }
-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-
-let passed = 0;
-let failed = 0;
-
-function check(desc: string, expected: string, actual: string) {
- if (actual.includes(expected)) {
- green(desc);
- passed++;
- } else {
- red(`${desc} (expected '${expected}', got '${actual}')`);
- failed++;
- }
-}
-
-async function main() {
- bold("\n========================================");
- bold(" OpenSandbox TypeScript SDK Lifecycle");
- bold("========================================\n");
- dim(`API: ${API_URL}`);
- console.log();
-
- // --- Create ---
- bold("[1/7] Creating sandbox...");
- const sandbox = await Sandbox.create({
- template: "base",
- timeout: 300,
- apiKey: API_KEY,
- apiUrl: API_URL,
- });
- green(`Created: ${sandbox.sandboxId}`);
- check("Status is running", "running", sandbox.status);
- if (sandbox.domain) {
- dim(`Domain: ${sandbox.domain}`);
- }
- console.log();
-
- // --- Run commands ---
- bold("[2/7] Running commands...");
- const echo = await sandbox.commands.run("echo hello-world");
- check("Echo command", "hello-world", echo.stdout.trim());
- check("Exit code 0", "0", String(echo.exitCode));
-
- const uname = await sandbox.commands.run("uname -s");
- check("Uname returns Linux", "Linux", uname.stdout.trim());
-
- const multi = await sandbox.commands.run("echo line1 && echo line2 && echo line3");
- check("Multi-command", "line1", multi.stdout);
- check("Multi-command has line3", "line3", multi.stdout);
- console.log();
-
- // --- File operations ---
- bold("[3/7] File operations...");
- await sandbox.files.write("/tmp/test.txt", "hello from SDK");
- const content = await sandbox.files.read("/tmp/test.txt");
- check("Write and read file", "hello from SDK", content);
-
- await sandbox.files.makeDir("/tmp/mydir");
- await sandbox.files.write("/tmp/mydir/nested.txt", "nested content");
- const nested = await sandbox.files.read("/tmp/mydir/nested.txt");
- check("Nested file read", "nested content", nested);
-
- const entries = await sandbox.files.list("/tmp");
- check("List /tmp has test.txt", "test.txt", entries.map(e => e.name).join(","));
-
- const exists = await sandbox.files.exists("/tmp/test.txt");
- check("File exists", "true", String(exists));
-
- const notExists = await sandbox.files.exists("/tmp/nope.txt");
- check("File not exists", "false", String(notExists));
- console.log();
-
- // --- Environment variables ---
- bold("[4/7] Environment in commands...");
- const envResult = await sandbox.commands.run("echo $MY_VAR", { env: { MY_VAR: "secret-value" } });
- check("Env var passed to command", "secret-value", envResult.stdout.trim());
- console.log();
-
- // --- Working directory ---
- bold("[5/7] Working directory...");
- await sandbox.files.makeDir("/tmp/workdir");
- await sandbox.files.write("/tmp/workdir/data.txt", "workdir-data");
- const cwdResult = await sandbox.commands.run("cat data.txt", { cwd: "/tmp/workdir" });
- check("Working directory respected", "workdir-data", cwdResult.stdout.trim());
- console.log();
-
- // --- Domain / subdomain ---
- bold("[6/7] Subdomain domain...");
- if (sandbox.domain) {
- green(`Domain assigned: ${sandbox.domain}`);
- } else {
- dim("No domain assigned (OPENSANDBOX_SANDBOX_DOMAIN not configured on server)");
- }
- console.log();
-
- // --- isRunning + kill ---
- bold("[7/7] Lifecycle: isRunning → kill → isRunning...");
- const running1 = await sandbox.isRunning();
- check("isRunning before kill", "true", String(running1));
-
- await sandbox.kill();
- green("Sandbox killed");
-
- // Brief pause for state propagation
- await new Promise(r => globalThis.setTimeout(r, 500));
-
- const running2 = await sandbox.isRunning();
- check("isRunning after kill", "false", String(running2));
- console.log();
-
- // --- Summary ---
- bold("========================================");
- bold(` Results: ${passed} passed, ${failed} failed`);
- bold("========================================\n");
-
- if (failed > 0) process.exit(1);
-}
-
-main().catch((err) => {
- console.error("Fatal error:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/run-all-tests.ts b/sdks/typescript/examples/run-all-tests.ts
deleted file mode 100644
index 376c3851..00000000
--- a/sdks/typescript/examples/run-all-tests.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-/**
- * OpenSandbox Production Test Suite Runner
- *
- * Runs all production tests in sequence, with a summary at the end.
- * Tests are ordered from fast/simple to slow/complex.
- *
- * Usage:
- * npx tsx examples/run-all-tests.ts # Run all tests
- * npx tsx examples/run-all-tests.ts --skip-slow # Skip timeout test (waits ~2min)
- *
- * Individual tests:
- * npx tsx examples/test-python-sdk.ts
- * npx tsx examples/test-multi-template.ts
- * npx tsx examples/test-commands.ts
- * npx tsx examples/test-file-ops.ts
- * npx tsx examples/test-reconnect.ts
- * npx tsx examples/test-domain-tls.ts
- * npx tsx examples/test-concurrent.ts
- * npx tsx examples/test-hibernation-stress.ts
- * npx tsx examples/test-timeout.ts
- * npx tsx examples/webhook-demo.ts
- */
-
-import { execSync } from "child_process";
-import * as path from "path";
-import { fileURLToPath } from "url";
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-
-const BOLD = "\x1b[1m";
-const GREEN = "\x1b[32m";
-const RED = "\x1b[31m";
-const DIM = "\x1b[2m";
-const RESET = "\x1b[0m";
-const CYAN = "\x1b[36m";
-
-const skipSlow = process.argv.includes("--skip-slow");
-
-interface TestSuite {
- name: string;
- file: string;
- slow?: boolean;
- description: string;
-}
-
-const SUITES: TestSuite[] = [
- { name: "Environment", file: "test-environment.ts", description: "Root access, apt/npm/pip install, dev tools" },
- { name: "Commands", file: "test-commands.ts", description: "Shell commands, stderr, exit codes, pipes, concurrency" },
- { name: "File Ops", file: "test-file-ops.ts", description: "Large files, special chars, nested dirs, deletion" },
- { name: "Python SDK", file: "test-python-sdk.ts", description: "Python template, stdlib, file ops from Python" },
- { name: "Reconnect", file: "test-reconnect.ts", description: "Sandbox.connect(), state persistence, multi-conn" },
- { name: "Domain/TLS", file: "test-domain-tls.ts", description: "Subdomains, TLS certs, routing isolation" },
- { name: "Concurrent", file: "test-concurrent.ts", description: "5 sandboxes in parallel, isolation, parallel ops" },
- { name: "Hibernation", file: "test-hibernation-stress.ts", description: "Multi-cycle hibernate/wake, large state, auto-wake" },
- { name: "Checkpoints", file: "test-checkpoints.ts", description: "Create, list, restore, fork, delete checkpoints, limits" },
- { name: "Snapshot Envs", file: "test-snapshot-envs.ts", description: "User envs survive snapshot fork as plaintext; secret-store envs stay sealed" },
- { name: "Timeout", file: "test-timeout.ts", slow: true, description: "30s timeout, setTimeout(), rolling timeout (takes ~2min)" },
-];
-
-async function main() {
- console.log(`${BOLD}\n╔════════════════════════════════════════════════════════╗`);
- console.log(`║ OpenSandbox Production Test Suite ║`);
- console.log(`╚════════════════════════════════════════════════════════╝${RESET}\n`);
-
- const filteredSuites = skipSlow ? SUITES.filter(s => !s.slow) : SUITES;
-
- console.log(`${DIM}Running ${filteredSuites.length} test suites${skipSlow ? " (slow tests skipped)" : ""}${RESET}`);
- console.log(`${DIM}${"─".repeat(60)}${RESET}\n`);
-
- const results: { name: string; passed: boolean; durationMs: number; error?: string }[] = [];
- const totalStart = Date.now();
-
- for (let i = 0; i < filteredSuites.length; i++) {
- const suite = filteredSuites[i];
- const filePath = path.join(__dirname, suite.file);
-
- console.log(`${BOLD}[${i + 1}/${filteredSuites.length}] ${suite.name}${RESET}`);
- console.log(`${DIM} ${suite.description}${RESET}`);
- console.log(`${DIM} Running: npx tsx ${suite.file}${RESET}\n`);
-
- const start = Date.now();
- try {
- execSync(`npx tsx "${filePath}"`, {
- stdio: "inherit",
- env: { ...process.env },
- timeout: 300000, // 5 min max per suite
- });
- const durationMs = Date.now() - start;
- results.push({ name: suite.name, passed: true, durationMs });
- console.log(`${GREEN}── ${suite.name}: PASSED (${(durationMs / 1000).toFixed(1)}s) ──${RESET}\n`);
- } catch (err: any) {
- const durationMs = Date.now() - start;
- results.push({ name: suite.name, passed: false, durationMs, error: err.message });
- console.log(`${RED}── ${suite.name}: FAILED (${(durationMs / 1000).toFixed(1)}s) ──${RESET}\n`);
- }
- }
-
- const totalMs = Date.now() - totalStart;
-
- // ── Summary ─────────────────────────────────────────────────────────
- console.log(`\n${BOLD}╔════════════════════════════════════════════════════════╗`);
- console.log(`║ Test Results ║`);
- console.log(`╠════════════════════════════════════════════════════════╣${RESET}`);
-
- const maxNameLen = Math.max(...results.map(r => r.name.length));
- for (const r of results) {
- const icon = r.passed ? `${GREEN}✓${RESET}` : `${RED}✗${RESET}`;
- const name = r.name.padEnd(maxNameLen);
- const duration = `${(r.durationMs / 1000).toFixed(1)}s`.padStart(7);
- console.log(` ${icon} ${name} ${duration}`);
- }
-
- const passedCount = results.filter(r => r.passed).length;
- const failedCount = results.filter(r => !r.passed).length;
-
- console.log(`${BOLD}\n╠════════════════════════════════════════════════════════╣`);
- console.log(`║ ${passedCount} passed, ${failedCount} failed | Total: ${(totalMs / 1000).toFixed(1)}s${" ".repeat(Math.max(0, 32 - String(passedCount).length - String(failedCount).length - String((totalMs / 1000).toFixed(1)).length))}║`);
- console.log(`╚════════════════════════════════════════════════════════╝${RESET}\n`);
-
- if (failedCount > 0) {
- console.log(`${RED}Failed suites:${RESET}`);
- for (const r of results.filter(r => !r.passed)) {
- console.log(` ${RED}✗ ${r.name}${RESET}`);
- }
- console.log();
- process.exit(1);
- }
-}
-
-main().catch((err) => {
- console.error("Fatal error:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/stream-demo.ts b/sdks/typescript/examples/stream-demo.ts
deleted file mode 100644
index d3952827..00000000
--- a/sdks/typescript/examples/stream-demo.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-/**
- * stream-demo.ts — simulates apt-install-style output over ~6 seconds via
- * shell.run(), printing each chunk with its arrival timestamp so you can
- * see exactly how streaming feels in practice.
- *
- * Usage:
- * cd sdks/typescript
- * npx tsx examples/stream-demo.ts
- */
-
-import { Sandbox } from "../src/index.js";
-
-const API_URL = process.env.OPENCOMPUTER_API_URL || "https://app.opencomputer.dev";
-const API_KEY = process.env.OPENCOMPUTER_API_KEY || "opensandbox-dev";
-
-// Pseudo-apt output. Uses /bin/echo (external, flushes on exit) rather
-// than bash builtins so glibc block-buffering doesn't hide the streaming.
-const APT_SIM = String.raw`
-/bin/echo "Reading package lists..."
-sleep 0.3
-/bin/echo "Building dependency tree..."
-sleep 0.2
-/bin/echo "Reading state information..."
-sleep 0.4
-/bin/echo "The following NEW packages will be installed:"
-/bin/echo " libfoo1 libfoo-dev pkg-a pkg-b pkg-c"
-sleep 0.3
-/bin/echo "0 upgraded, 5 newly installed, 0 to remove and 0 not upgraded."
-/bin/echo "Need to get 4,321 kB of archives."
-/bin/echo "After this operation, 12.3 MB of additional disk space will be used."
-sleep 0.4
-for i in 1 2 3 4 5; do
- /bin/echo "Get:$i http://deb.example.com/debian bookworm/main amd64 pkg-$i"
- sleep 0.2
-done
-/bin/echo "Fetched 4,321 kB in 1s (4,321 kB/s)"
-sleep 0.3
-for i in 1 2 3 4 5; do
- /bin/echo "Selecting previously unselected package pkg-$i."
- /bin/echo "Unpacking pkg-$i (1.0-$i) ..."
- sleep 0.15
- /bin/echo "Setting up pkg-$i (1.0-$i) ..."
- sleep 0.15
-done
-/bin/echo "W: Could not fetch http://example.com/deprecated — ignoring" >&2
-/bin/echo "Processing triggers for libc-bin (2.36-9+deb12u3) ..."
-sleep 0.4
-/bin/echo "Processing triggers for man-db (2.11.2-2) ..."
-sleep 0.5
-/bin/echo "done."
-`;
-
-async function main() {
- console.log(`API: ${API_URL}`);
- const sandbox = await Sandbox.create({
- apiUrl: API_URL,
- apiKey: API_KEY,
- template: "base",
- });
- console.log(`sandbox: ${sandbox.sandboxId}`);
-
- const decoder = new TextDecoder();
- const t0 = Date.now();
- let outCount = 0;
- let errCount = 0;
- let lastT = t0;
-
- const fmt = (n: number) => (n / 1000).toFixed(2).padStart(5, " ");
-
- try {
- const sh = await sandbox.exec.shell();
-
- const onStdout = (b: Uint8Array) => {
- outCount++;
- const now = Date.now();
- const gap = now - lastT;
- lastT = now;
- const text = decoder.decode(b).replace(/\n+$/, "");
- console.log(`[+${fmt(now - t0)}s Δ${fmt(gap)}s OUT] ${text}`);
- };
-
- const onStderr = (b: Uint8Array) => {
- errCount++;
- const now = Date.now();
- const gap = now - lastT;
- lastT = now;
- const text = decoder.decode(b).replace(/\n+$/, "");
- console.log(`[+${fmt(now - t0)}s Δ${fmt(gap)}s ERR] ${text}`);
- };
-
- console.log("--- starting simulated apt-install ---");
- const r = await sh.run(APT_SIM, { onStdout, onStderr });
- const total = (Date.now() - t0) / 1000;
- console.log("--- done ---");
- console.log(
- `exit=${r.exitCode} total_wall=${total.toFixed(2)}s ` +
- `stdout_chunks=${outCount} stderr_chunks=${errCount}`,
- );
- console.log(`stdout_bytes=${r.stdout.length} stderr_bytes=${r.stderr.length}`);
- await sh.close();
- } finally {
- await sandbox.kill();
- }
-}
-
-main().catch((err) => {
- console.error(err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/stress-tests.ts b/sdks/typescript/examples/stress-tests.ts
deleted file mode 100644
index 3aa7cbe6..00000000
--- a/sdks/typescript/examples/stress-tests.ts
+++ /dev/null
@@ -1,987 +0,0 @@
-/**
- * Stress Tests for Checkpoint System (50GB Dev Environment)
- *
- * 10 tests designed to shake out resource leaks, race conditions, and edge
- * cases in the checkpoint/fork/restore/golden-snapshot pipeline. Sized for
- * the dev environment with ~50GB NVMe at /data.
- *
- * Each test is self-contained: creates its own sandboxes, cleans up after
- * itself, and reports pass/fail + timing.
- *
- * Env vars:
- * STRESS_ONLY=3 Run only test 3
- * STRESS_SKIP=6,8 Skip tests 6 and 8
- *
- * Usage:
- * npx tsx examples/stress-tests.ts
- */
-
-import { Sandbox } from "../src/index";
-
-// ── Formatting helpers ───────────────────────────────────────────────────
-
-function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }
-function red(msg: string) { console.log(`\x1b[31m✗ ${msg}\x1b[0m`); }
-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-function cyan(msg: string) { console.log(`\x1b[36m→ ${msg}\x1b[0m`); }
-function yellow(msg: string) { console.log(`\x1b[33m⚠ ${msg}\x1b[0m`); }
-
-function sleep(ms: number) {
- return new Promise((r) => globalThis.setTimeout(r, ms));
-}
-
-function formatMs(ms: number): string {
- if (ms < 1000) return `${ms}ms`;
- return `${(ms / 1000).toFixed(2)}s`;
-}
-
-// ── Timing + assertion infrastructure ────────────────────────────────────
-
-let totalPassed = 0;
-let totalFailed = 0;
-
-function check(desc: string, condition: boolean, detail?: string): boolean {
- if (condition) {
- green(desc);
- totalPassed++;
- } else {
- red(`${desc}${detail ? ` (${detail})` : ""}`);
- totalFailed++;
- }
- return condition;
-}
-
-async function timed<T>(fn: () => Promise<T>): Promise<{ result: T; ms: number }> {
- const start = Date.now();
- const result = await fn();
- return { result, ms: Date.now() - start };
-}
-
-async function waitForReady(sandbox: Sandbox, checkpointId: string, timeoutMs = 120000): Promise<boolean> {
- const start = Date.now();
- while (Date.now() - start < timeoutMs) {
- const list = await sandbox.listCheckpoints();
- const cp = list.find((c) => c.id === checkpointId);
- if (cp && cp.status === "ready") return true;
- if (cp && cp.status !== "processing") return false;
- await sleep(2000);
- }
- return false;
-}
-
-async function killAll(sandboxes: Sandbox[]) {
- await Promise.allSettled(sandboxes.map((sb) => sb.kill().catch(() => {})));
-}
-
-// ── Test 1: Max Concurrent Creates ───────────────────────────────────────
-
-async function test1_maxConcurrentCreates() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Test 1: Max Concurrent Creates (20 sandboxes) ║");
- bold("╚══════════════════════════════════════════════════╝\n");
- dim("Validates: golden snapshot under load, TAP allocation, parallel boot");
- dim("Disk: ~3GB (reflinked)\n");
-
- const COUNT = 20;
- const sandboxes: Sandbox[] = [];
-
- try {
- // Create 20 sandboxes in parallel
- cyan(`Creating ${COUNT} sandboxes simultaneously...`);
- const createStart = Date.now();
- const createPromises = Array.from({ length: COUNT }, (_, i) =>
- timed(() => Sandbox.create({ template: "base", timeout: 120 }))
- .then((r) => ({ index: i, sandbox: r.result, ms: r.ms }))
- );
-
- const results = await Promise.allSettled(createPromises);
- const createWallClock = Date.now() - createStart;
-
- let successCount = 0;
- const createTimes: number[] = [];
- for (const r of results) {
- if (r.status === "fulfilled") {
- sandboxes.push(r.value.sandbox);
- createTimes.push(r.value.ms);
- successCount++;
- } else {
- dim(`Create failed: ${r.reason.message}`);
- }
- }
-
- check(`All ${COUNT} sandboxes created`, successCount === COUNT, `${successCount}/${COUNT}`);
- if (createTimes.length > 0) {
- const sorted = [...createTimes].sort((a, b) => a - b);
- dim(`Create times: min=${formatMs(sorted[0])}, avg=${formatMs(Math.round(createTimes.reduce((s, v) => s + v, 0) / createTimes.length))}, max=${formatMs(sorted[sorted.length - 1])}`);
- dim(`Wall clock: ${formatMs(createWallClock)}`);
- }
-
- // Run commands on all in parallel
- cyan(`Running echo on all ${sandboxes.length} sandboxes...`);
- const { ms: cmdMs } = await timed(async () => {
- const cmdPromises = sandboxes.map((sb, i) =>
- sb.commands.run(`echo sandbox-${i}`).then((r) => ({ index: i, stdout: r.stdout.trim() }))
- );
- const cmdResults = await Promise.allSettled(cmdPromises);
- let cmdOk = 0;
- for (const r of cmdResults) {
- if (r.status === "fulfilled" && r.value.stdout === `sandbox-${r.value.index}`) cmdOk++;
- }
- check(`All ${sandboxes.length} commands returned correct output`, cmdOk === sandboxes.length, `${cmdOk}/${sandboxes.length}`);
- });
- dim(`All commands completed in ${formatMs(cmdMs)}`);
-
- // Kill all in parallel
- cyan("Killing all sandboxes...");
- const { ms: killMs } = await timed(() => killAll(sandboxes));
- dim(`All killed in ${formatMs(killMs)}`);
-
- } finally {
- await killAll(sandboxes);
- }
-}
-
-// ── Test 2: Checkpoint Storm ─────────────────────────────────────────────
-
-async function test2_checkpointStorm() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Test 2: Checkpoint Storm (10 across 2 sandboxes)║");
- bold("╚══════════════════════════════════════════════════╝\n");
- dim("Validates: concurrent checkpoint creation, async pipeline, max limit");
- dim("Disk: ~12GB peak\n");
-
- const sandboxes: Sandbox[] = [];
-
- try {
- // Create 2 sandboxes
- cyan("Creating 2 sandboxes...");
- const sb1 = await Sandbox.create({ template: "base", timeout: 300 });
- const sb2 = await Sandbox.create({ template: "base", timeout: 300 });
- sandboxes.push(sb1, sb2);
- dim(`Sandbox A: ${sb1.sandboxId}`);
- dim(`Sandbox B: ${sb2.sandboxId}`);
-
- // Write 500MB payload to each
- cyan("Writing 500MB payload to each sandbox...");
- await Promise.all([
- sb1.commands.run("dd if=/dev/urandom of=/workspace/payload.bin bs=1M count=500 2>/dev/null", { timeout: 120 }),
- sb2.commands.run("dd if=/dev/urandom of=/workspace/payload.bin bs=1M count=500 2>/dev/null", { timeout: 120 }),
- ]);
- green("Payloads written");
-
- // Create 5 checkpoints on each — wait for ready between iterations
- // to avoid queueing (each snapshot pauses the VM serially)
- cyan("Creating 5 checkpoints on each sandbox (10 total)...");
- const checkpoints: { sandbox: Sandbox; id: string; name: string; ms: number }[] = [];
-
- for (let i = 0; i < 5; i++) {
- // Fire both sandboxes in parallel for each iteration
- const [r1, r2] = await Promise.all([
- timed(() => sb1.createCheckpoint(`storm-a-${i}`)),
- timed(() => sb2.createCheckpoint(`storm-b-${i}`)),
- ]);
- checkpoints.push(
- { sandbox: sb1, id: r1.result.id, name: `storm-a-${i}`, ms: r1.ms },
- { sandbox: sb2, id: r2.result.id, name: `storm-b-${i}`, ms: r2.ms },
- );
- dim(` #${i}: A=${formatMs(r1.ms)}, B=${formatMs(r2.ms)}`);
-
- // Wait for this pair to be ready before creating the next pair
- // (memory snapshot is serialized per VM — queueing causes timeouts)
- await Promise.all([
- waitForReady(sb1, r1.result.id, 180000),
- waitForReady(sb2, r2.result.id, 180000),
- ]);
- }
-
- check("All 10 checkpoints created", checkpoints.length === 10);
-
- // Verify all reached "ready"
- cyan("Verifying all 10 checkpoints are ready...");
- const readyStart = Date.now();
- let readyCount = 0;
- for (const cp of checkpoints) {
- const list = await cp.sandbox.listCheckpoints();
- const found = list.find((c) => c.id === cp.id);
- if (found && found.status === "ready") readyCount++;
- else dim(` ${cp.name} status=${found?.status ?? "not found"}`);
- }
- const readyMs = Date.now() - readyStart;
-
- check(`All 10 checkpoints ready`, readyCount === 10, `${readyCount}/10`);
- dim(`Verification took: ${formatMs(readyMs)}`);
-
- // Delete all checkpoints
- cyan("Deleting all checkpoints...");
- for (const cp of checkpoints) {
- await cp.sandbox.deleteCheckpoint(cp.id).catch(() => {});
- }
- green("All checkpoints deleted");
-
- } finally {
- await killAll(sandboxes);
- }
-}
-
-// ── Test 3: Fork Fan-Out ─────────────────────────────────────────────────
-
-async function test3_forkFanOut() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Test 3: Fork Fan-Out (8 forks from 1 checkpoint)║");
- bold("╚══════════════════════════════════════════════════╝\n");
- dim("Validates: reflink fan-out, concurrent fork boot, state isolation");
- dim("Disk: ~3GB\n");
-
- const sandboxes: Sandbox[] = [];
- let checkpointId = "";
-
- try {
- // Create source sandbox with state
- cyan("Creating source sandbox...");
- const source = await Sandbox.create({ template: "base", timeout: 300 });
- sandboxes.push(source);
- dim(`Source: ${source.sandboxId}`);
-
- await source.commands.run("echo fork-source > /workspace/marker.txt");
- await source.commands.run("echo 'unique-data-12345' > /workspace/data.txt");
- green("Source state written");
-
- // Checkpoint
- cyan("Creating checkpoint...");
- const { result: cp } = await timed(() => source.createCheckpoint("fan-out"));
- checkpointId = cp.id;
- const ready = await waitForReady(source, cp.id);
- check("Checkpoint ready", ready);
-
- if (!ready) throw new Error("Checkpoint not ready, cannot proceed");
-
- // Fork 8 in parallel
- const FORK_COUNT = 8;
- cyan(`Forking ${FORK_COUNT} sandboxes in parallel...`);
- const forkStart = Date.now();
- const forkPromises = Array.from({ length: FORK_COUNT }, (_, i) =>
- timed(() => Sandbox.createFromCheckpoint(cp.id))
- .then((r) => ({ index: i, sandbox: r.result, ms: r.ms }))
- );
-
- const forkResults = await Promise.allSettled(forkPromises);
- const forkWallClock = Date.now() - forkStart;
-
- const forkTimes: number[] = [];
- let forkSuccess = 0;
- for (const r of forkResults) {
- if (r.status === "fulfilled") {
- sandboxes.push(r.value.sandbox);
- forkTimes.push(r.value.ms);
- forkSuccess++;
- } else {
- dim(`Fork failed: ${r.reason.message}`);
- }
- }
-
- check(`All ${FORK_COUNT} forks created`, forkSuccess === FORK_COUNT, `${forkSuccess}/${FORK_COUNT}`);
- if (forkTimes.length > 0) {
- const sorted = [...forkTimes].sort((a, b) => a - b);
- dim(`Fork times: min=${formatMs(sorted[0])}, avg=${formatMs(Math.round(forkTimes.reduce((s, v) => s + v, 0) / forkTimes.length))}, max=${formatMs(sorted[sorted.length - 1])}`);
- dim(`Wall clock: ${formatMs(forkWallClock)}`);
- }
-
- // Verify all forks have correct state
- cyan("Verifying fork state...");
- const forks = sandboxes.slice(1); // skip source
- const verifyPromises = forks.map((sb, i) =>
- sb.commands.run("cat /workspace/marker.txt").then((r) => ({ index: i, marker: r.stdout.trim() }))
- );
-
- const verifyResults = await Promise.allSettled(verifyPromises);
- let verifyOk = 0;
- for (const r of verifyResults) {
- if (r.status === "fulfilled" && r.value.marker === "fork-source") verifyOk++;
- }
- check(`All forks have correct marker`, verifyOk === forks.length, `${verifyOk}/${forks.length}`);
-
- // Verify isolation: write unique file to each fork, read back
- cyan("Verifying isolation across forks...");
- await Promise.all(forks.map((sb, i) =>
- sb.commands.run(`echo fork-${i} > /workspace/identity.txt`)
- ));
-
- const isolationPromises = forks.map((sb, i) =>
- sb.commands.run("cat /workspace/identity.txt").then((r) => ({ index: i, content: r.stdout.trim() }))
- );
- const isolationResults = await Promise.all(isolationPromises);
- let isolationOk = 0;
- for (const { index, content } of isolationResults) {
- if (content === `fork-${index}`) isolationOk++;
- }
- check(`All forks are isolated`, isolationOk === forks.length, `${isolationOk}/${forks.length}`);
-
- } finally {
- if (checkpointId && sandboxes.length > 0) {
- await sandboxes[0].deleteCheckpoint(checkpointId).catch(() => {});
- }
- await killAll(sandboxes);
- }
-}
-
-// ── Test 4: Restore Thrash ───────────────────────────────────────────────
-
-async function test4_restoreThrash() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Test 4: Restore Thrash (20 rapid restores) ║");
- bold("╚══════════════════════════════════════════════════╝\n");
- dim("Validates: warm restore stability, rapid kill/boot cycles, state correctness");
- dim("Disk: ~3GB\n");
-
- const sandboxes: Sandbox[] = [];
- const checkpointIds: string[] = [];
-
- try {
- // Create sandbox with payload
- cyan("Creating sandbox with 500MB payload...");
- const sandbox = await Sandbox.create({ template: "base", timeout: 300 });
- sandboxes.push(sandbox);
- await sandbox.commands.run("dd if=/dev/urandom of=/workspace/payload.bin bs=1M count=500 2>/dev/null", { timeout: 120 });
-
- // Create checkpoint A with marker=A
- await sandbox.commands.run("echo state-A > /workspace/marker.txt");
- const cpA = await sandbox.createCheckpoint("thrash-A");
- checkpointIds.push(cpA.id);
- const readyA = await waitForReady(sandbox, cpA.id);
- check("Checkpoint A ready", readyA);
-
- // Create checkpoint B with marker=B
- await sandbox.commands.run("echo state-B > /workspace/marker.txt");
- const cpB = await sandbox.createCheckpoint("thrash-B");
- checkpointIds.push(cpB.id);
- const readyB = await waitForReady(sandbox, cpB.id);
- check("Checkpoint B ready", readyB);
-
- if (!readyA || !readyB) throw new Error("Checkpoints not ready");
-
- // Alternate restoring 20 times
- const ITERATIONS = 20;
- cyan(`Running ${ITERATIONS} rapid restores (alternating A/B)...`);
- const restoreTimes: number[] = [];
- const cmdTimes: number[] = [];
- let errors = 0;
-
- for (let i = 0; i < ITERATIONS; i++) {
- const targetCp = i % 2 === 0 ? cpA.id : cpB.id;
- const expectedMarker = i % 2 === 0 ? "state-A" : "state-B";
-
- try {
- const { ms: restoreMs } = await timed(() => sandbox.restoreCheckpoint(targetCp));
- restoreTimes.push(restoreMs);
-
- const { result: cmd, ms: cmdMs } = await timed(() =>
- sandbox.commands.run("cat /workspace/marker.txt")
- );
- cmdTimes.push(cmdMs);
-
- const marker = cmd.stdout.trim();
- if (marker !== expectedMarker) {
- red(` #${i + 1}: expected ${expectedMarker}, got ${marker}`);
- errors++;
- } else if (i % 5 === 0) {
- dim(` #${i + 1}: restore=${formatMs(restoreMs)}, cmd=${formatMs(cmdMs)} ✓`);
- }
- } catch (err: any) {
- red(` #${i + 1}: ${err.message}`);
- errors++;
- }
- }
-
- check(`All ${ITERATIONS} restores completed correctly`, errors === 0, `${errors} errors`);
-
- if (restoreTimes.length > 0) {
- const sorted = [...restoreTimes].sort((a, b) => a - b);
- dim(`Restore: min=${formatMs(sorted[0])}, avg=${formatMs(Math.round(restoreTimes.reduce((s, v) => s + v, 0) / restoreTimes.length))}, max=${formatMs(sorted[sorted.length - 1])}`);
- }
- if (cmdTimes.length > 0) {
- const sorted = [...cmdTimes].sort((a, b) => a - b);
- dim(`First cmd: min=${formatMs(sorted[0])}, avg=${formatMs(Math.round(cmdTimes.reduce((s, v) => s + v, 0) / cmdTimes.length))}, max=${formatMs(sorted[sorted.length - 1])}`);
- }
-
- } finally {
- for (const cpId of checkpointIds) {
- await sandboxes[0]?.deleteCheckpoint(cpId).catch(() => {});
- }
- await killAll(sandboxes);
- }
-}
-
-// ── Test 5: Disk Fill & CoW Divergence ───────────────────────────────────
-
-async function test5_cowDivergence() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Test 5: Disk Fill & CoW Divergence ║");
- bold("╚══════════════════════════════════════════════════╝\n");
- dim("Validates: reflink CoW under divergent writes, disk accounting, restore correctness");
- dim("Disk: ~10GB peak\n");
-
- const sandboxes: Sandbox[] = [];
- const checkpointIds: string[] = [];
-
- try {
- cyan("Creating sandbox...");
- const sandbox = await Sandbox.create({ template: "base", timeout: 300 });
- sandboxes.push(sandbox);
-
- // Write 3GB payload
- cyan("Writing 3GB payload...");
- await sandbox.commands.run("dd if=/dev/urandom of=/workspace/payload.bin bs=1M count=3072 2>/dev/null", { timeout: 300 });
- const hash1Cmd = await sandbox.commands.run("md5sum /workspace/payload.bin", { timeout: 300 });
- const hashBefore = hash1Cmd.stdout.trim().split(/\s+/)[0];
- dim(`Original hash: ${hashBefore}`);
-
- // Checkpoint before diverge
- cyan("Creating checkpoint before-diverge...");
- const cpBefore = await sandbox.createCheckpoint("before-diverge");
- checkpointIds.push(cpBefore.id);
- check("Checkpoint before-diverge created", await waitForReady(sandbox, cpBefore.id));
-
- // Overwrite first 2GB (triggers CoW on original blocks)
- cyan("Overwriting first 2GB (triggers CoW)...");
- await sandbox.commands.run("dd if=/dev/urandom of=/workspace/payload.bin bs=1M count=2048 conv=notrunc 2>/dev/null", { timeout: 300 });
- const hash2Cmd = await sandbox.commands.run("md5sum /workspace/payload.bin", { timeout: 300 });
- const hashAfter = hash2Cmd.stdout.trim().split(/\s+/)[0];
- dim(`Modified hash: ${hashAfter}`);
-
- check("Hashes differ after overwrite", hashBefore !== hashAfter);
-
- // Check disk usage inside VM
- const dfCmd = await sandbox.commands.run("df -h /workspace");
- dim(`Disk usage after CoW divergence:\n ${dfCmd.stdout.trim().split("\n").join("\n ")}`);
-
- // Checkpoint after diverge
- cyan("Creating checkpoint after-diverge...");
- const cpAfter = await sandbox.createCheckpoint("after-diverge");
- checkpointIds.push(cpAfter.id);
- check("Checkpoint after-diverge created", await waitForReady(sandbox, cpAfter.id));
-
- // Restore to before-diverge, verify original hash
- cyan("Restoring to before-diverge...");
- await sandbox.restoreCheckpoint(cpBefore.id);
- const restoreHash1Cmd = await sandbox.commands.run("md5sum /workspace/payload.bin", { timeout: 300 });
- const restoredHash1 = restoreHash1Cmd.stdout.trim().split(/\s+/)[0];
- check("Restored hash matches original", restoredHash1 === hashBefore, `got ${restoredHash1}`);
-
- // Restore to after-diverge, verify modified hash
- cyan("Restoring to after-diverge...");
- await sandbox.restoreCheckpoint(cpAfter.id);
- const restoreHash2Cmd = await sandbox.commands.run("md5sum /workspace/payload.bin", { timeout: 300 });
- const restoredHash2 = restoreHash2Cmd.stdout.trim().split(/\s+/)[0];
- check("Restored hash matches modified", restoredHash2 === hashAfter, `got ${restoredHash2}`);
-
- } finally {
- for (const cpId of checkpointIds) {
- await sandboxes[0]?.deleteCheckpoint(cpId).catch(() => {});
- }
- await killAll(sandboxes);
- }
-}
-
-// ── Test 6: Large Workspace Checkpoint (5GB) ─────────────────────────────
-
-async function test6_largeCheckpoint() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Test 6: Large Workspace Checkpoint (5GB) ║");
- bold("╚══════════════════════════════════════════════════╝\n");
- dim("Validates: large checkpoint create/fork, S3 upload, data integrity");
- dim("Disk: ~8GB peak\n");
-
- const sandboxes: Sandbox[] = [];
- let checkpointId = "";
-
- try {
- cyan("Creating sandbox...");
- const sandbox = await Sandbox.create({ template: "base", timeout: 600 });
- sandboxes.push(sandbox);
-
- // Write 5GB in 1GB chunks
- cyan("Writing 5GB payload in 1GB chunks...");
- const hashes: string[] = [];
- for (let i = 0; i < 5; i++) {
- const { ms } = await timed(async () => {
- await sandbox.commands.run(`dd if=/dev/urandom of=/workspace/chunk-${i}.bin bs=1M count=1024 2>/dev/null`, { timeout: 300 });
- });
- const hashCmd = await sandbox.commands.run(`md5sum /workspace/chunk-${i}.bin`, { timeout: 60 });
- hashes.push(hashCmd.stdout.trim().split(/\s+/)[0]);
- dim(` Chunk ${i}: ${formatMs(ms)}, hash=${hashes[i].slice(0, 12)}...`);
- }
-
- // Create checkpoint
- cyan("Creating checkpoint of 5GB workspace...");
- const { result: cp, ms: createMs } = await timed(() => sandbox.createCheckpoint("large-5gb"));
- checkpointId = cp.id;
- dim(`Checkpoint create API: ${formatMs(createMs)}`);
-
- // Wait for ready (may take a while for S3 upload)
- cyan("Waiting for checkpoint ready (S3 upload)...");
- const { ms: readyMs } = await timed(async () => {
- const ready = await waitForReady(sandbox, cp.id, 600000); // 10 min timeout
- check("Checkpoint ready", ready);
- });
- dim(`Time to ready: ${formatMs(readyMs)}`);
-
- // Fork from checkpoint
- cyan("Forking from checkpoint...");
- const { result: fork, ms: forkMs } = await timed(() => Sandbox.createFromCheckpoint(cp.id));
- sandboxes.push(fork);
- dim(`Fork created in ${formatMs(forkMs)}: ${fork.sandboxId}`);
-
- // Verify all chunk hashes in fork
- cyan("Verifying 5GB data integrity in fork...");
- let hashOk = 0;
- for (let i = 0; i < 5; i++) {
- const hashCmd = await fork.commands.run(`md5sum /workspace/chunk-${i}.bin`, { timeout: 60 });
- const forkHash = hashCmd.stdout.trim().split(/\s+/)[0];
- if (forkHash === hashes[i]) {
- hashOk++;
- } else {
- dim(` Chunk ${i}: MISMATCH (expected ${hashes[i].slice(0, 12)}, got ${forkHash.slice(0, 12)})`);
- }
- }
- check(`All 5 chunk hashes match in fork`, hashOk === 5, `${hashOk}/5`);
-
- } finally {
- if (checkpointId && sandboxes.length > 0) {
- await sandboxes[0].deleteCheckpoint(checkpointId).catch(() => {});
- }
- await killAll(sandboxes);
- }
-}
-
-// ── Test 7: Rapid Create-Kill Cycle ──────────────────────────────────────
-
-async function test7_rapidCreateKill() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Test 7: Rapid Create-Kill Cycle (50 iterations)║");
- bold("╚══════════════════════════════════════════════════╝\n");
- dim("Validates: resource leak detection (TAP, disk, FDs)");
- dim("Disk: ~0 (cleaned each cycle)\n");
-
- const ITERATIONS = 50;
- const createTimes: number[] = [];
- const killTimes: number[] = [];
- let errors = 0;
-
- // We can't check host disk from the SDK, so we track sandbox-side metrics
- cyan(`Running ${ITERATIONS} create-kill cycles...`);
-
- for (let i = 0; i < ITERATIONS; i++) {
- try {
- const { result: sb, ms: createMs } = await timed(() =>
- Sandbox.create({ template: "base", timeout: 60 })
- );
- createTimes.push(createMs);
-
- // Verify it boots
- const cmd = await sb.commands.run("echo alive");
- if (cmd.stdout.trim() !== "alive") {
- errors++;
- dim(` #${i + 1}: wrong output: ${cmd.stdout.trim()}`);
- }
-
- const { ms: killMs } = await timed(() => sb.kill());
- killTimes.push(killMs);
-
- // Progress report every 10 iterations
- if ((i + 1) % 10 === 0) {
- dim(` ${i + 1}/${ITERATIONS}: create=${formatMs(createMs)}, kill=${formatMs(killMs)}`);
- }
- } catch (err: any) {
- errors++;
- red(` #${i + 1}: ${err.message}`);
- }
- }
-
- check(`All ${ITERATIONS} cycles completed without errors`, errors === 0, `${errors} errors`);
-
- if (createTimes.length > 0) {
- const sorted = [...createTimes].sort((a, b) => a - b);
- dim(`Create: min=${formatMs(sorted[0])}, avg=${formatMs(Math.round(createTimes.reduce((s, v) => s + v, 0) / createTimes.length))}, max=${formatMs(sorted[sorted.length - 1])}`);
- }
- if (killTimes.length > 0) {
- const sorted = [...killTimes].sort((a, b) => a - b);
- dim(`Kill: min=${formatMs(sorted[0])}, avg=${formatMs(Math.round(killTimes.reduce((s, v) => s + v, 0) / killTimes.length))}, max=${formatMs(sorted[sorted.length - 1])}`);
- }
-
- // Check for timing degradation (last 10 vs first 10)
- if (createTimes.length >= 20) {
- const first10Avg = createTimes.slice(0, 10).reduce((s, v) => s + v, 0) / 10;
- const last10Avg = createTimes.slice(-10).reduce((s, v) => s + v, 0) / 10;
- const ratio = last10Avg / first10Avg;
- check(
- `No timing degradation (last 10 / first 10 ratio)`,
- ratio < 2.0,
- `ratio=${ratio.toFixed(2)} (first10=${formatMs(Math.round(first10Avg))}, last10=${formatMs(Math.round(last10Avg))})`
- );
- }
-}
-
-// ── Test 8: Long-Running Stability ───────────────────────────────────────
-
-async function test8_longRunning() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Test 8: Long-Running Stability (10 VMs, 5 min) ║");
- bold("╚══════════════════════════════════════════════════╝\n");
- dim("Validates: golden VMs stay responsive, no timeout/crash over time");
- dim("Disk: ~2GB\n");
-
- const VM_COUNT = 10;
- const DURATION_MS = 5 * 60 * 1000; // 5 minutes
- const INTERVAL_MS = 30 * 1000; // 30 seconds
- const sandboxes: Sandbox[] = [];
-
- try {
- // Create 10 sandboxes
- cyan(`Creating ${VM_COUNT} sandboxes...`);
- const createStart = Date.now();
- const createPromises = Array.from({ length: VM_COUNT }, () =>
- Sandbox.create({ template: "base", timeout: 600 })
- );
- const createResults = await Promise.allSettled(createPromises);
- for (const r of createResults) {
- if (r.status === "fulfilled") sandboxes.push(r.value);
- }
- const createMs = Date.now() - createStart;
- check(`All ${VM_COUNT} sandboxes created`, sandboxes.length === VM_COUNT, `${sandboxes.length}/${VM_COUNT}`);
- dim(`Created in ${formatMs(createMs)}`);
-
- // Poll every 30 seconds for 5 minutes
- const rounds = Math.ceil(DURATION_MS / INTERVAL_MS);
- let totalFailures = 0;
-
- for (let round = 1; round <= rounds; round++) {
- if (round > 1) await sleep(INTERVAL_MS);
-
- cyan(`Round ${round}/${rounds}...`);
- const roundStart = Date.now();
- const cmdPromises = sandboxes.map((sb, i) =>
- sb.commands.run("uptime", { timeout: 10 })
- .then((r) => ({ index: i, ok: true, ms: Date.now() - roundStart }))
- .catch((err) => ({ index: i, ok: false, ms: Date.now() - roundStart, error: err.message }))
- );
-
- const results = await Promise.allSettled(cmdPromises);
- let roundOk = 0;
- const roundTimes: number[] = [];
- for (const r of results) {
- if (r.status === "fulfilled") {
- if (r.value.ok) {
- roundOk++;
- roundTimes.push(r.value.ms);
- } else {
- dim(` VM ${(r.value as any).index}: failed - ${(r.value as any).error}`);
- }
- }
- }
-
- if (roundOk < sandboxes.length) totalFailures += (sandboxes.length - roundOk);
- const avgMs = roundTimes.length > 0 ? Math.round(roundTimes.reduce((s, v) => s + v, 0) / roundTimes.length) : 0;
- dim(` ${roundOk}/${sandboxes.length} responded, avg=${formatMs(avgMs)}`);
- }
-
- check(`All VMs stayed responsive (${rounds} rounds)`, totalFailures === 0, `${totalFailures} failures`);
-
- // Final verification: write + read
- cyan("Final write/read verification...");
- const writePromises = sandboxes.map((sb, i) =>
- sb.files.write("/tmp/stability.txt", `vm-${i}-stable`)
- );
- await Promise.all(writePromises);
-
- const readPromises = sandboxes.map((sb, i) =>
- sb.files.read("/tmp/stability.txt").then((c) => ({ index: i, ok: c === `vm-${i}-stable` }))
- );
- const readResults = await Promise.all(readPromises);
- const readOk = readResults.filter((r) => r.ok).length;
- check(`All VMs write/read correctly`, readOk === sandboxes.length, `${readOk}/${sandboxes.length}`);
-
- } finally {
- await killAll(sandboxes);
- }
-}
-
-// ── Test 9: Concurrent Checkpoint + Exec ─────────────────────────────────
-
-async function test9_concurrentCheckpointExec() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Test 9: Concurrent Checkpoint + Exec ║");
- bold("╚══════════════════════════════════════════════════╝\n");
- dim("Validates: sandbox stays responsive during checkpoint (reflink-only, ~2ms pause)");
- dim("Disk: ~4GB\n");
-
- const sandboxes: Sandbox[] = [];
- let checkpointId = "";
-
- try {
- cyan("Creating sandbox with 1GB payload...");
- const sandbox = await Sandbox.create({ template: "base", timeout: 300 });
- sandboxes.push(sandbox);
- await sandbox.commands.run("dd if=/dev/urandom of=/workspace/payload.bin bs=1M count=1024 2>/dev/null", { timeout: 120 });
- await sandbox.commands.run("echo concurrent-test > /workspace/marker.txt");
-
- // Create checkpoint — the VM pause is ~2ms (reflink only, no memory snapshot).
- // The API returns immediately with status=processing. S3 upload happens async.
- cyan("Starting checkpoint creation...");
- const cp = await sandbox.createCheckpoint("concurrent-test");
- checkpointId = cp.id;
- dim(`Checkpoint initiated: ${cp.id.slice(0, 8)}...`);
-
- // Run 10 commands immediately — sandbox should stay responsive since
- // checkpoint pause is only ~2ms for reflink copies.
- cyan("Running 10 commands immediately after checkpoint...");
- const cmdResults: { index: number; ok: boolean; ms: number }[] = [];
-
- for (let i = 0; i < 10; i++) {
- try {
- const { result, ms } = await timed(() =>
- sandbox.commands.run(`echo cmd-${i}`)
- );
- cmdResults.push({ index: i, ok: result.stdout.trim() === `cmd-${i}`, ms });
- } catch (err: any) {
- cmdResults.push({ index: i, ok: false, ms: 0 });
- dim(` cmd-${i}: failed - ${err.message}`);
- }
- }
-
- const cmdOk = cmdResults.filter((r) => r.ok).length;
- check(`All 10 commands succeeded during checkpoint`, cmdOk === 10, `${cmdOk}/10`);
-
- const cmdTimesMs = cmdResults.filter((r) => r.ok).map((r) => r.ms);
- if (cmdTimesMs.length > 0) {
- const avg = Math.round(cmdTimesMs.reduce((s, v) => s + v, 0) / cmdTimesMs.length);
- dim(`Command latency during checkpoint: avg=${formatMs(avg)}`);
- }
-
- // Wait for checkpoint to finish
- cyan("Waiting for checkpoint to become ready...");
- const { ms: readyMs } = await timed(async () => {
- const ready = await waitForReady(sandbox, cp.id);
- check("Checkpoint completed successfully", ready);
- });
- dim(`Time to ready: ${formatMs(readyMs)}`);
-
- // Validate checkpoint by forking (cold boot — no memory snapshot)
- cyan("Validating checkpoint by forking...");
- const fork = await Sandbox.createFromCheckpoint(cp.id);
- sandboxes.push(fork);
- const forkMarker = await fork.commands.run("cat /workspace/marker.txt");
- check("Fork has correct state", forkMarker.stdout.trim() === "concurrent-test", forkMarker.stdout.trim());
-
- } finally {
- if (checkpointId && sandboxes.length > 0) {
- await sandboxes[0].deleteCheckpoint(checkpointId).catch(() => {});
- }
- await killAll(sandboxes);
- }
-}
-
-// ── Test 10: Full Lifecycle Chaos ────────────────────────────────────────
-
-async function test10_lifecycleChaos() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Test 10: Full Lifecycle Chaos ║");
- bold("╚══════════════════════════════════════════════════╝\n");
- dim("Validates: mixed concurrent operations, realistic load patterns");
- dim("Disk: ~10GB peak\n");
-
- const SB_COUNT = 3; // sized for dev worker (max_capacity=5, need room for forks)
- const allSandboxes: Sandbox[] = [];
- const checkpointIds: { sandboxIdx: number; id: string }[] = [];
-
- try {
- // Phase 1: Create sandboxes in parallel
- cyan(`Phase 1: Creating ${SB_COUNT} sandboxes...`);
- const { ms: createMs } = await timed(async () => {
- const results = await Promise.allSettled(
- Array.from({ length: SB_COUNT }, () => Sandbox.create({ template: "base", timeout: 300 }))
- );
- for (const r of results) {
- if (r.status === "fulfilled") allSandboxes.push(r.value);
- }
- });
- check(`${SB_COUNT} sandboxes created`, allSandboxes.length === SB_COUNT, `${allSandboxes.length}/${SB_COUNT}`);
- if (allSandboxes.length < SB_COUNT) throw new Error(`Only created ${allSandboxes.length}/${SB_COUNT} sandboxes`);
- dim(`Created in ${formatMs(createMs)}`);
-
- // Phase 2: Write 500MB to each
- cyan("Phase 2: Writing 500MB payload to each...");
- const { ms: writeMs } = await timed(async () => {
- await Promise.all(allSandboxes.map((sb, i) =>
- sb.commands.run(`dd if=/dev/urandom of=/workspace/payload.bin bs=1M count=500 2>/dev/null && echo chaos-${i} > /workspace/marker.txt`, { timeout: 120 })
- ));
- });
- dim(`Payloads written in ${formatMs(writeMs)}`);
-
- // Phase 3: Checkpoint all
- cyan("Phase 3: Creating 1 checkpoint on each...");
- for (let i = 0; i < allSandboxes.length; i++) {
- const cp = await allSandboxes[i].createCheckpoint(`chaos-${i}`);
- checkpointIds.push({ sandboxIdx: i, id: cp.id });
- }
-
- // Wait for all ready
- cyan("Waiting for all checkpoints ready...");
- let readyCount = 0;
- for (const cp of checkpointIds) {
- if (await waitForReady(allSandboxes[cp.sandboxIdx], cp.id)) readyCount++;
- }
- check(`All ${SB_COUNT} checkpoints ready`, readyCount === SB_COUNT, `${readyCount}/${SB_COUNT}`);
-
- // Phase 4: Kill 1 sandbox to make room, then fork 2 from checkpoints
- cyan("Phase 4: Killing sandbox 0 to make room for forks...");
- await allSandboxes[0].kill();
-
- cyan("Phase 4: Forking 2 sandboxes from checkpoints...");
- const fork1 = await Sandbox.createFromCheckpoint(checkpointIds[0].id);
- allSandboxes.push(fork1);
- const fork2 = await Sandbox.createFromCheckpoint(checkpointIds[2].id);
- allSandboxes.push(fork2);
-
- // Verify fork state
- const fork1Marker = await fork1.commands.run("cat /workspace/marker.txt");
- check("Fork 1 has correct state", fork1Marker.stdout.trim() === "chaos-0", fork1Marker.stdout.trim());
- const fork2Marker = await fork2.commands.run("cat /workspace/marker.txt");
- check("Fork 2 has correct state", fork2Marker.stdout.trim() === "chaos-2", fork2Marker.stdout.trim());
-
- // Phase 5: Restore 1 sandbox to its checkpoint
- cyan("Phase 5: Restoring sandbox 1...");
- await allSandboxes[1].commands.run("echo modified > /workspace/marker.txt");
- await allSandboxes[1].restoreCheckpoint(checkpointIds[1].id);
- const restored1 = await allSandboxes[1].commands.run("cat /workspace/marker.txt");
- check("Sandbox 1 restored correctly", restored1.stdout.trim() === "chaos-1", restored1.stdout.trim());
-
- // Phase 6: Verify remaining sandboxes respond (0 killed, 1,2 alive, 3=fork1, 4=fork2)
- cyan("Phase 6: Verifying remaining sandboxes...");
- const remainingIndices = [1, 2, 3, 4]; // indices into allSandboxes (0 killed)
- let respondOk = 0;
- for (const idx of remainingIndices) {
- try {
- const cmd = await allSandboxes[idx].commands.run("echo alive");
- if (cmd.stdout.trim() === "alive") respondOk++;
- } catch {
- dim(` Sandbox at index ${idx} not responding`);
- }
- }
- check(`All ${remainingIndices.length} remaining sandboxes respond`, respondOk === remainingIndices.length, `${respondOk}/${remainingIndices.length}`);
-
- // Phase 8: Delete all checkpoints
- cyan("Phase 8: Deleting all checkpoints...");
- for (const cp of checkpointIds) {
- // Use any living sandbox that owns the checkpoint
- const sb = allSandboxes[cp.sandboxIdx];
- await sb.deleteCheckpoint(cp.id).catch(() => {});
- }
- green("All checkpoints deleted");
-
- } finally {
- await killAll(allSandboxes);
- }
-}
-
-// ── Main runner ──────────────────────────────────────────────────────────
-
-interface TestEntry {
- num: number;
- name: string;
- fn: () => Promise<void>;
-}
-
-const ALL_TESTS: TestEntry[] = [
- { num: 1, name: "Max Concurrent Creates", fn: test1_maxConcurrentCreates },
- { num: 2, name: "Checkpoint Storm", fn: test2_checkpointStorm },
- { num: 3, name: "Fork Fan-Out", fn: test3_forkFanOut },
- { num: 4, name: "Restore Thrash", fn: test4_restoreThrash },
- { num: 5, name: "Disk Fill & CoW Divergence", fn: test5_cowDivergence },
- { num: 6, name: "Large Workspace Checkpoint (5GB)", fn: test6_largeCheckpoint },
- { num: 7, name: "Rapid Create-Kill Cycle", fn: test7_rapidCreateKill },
- { num: 8, name: "Long-Running Stability", fn: test8_longRunning },
- { num: 9, name: "Concurrent Checkpoint + Exec", fn: test9_concurrentCheckpointExec },
- { num: 10, name: "Full Lifecycle Chaos", fn: test10_lifecycleChaos },
-];
-
-async function main() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Stress Test Suite (50GB Dev) ║");
- bold("╚══════════════════════════════════════════════════╝\n");
-
- const only = process.env.STRESS_ONLY ? parseInt(process.env.STRESS_ONLY, 10) : 0;
- const skip = new Set(
- (process.env.STRESS_SKIP || "").split(",").filter(Boolean).map((s) => parseInt(s, 10))
- );
-
- const testsToRun = ALL_TESTS.filter((t) => {
- if (only > 0) return t.num === only;
- return !skip.has(t.num);
- });
-
- dim(`Running ${testsToRun.length} of ${ALL_TESTS.length} tests`);
- if (only > 0) dim(`STRESS_ONLY=${only}`);
- if (skip.size > 0) dim(`STRESS_SKIP=${Array.from(skip).join(",")}`);
-
- const testResults: { name: string; passed: number; failed: number; ms: number; error?: string }[] = [];
-
- for (let ti = 0; ti < testsToRun.length; ti++) {
- const test = testsToRun[ti];
-
- // Let worker finish cleanup from previous test
- if (ti > 0) await sleep(3000);
-
- const beforePassed = totalPassed;
- const beforeFailed = totalFailed;
- const start = Date.now();
-
- try {
- await test.fn();
- testResults.push({
- name: `${test.num}. ${test.name}`,
- passed: totalPassed - beforePassed,
- failed: totalFailed - beforeFailed,
- ms: Date.now() - start,
- });
- } catch (err: any) {
- red(`Test ${test.num} crashed: ${err.message}`);
- if (err.stack) dim(err.stack);
- totalFailed++;
- testResults.push({
- name: `${test.num}. ${test.name}`,
- passed: totalPassed - beforePassed,
- failed: totalFailed - beforeFailed,
- ms: Date.now() - start,
- error: err.message,
- });
- }
- }
-
- // ── Summary ────────────────────────────────────────────────────────────
- console.log();
- bold("╔══════════════════════════════════════════════════╗");
- bold("║ Summary ║");
- bold("╚══════════════════════════════════════════════════╝\n");
-
- const nameWidth = Math.max(...testResults.map((r) => r.name.length), 4);
- for (const r of testResults) {
- const status = r.failed === 0 ? "\x1b[32mPASS\x1b[0m" : "\x1b[31mFAIL\x1b[0m";
- const line = ` ${status} ${r.name.padEnd(nameWidth)} ${formatMs(r.ms).padStart(8)} (${r.passed}✓ ${r.failed}✗)`;
- console.log(line);
- if (r.error) dim(` Error: ${r.error}`);
- }
-
- console.log();
- bold(`Total: ${totalPassed} passed, ${totalFailed} failed`);
- const totalMs = testResults.reduce((s, r) => s + r.ms, 0);
- dim(`Total time: ${formatMs(totalMs)}`);
- console.log();
-
- if (totalFailed > 0) process.exit(1);
-}
-
-main().catch((err) => {
- console.error("Fatal:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/test-allowed-hosts.ts b/sdks/typescript/examples/test-allowed-hosts.ts
deleted file mode 100644
index f452edc7..00000000
--- a/sdks/typescript/examples/test-allowed-hosts.ts
+++ /dev/null
@@ -1,196 +0,0 @@
-/**
- * sandbox.getAllowedHosts() Test
- *
- * Verifies AllowedHostsInfo returned by sandbox.getAllowedHosts():
- * - sandboxID string
- * - secretStore string | undefined (undefined when no store)
- * - egressAllowlist string[] (hosts reachable via secrets proxy)
- * - perSecretAllowedHosts Record<string, string[]> (per-secret host restrictions)
- *
- * The server response also includes `baseSecretStore` (parent name for layered
- * forks; omitted when empty). The SDK type doesn't expose it yet, so the test
- * reads it via cast.
- *
- * Cases covered:
- * 1. Sandbox with no secret store → secretStore undefined, empty allowlist
- * 2. Sandbox with secret store → store name + aggregated egress allowlist
- * 3. Per-secret allowedHosts → surfaced under perSecretAllowedHosts
- * 4. Forked store (createFromCheckpoint) → baseSecretStore reflects parent
- *
- * Usage:
- * OPENCOMPUTER_API_URL=... OPENCOMPUTER_API_KEY=... npx tsx examples/test-allowed-hosts.ts
- */
-
-import { Sandbox, SecretStore } from "../src/index";
-
-function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }
-function red(msg: string, detail?: string) {
- console.log(`\x1b[31m✗ ${msg}${detail ? ` — ${detail}` : ""}\x1b[0m`);
-}
-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-
-let passed = 0;
-let failed = 0;
-
-function check(desc: string, condition: boolean, detail?: string) {
- if (condition) { green(desc); passed++; }
- else { red(desc, detail); failed++; }
-}
-
-async function main() {
- bold("\n=== sandbox.getAllowedHosts() ===\n");
-
- const suffix = Date.now();
- const baseStoreName = `allowed-hosts-base-${suffix}`;
- const forkStoreName = `allowed-hosts-fork-${suffix}`;
-
- let baseStoreId: string | null = null;
- let forkStoreId: string | null = null;
- let plainSandbox: Sandbox | null = null;
- let storeSandbox: Sandbox | null = null;
- let forkedSandbox: Sandbox | null = null;
- let checkpointId: string | null = null;
-
- try {
- // ── Setup: two secret stores ──────────────────────────────────────
- bold("--- Setup: create base + fork secret stores ---\n");
-
- const baseStore = await SecretStore.create({
- name: baseStoreName,
- egressAllowlist: ["api.anthropic.com", "github.com"],
- });
- baseStoreId = baseStore.id;
- await SecretStore.setSecret(baseStoreId, "GIT_TOKEN", "git_xyz", {
- allowedHosts: ["github.com"],
- });
- await SecretStore.setSecret(baseStoreId, "ANTHROPIC_KEY", "sk-ant-xyz");
- dim(`Base store: ${baseStoreId} (${baseStoreName})`);
-
- const forkStore = await SecretStore.create({
- name: forkStoreName,
- egressAllowlist: ["httpbin.org"],
- });
- forkStoreId = forkStore.id;
- await SecretStore.setSecret(forkStoreId, "EXTRA_KEY", "extra_val", {
- allowedHosts: ["httpbin.org"],
- });
- dim(`Fork store: ${forkStoreId} (${forkStoreName})`);
- console.log();
-
- // ── Case 1: sandbox with no secret store ──────────────────────────
- bold("--- Case 1: sandbox with no secret store ---\n");
-
- plainSandbox = await Sandbox.create({ timeout: 120 });
- const plainInfo = await plainSandbox.getAllowedHosts();
- const plainBase = (plainInfo as { baseSecretStore?: string }).baseSecretStore;
-
- check("sandboxID matches", plainInfo.sandboxID === plainSandbox.sandboxId,
- `got "${plainInfo.sandboxID}"`);
- check("secretStore is unset", plainInfo.secretStore === undefined,
- `got ${JSON.stringify(plainInfo.secretStore)}`);
- check("baseSecretStore is unset", plainBase === undefined || plainBase === "",
- `got ${JSON.stringify(plainBase)}`);
- check("egressAllowlist is empty array",
- Array.isArray(plainInfo.egressAllowlist) && plainInfo.egressAllowlist.length === 0,
- `got ${JSON.stringify(plainInfo.egressAllowlist)}`);
- check("perSecretAllowedHosts has no entries",
- Object.keys(plainInfo.perSecretAllowedHosts ?? {}).length === 0,
- `got ${JSON.stringify(plainInfo.perSecretAllowedHosts)}`);
- console.log();
-
- // ── Case 2 + 3: sandbox with secret store + per-secret hosts ──────
- bold("--- Case 2/3: sandbox with secret store ---\n");
-
- storeSandbox = await Sandbox.create({
- secretStore: baseStoreName,
- timeout: 120,
- });
- const storeInfo = await storeSandbox.getAllowedHosts();
- const storeBase = (storeInfo as { baseSecretStore?: string }).baseSecretStore;
-
- check("sandboxID matches", storeInfo.sandboxID === storeSandbox.sandboxId);
- check("secretStore name matches", storeInfo.secretStore === baseStoreName,
- `got "${storeInfo.secretStore}"`);
- check("baseSecretStore is unset (no fork)",
- storeBase === undefined || storeBase === "",
- `got ${JSON.stringify(storeBase)}`);
-
- const egress = storeInfo.egressAllowlist ?? [];
- check("egressAllowlist contains api.anthropic.com",
- egress.includes("api.anthropic.com"), `got ${JSON.stringify(egress)}`);
- check("egressAllowlist contains github.com",
- egress.includes("github.com"), `got ${JSON.stringify(egress)}`);
-
- const perSecret = storeInfo.perSecretAllowedHosts ?? {};
- check("perSecretAllowedHosts has GIT_TOKEN", "GIT_TOKEN" in perSecret,
- `keys: ${Object.keys(perSecret).join(", ")}`);
- check("GIT_TOKEN restricted to github.com",
- Array.isArray(perSecret.GIT_TOKEN) &&
- perSecret.GIT_TOKEN.length === 1 &&
- perSecret.GIT_TOKEN[0] === "github.com",
- `got ${JSON.stringify(perSecret.GIT_TOKEN)}`);
- check("ANTHROPIC_KEY has no per-secret restriction",
- !("ANTHROPIC_KEY" in perSecret),
- "secret without allowedHosts should not appear in perSecretAllowedHosts");
- console.log();
-
- // ── Case 4: forked sandbox via createFromCheckpoint ──────────────
- bold("--- Case 4: forked sandbox (baseSecretStore) ---\n");
-
- checkpointId = (await storeSandbox.createCheckpoint(`allowed-hosts-cp-${suffix}`)).id;
- dim(`Checkpoint: ${checkpointId}`);
-
- forkedSandbox = await Sandbox.createFromCheckpoint(checkpointId, {
- secretStore: forkStoreName,
- timeout: 120,
- });
- const forkInfo = await forkedSandbox.getAllowedHosts();
- const forkBase = (forkInfo as { baseSecretStore?: string }).baseSecretStore;
-
- check("sandboxID matches", forkInfo.sandboxID === forkedSandbox.sandboxId);
- check("secretStore is fork store", forkInfo.secretStore === forkStoreName,
- `got "${forkInfo.secretStore}"`);
- check("baseSecretStore is parent store",
- forkBase === baseStoreName,
- `got ${JSON.stringify(forkBase)}`);
-
- const forkEgress = forkInfo.egressAllowlist ?? [];
- check("forked egress includes parent host (github.com)",
- forkEgress.includes("github.com"), `got ${JSON.stringify(forkEgress)}`);
- check("forked egress includes child host (httpbin.org)",
- forkEgress.includes("httpbin.org"), `got ${JSON.stringify(forkEgress)}`);
-
- const forkPerSecret = forkInfo.perSecretAllowedHosts ?? {};
- check("forked perSecret includes parent GIT_TOKEN",
- "GIT_TOKEN" in forkPerSecret);
- check("forked perSecret includes child EXTRA_KEY",
- "EXTRA_KEY" in forkPerSecret);
- console.log();
-
- } catch (err: any) {
- red(`Fatal error: ${err.message}`);
- if (err.stack) dim(err.stack);
- failed++;
- } finally {
- // Cleanup
- for (const sb of [plainSandbox, storeSandbox, forkedSandbox]) {
- if (sb) { try { await sb.kill(); } catch {} }
- }
- if (checkpointId && storeSandbox) {
- try { await storeSandbox.deleteCheckpoint(checkpointId); } catch {}
- }
- if (forkStoreId) { try { await SecretStore.delete(forkStoreId); } catch {} }
- if (baseStoreId) { try { await SecretStore.delete(baseStoreId); } catch {} }
- }
-
- bold("========================================");
- bold(` Results: ${passed} passed, ${failed} failed`);
- bold("========================================\n");
- if (failed > 0) process.exit(1);
-}
-
-main().catch((err) => {
- console.error("Fatal error:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/test-checkpoint-patches.ts b/sdks/typescript/examples/test-checkpoint-patches.ts
deleted file mode 100644
index 9bbc3ed9..00000000
--- a/sdks/typescript/examples/test-checkpoint-patches.ts
+++ /dev/null
@@ -1,298 +0,0 @@
-/**
- * Checkpoint Patch System Test
- *
- * Tests:
- * 1. Create a sandbox, checkpoint it, create a patch
- * 2. Fork a sandbox — verify patch is applied on boot
- * 3. Create a second patch, hibernate fork, wake it — verify both patches applied
- * 4. List patches and verify ordering
- * 5. Bad patch blocks the chain
- * 6. Delete the bad patch — recovery on next wake
- * 7. Delete a patch and verify list updates
- *
- * Usage:
- * npx tsx examples/test-checkpoint-patches.ts
- *
- * Environment:
- * OPENCOMPUTER_API_URL (default: https://app.opencomputer.dev)
- * OPENCOMPUTER_API_KEY (required)
- */
-
-import { Sandbox } from "../src/index";
-
-function green(msg: string) { console.log(`\x1b[32m\u2713 ${msg}\x1b[0m`); }
-function red(msg: string) { console.log(`\x1b[31m\u2717 ${msg}\x1b[0m`); }
-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-
-let passed = 0;
-let failed = 0;
-
-function check(desc: string, condition: boolean, detail?: string) {
- if (condition) {
- green(desc);
- passed++;
- } else {
- red(`${desc}${detail ? ` (${detail})` : ""}`);
- failed++;
- }
-}
-
-async function sleep(ms: number) {
- return new Promise((r) => globalThis.setTimeout(r, ms));
-}
-
-async function waitForSandboxReady(sandbox: Sandbox, timeoutMs = 60000): Promise<boolean> {
- const start = Date.now();
- while (Date.now() - start < timeoutMs) {
- try {
- const result = await sandbox.commands.run("echo ready", { timeout: 10 });
- if (result.stdout.trim() === "ready") return true;
- } catch {
- // sandbox not ready yet
- }
- await sleep(3000);
- }
- return false;
-}
-
-async function waitForCheckpointReady(sandbox: Sandbox, checkpointId: string, timeoutMs = 60000): Promise<boolean> {
- const start = Date.now();
- while (Date.now() - start < timeoutMs) {
- const checkpoints = await sandbox.listCheckpoints();
- const cp = checkpoints.find((c) => c.id === checkpointId);
- if (cp && cp.status === "ready") return true;
- if (cp && cp.status !== "processing") return false;
- await sleep(2000);
- }
- return false;
-}
-
-async function main() {
- bold("\n====================================================");
- bold(" Checkpoint Patch System Test");
- bold("====================================================\n");
-
- const sandboxes: Sandbox[] = [];
-
- try {
- // ── Setup: Create source sandbox with initial state ──────────
- bold("--- Setup: Create source sandbox and checkpoint ---\n");
-
- const source = await Sandbox.create({ template: "base", timeout: 600 });
- sandboxes.push(source);
- green(`Created source sandbox: ${source.sandboxId}`);
-
- await source.commands.run("echo 'python3.10' > /root/python-version.txt");
- const initial = await source.commands.run("cat /root/python-version.txt");
- check("Initial state set", initial.stdout.trim() === "python3.10");
-
- const cp = await source.createCheckpoint("patch-base");
- dim(`Checkpoint ID: ${cp.id}`);
-
- dim("Waiting for checkpoint to be ready...");
- const ready = await waitForCheckpointReady(source, cp.id);
- check("Checkpoint is ready", ready);
- if (!ready) throw new Error("Checkpoint not ready, cannot proceed");
- console.log();
-
- // ── Test 1: Create a patch ──────────────────────────────────
- bold("--- Test 1: Create a patch ---\n");
-
- const patchResult = await Sandbox.createCheckpointPatch(cp.id, {
- script: "echo 'python3.11' > /root/python-version.txt && echo 'patched' > /root/patch-applied.txt",
- description: "Upgrade Python version marker",
- });
-
- check("Patch created", patchResult.patch.id !== undefined);
- check("Patch sequence is 1", patchResult.patch.sequence === 1);
- dim(`Patch ID: ${patchResult.patch.id}`);
- console.log();
-
- // ── Test 2: Fork sandbox — patch applied on boot ────────────
- bold("--- Test 2: Fork sandbox — patch applied on boot ---\n");
-
- const fork1 = await Sandbox.createFromCheckpoint(cp.id, { timeout: 600 });
- sandboxes.push(fork1);
- green(`Fork 1 created: ${fork1.sandboxId}`);
-
- dim("Waiting for fork 1 to be ready...");
- const fork1Ready = await waitForSandboxReady(fork1);
- check("Fork 1 is ready", fork1Ready);
- if (!fork1Ready) throw new Error("Fork 1 not ready, cannot proceed");
-
- // Give patches a moment to complete after sandbox is accepting commands
- await sleep(5000);
-
- const f1Patched = await fork1.commands.run("cat /root/python-version.txt");
- check("Fork 1 has patched state (applied on boot)", f1Patched.stdout.trim() === "python3.11", `got: ${f1Patched.stdout.trim()}`);
-
- const f1Marker = await fork1.commands.run("cat /root/patch-applied.txt");
- check("Fork 1 has patch marker", f1Marker.stdout.trim() === "patched");
- console.log();
-
- // ── Test 3: Second patch + hibernate/wake ───────────────────
- bold("--- Test 3: Second patch applied after hibernate + wake ---\n");
-
- const patch2Result = await Sandbox.createCheckpointPatch(cp.id, {
- script: "echo 'security-fix-applied' > /root/security-patch.txt",
- description: "Security hotfix",
- });
-
- check("Second patch created", patch2Result.patch.id !== undefined);
- check("Patch sequence is 2", patch2Result.patch.sequence === 2);
-
- const f1Security = await fork1.commands.run("test -f /root/security-patch.txt && echo exists || echo missing");
- check("Patch not applied to running sandbox", f1Security.stdout.trim() === "missing");
-
- dim("Hibernating fork 1...");
- await fork1.hibernate();
- green("Fork 1 hibernated");
-
- await sleep(3000);
-
- dim("Waking fork 1...");
- await fork1.wake({ timeout: 600 });
- green("Fork 1 woken");
-
- dim("Waiting for fork 1 to be ready after wake...");
- const fork1WakeReady = await waitForSandboxReady(fork1);
- check("Fork 1 ready after wake", fork1WakeReady);
- await sleep(5000);
-
- const f1SecurityAfterWake = await fork1.commands.run("cat /root/security-patch.txt");
- check("Second patch applied after wake", f1SecurityAfterWake.stdout.trim() === "security-fix-applied", `got: ${f1SecurityAfterWake.stdout.trim()}`);
-
- const f1PythonAfterWake = await fork1.commands.run("cat /root/python-version.txt");
- check("Prior patch state preserved after wake", f1PythonAfterWake.stdout.trim() === "python3.11", `got: ${f1PythonAfterWake.stdout.trim()}`);
- console.log();
-
- // ── Test 4: List patches ─────────────────────────────────────
- bold("--- Test 4: List patches ---\n");
-
- const patches = await Sandbox.listCheckpointPatches(cp.id);
- check("2 patches listed", patches.length === 2, `got ${patches.length}`);
- check("First patch has sequence 1", patches[0]?.sequence === 1);
- check("Second patch has sequence 2", patches[1]?.sequence === 2);
- console.log();
-
- // ── Test 5: Bad patch blocks the chain ───────────────────────
- bold("--- Test 5: Bad patch blocks the chain ---\n");
-
- const badPatch = await Sandbox.createCheckpointPatch(cp.id, {
- script: "exit 1",
- description: "Intentionally failing patch",
- });
-
- check("Bad patch created", badPatch.patch.id !== undefined);
- check("Bad patch sequence is 3", badPatch.patch.sequence === 3);
- dim(`Bad patch ID: ${badPatch.patch.id}`);
-
- // Add a 4th patch after the bad one
- const patch4Result = await Sandbox.createCheckpointPatch(cp.id, {
- script: "echo 'post-bad' > /root/patch4.txt",
- description: "Patch after the bad one",
- });
- check("Patch 4 created (after bad)", patch4Result.patch.sequence === 4);
-
- // Fork — bad patch should block patch 4 from applying
- const fork2 = await Sandbox.createFromCheckpoint(cp.id, { timeout: 600 });
- sandboxes.push(fork2);
- green(`Fork 2 created: ${fork2.sandboxId}`);
-
- dim("Waiting for fork 2 to be ready...");
- const fork2Ready = await waitForSandboxReady(fork2);
- check("Fork 2 is ready", fork2Ready);
- if (!fork2Ready) throw new Error("Fork 2 not ready, cannot proceed");
- await sleep(5000);
-
- // Patches 1+2 should apply, patch 3 fails, patch 4 never runs
- const f2Patched = await fork2.commands.run("cat /root/python-version.txt");
- check("Good patches applied before bad one", f2Patched.stdout.trim() === "python3.11", `got: ${f2Patched.stdout.trim()}`);
-
- const f2Security = await fork2.commands.run("cat /root/security-patch.txt");
- check("Patch 2 applied", f2Security.stdout.trim() === "security-fix-applied", `got: ${f2Security.stdout.trim()}`);
-
- const f2Patch4 = await fork2.commands.run("test -f /root/patch4.txt && echo exists || echo missing");
- check("Patch 4 blocked by bad patch 3", f2Patch4.stdout.trim() === "missing");
- console.log();
-
- // ── Test 6: Delete bad patch — recovery on wake ──────────────
- bold("--- Test 6: Delete bad patch — recovery on wake ---\n");
-
- dim(`Deleting bad patch ${badPatch.patch.id}...`);
- await Sandbox.deleteCheckpointPatch(cp.id, badPatch.patch.id);
- green("Bad patch deleted");
-
- // Verify it's gone from the list
- const patchesAfterDelete = await Sandbox.listCheckpointPatches(cp.id);
- check("3 patches remaining after delete", patchesAfterDelete.length === 3, `got ${patchesAfterDelete.length}`);
- const sequences = patchesAfterDelete.map((p) => p.sequence);
- check("Remaining sequences are 1, 2, 4", JSON.stringify(sequences) === "[1,2,4]", `got ${JSON.stringify(sequences)}`);
-
- // Hibernate fork2 and wake — patch 4 should now apply (bad patch 3 is gone)
- dim("Hibernating fork 2...");
- await fork2.hibernate();
- green("Fork 2 hibernated");
-
- await sleep(3000);
-
- dim("Waking fork 2...");
- await fork2.wake({ timeout: 600 });
- green("Fork 2 woken");
-
- dim("Waiting for fork 2 to be ready after wake...");
- const fork2WakeReady = await waitForSandboxReady(fork2);
- check("Fork 2 ready after wake", fork2WakeReady);
- await sleep(5000);
-
- const f2Patch4AfterWake = await fork2.commands.run("cat /root/patch4.txt");
- check("Patch 4 applied after deleting bad patch and waking", f2Patch4AfterWake.stdout.trim() === "post-bad", `got: ${f2Patch4AfterWake.stdout.trim()}`);
-
- // Prior state still intact
- const f2PythonAfterWake = await fork2.commands.run("cat /root/python-version.txt");
- check("All prior patches preserved", f2PythonAfterWake.stdout.trim() === "python3.11", `got: ${f2PythonAfterWake.stdout.trim()}`);
- console.log();
-
- // ── Test 7: Delete is idempotent ─────────────────────────────
- bold("--- Test 7: Delete is idempotent ---\n");
-
- // Deleting the same patch again should not throw
- let deleteAgainOk = true;
- try {
- await Sandbox.deleteCheckpointPatch(cp.id, badPatch.patch.id);
- } catch {
- deleteAgainOk = false;
- }
- check("Deleting already-deleted patch does not throw", deleteAgainOk);
- console.log();
-
- } catch (err: any) {
- red(`Fatal error: ${err.message}`);
- if (err.stack) dim(err.stack);
- failed++;
- } finally {
- // Cleanup
- bold("--- Cleanup ---\n");
- for (const sb of sandboxes) {
- try {
- await sb.kill();
- green(`Killed ${sb.sandboxId}`);
- } catch {
- /* best effort */
- }
- }
- }
-
- // --- Summary ---
- console.log();
- bold("========================================");
- bold(` Results: ${passed} passed, ${failed} failed`);
- bold("========================================\n");
- if (failed > 0) process.exit(1);
-}
-
-main().catch((err) => {
- console.error("Fatal error:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/test-checkpoints.ts b/sdks/typescript/examples/test-checkpoints.ts
deleted file mode 100644
index 5455a5a6..00000000
--- a/sdks/typescript/examples/test-checkpoints.ts
+++ /dev/null
@@ -1,244 +0,0 @@
-/**
- * Checkpoint Feature Test
- *
- * Tests:
- * 1. Create a named checkpoint of a running sandbox
- * 2. List checkpoints
- * 3. Create a second checkpoint with different state
- * 4. Restore to first checkpoint (in-place revert)
- * 5. Verify state was reverted
- * 6. Fork a new sandbox from a checkpoint
- * 7. Verify forked sandbox has checkpoint state
- * 8. Delete a checkpoint
- * 9. Duplicate name is rejected
- * 10. Max 10 checkpoint limit
- *
- * Usage:
- * npx tsx examples/test-checkpoints.ts
- */
-
-import { Sandbox } from "../src/index";
-
-function green(msg: string) { console.log(`\x1b[32m\u2713 ${msg}\x1b[0m`); }
-function red(msg: string) { console.log(`\x1b[31m\u2717 ${msg}\x1b[0m`); }
-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-
-let passed = 0;
-let failed = 0;
-
-function check(desc: string, condition: boolean, detail?: string) {
- if (condition) {
- green(desc);
- passed++;
- } else {
- red(`${desc}${detail ? ` (${detail})` : ""}`);
- failed++;
- }
-}
-
-async function sleep(ms: number) {
- return new Promise((r) => globalThis.setTimeout(r, ms));
-}
-
-async function waitForCheckpointReady(sandbox: Sandbox, checkpointId: string, timeoutMs = 60000): Promise<boolean> {
- const start = Date.now();
- while (Date.now() - start < timeoutMs) {
- const checkpoints = await sandbox.listCheckpoints();
- const cp = checkpoints.find((c) => c.id === checkpointId);
- if (cp && cp.status === "ready") return true;
- if (cp && cp.status !== "processing") return false; // failed or other
- await sleep(2000);
- }
- return false;
-}
-
-async function main() {
- bold("\n\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557");
- bold("\u2551 Checkpoint Feature Test \u2551");
- bold("\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\n");
-
- let sandbox: Sandbox | null = null;
- let forkedSandbox: Sandbox | null = null;
-
- try {
- // ── Setup: Create sandbox and write initial state ──────────────
- bold("━━━ Setup: Create sandbox ━━━\n");
-
- sandbox = await Sandbox.create({ template: "base", timeout: 300 });
- green(`Created sandbox: ${sandbox.sandboxId}`);
-
- // Write a marker file so we can verify state after restore
- await sandbox.commands.run("echo version-1 > /workspace/marker.txt");
- const v1 = await sandbox.commands.run("cat /workspace/marker.txt");
- check("Initial state written", v1.stdout.trim() === "version-1");
- console.log();
-
- // ── Test 1: Create first checkpoint ───────────────────────────
- bold("━━━ Test 1: Create checkpoint ━━━\n");
-
- const cp1 = await sandbox.createCheckpoint("v1-baseline");
- check("Checkpoint created", cp1.id !== undefined && cp1.id.length > 0);
- check("Checkpoint name is correct", cp1.name === "v1-baseline");
- check("Checkpoint status is processing or ready", cp1.status === "processing" || cp1.status === "ready");
- dim(`Checkpoint ID: ${cp1.id}`);
- console.log();
-
- // ── Test 2: List checkpoints ──────────────────────────────────
- bold("━━━ Test 2: List checkpoints ━━━\n");
-
- const list1 = await sandbox.listCheckpoints();
- check("List returns 1 checkpoint", list1.length === 1, `got ${list1.length}`);
- check("Listed checkpoint has correct name", list1[0]?.name === "v1-baseline");
- console.log();
-
- // ── Test 3: Modify state and create second checkpoint ─────────
- bold("━━━ Test 3: Create second checkpoint with different state ━━━\n");
-
- await sandbox.commands.run("echo version-2 > /workspace/marker.txt");
- await sandbox.commands.run("echo extra-data > /workspace/extra.txt");
- const v2 = await sandbox.commands.run("cat /workspace/marker.txt");
- check("State modified to version-2", v2.stdout.trim() === "version-2");
-
- const cp2 = await sandbox.createCheckpoint("v2-modified");
- check("Second checkpoint created", cp2.id !== undefined);
- dim(`Checkpoint ID: ${cp2.id}`);
-
- const list2 = await sandbox.listCheckpoints();
- check("List now returns 2 checkpoints", list2.length === 2, `got ${list2.length}`);
- console.log();
-
- // ── Test 4: Wait for first checkpoint to be ready ─────────────
- bold("━━━ Test 4: Wait for checkpoint ready ━━━\n");
-
- dim("Waiting for v1-baseline checkpoint to become ready...");
- const cp1Ready = await waitForCheckpointReady(sandbox, cp1.id);
- check("First checkpoint is ready", cp1Ready);
-
- if (!cp1Ready) {
- red("Cannot proceed with restore tests - checkpoint not ready");
- throw new Error("Checkpoint not ready");
- }
- console.log();
-
- // ── Test 5: Restore to first checkpoint ───────────────────────
- bold("━━━ Test 5: Restore to v1-baseline checkpoint ━━━\n");
-
- dim("Restoring sandbox to v1-baseline...");
- await sandbox.restoreCheckpoint(cp1.id);
- green("Restore completed");
-
- // Wait a moment for the VM to boot
- await sleep(3000);
-
- // Verify state was reverted
- const restored = await sandbox.commands.run("cat /workspace/marker.txt");
- check("Marker file reverted to version-1", restored.stdout.trim() === "version-1", `got: ${restored.stdout.trim()}`);
-
- // The extra.txt should NOT exist since it was created after v1
- const extraCheck = await sandbox.commands.run("test -f /workspace/extra.txt && echo exists || echo missing");
- check("Extra file does not exist after restore", extraCheck.stdout.trim() === "missing", `got: ${extraCheck.stdout.trim()}`);
- console.log();
-
- // ── Test 6: Wait for second checkpoint and fork ───────────────
- bold("━━━ Test 6: Fork new sandbox from v2-modified checkpoint ━━━\n");
-
- dim("Waiting for v2-modified checkpoint to become ready...");
- const cp2Ready = await waitForCheckpointReady(sandbox, cp2.id);
- check("Second checkpoint is ready", cp2Ready);
-
- if (cp2Ready) {
- dim("Creating new sandbox from v2-modified checkpoint...");
- forkedSandbox = await Sandbox.createFromCheckpoint(cp2.id);
- green(`Forked sandbox created: ${forkedSandbox.sandboxId}`);
- check("Forked sandbox has different ID", forkedSandbox.sandboxId !== sandbox.sandboxId);
-
- // Wait for forked sandbox to be ready
- await sleep(3000);
-
- // Verify the forked sandbox has v2 state
- const forkedMarker = await forkedSandbox.commands.run("cat /workspace/marker.txt");
- check("Forked sandbox has version-2 state", forkedMarker.stdout.trim() === "version-2", `got: ${forkedMarker.stdout.trim()}`);
-
- const forkedExtra = await forkedSandbox.commands.run("cat /workspace/extra.txt");
- check("Forked sandbox has extra.txt", forkedExtra.stdout.trim() === "extra-data", `got: ${forkedExtra.stdout.trim()}`);
- } else {
- dim("Skipping fork test - checkpoint not ready");
- }
- console.log();
-
- // ── Test 7: Delete a checkpoint ───────────────────────────────
- bold("━━━ Test 7: Delete checkpoint ━━━\n");
-
- await sandbox.deleteCheckpoint(cp2.id);
- green("Deleted v2-modified checkpoint");
-
- const listAfterDelete = await sandbox.listCheckpoints();
- check("List returns 1 checkpoint after delete", listAfterDelete.length === 1, `got ${listAfterDelete.length}`);
- check("Remaining checkpoint is v1-baseline", listAfterDelete[0]?.name === "v1-baseline");
- console.log();
-
- // ── Test 8: Duplicate name rejected ───────────────────────────
- bold("━━━ Test 8: Duplicate checkpoint name ━━━\n");
-
- try {
- await sandbox.createCheckpoint("v1-baseline");
- red("Should have rejected duplicate name");
- failed++;
- } catch (err: any) {
- check("Duplicate name rejected with error", err.message.includes("409") || err.message.includes("already exists"), err.message);
- }
- console.log();
-
- // ── Test 9: Max 10 checkpoints limit ──────────────────────────
- bold("━━━ Test 9: Max checkpoint limit ━━━\n");
-
- // We already have 1 checkpoint (v1-baseline), create 9 more to hit the limit
- dim("Creating 9 more checkpoints to reach the limit...");
- for (let i = 2; i <= 10; i++) {
- try {
- await sandbox.createCheckpoint(`limit-test-${i}`);
- } catch (err: any) {
- red(`Failed to create checkpoint limit-test-${i}: ${err.message}`);
- failed++;
- }
- }
-
- const listFull = await sandbox.listCheckpoints();
- check("10 checkpoints exist", listFull.length === 10, `got ${listFull.length}`);
-
- // The 11th should fail
- try {
- await sandbox.createCheckpoint("one-too-many");
- red("Should have rejected 11th checkpoint");
- failed++;
- } catch (err: any) {
- check("11th checkpoint rejected (max 10)", err.message.includes("400") || err.message.includes("maximum"), err.message);
- }
- console.log();
-
- } catch (err: any) {
- red(`Fatal error: ${err.message}`);
- if (err.stack) dim(err.stack);
- failed++;
- } finally {
- // Cleanup
- if (forkedSandbox) {
- try { await forkedSandbox.kill(); green("Forked sandbox killed"); } catch { /* best effort */ }
- }
- if (sandbox) {
- try { await sandbox.kill(); green("Original sandbox killed"); } catch { /* best effort */ }
- }
- }
-
- // --- Summary ---
- bold("========================================");
- bold(` Results: ${passed} passed, ${failed} failed`);
- bold("========================================\n");
- if (failed > 0) process.exit(1);
-}
-
-main().catch((err) => {
- console.error("Fatal error:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/test-commands.ts b/sdks/typescript/examples/test-commands.ts
deleted file mode 100644
index 1d39a702..00000000
--- a/sdks/typescript/examples/test-commands.ts
+++ /dev/null
@@ -1,236 +0,0 @@
-/**
- * Command Edge Cases Test
- *
- * Tests:
- * 1. Long-running command with timeout
- * 2. Command that writes to stderr
- * 3. Non-zero exit codes
- * 4. Large stdout output
- * 5. Environment variable passing
- * 6. Working directory
- * 7. Pipe and shell features
- * 8. Concurrent commands on same sandbox
- *
- * Usage:
- * npx tsx examples/test-commands.ts
- */
-
-import { Sandbox } from "../src/index";
-
-function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }
-function red(msg: string) { console.log(`\x1b[31m✗ ${msg}\x1b[0m`); }
-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-
-let passed = 0;
-let failed = 0;
-
-function check(desc: string, condition: boolean, detail?: string) {
- if (condition) {
- green(desc);
- passed++;
- } else {
- red(`${desc}${detail ? ` (${detail})` : ""}`);
- failed++;
- }
-}
-
-async function main() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Command Edge Cases Test ║");
- bold("╚══════════════════════════════════════════════════╝\n");
-
- let sandbox: Sandbox | null = null;
-
- try {
- sandbox = await Sandbox.create({ template: "base", timeout: 120 });
- green(`Created sandbox: ${sandbox.sandboxId}`);
- console.log();
-
- // ── Test 1: Basic command ───────────────────────────────────────
- bold("━━━ Test 1: Basic commands ━━━\n");
-
- const echo = await sandbox.commands.run("echo hello-world");
- check("Echo returns correct output", echo.stdout.trim() === "hello-world");
- check("Echo exit code is 0", echo.exitCode === 0);
-
- const multi = await sandbox.commands.run("echo line1 && echo line2 && echo line3");
- const lines = multi.stdout.trim().split("\n");
- check("Multi-command outputs 3 lines", lines.length === 3);
- check("Multi-command content correct", lines[0] === "line1" && lines[2] === "line3");
- console.log();
-
- // ── Test 2: stderr handling ─────────────────────────────────────
- bold("━━━ Test 2: stderr handling ━━━\n");
-
- const stderrCmd = await sandbox.commands.run("echo error-msg >&2");
- check("stderr captured", stderrCmd.stderr.trim() === "error-msg");
- check("stdout empty when writing to stderr", stderrCmd.stdout.trim() === "");
- check("Exit code 0 even with stderr", stderrCmd.exitCode === 0);
-
- // Mixed stdout + stderr
- const mixed = await sandbox.commands.run("echo stdout-data && echo stderr-data >&2");
- check("Mixed: stdout captured", mixed.stdout.includes("stdout-data"));
- check("Mixed: stderr captured", mixed.stderr.includes("stderr-data"));
- console.log();
-
- // ── Test 3: Non-zero exit codes ─────────────────────────────────
- bold("━━━ Test 3: Non-zero exit codes ━━━\n");
-
- const exit1 = await sandbox.commands.run("exit 1");
- check("Exit code 1 captured", exit1.exitCode === 1, `got ${exit1.exitCode}`);
-
- const exit42 = await sandbox.commands.run("exit 42");
- check("Exit code 42 captured", exit42.exitCode === 42, `got ${exit42.exitCode}`);
-
- const falseCmd = await sandbox.commands.run("false");
- check("'false' returns exit code 1", falseCmd.exitCode === 1, `got ${falseCmd.exitCode}`);
-
- const notFound = await sandbox.commands.run("nonexistent-command-xyz 2>&1 || true");
- check("Non-existent command handled", notFound.exitCode === 0);
- console.log();
-
- // ── Test 4: Large stdout ────────────────────────────────────────
- bold("━━━ Test 4: Large stdout output ━━━\n");
-
- // Generate ~100KB of output
- const largeOut = await sandbox.commands.run("seq 1 10000");
- const lineCount = largeOut.stdout.trim().split("\n").length;
- check("10000 lines of output captured", lineCount === 10000, `got ${lineCount} lines`);
- dim(`Output size: ${largeOut.stdout.length} chars`);
-
- // Verify first and last
- const largeLines = largeOut.stdout.trim().split("\n");
- check("First line is 1", largeLines[0] === "1");
- check("Last line is 10000", largeLines[lineCount - 1] === "10000");
- console.log();
-
- // ── Test 5: Environment variables ───────────────────────────────
- bold("━━━ Test 5: Environment variable passing ━━━\n");
-
- const envResult = await sandbox.commands.run("echo $MY_VAR", {
- env: { MY_VAR: "secret-value-123" },
- });
- check("Env var passed correctly", envResult.stdout.trim() === "secret-value-123");
-
- // Multiple env vars
- const multiEnv = await sandbox.commands.run('echo "$A:$B:$C"', {
- env: { A: "alpha", B: "beta", C: "gamma" },
- });
- check("Multiple env vars", multiEnv.stdout.trim() === "alpha:beta:gamma");
-
- // Env var with special characters
- const specialEnv = await sandbox.commands.run("echo $SPECIAL", {
- env: { SPECIAL: "hello world with spaces & stuff" },
- });
- check("Env var with special chars", specialEnv.stdout.trim() === "hello world with spaces & stuff");
- console.log();
-
- // ── Test 6: Working directory ───────────────────────────────────
- bold("━━━ Test 6: Working directory ━━━\n");
-
- await sandbox.commands.run("mkdir -p /tmp/workdir/sub");
- await sandbox.files.write("/tmp/workdir/sub/data.txt", "found-it");
-
- const cwdResult = await sandbox.commands.run("cat data.txt", {
- cwd: "/tmp/workdir/sub",
- });
- check("Working directory respected", cwdResult.stdout.trim() === "found-it");
-
- const pwdResult = await sandbox.commands.run("pwd", { cwd: "/tmp/workdir" });
- check("pwd reflects cwd", pwdResult.stdout.trim() === "/tmp/workdir");
- console.log();
-
- // ── Test 7: Shell features ──────────────────────────────────────
- bold("━━━ Test 7: Shell features (pipes, redirects, subshells) ━━━\n");
-
- // Pipes
- const pipeResult = await sandbox.commands.run("echo 'hello world' | tr ' ' '-'");
- check("Pipe works", pipeResult.stdout.trim() === "hello-world");
-
- // Subshell
- const subshell = await sandbox.commands.run("echo $(hostname)");
- check("Command substitution works", subshell.stdout.trim().length > 0, subshell.stdout.trim());
-
- // Redirect
- await sandbox.commands.run("echo redirect-test > /tmp/redirect.txt");
- const redirectContent = await sandbox.files.read("/tmp/redirect.txt");
- check("Redirect to file works", redirectContent.trim() === "redirect-test");
-
- // Wildcards
- await sandbox.commands.run("touch /tmp/wc-a.txt /tmp/wc-b.txt /tmp/wc-c.txt");
- const wcResult = await sandbox.commands.run("ls /tmp/wc-*.txt | wc -l");
- check("Wildcard expansion works", wcResult.stdout.trim() === "3");
-
- // Arithmetic
- const arith = await sandbox.commands.run("echo $((42 * 7))");
- check("Arithmetic expansion works", arith.stdout.trim() === "294");
-
- // Here string (bash-only feature, use bash explicitly)
- const hereStr = await sandbox.commands.run("bash -c \"cat <<< 'here-string-data'\"");
- check("Here string works", hereStr.stdout.trim() === "here-string-data");
- console.log();
-
- // ── Test 8: Concurrent commands on same sandbox ─────────────────
- bold("━━━ Test 8: Concurrent commands on same sandbox ━━━\n");
-
- const concurrentStart = Date.now();
- const concurrentPromises = Array.from({ length: 10 }, (_, i) =>
- sandbox!.commands.run(`echo concurrent-${i}`).then((r) => ({
- index: i,
- output: r.stdout.trim(),
- exitCode: r.exitCode,
- })),
- );
-
- const concurrentResults = await Promise.all(concurrentPromises);
- const concurrentMs = Date.now() - concurrentStart;
-
- let allCorrect = true;
- for (const r of concurrentResults) {
- if (r.output !== `concurrent-${r.index}` || r.exitCode !== 0) {
- allCorrect = false;
- dim(`Command ${r.index}: expected "concurrent-${r.index}", got "${r.output}" (exit ${r.exitCode})`);
- }
- }
- check("10 concurrent commands all returned correctly", allCorrect);
- dim(`Total concurrent time: ${concurrentMs}ms`);
- console.log();
-
- // ── Test 9: Command timeout ─────────────────────────────────────
- bold("━━━ Test 9: Command timeout ━━━\n");
-
- const timeoutStart = Date.now();
- try {
- await sandbox.commands.run("sleep 30", { timeout: 3 });
- // If it returns, check that it was killed (non-zero exit)
- const timeoutMs = Date.now() - timeoutStart;
- check("Command timed out within ~3s", timeoutMs < 10000, `took ${timeoutMs}ms`);
- } catch (err: any) {
- const timeoutMs = Date.now() - timeoutStart;
- check("Command timed out within ~3s", timeoutMs < 10000, `took ${timeoutMs}ms, error: ${err.message}`);
- }
- console.log();
-
- } catch (err: any) {
- red(`Fatal error: ${err.message}`);
- if (err.stack) dim(err.stack);
- failed++;
- } finally {
- if (sandbox) {
- await sandbox.kill();
- green("Sandbox killed");
- }
- }
-
- // --- Summary ---
- bold("========================================");
- bold(` Results: ${passed} passed, ${failed} failed`);
- bold("========================================\n");
- if (failed > 0) process.exit(1);
-}
-
-main().catch((err) => {
- console.error("Fatal error:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/test-concurrent.ts b/sdks/typescript/examples/test-concurrent.ts
deleted file mode 100644
index c8f0bed1..00000000
--- a/sdks/typescript/examples/test-concurrent.ts
+++ /dev/null
@@ -1,242 +0,0 @@
-/**
- * Concurrent Sandbox Test
- *
- * Tests:
- * 1. Create 5 sandboxes simultaneously
- * 2. Run commands on all in parallel
- * 3. Verify each sandbox is isolated
- * 4. Kill all in parallel
- *
- * Usage:
- * npx tsx examples/test-concurrent.ts
- */
-
-import { Sandbox } from "../src/index";
-
-function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }
-function red(msg: string) { console.log(`\x1b[31m✗ ${msg}\x1b[0m`); }
-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-
-let passed = 0;
-let failed = 0;
-
-function check(desc: string, condition: boolean, detail?: string) {
- if (condition) {
- green(desc);
- passed++;
- } else {
- red(`${desc}${detail ? ` (${detail})` : ""}`);
- failed++;
- }
-}
-
-const SANDBOX_COUNT = 5;
-
-async function main() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Concurrent Sandbox Test ║");
- bold("╚══════════════════════════════════════════════════╝\n");
-
- const sandboxes: Sandbox[] = [];
-
- try {
- // ── Test 1: Create N sandboxes simultaneously ───────────────────
- bold(`━━━ Test 1: Create ${SANDBOX_COUNT} sandboxes simultaneously ━━━\n`);
-
- const createStart = Date.now();
- const createPromises = Array.from({ length: SANDBOX_COUNT }, (_, i) =>
- Sandbox.create({ template: "base", timeout: 120 })
- .then((sb) => {
- dim(`Sandbox ${i + 1}: ${sb.sandboxId} (${sb.domain})`);
- return sb;
- }),
- );
-
- const results = await Promise.allSettled(createPromises);
- const createMs = Date.now() - createStart;
-
- for (let i = 0; i < results.length; i++) {
- const r = results[i];
- if (r.status === "fulfilled") {
- sandboxes.push(r.value);
- check(`Sandbox ${i + 1} created`, true);
- } else {
- check(`Sandbox ${i + 1} created`, false, r.reason.message);
- }
- }
- dim(`Total create time: ${createMs}ms (${(createMs / SANDBOX_COUNT).toFixed(0)}ms avg)`);
- console.log();
-
- // ── Test 2: Run commands on all in parallel ─────────────────────
- bold("━━━ Test 2: Run commands on all sandboxes in parallel ━━━\n");
-
- const cmdStart = Date.now();
- const cmdPromises = sandboxes.map((sb, i) =>
- sb.commands.run(`echo "sandbox-${i}-${sb.sandboxId}"`).then((r) => ({
- index: i,
- id: sb.sandboxId,
- result: r,
- })),
- );
-
- const cmdResults = await Promise.allSettled(cmdPromises);
- const cmdMs = Date.now() - cmdStart;
-
- for (const r of cmdResults) {
- if (r.status === "fulfilled") {
- const { index, id, result } = r.value;
- const expected = `sandbox-${index}-${id}`;
- check(
- `Sandbox ${index + 1} echo correct`,
- result.stdout.trim() === expected,
- result.stdout.trim(),
- );
- } else {
- check("Command execution", false, r.reason.message);
- }
- }
- dim(`Total command time: ${cmdMs}ms`);
- console.log();
-
- // ── Test 3: Verify isolation ────────────────────────────────────
- bold("━━━ Test 3: Verify sandbox isolation ━━━\n");
-
- // Write a unique file to each sandbox
- const writePromises = sandboxes.map((sb, i) =>
- sb.files.write("/tmp/identity.txt", `sandbox-${i}`),
- );
- await Promise.all(writePromises);
-
- // Read back from each — should only see its own identity
- const readPromises = sandboxes.map((sb, i) =>
- sb.files.read("/tmp/identity.txt").then((content) => ({
- index: i,
- content,
- })),
- );
-
- const readResults = await Promise.all(readPromises);
- for (const { index, content } of readResults) {
- check(
- `Sandbox ${index + 1} sees only its own data`,
- content === `sandbox-${index}`,
- content,
- );
- }
-
- // Verify PID namespaces are isolated
- const pidPromises = sandboxes.map((sb, i) =>
- sb.commands.run("echo $$").then((r) => ({
- index: i,
- pid: r.stdout.trim(),
- })),
- );
-
- const pidResults = await Promise.all(pidPromises);
- // In isolated PID namespaces, PIDs should be low numbers
- for (const { index, pid } of pidResults) {
- dim(`Sandbox ${index + 1} shell PID: ${pid}`);
- }
- // Check that they all have independent PID spaces (PIDs should be same or similar low numbers)
- const uniquePids = new Set(pidResults.map((r) => r.pid));
- // With PID namespaces, most will have the same low PID number
- check(
- "PID namespace isolation (low PIDs)",
- pidResults.every((r) => parseInt(r.pid) < 1000),
- `PIDs: ${pidResults.map((r) => r.pid).join(", ")}`,
- );
- console.log();
-
- // ── Test 4: Parallel file operations ────────────────────────────
- bold("━━━ Test 4: Parallel file operations across sandboxes ━━━\n");
-
- // Each sandbox creates 10 files and reads them back
- const fileOpPromises = sandboxes.map(async (sb, i) => {
- const writes = Array.from({ length: 10 }, (_, j) =>
- sb.files.write(`/tmp/file-${j}.txt`, `sb${i}-file${j}`),
- );
- await Promise.all(writes);
-
- const reads = Array.from({ length: 10 }, (_, j) =>
- sb.files.read(`/tmp/file-${j}.txt`),
- );
- const contents = await Promise.all(reads);
-
- return {
- index: i,
- allCorrect: contents.every((c, j) => c === `sb${i}-file${j}`),
- count: contents.length,
- };
- });
-
- const fileResults = await Promise.all(fileOpPromises);
- for (const { index, allCorrect, count } of fileResults) {
- check(
- `Sandbox ${index + 1}: ${count} files written and verified`,
- allCorrect,
- );
- }
- console.log();
-
- // ── Test 5: List all sandboxes (API check) ──────────────────────
- bold("━━━ Test 5: Verify all sandboxes visible via API ━━━\n");
-
- // Use isRunning to verify all are still up
- const statusPromises = sandboxes.map((sb, i) =>
- sb.isRunning().then((running) => ({ index: i, running })),
- );
- const statuses = await Promise.all(statusPromises);
- for (const { index, running } of statuses) {
- check(`Sandbox ${index + 1} still running`, running);
- }
- console.log();
-
- // ── Test 6: Kill all in parallel ────────────────────────────────
- bold(`━━━ Test 6: Kill all ${SANDBOX_COUNT} sandboxes simultaneously ━━━\n`);
-
- const killStart = Date.now();
- const killPromises = sandboxes.map((sb, i) =>
- sb.kill().then(() => ({ index: i, success: true }))
- .catch((err) => ({ index: i, success: false, error: err.message })),
- );
-
- const killResults = await Promise.all(killPromises);
- const killMs = Date.now() - killStart;
-
- for (const r of killResults) {
- check(`Sandbox ${r.index + 1} killed`, r.success, (r as any).error);
- }
- dim(`Total kill time: ${killMs}ms`);
-
- // Verify they're all gone
- await new Promise((r) => globalThis.setTimeout(r, 1000));
- const postKillPromises = sandboxes.map((sb, i) =>
- sb.isRunning().then((running) => ({ index: i, running })),
- );
- const postKill = await Promise.all(postKillPromises);
- for (const { index, running } of postKill) {
- check(`Sandbox ${index + 1} confirmed stopped`, !running);
- }
- console.log();
-
- } catch (err: any) {
- red(`Fatal error: ${err.message}`);
- failed++;
- // Kill any sandboxes that were created
- for (const sb of sandboxes) {
- try { await sb.kill(); } catch {}
- }
- }
-
- // --- Summary ---
- bold("========================================");
- bold(` Results: ${passed} passed, ${failed} failed`);
- bold("========================================\n");
- if (failed > 0) process.exit(1);
-}
-
-main().catch((err) => {
- console.error("Fatal error:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/test-declarative-images.ts b/sdks/typescript/examples/test-declarative-images.ts
deleted file mode 100644
index 7f87867e..00000000
--- a/sdks/typescript/examples/test-declarative-images.ts
+++ /dev/null
@@ -1,375 +0,0 @@
-/**
- * Declarative Image Builder & Snapshots Test
- *
- * Demonstrates and tests both patterns for defining sandbox environments:
- *
- * Pattern 1 — On-demand images (cached by content hash):
- * const image = Image.base('ubuntu').aptInstall(['curl']).pipInstall(['requests'])
- * const sandbox = await Sandbox.create({ image })
- *
- * Pattern 2 — Pre-built named snapshots:
- * await snapshots.create({ name: 'my-env', image })
- * const sandbox = await Sandbox.create({ snapshot: 'my-env' })
- *
- * Tests:
- * 1. Build an image with apt + pip + env + workdir
- * 2. Create sandbox from image (first build — cold)
- * 3. Verify packages are installed
- * 4. Verify env vars are set
- * 5. Verify workdir was created
- * 6. Create a second sandbox from the same image (cache hit — fast)
- * 7. Verify cache hit was significantly faster
- * 8. Create a named snapshot from an image
- * 9. List snapshots
- * 10. Create sandbox from named snapshot
- * 11. Verify snapshot sandbox has correct state
- * 12. Delete snapshot
- * 13. Image immutability — chaining produces new instances
- * 14. runCommands step
- *
- * Usage:
- * npx tsx examples/test-declarative-images.ts
- */
-
-import { Sandbox, Image, Snapshots } from "../src/index";
-
-function green(msg: string) { console.log(`\x1b[32m\u2713 ${msg}\x1b[0m`); }
-function red(msg: string) { console.log(`\x1b[31m\u2717 ${msg}\x1b[0m`); }
-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-
-let passed = 0;
-let failed = 0;
-
-function check(desc: string, condition: boolean, detail?: string) {
- if (condition) {
- green(desc);
- passed++;
- } else {
- red(`${desc}${detail ? ` (${detail})` : ""}`);
- failed++;
- }
-}
-
-async function main() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Declarative Image Builder & Snapshots Test ║");
- bold("╚══════════════════════════════════════════════════╝\n");
-
- const sandboxes: Sandbox[] = [];
- const snapshots = new Snapshots();
-
- try {
- // ── Test: Image class immutability ─────────────────────────────
- bold("━━━ Test: Image builder basics ━━━\n");
-
- const base = Image.base();
- const withCurl = base.aptInstall(["curl"]);
- const withPython = withCurl.pipInstall(["requests"]);
-
- check("Image.base() uses default base", base.toJSON().base === "base");
- check("Image is immutable — aptInstall returns new instance", base.toJSON().steps.length === 0);
- check("Chained image has 1 step", withCurl.toJSON().steps.length === 1);
- check("Further chained image has 2 steps", withPython.toJSON().steps.length === 2);
-
- // Cache keys should differ
- check("Different images have different cache keys", base.cacheKey() !== withCurl.cacheKey());
- check("Same image produces same cache key", base.cacheKey() === Image.base().cacheKey());
-
- // File operations
- const withFile = base.addFile("/workspace/config.json", '{"key": "value"}');
- check("addFile creates a step", withFile.toJSON().steps.length === 1);
- check("addFile step type is correct", withFile.toJSON().steps[0].type === "add_file");
- console.log();
-
- // ── Pattern 1: On-demand image creation ───────────────────────
- bold("━━━ Pattern 1: On-demand image (first build — cold) ━━━\n");
-
- const image = Image.base()
- .aptInstall(["curl", "jq"])
- .runCommands("mkdir -p /workspace/project")
- .env({ MY_VAR: "hello-from-image", PROJECT_ROOT: "/workspace/project" })
- .workdir("/workspace/project");
-
- dim(`Image manifest: ${JSON.stringify(image.toJSON(), null, 2)}`);
- dim(`Cache key: ${image.cacheKey()}`);
- dim("Creating sandbox from image (this will build on first run)...");
-
- const t1Start = Date.now();
- const sandbox1 = await Sandbox.create({ image, timeout: 300 });
- const t1Elapsed = Date.now() - t1Start;
- sandboxes.push(sandbox1);
-
- green(`Sandbox created: ${sandbox1.sandboxId} (${t1Elapsed}ms)`);
- check("Sandbox created successfully", sandbox1.status === "running" || sandbox1.status === "creating");
- console.log();
-
- // ── Verify installed packages ─────────────────────────────────
- bold("━━━ Verify: Packages installed ━━━\n");
-
- const curlCheck = await sandbox1.commands.run("which curl");
- check("curl is installed", curlCheck.exitCode === 0, `exit=${curlCheck.exitCode}`);
-
- const jqCheck = await sandbox1.commands.run("which jq");
- check("jq is installed", jqCheck.exitCode === 0, `exit=${jqCheck.exitCode}`);
- console.log();
-
- // ── Verify env vars ───────────────────────────────────────────
- bold("━━━ Verify: Environment variables ━━━\n");
-
- const envCheck = await sandbox1.commands.run("bash -lc 'echo $MY_VAR'");
- check("MY_VAR is set", envCheck.stdout.trim() === "hello-from-image", `got: "${envCheck.stdout.trim()}"`);
-
- const rootCheck = await sandbox1.commands.run("bash -lc 'echo $PROJECT_ROOT'");
- check("PROJECT_ROOT is set", rootCheck.stdout.trim() === "/workspace/project", `got: "${rootCheck.stdout.trim()}"`);
- console.log();
-
- // ── Verify workdir ────────────────────────────────────────────
- bold("━━━ Verify: Working directory ━━━\n");
-
- const dirCheck = await sandbox1.commands.run("test -d /workspace/project && echo exists");
- check("/workspace/project exists", dirCheck.stdout.trim() === "exists");
- console.log();
-
- // ── Cache hit: second sandbox from same image ─────────────────
- bold("━━━ Pattern 1: Cache hit (second sandbox, same image) ━━━\n");
-
- dim("Creating second sandbox from same image (should be cached)...");
- const t2Start = Date.now();
- const sandbox2 = await Sandbox.create({ image, timeout: 300 });
- const t2Elapsed = Date.now() - t2Start;
- sandboxes.push(sandbox2);
-
- green(`Second sandbox created: ${sandbox2.sandboxId} (${t2Elapsed}ms)`);
-
- // Cache hit should be faster (no build step)
- if (t1Elapsed > 5000) {
- // Only check speedup if cold build took meaningful time
- check(
- `Cache hit is faster (${t2Elapsed}ms vs ${t1Elapsed}ms cold build)`,
- t2Elapsed < t1Elapsed,
- `cold=${t1Elapsed}ms, cached=${t2Elapsed}ms`
- );
- } else {
- dim(`Cold build was fast (${t1Elapsed}ms) — skipping speedup check`);
- }
-
- // Verify cached sandbox also has the packages
- const curlCheck2 = await sandbox2.commands.run("which curl");
- check("Cached sandbox also has curl", curlCheck2.exitCode === 0);
- console.log();
-
- // Kill sandboxes before creating more (avoid hitting org concurrency limits)
- for (const sb of sandboxes) {
- try { await sb.kill(); } catch { /* best effort */ }
- }
- sandboxes.length = 0;
-
- // ── Pattern 2: Pre-built named snapshot ───────────────────────
- bold("━━━ Pattern 2: Create named snapshot ━━━\n");
-
- const snapshotImage = Image.base()
- .runCommands(
- "echo 'snapshot-marker' > /workspace/snapshot-test.txt",
- "mkdir -p /workspace/data"
- )
- .env({ SNAPSHOT_ENV: "from-snapshot" });
-
- dim("Creating snapshot 'test-env'...");
- const snapshotInfo = await snapshots.create({
- name: "test-env",
- image: snapshotImage,
- });
- green(`Snapshot created: ${snapshotInfo.name} (status=${snapshotInfo.status})`);
- check("Snapshot status is ready", snapshotInfo.status === "ready");
- console.log();
-
- // ── List snapshots ────────────────────────────────────────────
- bold("━━━ Verify: List snapshots ━━━\n");
-
- const snapshotList = await snapshots.list();
- const found = snapshotList.find((s) => s.name === "test-env");
- check("Snapshot appears in list", found !== undefined);
- check("Snapshot has correct name", found?.name === "test-env");
- console.log();
-
- // ── Get snapshot by name ──────────────────────────────────────
- bold("━━━ Verify: Get snapshot by name ━━━\n");
-
- const fetched = await snapshots.get("test-env");
- check("Fetched snapshot matches", fetched.name === "test-env");
- check("Fetched snapshot is ready", fetched.status === "ready");
- console.log();
-
- // ── Create sandbox from named snapshot ────────────────────────
- bold("━━━ Pattern 2: Create sandbox from named snapshot ━━━\n");
-
- dim("Creating sandbox from snapshot 'test-env'...");
- const t3Start = Date.now();
- const sandbox3 = await Sandbox.create({ snapshot: "test-env", timeout: 300 });
- const t3Elapsed = Date.now() - t3Start;
- sandboxes.push(sandbox3);
-
- green(`Sandbox from snapshot: ${sandbox3.sandboxId} (${t3Elapsed}ms)`);
- check("Sandbox created successfully", sandbox3.status === "running" || sandbox3.status === "creating");
-
- // Verify snapshot state
- const markerCheck = await sandbox3.commands.run("cat /workspace/snapshot-test.txt");
- check("Snapshot marker file exists", markerCheck.stdout.trim() === "snapshot-marker", `got: "${markerCheck.stdout.trim()}"`);
-
- const snapshotEnvCheck = await sandbox3.commands.run("bash -lc 'echo $SNAPSHOT_ENV'");
- check("Snapshot env var is set", snapshotEnvCheck.stdout.trim() === "from-snapshot", `got: "${snapshotEnvCheck.stdout.trim()}"`);
-
- const dataDirCheck = await sandbox3.commands.run("test -d /workspace/data && echo exists");
- check("/workspace/data exists", dataDirCheck.stdout.trim() === "exists");
- console.log();
-
- // ── Delete snapshot ───────────────────────────────────────────
- bold("━━━ Cleanup: Delete snapshot ━━━\n");
-
- await snapshots.delete("test-env");
- green("Snapshot 'test-env' deleted");
-
- const listAfterDelete = await snapshots.list();
- const deletedFound = listAfterDelete.find((s) => s.name === "test-env");
- check("Snapshot no longer in list", deletedFound === undefined);
- console.log();
-
- // Kill snapshot sandbox before creating more
- for (const sb of sandboxes) {
- try { await sb.kill(); } catch { /* best effort */ }
- }
- sandboxes.length = 0;
-
- // ── Test: runCommands with multiple commands ──────────────────
- bold("━━━ Test: runCommands with multiple commands ━━━\n");
-
- const multiImage = Image.base()
- .runCommands(
- "echo hello > /workspace/a.txt",
- "echo world > /workspace/b.txt",
- "cat /workspace/a.txt /workspace/b.txt > /workspace/combined.txt"
- );
-
- dim("Creating sandbox with multi-command image...");
- const sandbox4 = await Sandbox.create({ image: multiImage, timeout: 300 });
- sandboxes.push(sandbox4);
-
- const combined = await sandbox4.commands.run("cat /workspace/combined.txt");
- check("Multiple runCommands executed", combined.stdout.includes("hello") && combined.stdout.includes("world"), `got: "${combined.stdout.trim()}"`);
- console.log();
-
- // Kill sandboxes before next test
- for (const sb of sandboxes) {
- try { await sb.kill(); } catch { /* best effort */ }
- }
- sandboxes.length = 0;
-
- // ── Test: addFile step ──────────────────────────────────────────
- bold("━━━ Test: addFile — bake files into the image ━━━\n");
-
- const fileImage = Image.base()
- .addFile("/workspace/config.json", '{"env": "production", "debug": false}')
- .addFile("/workspace/setup.sh", "#!/bin/bash\necho 'Hello from setup!'")
- .runCommands("chmod +x /workspace/setup.sh");
-
- dim("Creating sandbox with embedded files...");
- const sandbox5 = await Sandbox.create({ image: fileImage, timeout: 300 });
- sandboxes.push(sandbox5);
-
- const configCheck = await sandbox5.commands.run("cat /workspace/config.json");
- check("addFile wrote config.json", configCheck.stdout.includes('"env": "production"'), `got: "${configCheck.stdout.trim()}"`);
-
- const setupCheck = await sandbox5.commands.run("/workspace/setup.sh");
- check("addFile wrote executable script", setupCheck.stdout.trim() === "Hello from setup!", `got: "${setupCheck.stdout.trim()}"`);
- console.log();
-
- // Kill sandboxes before next test
- for (const sb of sandboxes) {
- try { await sb.kill(); } catch { /* best effort */ }
- }
- sandboxes.length = 0;
-
- // ── Test: Build log streaming ───────────────────────────────────
- bold("━━━ Test: Build log streaming (onBuildLog callback) ━━━\n");
-
- const logImage = Image.base()
- .runCommands("echo 'build step 1'", "echo 'build step 2'");
-
- const buildLogs: string[] = [];
- dim("Creating sandbox with build log streaming...");
- const sandbox6 = await Sandbox.create({
- image: logImage,
- timeout: 300,
- onBuildLog: (log) => {
- buildLogs.push(log);
- dim(` build: ${log}`);
- },
- });
- sandboxes.push(sandbox6);
-
- check("Build log callback was called", buildLogs.length > 0, `got ${buildLogs.length} logs`);
- check("Sandbox created via SSE stream", sandbox6.status === "running" || sandbox6.status === "creating");
- console.log();
-
- // Kill sandboxes before next test
- for (const sb of sandboxes) {
- try { await sb.kill(); } catch { /* best effort */ }
- }
- sandboxes.length = 0;
-
- // ── Test: Snapshot build log streaming ──────────────────────────
- bold("━━━ Test: Snapshot build log streaming (onBuildLogs) ━━━\n");
-
- const snapshotLogImage = Image.base()
- .runCommands("echo 'snapshot build'");
-
- const snapshotLogs: string[] = [];
- dim("Creating snapshot with build log streaming...");
- const streamedSnapshot = await snapshots.create({
- name: "test-streamed",
- image: snapshotLogImage,
- onBuildLogs: (log) => {
- snapshotLogs.push(log);
- dim(` snapshot build: ${log}`);
- },
- });
-
- check("Snapshot build log callback was called", snapshotLogs.length > 0, `got ${snapshotLogs.length} logs`);
- check("Streamed snapshot has name", streamedSnapshot.name === "test-streamed");
- check("Streamed snapshot is ready", streamedSnapshot.status === "ready");
-
- // Cleanup streamed snapshot
- await snapshots.delete("test-streamed");
- green("Cleaned up test-streamed snapshot");
- console.log();
-
- } catch (err: any) {
- red(`Fatal error: ${err.message}`);
- if (err.stack) dim(err.stack);
- failed++;
- } finally {
- // Cleanup: kill all sandboxes
- bold("━━━ Cleanup ━━━\n");
- for (const sb of sandboxes) {
- try {
- await sb.kill();
- dim(`Killed ${sb.sandboxId}`);
- } catch { /* best effort */ }
- }
- // Clean up any leftover test snapshots
- try { await snapshots.delete("test-env"); } catch { /* may already be deleted */ }
- try { await snapshots.delete("test-streamed"); } catch { /* may already be deleted */ }
- }
-
- // --- Summary ---
- bold("========================================");
- bold(` Results: ${passed} passed, ${failed} failed`);
- bold("========================================\n");
- if (failed > 0) process.exit(1);
-}
-
-main().catch((err) => {
- console.error("Fatal error:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/test-disk-size.ts b/sdks/typescript/examples/test-disk-size.ts
deleted file mode 100644
index 26053bb6..00000000
--- a/sdks/typescript/examples/test-disk-size.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-/**
- * Disk Size Test
- *
- * Verifies the `diskMB` sandbox creation parameter:
- * 1. Default (no arg) → 20GB workspace
- * 2. Explicit 20GB → 20GB workspace
- * 3. Explicit 30GB → 30GB workspace (requires org `max_disk_mb` ≥ 30720)
- * 4. Below minimum → rejected with 400
- *
- * Larger disk sizes are in closed beta — contact us to raise your org's
- * max_disk_mb ceiling: https://cal.com/team/digger/opencomputer-founder-chat
- *
- * Usage:
- * npx tsx examples/test-disk-size.ts
- *
- * Environment:
- * OPENCOMPUTER_API_URL (default: http://localhost:8080)
- * OPENCOMPUTER_API_KEY (default: test-key)
- */
-
-import { Sandbox } from "../src/index";
-
-const API_URL = process.env.OPENCOMPUTER_API_URL ?? "http://localhost:8080";
-const API_KEY = process.env.OPENCOMPUTER_API_KEY ?? "test-key";
-
-function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }
-function red(msg: string) { console.log(`\x1b[31m✗ ${msg}\x1b[0m`); }
-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-
-let passed = 0;
-let failed = 0;
-
-async function runCase(
- label: string,
- diskMB: number | undefined,
- expect: { size?: string; reject?: boolean },
-) {
- bold(`\n${label}`);
- try {
- const sb = await Sandbox.create({
- apiUrl: API_URL,
- apiKey: API_KEY,
- timeout: 120,
- ...(diskMB !== undefined ? { diskMB } : {}),
- });
- dim(`created ${sb.sandboxId}`);
- try {
- const r = await sb.exec.run("df -h /home/sandbox | tail -1");
- dim(`df: ${r.stdout.trim()}`);
- if (expect.reject) {
- red(`expected rejection but sandbox was created`);
- failed++;
- } else if (expect.size && r.stdout.includes(expect.size)) {
- green(`workspace reports ${expect.size}`);
- passed++;
- } else {
- red(`expected ${expect.size} in df output`);
- failed++;
- }
- } finally {
- await sb.kill();
- }
- } catch (e: any) {
- if (expect.reject) {
- green(`rejected as expected (${e.message.split("\n")[0]})`);
- passed++;
- } else {
- red(`unexpected error: ${e.message}`);
- failed++;
- }
- }
-}
-
-(async () => {
- bold("OpenComputer SDK — disk size test");
- dim(`API: ${API_URL}`);
-
- await runCase("default (no diskMB)", undefined, { size: "20G" });
- await runCase("explicit 20GB", 20480, { size: "20G" });
- await runCase("30GB", 30720, { size: "30G" });
- await runCase("below minimum (8GB)", 8192, { reject: true });
-
- console.log();
- bold(`Results: ${passed} passed, ${failed} failed`);
- process.exit(failed > 0 ? 1 : 0);
-})();
diff --git a/sdks/typescript/examples/test-docker-networking.ts b/sdks/typescript/examples/test-docker-networking.ts
deleted file mode 100644
index 63e03812..00000000
--- a/sdks/typescript/examples/test-docker-networking.ts
+++ /dev/null
@@ -1,187 +0,0 @@
-/**
- * Docker Networking Test
- *
- * Tests Docker bridge networking inside a sandbox VM:
- * 1. Kernel module loading (bridge, veth, netfilter)
- * 2. Docker daemon startup with bridge networking
- * 3. Container → internet connectivity (ping + DNS)
- * 4. Host → container latency
- * 5. Container ↔ container latency
- * 6. Container → internet throughput
- * 7. Docker images land on data disk (/home/sandbox/.docker)
- *
- * Usage:
- * npx tsx examples/test-docker-networking.ts
- */
-
-import { Sandbox } from "../src/index";
-
-function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }
-function red(msg: string) { console.log(`\x1b[31m✗ ${msg}\x1b[0m`); }
-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-
-let passed = 0;
-let failed = 0;
-
-function check(desc: string, condition: boolean, detail?: string) {
- if (condition) {
- green(desc);
- passed++;
- } else {
- red(`${desc}${detail ? ` — ${detail}` : ""}`);
- failed++;
- }
-}
-
-/** Run a command as root with a timeout, return stdout */
-async function run(sandbox: Sandbox, cmd: string, timeout = 30): Promise<{ stdout: string; stderr: string; exitCode: number }> {
- const result = await sandbox.commands.run(`sudo bash -c '${cmd.replace(/'/g, "'\\''")}'`, { timeout });
- return result;
-}
-
-async function main() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Docker Networking Test ║");
- bold("╚══════════════════════════════════════════════════╝\n");
-
- let sandbox: Sandbox | null = null;
-
- try {
- sandbox = await Sandbox.create({ timeout: 300 });
- green(`Created sandbox: ${sandbox.sandboxId}`);
- console.log();
-
- // ── Test 1: Kernel modules ───────────────────────────────────────
- bold("━━━ Test 1: Kernel module loading ━━━\n");
-
- const modules = ["bridge", "veth", "br_netfilter", "ip_tables", "nf_nat", "nf_conntrack"];
- for (const mod of modules) {
- const result = await run(sandbox, `modprobe ${mod} 2>&1 && echo OK`);
- check(`modprobe ${mod}`, result.stdout.includes("OK"), result.stdout.trim());
- }
- console.log();
-
- // ── Test 2: Install Docker ───────────────────────────────────────
- bold("━━━ Test 2: Install Docker ━━━\n");
-
- dim("Installing docker.io (this takes ~30s)...");
- const install = await run(sandbox, "apt-get update -qq 2>/dev/null && apt-get install -y -qq docker.io 2>&1 | tail -1", 180);
- check("Docker installed", install.exitCode === 0, install.stderr);
-
- const daemonJson = await run(sandbox, "cat /etc/docker/daemon.json");
- check("daemon.json has data-root on data disk", daemonJson.stdout.includes("/home/sandbox/.docker"));
- check("daemon.json does not disable bridge", !daemonJson.stdout.includes('"bridge": "none"'));
- dim(`daemon.json: ${daemonJson.stdout.trim()}`);
- console.log();
-
- // ── Test 3: Start Docker daemon ──────────────────────────────────
- bold("━━━ Test 3: Docker daemon with bridge networking ━━━\n");
-
- await run(sandbox, "echo 1 > /proc/sys/net/ipv4/ip_forward");
- await run(sandbox, "/usr/bin/dockerd </dev/null >/tmp/dockerd.log 2>&1 & sleep 1");
-
- // Wait for dockerd to be ready
- dim("Waiting for dockerd...");
- let dockerReady = false;
- for (let i = 0; i < 20; i++) {
- const ver = await run(sandbox, "/usr/bin/docker version --format '{{.Server.Version}}' 2>/dev/null");
- if (ver.exitCode === 0 && ver.stdout.trim()) {
- dockerReady = true;
- dim(`Docker version: ${ver.stdout.trim()}`);
- break;
- }
- await new Promise(r => setTimeout(r, 1000));
- }
- check("Docker daemon started with bridge networking", dockerReady);
-
- if (!dockerReady) {
- const log = await run(sandbox, "tail -10 /tmp/dockerd.log");
- dim(`dockerd log: ${log.stdout}`);
- throw new Error("Docker daemon failed to start");
- }
-
- const info = await run(sandbox, "/usr/bin/docker info --format '{{.Driver}} / {{json .Plugins.Network}}' 2>/dev/null");
- check("Bridge network driver available", info.stdout.includes("bridge"));
- dim(`Docker info: ${info.stdout.trim()}`);
- console.log();
-
- // ── Test 4: Container → Internet ─────────────────────────────────
- bold("━━━ Test 4: Container → Internet ━━━\n");
-
- const ping = await run(sandbox, "/usr/bin/docker run --rm alpine:3.19 ping -c5 -W3 8.8.8.8 2>&1", 60);
- check("Container can ping 8.8.8.8", ping.stdout.includes("0% packet loss"));
- const avgMatch = ping.stdout.match(/min\/avg\/max = [\d.]+\/([\d.]+)/);
- if (avgMatch) dim(`Avg latency to 8.8.8.8: ${avgMatch[1]}ms`);
-
- const dns = await run(sandbox, "/usr/bin/docker run --rm alpine:3.19 ping -c3 -W3 google.com 2>&1", 30);
- check("Container DNS resolution works", dns.stdout.includes("0% packet loss"));
- const dnsMatch = dns.stdout.match(/min\/avg\/max = [\d.]+\/([\d.]+)/);
- if (dnsMatch) dim(`Avg latency to google.com: ${dnsMatch[1]}ms`);
-
- const dl = await run(sandbox, "/usr/bin/docker run --rm alpine:3.19 wget -O /dev/null http://speedtest.tele2.net/10MB.zip 2>&1", 60);
- check("Container can download from internet", dl.stdout.includes("saved") || dl.exitCode === 0);
- console.log();
-
- // ── Test 5: Host → Container latency ─────────────────────────────
- bold("━━━ Test 5: Host ↔ Container latency ━━━\n");
-
- await run(sandbox, "/usr/bin/docker run -d --name ping-target alpine:3.19 sleep 60 2>/dev/null");
- const cip = await run(sandbox, "/usr/bin/docker inspect -f '{{.NetworkSettings.IPAddress}}' ping-target 2>/dev/null");
- const containerIP = cip.stdout.trim();
- check("Container got bridge IP", containerIP.startsWith("172.17."));
- dim(`Container IP: ${containerIP}`);
-
- const hostPing = await run(sandbox, `ping -c10 -W3 ${containerIP} 2>&1`);
- check("Host can ping container", hostPing.stdout.includes("0% packet loss"));
- const hostMatch = hostPing.stdout.match(/min\/avg\/max(?:\/mdev)? = [\d.]+\/([\d.]+)/);
- if (hostMatch) dim(`Host → container avg latency: ${hostMatch[1]}ms`);
-
- await run(sandbox, "/usr/bin/docker rm -f ping-target 2>/dev/null");
- console.log();
-
- // ── Test 6: Container ↔ Container ────────────────────────────────
- bold("━━━ Test 6: Container ↔ Container ━━━\n");
-
- await run(sandbox, "/usr/bin/docker network create bench-net 2>/dev/null");
- await run(sandbox, "/usr/bin/docker run -d --name ctr-a --network bench-net alpine:3.19 sleep 60 2>/dev/null");
-
- const c2c = await run(sandbox, "/usr/bin/docker run --rm --network bench-net alpine:3.19 ping -c10 ctr-a 2>&1", 30);
- check("Container ↔ container ping works", c2c.stdout.includes("0% packet loss"));
- const c2cMatch = c2c.stdout.match(/min\/avg\/max = [\d.]+\/([\d.]+)/);
- if (c2cMatch) dim(`Container ↔ container avg latency: ${c2cMatch[1]}ms`);
-
- await run(sandbox, "/usr/bin/docker rm -f ctr-a 2>/dev/null");
- await run(sandbox, "/usr/bin/docker network rm bench-net 2>/dev/null");
- console.log();
-
- // ── Test 7: Docker images on data disk ───────────────────────────
- bold("━━━ Test 7: Docker data on data disk ━━━\n");
-
- const dockerDir = await run(sandbox, "du -sh /home/sandbox/.docker 2>/dev/null");
- check("Docker data stored on data disk", dockerDir.stdout.includes("/home/sandbox/.docker"));
- dim(`Docker data size: ${dockerDir.stdout.trim()}`);
-
- const disk = await run(sandbox, "df -h / /home/sandbox");
- dim(`Disk usage:\n${disk.stdout}`);
- console.log();
-
- } catch (err) {
- red(`Error: ${err}`);
- failed++;
- } finally {
- if (sandbox) {
- await sandbox.kill();
- dim(`Sandbox ${sandbox.sandboxId} destroyed`);
- }
- }
-
- // ── Summary ──────────────────────────────────────────────────────
- bold("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
- bold(`Results: ${passed} passed, ${failed} failed`);
- if (failed > 0) {
- process.exit(1);
- }
-}
-
-main();
diff --git a/sdks/typescript/examples/test-domain-tls.ts b/sdks/typescript/examples/test-domain-tls.ts
deleted file mode 100644
index ce0af198..00000000
--- a/sdks/typescript/examples/test-domain-tls.ts
+++ /dev/null
@@ -1,237 +0,0 @@
-/**
- * Domain & TLS Verification Test
- *
- * Tests:
- * 1. Each sandbox gets a unique subdomain
- * 2. HTTPS works with valid Let's Encrypt cert
- * 3. HTTP server inside sandbox is reachable via subdomain
- * 4. Multiple subdomains get individual certs
- * 5. Subdomain routes to correct sandbox
- *
- * Usage:
- * npx tsx examples/test-domain-tls.ts
- */
-
-import { Sandbox } from "../src/index";
-import * as tls from "tls";
-
-function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }
-function red(msg: string) { console.log(`\x1b[31m✗ ${msg}\x1b[0m`); }
-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-
-function sleep(ms: number) {
- return new Promise((r) => globalThis.setTimeout(r, ms));
-}
-
-let passed = 0;
-let failed = 0;
-
-function check(desc: string, condition: boolean, detail?: string) {
- if (condition) {
- green(desc);
- passed++;
- } else {
- red(`${desc}${detail ? ` (${detail})` : ""}`);
- failed++;
- }
-}
-
-function getTlsCertInfo(hostname: string): Promise<{ issuer: string; subject: string; validTo: string; valid: boolean }> {
- return new Promise((resolve, reject) => {
- const socket = tls.connect(443, hostname, { servername: hostname }, () => {
- const cert = socket.getPeerCertificate();
- const authorized = socket.authorized;
- socket.end();
- resolve({
- issuer: cert.issuer?.O || "unknown",
- subject: cert.subject?.CN || "unknown",
- validTo: cert.valid_to || "unknown",
- valid: authorized,
- });
- });
- socket.on("error", reject);
- socket.setTimeout(10000, () => {
- socket.destroy();
- reject(new Error("TLS connection timeout"));
- });
- });
-}
-
-// Simple HTTP server for sandbox
-const HTTP_SERVER = `
-const http = require('http');
-const os = require('os');
-const server = http.createServer((req, res) => {
- res.writeHead(200, {'Content-Type':'application/json'});
- res.end(JSON.stringify({
- path: req.url,
- hostname: os.hostname(),
- sandboxId: process.env.SANDBOX_ID || 'unknown',
- timestamp: Date.now()
- }));
-});
-server.listen(8080, '0.0.0.0', () => console.log('Server ready'));
-`;
-
-async function main() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Domain & TLS Verification Test ║");
- bold("╚══════════════════════════════════════════════════╝\n");
-
- const sandboxes: Sandbox[] = [];
-
- try {
- // ── Test 1: Unique subdomains ───────────────────────────────────
- bold("━━━ Test 1: Unique subdomain assignment ━━━\n");
-
- // Create 3 sandboxes and verify unique domains
- for (let i = 0; i < 3; i++) {
- const sb = await Sandbox.create({ timeout: 120 });
- sandboxes.push(sb);
- dim(`Sandbox ${i + 1}: ${sb.sandboxId} → ${sb.getPreviewDomain(8080)}`);
- }
-
- const domains = sandboxes.map(s => s.getPreviewDomain(8080));
- const uniqueDomains = new Set(domains);
- check("All 3 sandboxes got unique domains", uniqueDomains.size === 3);
- check("All domains end with .workers.opencomputer.dev",
- domains.every(d => d.endsWith(".workers.opencomputer.dev")));
- check("All domains are subdomains (single level)",
- domains.every(d => d.split(".workers.opencomputer.dev")[0].indexOf(".") === -1));
- console.log();
-
- // ── Test 2: TLS certificate validation ──────────────────────────
- bold("━━━ Test 2: TLS certificate validation ━━━\n");
-
- // Start HTTP servers on all sandboxes
- for (let i = 0; i < sandboxes.length; i++) {
- await sandboxes[i].files.write("/tmp/server.js", HTTP_SERVER);
- await sandboxes[i].commands.run(
- `SANDBOX_ID=${sandboxes[i].sandboxId} nohup node /tmp/server.js > /tmp/server.log 2>&1 &`,
- );
- }
- await sleep(2000);
-
- // Check TLS cert on first sandbox
- try {
- const certInfo = await getTlsCertInfo(sandboxes[0].getPreviewDomain(8080));
- check("TLS certificate is valid", certInfo.valid);
- check("Certificate issued by trusted CA",
- certInfo.issuer.includes("Let's Encrypt") ||
- certInfo.issuer.includes("R3") ||
- certInfo.issuer.includes("R10") ||
- certInfo.issuer.includes("R11") ||
- certInfo.issuer.includes("E5") ||
- certInfo.issuer.includes("E6") ||
- certInfo.issuer.includes("Google Trust Services") ||
- certInfo.issuer.includes("GTS"),
- certInfo.issuer);
- dim(`Issuer: ${certInfo.issuer}`);
- dim(`Subject: ${certInfo.subject}`);
- dim(`Valid to: ${certInfo.validTo}`);
- } catch (err: any) {
- check("TLS connection succeeded", false, err.message);
- }
- console.log();
-
- // ── Test 3: HTTPS requests work ─────────────────────────────────
- bold("━━━ Test 3: HTTPS requests to sandbox servers ━━━\n");
-
- for (let i = 0; i < sandboxes.length; i++) {
- try {
- const resp = await fetch(`https://${sandboxes[i].getPreviewDomain(8080)}/test-path`);
- check(`Sandbox ${i + 1}: HTTPS 200`, resp.ok, `status ${resp.status}`);
-
- if (resp.ok) {
- const data = await resp.json();
- check(`Sandbox ${i + 1}: correct path`, data.path === "/test-path", data.path);
- check(`Sandbox ${i + 1}: has hostname`, !!data.hostname);
- }
- } catch (err: any) {
- check(`Sandbox ${i + 1}: HTTPS request`, false, err.message);
- }
- }
- console.log();
-
- // ── Test 4: Subdomain routes to correct sandbox ─────────────────
- bold("━━━ Test 4: Subdomain routing isolation ━━━\n");
-
- // Each sandbox server returns its sandbox ID — verify routing is correct
- const routingResults = await Promise.all(
- sandboxes.map(async (sb, i) => {
- try {
- const resp = await fetch(`https://${sb.getPreviewDomain(8080)}/`);
- const data = await resp.json();
- return { index: i, sandboxId: sb.sandboxId, returnedId: data.sandboxId, hostname: data.hostname };
- } catch (err: any) {
- return { index: i, sandboxId: sb.sandboxId, returnedId: "error", hostname: err.message };
- }
- }),
- );
-
- for (const r of routingResults) {
- check(
- `Sandbox ${r.index + 1}: routed to correct container`,
- r.returnedId === r.sandboxId,
- `expected ${r.sandboxId}, got ${r.returnedId}`,
- );
- }
-
- // Cross-check: request to sandbox 1's domain should NOT get sandbox 2's response
- if (sandboxes.length >= 2) {
- const cross1 = await fetch(`https://${sandboxes[0].getPreviewDomain(8080)}/`);
- const cross1Data = await cross1.json();
- const cross2 = await fetch(`https://${sandboxes[1].getPreviewDomain(8080)}/`);
- const cross2Data = await cross2.json();
- check(
- "Cross-routing: different sandboxes return different IDs",
- cross1Data.sandboxId !== cross2Data.sandboxId,
- );
- }
- console.log();
-
- // ── Test 5: Multiple methods ────────────────────────────────────
- bold("━━━ Test 5: HTTP methods through TLS ━━━\n");
-
- const domain = sandboxes[0].getPreviewDomain(8080);
- const getResp = await fetch(`https://${domain}/get-test`);
- check("GET request works", getResp.ok);
-
- const postResp = await fetch(`https://${domain}/post-test`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ test: true }),
- });
- check("POST request works", postResp.ok);
-
- const putResp = await fetch(`https://${domain}/put-test`, {
- method: "PUT",
- body: "put-data",
- });
- check("PUT request works", putResp.ok);
- console.log();
-
- } catch (err: any) {
- red(`Fatal error: ${err.message}`);
- if (err.stack) dim(err.stack);
- failed++;
- } finally {
- // Kill all sandboxes
- for (const sb of sandboxes) {
- try { await sb.kill(); } catch {}
- }
- if (sandboxes.length > 0) green(`${sandboxes.length} sandboxes killed`);
- }
-
- // --- Summary ---
- bold("========================================");
- bold(` Results: ${passed} passed, ${failed} failed`);
- bold("========================================\n");
- if (failed > 0) process.exit(1);
-}
-
-main().catch((err) => {
- console.error("Fatal error:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/test-environment.ts b/sdks/typescript/examples/test-environment.ts
deleted file mode 100644
index fd675c28..00000000
--- a/sdks/typescript/examples/test-environment.ts
+++ /dev/null
@@ -1,166 +0,0 @@
-/**
- * Environment & Sandbox Configuration Test
- *
- * Verifies the sandbox environment is set up correctly for normal development:
- * - Running as root (can install packages, modify system files)
- * - HOME=/root (standard root home)
- * - /workspace is a separate persistent disk
- * - npm, pip, git, python, node all work
- * - npm install works in /workspace
- *
- * Usage:
- * npx tsx examples/test-environment.ts
- */
-
-import { Sandbox } from "../src/index";
-
-function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }
-function red(msg: string) { console.log(`\x1b[31m✗ ${msg}\x1b[0m`); }
-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-
-let passed = 0;
-let failed = 0;
-
-function check(desc: string, condition: boolean, detail?: string) {
- if (condition) {
- green(desc);
- passed++;
- } else {
- red(`${desc}${detail ? ` (${detail})` : ""}`);
- failed++;
- }
-}
-
-async function main() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Environment & Sandbox Config Test ║");
- bold("╚══════════════════════════════════════════════════╝\n");
-
- let sandbox: Sandbox | null = null;
-
- try {
- sandbox = await Sandbox.create({ template: "base", timeout: 120 });
- green(`Created sandbox: ${sandbox.sandboxId}`);
- console.log();
-
- // ── Test 1: Running as sandbox user with sudo ──────────────
- bold("━━━ Test 1: Running as sandbox user ━━━\n");
-
- const whoami = await sandbox.commands.run("whoami");
- check("Running as sandbox", whoami.stdout.trim() === "sandbox",
- `got "${whoami.stdout.trim()}"`);
-
- const idResult = await sandbox.commands.run("id -u");
- check("UID is 1000", idResult.stdout.trim() === "1000",
- `got "${idResult.stdout.trim()}"`);
-
- const sudoResult = await sandbox.commands.run("sudo whoami");
- check("sudo works (passwordless)", sudoResult.stdout.trim() === "root",
- `got "${sudoResult.stdout.trim()}"`);
-
- // ── Test 2: HOME is /home/sandbox ────────────────────────────
- bold("━━━ Test 2: HOME environment ━━━\n");
-
- const homeResult = await sandbox.commands.run("echo $HOME");
- check("HOME is /home/sandbox", homeResult.stdout.trim() === "/home/sandbox",
- `got "${homeResult.stdout.trim()}"`);
-
- // ── Test 3: /workspace is a separate disk ───────────────────
- bold("━━━ Test 3: /workspace filesystem ━━━\n");
-
- const dfResult = await sandbox.commands.run("df -h /workspace | tail -1");
- const dfLine = dfResult.stdout.trim();
- dim(`df output: ${dfLine}`);
- check("/workspace is NOT on /dev/root", !dfLine.startsWith("/dev/root"));
- check("/workspace is mounted", dfLine.includes("/workspace"));
-
- const wsExists = await sandbox.commands.run("test -d /workspace && echo yes || echo no");
- check("/workspace directory exists", wsExists.stdout.trim() === "yes");
- console.log();
-
- // ── Test 4: Can install system packages ─────────────────────
- bold("━━━ Test 4: Package installation (apt) ━━━\n");
-
- const aptResult = await sandbox.commands.run(
- "sudo apt-get update -qq > /dev/null 2>&1 && sudo apt-get install -y -qq cowsay > /dev/null 2>&1 && /usr/games/cowsay moo | head -1",
- { timeout: 30 }
- );
- check("apt install works", aptResult.exitCode === 0,
- `exit code ${aptResult.exitCode}`);
- console.log();
-
- // ── Test 5: npm install in /workspace ────────────────────────
- bold("━━━ Test 5: npm install in /workspace ━━━\n");
-
- await sandbox.commands.run("mkdir -p /workspace/npm-test");
- await sandbox.files.write("/workspace/npm-test/package.json", JSON.stringify({
- name: "test",
- version: "1.0.0",
- dependencies: { "is-odd": "3.0.1" }
- }));
-
- const installResult = await sandbox.commands.run(
- "cd /workspace/npm-test && npm install 2>&1 | tail -1",
- { timeout: 30 }
- );
- dim(`npm install exit code: ${installResult.exitCode}`);
- check("npm install succeeds", installResult.exitCode === 0);
-
- const nodeModules = await sandbox.commands.run(
- "test -d /workspace/npm-test/node_modules && echo yes || echo no"
- );
- check("node_modules created in /workspace", nodeModules.stdout.trim() === "yes");
-
- const requireTest = await sandbox.commands.run(
- "cd /workspace/npm-test && node -e \"require('is-odd'); console.log('ok')\"",
- );
- check("Installed package works", requireTest.stdout.trim() === "ok");
- console.log();
-
- // ── Test 6: pip install ─────────────────────────────────────
- bold("━━━ Test 6: pip install ━━━\n");
-
- const pipResult = await sandbox.commands.run(
- "pip3 install -q requests 2>/dev/null && python3 -c \"import requests; print(requests.__version__)\"",
- { timeout: 30 }
- );
- check("pip install + import works", pipResult.exitCode === 0 && pipResult.stdout.trim().length > 0,
- `exit code ${pipResult.exitCode}`);
- dim(`requests version: ${pipResult.stdout.trim()}`);
- console.log();
-
- // ── Test 7: Tools available ─────────────────────────────────
- bold("━━━ Test 7: Development tools ━━━\n");
-
- const tools = ["git", "python3", "node", "npm", "curl", "jq"];
- for (const tool of tools) {
- const r = await sandbox.commands.run(`which ${tool}`);
- check(`${tool} available`, r.exitCode === 0, r.stdout.trim());
- }
- console.log();
-
- // Clean up
- await sandbox.commands.run("rm -rf /workspace/npm-test");
-
- } catch (err: any) {
- red(`Fatal error: ${err.message}`);
- if (err.stack) dim(err.stack);
- failed++;
- } finally {
- if (sandbox) {
- await sandbox.kill();
- green("Sandbox killed");
- }
- }
-
- bold("========================================");
- bold(` Results: ${passed} passed, ${failed} failed`);
- bold("========================================\n");
- if (failed > 0) process.exit(1);
-}
-
-main().catch((err) => {
- console.error("Fatal error:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/test-exec.ts b/sdks/typescript/examples/test-exec.ts
deleted file mode 100644
index 00f526c9..00000000
--- a/sdks/typescript/examples/test-exec.ts
+++ /dev/null
@@ -1,193 +0,0 @@
-/**
- * test-exec.ts — End-to-end test for the session-based exec API
- *
- * Usage:
- * cd sdks/typescript
- * npx tsx examples/test-exec.ts
- *
- * Environment:
- * OPENCOMPUTER_API_URL (default: http://localhost:8080)
- * OPENCOMPUTER_API_KEY (default: opensandbox-dev)
- */
-
-import { Sandbox } from "../src/index.js";
-
-const API_URL = process.env.OPENCOMPUTER_API_URL || "http://localhost:8080";
-const API_KEY = process.env.OPENCOMPUTER_API_KEY || "opensandbox-dev";
-
-const decoder = new TextDecoder();
-let passed = 0;
-let failed = 0;
-
-function assert(condition: boolean, msg: string) {
- if (condition) {
- passed++;
- console.log(` ✓ ${msg}`);
- } else {
- failed++;
- console.log(` ✗ ${msg}`);
- }
-}
-
-async function main() {
- console.log("=== OpenSandbox Exec API Test ===\n");
- console.log(`API: ${API_URL}`);
-
- // 1. Create sandbox
- console.log("\n--- 1. Creating sandbox ---");
- const sandbox = await Sandbox.create({
- apiUrl: API_URL,
- apiKey: API_KEY,
- template: "base",
- });
- console.log(` Sandbox: ${sandbox.sandboxId} (${sandbox.status})`);
- assert(sandbox.status === "running", "sandbox is running");
-
- // 2. exec.run() — quick command
- console.log("\n--- 2. exec.run('echo hello world') ---");
- const result = await sandbox.exec.run("echo hello world");
- console.log(` stdout: "${result.stdout.trim()}"`);
- assert(result.exitCode === 0, `exit code is 0 (got ${result.exitCode})`);
- assert(result.stdout.trim() === "hello world", "stdout matches");
-
- // 3. exec.run() — ls
- console.log("\n--- 3. exec.run('ls /') ---");
- const lsResult = await sandbox.exec.run("ls /");
- assert(lsResult.exitCode === 0, "exit code is 0");
- assert(lsResult.stdout.includes("usr"), "stdout contains 'usr'");
- assert(lsResult.stdout.includes("bin"), "stdout contains 'bin'");
-
- // 4. exec.run() with env vars
- console.log("\n--- 4. exec.run with env vars ---");
- const envResult = await sandbox.exec.run("echo $MY_VAR-$FOO", {
- env: { MY_VAR: "hello", FOO: "bar" },
- });
- console.log(` output: "${envResult.stdout.trim()}"`);
- assert(envResult.stdout.trim() === "hello-bar", "env vars passed correctly");
-
- // 5. exec.run() with cwd
- console.log("\n--- 5. exec.run('pwd') with cwd=/tmp ---");
- const cwdResult = await sandbox.exec.run("pwd", { cwd: "/tmp" });
- console.log(` pwd: "${cwdResult.stdout.trim()}"`);
- assert(cwdResult.stdout.trim() === "/tmp", "cwd is /tmp");
-
- // 6. exec.run() — non-zero exit code
- console.log("\n--- 6. exec.run('exit 42') ---");
- const failResult = await sandbox.exec.run("exit 42");
- console.log(` exit: ${failResult.exitCode}`);
- assert(
- failResult.exitCode === 42,
- `exit code is 42 (got ${failResult.exitCode})`,
- );
-
- // 7. exec.run() — stderr
- console.log("\n--- 7. exec.run stderr ---");
- const stderrResult = await sandbox.exec.run("echo error-msg >&2");
- console.log(` stderr: "${stderrResult.stderr.trim()}"`);
- assert(stderrResult.stderr.trim() === "error-msg", "stderr captured");
-
- // 8. exec.start() — streaming output
- console.log("\n--- 8. exec.start() — streaming ---");
- const lines: string[] = [];
- let streamExitCode = -1;
- const session = await sandbox.exec.start("sh", {
- args: ["-c", "for i in 1 2 3; do echo line-$i; sleep 0.1; done"],
- onStdout: (data) => {
- const text = decoder.decode(data);
- text
- .split("\n")
- .filter(Boolean)
- .forEach((l) => lines.push(l));
- },
- onExit: (code) => {
- streamExitCode = code;
- },
- });
- console.log(` session: ${session.sessionId}`);
- await session.done;
- assert(lines.includes("line-1"), "got line-1");
- assert(lines.includes("line-3"), "got line-3");
- assert(streamExitCode === 0, `stream exit code is 0 (got ${streamExitCode})`);
-
- // 9. exec.list()
- console.log("\n--- 9. exec.list() ---");
- const sessions = await sandbox.exec.list();
- console.log(` ${sessions.length} session(s)`);
- assert(sessions.length > 0, "has sessions");
-
- // 10. exec.start() + kill
- console.log("\n--- 10. exec.start('sleep 60') + kill ---");
- let killExitCode = -999;
- const sleepSession = await sandbox.exec.start("sleep", {
- args: ["60"],
- onExit: (code) => {
- killExitCode = code;
- },
- });
- await new Promise((resolve) => setTimeout(resolve, 500));
- await sleepSession.kill();
- await sleepSession.done;
- console.log(` exit after kill: ${killExitCode}`);
- assert(killExitCode !== -999, "got exit callback after kill");
-
- // 11. File write + read via exec
- console.log("\n--- 11. Write file + cat ---");
- await sandbox.files.write("/tmp/test.txt", "Hello from SDK!\n");
- const catResult = await sandbox.exec.run("cat /tmp/test.txt");
- console.log(` cat: "${catResult.stdout.trim()}"`);
- assert(catResult.stdout.trim() === "Hello from SDK!", "file content matches");
-
- // 12. Multi-command shell script
- console.log("\n--- 12. Multi-command script ---");
- const scriptResult = await sandbox.exec.run(
- "echo hostname=$(hostname); echo user=$(whoami); echo arch=$(uname -m)",
- );
- console.log(` ${scriptResult.stdout.trim()}`);
- assert(scriptResult.stdout.includes("hostname="), "has hostname");
- assert(scriptResult.stdout.includes("user="), "has user");
-
- // 13. Network connectivity
- console.log("\n--- 13. Network connectivity ---");
- const extPing = await sandbox.exec.run("ping -c 1 -W 3 8.8.8.8 2>&1", { timeout: 10 });
- const extReachable = extPing.stdout.includes("bytes from");
- console.log(` ping 8.8.8.8: ${extReachable ? "reachable" : "unreachable"}`);
- assert(extReachable, "external ping works");
-
- const dnsResult = await sandbox.exec.run("getent hosts google.com 2>&1 | head -1", { timeout: 10 });
- const dnsOk = dnsResult.exitCode === 0 && dnsResult.stdout.trim().length > 0;
- console.log(` DNS: ${dnsOk ? dnsResult.stdout.trim() : "failed"}`);
- assert(dnsOk, "DNS resolution works");
-
- // 14. apt-get update (streaming via start + await done)
- console.log("\n--- 14. apt-get update (streaming) ---");
- const aptLines: string[] = [];
- const aptSession = await sandbox.exec.start("sh", {
- args: ["-c", "apt-get update 2>&1 | head -10"],
- timeout: 30,
- onStdout: (data) => {
- const text = decoder.decode(data);
- for (const line of text.split("\n").filter(Boolean)) {
- aptLines.push(line);
- process.stdout.write(` > ${line}\n`);
- }
- },
- });
- const aptExitCode = await aptSession.done;
- console.log(` exit: ${aptExitCode} (${aptLines.length} lines)`);
- assert(aptExitCode === 0, "apt-get update succeeds");
- assert(aptLines.some((l) => l.includes("Hit:") || l.includes("Get:")), "apt-get fetched package lists");
-
- // 15. Cleanup
- console.log("\n--- 15. Killing sandbox ---");
- await sandbox.kill();
- assert(sandbox.status === "stopped", "sandbox stopped");
-
- // Summary
- console.log(`\n=== Results: ${passed} passed, ${failed} failed ===`);
- if (failed > 0) process.exit(1);
-}
-
-main().catch((err) => {
- console.error("\nTest failed:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/test-file-ops.ts b/sdks/typescript/examples/test-file-ops.ts
deleted file mode 100644
index c4f49f8f..00000000
--- a/sdks/typescript/examples/test-file-ops.ts
+++ /dev/null
@@ -1,205 +0,0 @@
-/**
- * File Operations Edge Cases Test
- *
- * Tests:
- * 1. Large file write/read (1MB)
- * 2. Binary-like content handling
- * 3. Deeply nested directories
- * 4. File deletion and overwrite
- * 5. List large directories
- * 6. Special characters in content
- * 7. Empty file handling
- * 8. File exists / not exists
- *
- * Usage:
- * npx tsx examples/test-file-ops.ts
- */
-
-import { Sandbox } from "../src/index";
-
-function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }
-function red(msg: string) { console.log(`\x1b[31m✗ ${msg}\x1b[0m`); }
-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-
-let passed = 0;
-let failed = 0;
-
-function check(desc: string, condition: boolean, detail?: string) {
- if (condition) {
- green(desc);
- passed++;
- } else {
- red(`${desc}${detail ? ` (${detail})` : ""}`);
- failed++;
- }
-}
-
-async function main() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ File Operations Edge Cases Test ║");
- bold("╚══════════════════════════════════════════════════╝\n");
-
- let sandbox: Sandbox | null = null;
-
- try {
- sandbox = await Sandbox.create({ template: "base", timeout: 120 });
- green(`Created sandbox: ${sandbox.sandboxId}`);
- console.log();
-
- // ── Test 1: Large file ──────────────────────────────────────────
- bold("━━━ Test 1: Large file (1MB) ━━━\n");
-
- const oneMB = "X".repeat(1024 * 1024);
- const writeStart = Date.now();
- await sandbox.files.write("/tmp/large.txt", oneMB);
- const writeMs = Date.now() - writeStart;
- dim(`Write: ${writeMs}ms`);
-
- const readStart = Date.now();
- const largeContent = await sandbox.files.read("/tmp/large.txt");
- const readMs = Date.now() - readStart;
- dim(`Read: ${readMs}ms`);
-
- check("1MB file size preserved", largeContent.length === oneMB.length, `${largeContent.length} bytes`);
- check("1MB file content intact", largeContent === oneMB);
- console.log();
-
- // ── Test 2: Special characters in content ───────────────────────
- bold("━━━ Test 2: Special characters ━━━\n");
-
- const specialContent = 'Hello "world" & <tag> \'quotes\' \\ newline\nTab\there 日本語 emoji🎉 nullish ?? chain?.';
- await sandbox.files.write("/tmp/special.txt", specialContent);
- const specialRead = await sandbox.files.read("/tmp/special.txt");
- check("Special characters preserved", specialRead === specialContent, `got: ${specialRead.substring(0, 50)}...`);
-
- // JSON content
- const jsonContent = JSON.stringify({ key: "value", nested: { arr: [1, 2, 3] }, unicode: "日本語" }, null, 2);
- await sandbox.files.write("/tmp/data.json", jsonContent);
- const jsonRead = await sandbox.files.read("/tmp/data.json");
- check("JSON content preserved", jsonRead === jsonContent);
-
- // Multi-line content
- const multiline = Array.from({ length: 100 }, (_, i) => `Line ${i + 1}: Some content here`).join("\n");
- await sandbox.files.write("/tmp/multiline.txt", multiline);
- const multiRead = await sandbox.files.read("/tmp/multiline.txt");
- check("100-line file preserved", multiRead === multiline, `lines: ${multiRead.split("\n").length}`);
- console.log();
-
- // ── Test 3: Deeply nested directories ───────────────────────────
- bold("━━━ Test 3: Deeply nested directories ━━━\n");
-
- const deepPath = "/tmp/a/b/c/d/e/f/g/h";
- // Create nested dirs step by step using commands (SDK mkdir doesn't do recursive)
- await sandbox.commands.run(`mkdir -p ${deepPath}`);
- await sandbox.files.write(`${deepPath}/deep.txt`, "bottom-of-tree");
- const deepContent = await sandbox.files.read(`${deepPath}/deep.txt`);
- check("8-level nested file created and read", deepContent === "bottom-of-tree");
-
- // List intermediate directory
- const midEntries = await sandbox.files.list("/tmp/a/b/c/d");
- check("Intermediate dir lists correctly", midEntries.some(e => e.name === "e" && e.isDir));
- console.log();
-
- // ── Test 4: File deletion and overwrite ──────────────────────────
- bold("━━━ Test 4: File deletion and overwrite ━━━\n");
-
- // Write → overwrite → verify new content
- await sandbox.files.write("/tmp/overwrite.txt", "original");
- let content = await sandbox.files.read("/tmp/overwrite.txt");
- check("Original content written", content === "original");
-
- await sandbox.files.write("/tmp/overwrite.txt", "overwritten");
- content = await sandbox.files.read("/tmp/overwrite.txt");
- check("Overwritten content correct", content === "overwritten");
-
- // Overwrite with shorter content
- await sandbox.files.write("/tmp/overwrite.txt", "short");
- content = await sandbox.files.read("/tmp/overwrite.txt");
- check("Shorter overwrite correct (no trailing data)", content === "short");
-
- // Delete
- const existsBefore = await sandbox.files.exists("/tmp/overwrite.txt");
- check("File exists before delete", existsBefore);
-
- await sandbox.files.remove("/tmp/overwrite.txt");
- const existsAfter = await sandbox.files.exists("/tmp/overwrite.txt");
- check("File gone after delete", !existsAfter);
-
- // Delete directory
- await sandbox.files.remove("/tmp/a");
- const dirGone = await sandbox.files.exists(`${deepPath}/deep.txt`);
- check("Recursive directory deletion", !dirGone);
- console.log();
-
- // ── Test 5: Large directory listing ─────────────────────────────
- bold("━━━ Test 5: Large directory listing ━━━\n");
-
- // Create 50 files
- await sandbox.commands.run(
- "for i in $(seq 1 50); do echo content-$i > /tmp/listtest-$i.txt; done",
- );
- const entries = await sandbox.files.list("/tmp");
- const listTestFiles = entries.filter(e => e.name.startsWith("listtest-"));
- check("50 files visible in listing", listTestFiles.length === 50, `found ${listTestFiles.length}`);
-
- // Verify entries have correct metadata
- const entry = listTestFiles[0];
- check("Entry has name", !!entry.name);
- check("Entry has isDir=false", entry.isDir === false);
- check("Entry has size > 0", entry.size > 0, `size=${entry.size}`);
- console.log();
-
- // ── Test 6: Empty file ──────────────────────────────────────────
- bold("━━━ Test 6: Empty file handling ━━━\n");
-
- await sandbox.files.write("/tmp/empty.txt", "");
- const emptyContent = await sandbox.files.read("/tmp/empty.txt");
- check("Empty file returns empty string", emptyContent === "", `got: "${emptyContent}"`);
- check("Empty file exists", await sandbox.files.exists("/tmp/empty.txt"));
- console.log();
-
- // ── Test 7: File exists / not exists ────────────────────────────
- bold("━━━ Test 7: File exists checks ━━━\n");
-
- check("Existing file → true", await sandbox.files.exists("/tmp/special.txt"));
- check("Non-existent file → false", !(await sandbox.files.exists("/tmp/nope-no-way.txt")));
- check("Non-existent deep path → false", !(await sandbox.files.exists("/tmp/no/such/path/file.txt")));
- console.log();
-
- // ── Test 8: Binary-like content ─────────────────────────────────
- bold("━━━ Test 8: Write via commands + read via SDK ━━━\n");
-
- // Write a script, execute it, read output via SDK
- await sandbox.commands.run('dd if=/dev/urandom bs=256 count=1 2>/dev/null | base64 > /tmp/random.b64');
- const b64Content = await sandbox.files.read("/tmp/random.b64");
- check("Base64 random data readable", b64Content.length > 100, `${b64Content.length} chars`);
-
- // Write via command, read via SDK
- await sandbox.commands.run('echo -n "command-written" > /tmp/cmd-file.txt');
- const cmdFileContent = await sandbox.files.read("/tmp/cmd-file.txt");
- check("Command-written file readable via SDK", cmdFileContent === "command-written");
- console.log();
-
- } catch (err: any) {
- red(`Fatal error: ${err.message}`);
- if (err.stack) dim(err.stack);
- failed++;
- } finally {
- if (sandbox) {
- await sandbox.kill();
- green("Sandbox killed");
- }
- }
-
- // --- Summary ---
- bold("========================================");
- bold(` Results: ${passed} passed, ${failed} failed`);
- bold("========================================\n");
- if (failed > 0) process.exit(1);
-}
-
-main().catch((err) => {
- console.error("Fatal error:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/test-hibernation-stress.ts b/sdks/typescript/examples/test-hibernation-stress.ts
deleted file mode 100644
index a9a30941..00000000
--- a/sdks/typescript/examples/test-hibernation-stress.ts
+++ /dev/null
@@ -1,259 +0,0 @@
-/**
- * Hibernation Stress Test
- *
- * Tests:
- * 1. Multiple hibernate/wake cycles on same sandbox
- * 2. Large state persistence across hibernation
- * 3. Rapid auto-wake via HTTP after hibernation
- * 4. Process state survives across cycles
- *
- * Usage:
- * npx tsx examples/test-hibernation-stress.ts
- */
-
-import { Sandbox } from "../src/index";
-
-function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }
-function red(msg: string) { console.log(`\x1b[31m✗ ${msg}\x1b[0m`); }
-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-function cyan(msg: string) { console.log(`\x1b[36m→ ${msg}\x1b[0m`); }
-
-function sleep(ms: number) {
- return new Promise((r) => globalThis.setTimeout(r, ms));
-}
-
-let passed = 0;
-let failed = 0;
-
-function check(desc: string, condition: boolean, detail?: string) {
- if (condition) {
- green(desc);
- passed++;
- } else {
- red(`${desc}${detail ? ` (${detail})` : ""}`);
- failed++;
- }
-}
-
-async function main() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Hibernation Stress Test ║");
- bold("╚══════════════════════════════════════════════════╝\n");
-
- let sandbox: Sandbox | null = null;
-
- try {
- // ── Setup: Create sandbox with a persistent server ──────────────
- bold("━━━ Setup: Create sandbox with counter server ━━━\n");
-
- sandbox = await Sandbox.create({ timeout: 300 });
- green(`Created: ${sandbox.sandboxId}`);
- dim(`Domain: ${sandbox.getPreviewDomain(8080)}`);
-
- // Write a server that maintains an in-memory counter
- const SERVER_CODE = `
-const http = require('http');
-const fs = require('fs');
-let counter = 0;
-try { counter = parseInt(fs.readFileSync('/tmp/counter.txt', 'utf8')) || 0; } catch {}
-const server = http.createServer((req, res) => {
- if (req.url === '/increment') {
- counter++;
- fs.writeFileSync('/tmp/counter.txt', String(counter));
- res.writeHead(200, {'Content-Type':'application/json'});
- res.end(JSON.stringify({counter}));
- } else if (req.url === '/health') {
- res.writeHead(200, {'Content-Type':'application/json'});
- res.end(JSON.stringify({counter, uptime: process.uptime().toFixed(1)+'s'}));
- } else {
- res.writeHead(404); res.end('not found');
- }
-});
-server.listen(8080, '0.0.0.0', () => console.log('Counter server on port 8080'));
-`;
-
- await sandbox.files.write("/tmp/counter-server.js", SERVER_CODE);
- await sandbox.commands.run("nohup node /tmp/counter-server.js > /tmp/server.log 2>&1 &");
- await sleep(1500);
-
- // Verify server is up
- const healthResp = await fetch(`https://${sandbox.getPreviewDomain(8080)}/health`);
- check("Counter server started", healthResp.ok);
- const health = await healthResp.json();
- dim(`Initial state: counter=${health.counter}, uptime=${health.uptime}`);
- console.log();
-
- // ── Test 1: Multiple hibernate/wake cycles ──────────────────────
- bold("━━━ Test 1: Multiple hibernate/wake cycles (3x) ━━━\n");
- const cycleTimes: { hibernate: number; wake: number }[] = [];
-
- for (let cycle = 1; cycle <= 3; cycle++) {
- cyan(`Cycle ${cycle}/3: Incrementing counter...`);
-
- // Increment counter before hibernate
- const incResp = await fetch(`https://${sandbox.getPreviewDomain(8080)}/increment`);
- const incData = await incResp.json();
- dim(`Counter = ${incData.counter}`);
-
- // Hibernate
- cyan(`Cycle ${cycle}/3: Hibernating...`);
- const hibStart = Date.now();
- await sandbox.hibernate();
- const hibMs = Date.now() - hibStart;
-
- await sleep(1000);
-
- // Wake
- cyan(`Cycle ${cycle}/3: Waking...`);
- const wakeStart = Date.now();
- await sandbox.wake();
- const wakeMs = Date.now() - wakeStart;
-
- // Need to wait a moment for server to be ready after restore
- await sleep(2000);
-
- cycleTimes.push({ hibernate: hibMs, wake: wakeMs });
- dim(`Hibernate: ${hibMs}ms, Wake: ${wakeMs}ms`);
-
- // Verify counter persisted
- const postWakeResp = await fetch(`https://${sandbox.getPreviewDomain(8080)}/health`);
- if (postWakeResp.ok) {
- const postWake = await postWakeResp.json();
- check(`Cycle ${cycle}: Counter persisted (${postWake.counter})`, postWake.counter === cycle);
- } else {
- check(`Cycle ${cycle}: Server responded after wake`, false, `status ${postWakeResp.status}`);
- }
- }
-
- console.log();
- dim("Cycle timing summary:");
- cycleTimes.forEach((t, i) => dim(` Cycle ${i + 1}: hibernate=${t.hibernate}ms, wake=${t.wake}ms`));
- console.log();
-
- // ── Test 2: Large state persistence ─────────────────────────────
- bold("━━━ Test 2: Large state persistence across hibernation ━━━\n");
-
- // Write a 500KB file
- const largeData = "A".repeat(500 * 1024);
- cyan("Writing 500KB file...");
- await sandbox.files.write("/tmp/large-state.bin", largeData);
-
- // Write 100 small files
- cyan("Writing 100 small files...");
- await sandbox.commands.run(
- "for i in $(seq 1 100); do echo \"file-content-$i\" > /tmp/batch-$i.txt; done",
- );
-
- // Hibernate with all this state
- cyan("Hibernating with large state...");
- const bigHibStart = Date.now();
- await sandbox.hibernate();
- const bigHibMs = Date.now() - bigHibStart;
- dim(`Hibernate with large state: ${bigHibMs}ms`);
-
- await sleep(1000);
-
- // Wake
- cyan("Waking...");
- const bigWakeStart = Date.now();
- await sandbox.wake();
- const bigWakeMs = Date.now() - bigWakeStart;
- dim(`Wake with large state: ${bigWakeMs}ms`);
- await sleep(1500);
-
- // Verify large file
- const largeContent = await sandbox.files.read("/tmp/large-state.bin");
- check("500KB file persisted", largeContent.length === largeData.length, `got ${largeContent.length} bytes`);
- check("500KB file content intact", largeContent === largeData);
-
- // Verify batch files (spot check)
- const file1 = await sandbox.files.read("/tmp/batch-1.txt");
- check("Batch file 1 persisted", file1.trim() === "file-content-1", file1.trim());
- const file50 = await sandbox.files.read("/tmp/batch-50.txt");
- check("Batch file 50 persisted", file50.trim() === "file-content-50", file50.trim());
- const file100 = await sandbox.files.read("/tmp/batch-100.txt");
- check("Batch file 100 persisted", file100.trim() === "file-content-100", file100.trim());
- console.log();
-
- // ── Test 3: Rapid auto-wake ─────────────────────────────────────
- bold("━━━ Test 3: Rapid auto-wake via HTTP ━━━\n");
-
- // Hibernate
- cyan("Hibernating for auto-wake test...");
- await sandbox.hibernate();
- await sleep(1000);
-
- // Immediately hit the domain - should trigger auto-wake
- cyan("Sending HTTP request to sleeping sandbox...");
- const autoWakeStart = Date.now();
- const autoWakeResp = await fetch(`https://${sandbox.getPreviewDomain(8080)}/health`);
- const autoWakeMs = Date.now() - autoWakeStart;
-
- check("Auto-wake HTTP returned 200", autoWakeResp.ok, `status ${autoWakeResp.status}`);
- if (autoWakeResp.ok) {
- const autoWakeData = await autoWakeResp.json();
- check("Counter still intact after auto-wake", autoWakeData.counter === 3, `counter=${autoWakeData.counter}`);
- dim(`Auto-wake latency: ${autoWakeMs}ms`);
- }
- console.log();
-
- // ── Test 4: Process state survives ──────────────────────────────
- bold("━━━ Test 4: Process state survives hibernation ━━━\n");
-
- // Update sandbox reference after auto-wake restored it
- sandbox = await Sandbox.connect(sandbox.sandboxId);
-
- // Get PID of node server before hibernate
- const pidBefore = await sandbox.commands.run("cat /tmp/server.log | head -1");
- dim(`Server log: ${pidBefore.stdout.trim()}`);
-
- // Increment counter to 4
- await fetch(`https://${sandbox.getPreviewDomain(8080)}/increment`);
- const preHibHealth = await fetch(`https://${sandbox.getPreviewDomain(8080)}/health`);
- const preHibData = await preHibHealth.json();
- check("Counter at 4 before final hibernate", preHibData.counter === 4, `counter=${preHibData.counter}`);
-
- // One more hibernate/wake cycle (use auto-wake via HTTP to avoid restore conflict)
- await sandbox.hibernate();
- await sleep(1000);
-
- // Auto-wake by hitting the domain instead of explicit wake()
- const finalHealth = await fetch(`https://${sandbox.getPreviewDomain(8080)}/health`);
- if (finalHealth.ok) {
- const finalData = await finalHealth.json();
- check("Counter persisted through final cycle", finalData.counter === 4, `counter=${finalData.counter}`);
- green(`Final state: counter=${finalData.counter}, uptime=${finalData.uptime}`);
- } else {
- check("Final health check", false, `status ${finalHealth.status}`);
- }
- console.log();
-
- } catch (err: any) {
- red(`Fatal error: ${err.message}`);
- if (err.stack) dim(err.stack);
- failed++;
- } finally {
- if (sandbox) {
- try {
- // Re-connect in case wake changed state
- const s = await Sandbox.connect(sandbox.sandboxId);
- await s.kill();
- green("Sandbox killed");
- } catch {
- dim("Sandbox may have already been cleaned up");
- }
- }
- }
-
- // --- Summary ---
- bold("========================================");
- bold(` Results: ${passed} passed, ${failed} failed`);
- bold("========================================\n");
- if (failed > 0) process.exit(1);
-}
-
-main().catch((err) => {
- console.error("Fatal error:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/test-large-files.ts b/sdks/typescript/examples/test-large-files.ts
deleted file mode 100644
index c9a7cf83..00000000
--- a/sdks/typescript/examples/test-large-files.ts
+++ /dev/null
@@ -1,199 +0,0 @@
-/**
- * Large File Streaming Test
- *
- * Tests:
- * 1. Write a 100MB file via SDK, read back and verify size
- * 2. Download 100MB file via signed URL, verify content integrity (SHA-256)
- * 3. Upload 100MB file via signed URL, verify content integrity
- * 4. Write 50MB via writeStream, read back via readStream
- *
- * Usage:
- * npx tsx examples/test-large-files.ts
- */
-
-import { createHash } from "crypto";
-import { Sandbox } from "../src/index";
-
-function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }
-function red(msg: string) { console.log(`\x1b[31m✗ ${msg}\x1b[0m`); }
-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-
-let passed = 0;
-let failed = 0;
-
-function check(desc: string, condition: boolean, detail?: string) {
- if (condition) {
- green(desc);
- passed++;
- } else {
- red(`${desc}${detail ? ` (${detail})` : ""}`);
- failed++;
- }
-}
-
-/** Generate deterministic data: repeating pattern so we can verify integrity */
-function generateData(sizeMB: number): Uint8Array {
- const size = sizeMB * 1024 * 1024;
- const buf = new Uint8Array(size);
- // Fill with repeating 256-byte pattern
- for (let i = 0; i < size; i++) {
- buf[i] = i % 256;
- }
- return buf;
-}
-
-function sha256(data: Uint8Array): string {
- return createHash("sha256").update(data).digest("hex");
-}
-
-async function streamToBuffer(stream: ReadableStream<Uint8Array>): Promise<Uint8Array> {
- const reader = stream.getReader();
- const chunks: Uint8Array[] = [];
- let totalLen = 0;
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- chunks.push(value);
- totalLen += value.length;
- }
- const result = new Uint8Array(totalLen);
- let offset = 0;
- for (const chunk of chunks) {
- result.set(chunk, offset);
- offset += chunk.length;
- }
- return result;
-}
-
-async function main() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Large File Streaming Test ║");
- bold("╚══════════════════════════════════════════════════╝\n");
-
- let sandbox: Sandbox | null = null;
-
- try {
- sandbox = await Sandbox.create({ template: "base", timeout: 300 });
- green(`Created sandbox: ${sandbox.sandboxId}`);
- console.log();
-
- // ── Test 1: Write and read 100MB file via SDK ────────────────
- bold("━━━ Test 1: Write/read 100MB file via SDK ━━━\n");
-
- const data100 = generateData(100);
- const hash100 = sha256(data100);
- dim(`Generated 100MB data, SHA-256: ${hash100.slice(0, 16)}...`);
-
- const t0 = Date.now();
- await sandbox.files.write("/root/large100.bin", data100);
- const writeMs = Date.now() - t0;
- dim(`Write took ${writeMs}ms (${(100 * 1000 / writeMs).toFixed(1)} MB/s)`);
- green("100MB write completed");
-
- const t1 = Date.now();
- const readBack = await sandbox.files.readBytes("/root/large100.bin");
- const readMs = Date.now() - t1;
- dim(`Read took ${readMs}ms (${(100 * 1000 / readMs).toFixed(1)} MB/s)`);
-
- check("Read returns correct size", readBack.length === data100.length,
- `got ${readBack.length}, expected ${data100.length}`);
- const readHash = sha256(readBack);
- check("SHA-256 matches after read", readHash === hash100,
- `got ${readHash.slice(0, 16)}...`);
- console.log();
-
- // ── Test 2: Download 100MB via signed URL ────────────────────
- bold("━━━ Test 2: Download 100MB via signed URL ━━━\n");
-
- const dlUrl = await sandbox.downloadUrl("/root/large100.bin", { expiresIn: 300 });
- dim(`Download URL generated`);
-
- const t2 = Date.now();
- const dlRes = await fetch(dlUrl);
- check("Signed URL returns 200", dlRes.status === 200);
-
- const contentLength = dlRes.headers.get("content-length");
- dim(`Content-Length: ${contentLength}`);
- check("Content-Length is 100MB", contentLength === String(data100.length));
-
- const dlData = new Uint8Array(await dlRes.arrayBuffer());
- const dlMs = Date.now() - t2;
- dim(`Download took ${dlMs}ms (${(100 * 1000 / dlMs).toFixed(1)} MB/s)`);
-
- check("Downloaded size correct", dlData.length === data100.length);
- const dlHash = sha256(dlData);
- check("SHA-256 matches via signed URL download", dlHash === hash100);
- console.log();
-
- // ── Test 3: Upload 100MB via signed URL ──────────────────────
- bold("━━━ Test 3: Upload 100MB via signed URL ━━━\n");
-
- const upUrl = await sandbox.uploadUrl("/root/uploaded100.bin");
- dim(`Upload URL generated`);
-
- const t3 = Date.now();
- const upRes = await fetch(upUrl, {
- method: "PUT",
- body: data100,
- });
- const upMs = Date.now() - t3;
- dim(`Upload took ${upMs}ms (${(100 * 1000 / upMs).toFixed(1)} MB/s)`);
- check("Upload returns 204", upRes.status === 204);
-
- // Verify via SDK readBytes
- const upReadBack = await sandbox.files.readBytes("/root/uploaded100.bin");
- check("Uploaded file size correct", upReadBack.length === data100.length);
- const upHash = sha256(upReadBack);
- check("SHA-256 matches after signed URL upload", upHash === hash100);
- console.log();
-
- // ── Test 4: readStream / writeStream (50MB) ──────────────────
- bold("━━━ Test 4: readStream / writeStream 50MB ━━━\n");
-
- const data50 = generateData(50);
- const hash50 = sha256(data50);
- dim(`Generated 50MB data, SHA-256: ${hash50.slice(0, 16)}...`);
-
- // writeStream
- const t4 = Date.now();
- await sandbox.files.writeStream("/root/stream50.bin", data50);
- const wsMs = Date.now() - t4;
- dim(`writeStream took ${wsMs}ms`);
- green("50MB writeStream completed");
-
- // readStream
- const t5 = Date.now();
- const readStream = await sandbox.files.readStream("/root/stream50.bin");
- const streamData = await streamToBuffer(readStream);
- const rsMs = Date.now() - t5;
- dim(`readStream took ${rsMs}ms`);
-
- check("readStream returns correct size", streamData.length === data50.length,
- `got ${streamData.length}, expected ${data50.length}`);
- const streamHash = sha256(streamData);
- check("SHA-256 matches via readStream", streamHash === hash50);
- console.log();
-
- } catch (err: any) {
- red(`Fatal error: ${err.message}`);
- if (err.stack) dim(err.stack);
- failed++;
- } finally {
- if (sandbox) {
- await sandbox.kill();
- green("Sandbox killed");
- }
- }
-
- // --- Summary ---
- bold("========================================");
- bold(` Results: ${passed} passed, ${failed} failed`);
- bold("========================================\n");
- if (failed > 0) process.exit(1);
-}
-
-main().catch((err) => {
- console.error("Fatal error:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/test-openclaw-snapshot-stress.ts b/sdks/typescript/examples/test-openclaw-snapshot-stress.ts
deleted file mode 100644
index 9bfecab6..00000000
--- a/sdks/typescript/examples/test-openclaw-snapshot-stress.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-/**
- * Stress test OpenClaw snapshot builds — runs N full builds, each with a unique
- * image (cache-busted) so every build goes through the full install flow.
- *
- * Usage:
- * OPENCOMPUTER_API_KEY=... npx tsx examples/test-openclaw-snapshot-stress.ts [count]
- *
- * Default: 5 builds
- */
-
-import { Image, Snapshots } from "@opencomputer/sdk/node";
-
-const API_URL = process.env.OPENCOMPUTER_API_URL || "https://app.opencomputer.dev";
-const API_KEY = process.env.OPENCOMPUTER_API_KEY;
-const COUNT = parseInt(process.argv[2] || "5", 10);
-
-if (!API_KEY) {
- console.error("Set OPENCOMPUTER_API_KEY");
- process.exit(1);
-}
-
-const snapshots = new Snapshots({ apiKey: API_KEY, apiUrl: API_URL });
-
-async function buildOne(i: number): Promise<{ name: string; durationMs: number; status: string }> {
- const name = `openclaw-stress-${Date.now()}-${i}`;
-
- // Cache-bust: unique marker file per build forces a fresh image
- const image = Image.base()
- .runCommands(
- "sudo apt-get update && sudo apt-get install -y curl ca-certificates gnupg",
- )
- .runCommands(
- "curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -",
- "sudo apt-get install -y nodejs",
- )
- .runCommands(
- "mkdir -p ~/npm-global",
- "npm config set prefix ~/npm-global",
- "npm install -g openclaw@latest",
- "echo 'export PATH=$HOME/npm-global/bin:$PATH' | sudo tee /etc/profile.d/npm-global.sh",
- )
- .runCommands("mkdir -p ~/.openclaw/workspace")
- .addFile(
- "/home/sandbox/start-openclaw.sh",
- `#!/bin/bash
-set -e
-export PATH=$HOME/npm-global/bin:$PATH
-[ -f ~/.openclaw/env ] && source ~/.openclaw/env
-cd ~
-nohup openclaw gateway --port 18789 > ~/.openclaw/gateway.log 2>&1 &
-for i in $(seq 1 30); do
- if openclaw gateway status > /dev/null 2>&1; then
- echo "OpenClaw gateway is ready"
- exit 0
- fi
- sleep 1
-done
-echo "Warning: gateway did not become ready within 30s"
-exit 1
-`,
- )
- .runCommands("sudo chmod +x ~/start-openclaw.sh")
- // Cache-bust: unique echo per build
- .runCommands(`echo "build-${name}" > /tmp/build-marker`);
-
- const t0 = Date.now();
- const info = await snapshots.create({
- name,
- image,
- onBuildLogs: (line: string) => {
- process.stdout.write(` [${i + 1}] ${line}\n`);
- },
- });
-
- return { name, durationMs: Date.now() - t0, status: info.status };
-}
-
-async function main() {
- console.log(`OpenClaw snapshot stress test: ${COUNT} full builds`);
- console.log(`API: ${API_URL}\n`);
-
- const results: { name: string; durationMs: number; status: string; error?: string }[] = [];
-
- for (let i = 0; i < COUNT; i++) {
- console.log(`\n── Build ${i + 1}/${COUNT} ──`);
- try {
- const result = await buildOne(i);
- results.push(result);
- console.log(` ✓ ${result.name} — ${(result.durationMs / 1000).toFixed(1)}s (${result.status})`);
- } catch (err: any) {
- results.push({ name: `build-${i}`, durationMs: 0, status: "failed", error: err.message });
- console.log(` ✗ FAILED: ${err.message}`);
- }
- }
-
- console.log(`\n══ Results ══`);
- const passed = results.filter((r) => r.status === "ready");
- const failed = results.filter((r) => r.status !== "ready");
- for (const r of results) {
- const dur = r.durationMs ? `${(r.durationMs / 1000).toFixed(1)}s` : "—";
- const icon = r.status === "ready" ? "✓" : "✗";
- console.log(` ${icon} ${r.name} ${dur} ${r.error || ""}`);
- }
- const durations = passed.map((r) => r.durationMs / 1000);
- if (durations.length > 0) {
- const avg = durations.reduce((a, b) => a + b, 0) / durations.length;
- console.log(`\n ${passed.length}/${COUNT} passed, avg ${avg.toFixed(1)}s`);
- }
- if (failed.length > 0) {
- process.exit(1);
- }
-}
-
-main().catch((err) => {
- console.error("Fatal:", err.message);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/test-openclaw-snapshot.ts b/sdks/typescript/examples/test-openclaw-snapshot.ts
deleted file mode 100644
index 02280466..00000000
--- a/sdks/typescript/examples/test-openclaw-snapshot.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-/**
- * Build a reusable OpenClaw snapshot (golden image equivalent).
- *
- * This creates a pre-built sandbox image with Node.js 22 and OpenClaw
- * pre-installed. Provisioning new employees boots from this snapshot in seconds.
- *
- * Usage:
- * npx tsx examples/test-openclaw-snapshot.ts
- *
- * Only needs to run once, or when you want to update the base OpenClaw version.
- */
-
-import { Sandbox } from "@opencomputer/sdk";
-import { Image, Snapshots } from "@opencomputer/sdk/node";
-
-const OC_API_URL = process.env.OPENCOMPUTER_API_URL || "https://app.opencomputer.dev";
-const OC_API_KEY = process.env.OPENCOMPUTER_API_KEY;
-const OPENCLAW_SNAPSHOT = "openclaw-test-" + Date.now();
-
-async function main() {
- const apiKey = OC_API_KEY;
- if (!apiKey) {
- console.error("Set OPENCOMPUTER_API_KEY");
- process.exit(1);
- }
-
- console.log("Building OpenClaw snapshot...");
- console.log("This installs Node.js 22 and OpenClaw into a reusable image.\n");
-
- const image = Image.base()
- .runCommands(
- "sudo apt-get update && sudo apt-get install -y curl ca-certificates gnupg",
- )
- // Install Node.js 22 via NodeSource
- .runCommands(
- "curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -",
- "sudo apt-get install -y nodejs",
- )
- // Install OpenClaw globally — npm prefix set to ~/npm-global so the
- // 200MB package lands on the large home disk, not the small rootfs.
- .runCommands(
- "mkdir -p ~/npm-global",
- "npm config set prefix ~/npm-global",
- "npm install -g openclaw@latest",
- "echo 'export PATH=$HOME/npm-global/bin:$PATH' | sudo tee /etc/profile.d/npm-global.sh",
- )
- // Create OpenClaw home directory
- .runCommands("mkdir -p ~/.openclaw/workspace")
- // Startup script
- .addFile(
- "/home/sandbox/start-openclaw.sh",
- `#!/bin/bash
-set -e
-export PATH=$HOME/npm-global/bin:$PATH
-
-# Source environment if present (ANTHROPIC_API_KEY, etc.)
-[ -f ~/.openclaw/env ] && source ~/.openclaw/env
-
-# Start OpenClaw gateway in background
-cd ~
-nohup openclaw gateway --port 18789 > ~/.openclaw/gateway.log 2>&1 &
-
-# Wait for gateway to be ready
-for i in $(seq 1 30); do
- if openclaw gateway status > /dev/null 2>&1; then
- echo "OpenClaw gateway is ready"
- exit 0
- fi
- sleep 1
-done
-
-echo "Warning: gateway did not become ready within 30s"
-exit 1
-`,
- )
- .runCommands("sudo chmod +x ~/start-openclaw.sh");
-
- const snapshots = new Snapshots({ apiKey, apiUrl: OC_API_URL });
-
- console.log("Creating snapshot (this may take a few minutes)...\n");
-
- await snapshots.create({
- name: OPENCLAW_SNAPSHOT,
- image,
- onBuildLogs: (line: string) => {
- process.stdout.write(` ${line}\n`);
- },
- });
-
- console.log(`\nSnapshot "${OPENCLAW_SNAPSHOT}" created successfully.`);
- console.log(
- "New employee sandboxes will boot from this snapshot in seconds.",
- );
-}
-
-main().catch((err) => {
- console.error("Failed to build snapshot:", err.message);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/test-preview-urls-e2e.ts b/sdks/typescript/examples/test-preview-urls-e2e.ts
deleted file mode 100644
index debd1c09..00000000
--- a/sdks/typescript/examples/test-preview-urls-e2e.ts
+++ /dev/null
@@ -1,163 +0,0 @@
-/**
- * Preview URL E2E Test — creates a sandbox, starts an HTTP server,
- * creates a preview URL, and tries to access it.
- *
- * Usage:
- * OPENCOMPUTER_API_KEY=<key> npx tsx examples/test-preview-urls-e2e.ts
- */
-
-import { Sandbox } from "../src/index";
-
-function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }
-function red(msg: string) { console.log(`\x1b[31m✗ ${msg}\x1b[0m`); }
-function yellow(msg: string) { console.log(`\x1b[33m⚠ ${msg}\x1b[0m`); }
-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-
-async function main() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Preview URL E2E Test ║");
- bold("╚══════════════════════════════════════════════════╝\n");
-
- let sandbox: Sandbox | null = null;
-
- try {
- // 1. Create sandbox
- bold("━━━ Step 1: Create sandbox ━━━\n");
- sandbox = await Sandbox.create({ template: "base", timeout: 600 });
- green(`Sandbox: ${sandbox.sandboxId}`);
- dim(`Domain: ${sandbox.domain}`);
- console.log();
-
- // 2. Start an HTTP server inside the sandbox
- bold("━━━ Step 2: Start HTTP server inside sandbox ━━━\n");
-
- // Create a simple HTML file
- await sandbox.files.write("/tmp/index.html",
- `<html><body><h1>Hello from sandbox ${sandbox.sandboxId}</h1></body></html>`
- );
-
- // Try python3 first, then python, then busybox httpd
- const startServer = await sandbox.commands.run(
- "which python3 && nohup python3 -m http.server 8080 --directory /tmp > /dev/null 2>&1 & " +
- "|| which python && nohup python -m http.server 8080 --directory /tmp > /dev/null 2>&1 & " +
- "|| (cd /tmp && nohup busybox httpd -f -p 8080 &)"
- );
- dim(`Server start: exit=${startServer.exitCode}`);
-
- // Wait for server to start
- await new Promise(r => setTimeout(r, 2000));
-
- // Verify via the default domain (which we know works)
- dim("Verifying via default domain...");
- const check = await sandbox.commands.run("curl -s http://localhost:8080/index.html || wget -qO- http://localhost:8080/index.html || echo 'NO_HTTP_CLIENT'");
- if (check.stdout.includes("Hello from sandbox")) {
- green("HTTP server running inside sandbox");
- } else {
- yellow("HTTP server may not be running — checking what's available...");
- const which = await sandbox.commands.run("which python3 python busybox curl wget 2>&1; ls /usr/bin/python* 2>&1 || true");
- dim(`Available: ${which.stdout.trim()}`);
- }
- console.log();
-
- // 3. Create preview URL
- bold("━━━ Step 3: Create preview URL ━━━\n");
- const preview = await sandbox.createPreviewURL();
- green(`Preview URL: https://${preview.hostname}`);
- dim(`SSL status: ${preview.sslStatus}`);
- dim(`CF hostname ID: ${preview.cfHostnameId}`);
- console.log();
-
- // 4. Wait for CF to activate hostname, then test routing
- bold("━━━ Step 4: Test access via preview URL ━━━\n");
- dim("Waiting for CF custom hostname to activate (may take 30-90s)...");
- console.log();
-
- const maxAttempts = 20;
- let success = false;
- for (let i = 0; i < maxAttempts; i++) {
- dim(`Attempt ${i + 1}/${maxAttempts}: fetching http://${preview.hostname}/index.html ...`);
- try {
- const resp = await fetch(`http://${preview.hostname}/index.html`, {
- signal: AbortSignal.timeout(10000),
- redirect: "manual",
- });
- dim(`Status: ${resp.status}`);
- if (resp.status === 200) {
- const body = await resp.text();
- if (body.includes("Hello from sandbox")) {
- green(`Preview URL is LIVE! Got sandbox response.`);
- dim(`Body: ${body.trim().substring(0, 100)}`);
- } else {
- green(`Preview URL is routing! (got 200, body may differ)`);
- dim(`Body: ${body.substring(0, 200)}`);
- }
- success = true;
- break;
- } else if (resp.status === 409) {
- dim("CF hostname still initializing...");
- } else if (resp.status === 502) {
- const body = await resp.text().catch(() => "");
- if (body.includes("sandbox") && body.includes("not available")) {
- yellow("Proxy routing works but sandbox unavailable (may need HTTP server)");
- dim(`Body: ${body.substring(0, 200)}`);
- } else {
- dim(`502 — origin error: ${body.substring(0, 100)}`);
- }
- } else if (resp.status === 301 || resp.status === 302) {
- dim(`Redirect to: ${resp.headers.get("location")}`);
- } else {
- const body = await resp.text().catch(() => "");
- dim(`Body: ${body.substring(0, 200)}`);
- }
- } catch (err: any) {
- dim(`Error: ${err.message}`);
- }
-
- if (i < maxAttempts - 1) {
- await new Promise(r => setTimeout(r, 5000));
- }
- }
-
- if (!success) {
- yellow("Preview URL didn't return 200 within the test window.");
- dim("CF hostname may need more time. Try manually:");
- dim(` curl -v http://${preview.hostname}/index.html`);
- }
- console.log();
-
- // 5. Check SSL status
- bold("━━━ Step 5: Check SSL status ━━━\n");
- const updated = await sandbox.getPreviewURL();
- if (updated) {
- dim(`SSL status: ${updated.sslStatus}`);
- if (updated.sslStatus === "active") {
- green("SSL is active! Try: https://" + updated.hostname);
- } else {
- yellow(`SSL still ${updated.sslStatus} — may take a few minutes.`);
- }
- }
- console.log();
-
- // Auto-cleanup instead of waiting
- bold("━━━ Cleaning up ━━━\n");
-
- } catch (err: any) {
- red(`Error: ${err.message}`);
- if (err.stack) dim(err.stack);
- } finally {
- if (sandbox) {
- try {
- await sandbox.deletePreviewURL();
- green("Preview URL deleted");
- } catch {}
- await sandbox.kill();
- green("Sandbox killed");
- }
- }
-}
-
-main().catch((err) => {
- console.error("Fatal error:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/test-preview-urls.ts b/sdks/typescript/examples/test-preview-urls.ts
deleted file mode 100644
index 599b2c7a..00000000
--- a/sdks/typescript/examples/test-preview-urls.ts
+++ /dev/null
@@ -1,171 +0,0 @@
-/**
- * Preview URL Test
- *
- * Tests the on-demand preview URL feature:
- * 1. Create sandbox — no preview URL yet
- * 2. GET preview URL — returns null (none exists)
- * 3. POST create preview URL — creates CF hostname
- * 4. GET preview URL — returns the created URL
- * 5. POST duplicate — returns error (409 conflict)
- * 6. DELETE preview URL — removes CF hostname + DB record
- * 7. GET after delete — returns null
- * 8. Create again + kill sandbox — auto-cleanup
- *
- * Usage:
- * OPENCOMPUTER_API_URL=http://3.135.246.117:8080 OPENCOMPUTER_API_KEY=<key> npx tsx examples/test-preview-urls.ts
- */
-
-import { Sandbox } from "../src/index";
-
-function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }
-function red(msg: string) { console.log(`\x1b[31m✗ ${msg}\x1b[0m`); }
-function yellow(msg: string) { console.log(`\x1b[33m⚠ ${msg}\x1b[0m`); }
-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-
-let passed = 0;
-let failed = 0;
-
-function check(desc: string, condition: boolean, detail?: string) {
- if (condition) {
- green(desc);
- passed++;
- } else {
- red(`${desc}${detail ? ` (${detail})` : ""}`);
- failed++;
- }
-}
-
-async function main() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Preview URL Test ║");
- bold("╚══════════════════════════════════════════════════╝\n");
-
- const apiUrl = process.env.OPENCOMPUTER_API_URL || "http://localhost:8080";
- dim(`API: ${apiUrl}`);
- console.log();
-
- let sandbox: Sandbox | null = null;
-
- try {
- // ── 1. Create sandbox ──────────────────────────────────────────
- bold("━━━ Step 1: Create sandbox ━━━\n");
- sandbox = await Sandbox.create({ template: "base", timeout: 600 });
- green(`Created sandbox: ${sandbox.sandboxId}`);
- dim(`Default domain: ${sandbox.domain}`);
- console.log();
-
- // ── 2. GET preview URL (none yet) ──────────────────────────────
- bold("━━━ Step 2: GET preview URL (expect null) ━━━\n");
- const noPreview = await sandbox.getPreviewURL();
- check("No preview URL before creation", noPreview === null);
- console.log();
-
- // ── 3. Create preview URL ──────────────────────────────────────
- bold("━━━ Step 3: Create preview URL ━━━\n");
- try {
- const preview = await sandbox.createPreviewURL({ authConfig: { public: true } });
- green(`Preview URL created!`);
- dim(`Hostname: ${preview.hostname}`);
- dim(`SSL status: ${preview.sslStatus}`);
- dim(`CF hostname ID: ${preview.cfHostnameId}`);
- dim(`Auth config: ${JSON.stringify(preview.authConfig)}`);
-
- check("Hostname contains sandbox ID", preview.hostname.startsWith(sandbox.sandboxId));
- check("SSL status is present", preview.sslStatus.length > 0);
- check("CF hostname ID is present", !!preview.cfHostnameId);
- console.log();
-
- // ── 4. GET preview URL (exists now) ──────────────────────────
- bold("━━━ Step 4: GET preview URL (expect match) ━━━\n");
- const got = await sandbox.getPreviewURL();
- check("GET returns preview URL", got !== null);
- check("Hostname matches", got?.hostname === preview.hostname);
- check("Auth config preserved", JSON.stringify(got?.authConfig) === JSON.stringify({ public: true }));
- console.log();
-
- // ── 5. Duplicate create (expect error) ───────────────────────
- bold("━━━ Step 5: Duplicate create (expect 409) ━━━\n");
- try {
- await sandbox.createPreviewURL();
- red("Should have thrown on duplicate create");
- failed++;
- } catch (err: any) {
- check("Duplicate create rejected", err.message.includes("409"));
- dim(`Error: ${err.message}`);
- }
- console.log();
-
- // ── 6. Delete preview URL ────────────────────────────────────
- bold("━━━ Step 6: Delete preview URL ━━━\n");
- await sandbox.deletePreviewURL();
- green("Preview URL deleted");
- passed++;
- console.log();
-
- // ── 7. GET after delete (expect null) ────────────────────────
- bold("━━━ Step 7: GET after delete (expect null) ━━━\n");
- const afterDelete = await sandbox.getPreviewURL();
- check("Preview URL is gone after delete", afterDelete === null);
- console.log();
-
- // ── 8. Auto-cleanup on kill ──────────────────────────────────
- bold("━━━ Step 8: Auto-cleanup on kill ━━━\n");
- const preview2 = await sandbox.createPreviewURL();
- green(`Created preview URL for cleanup test: ${preview2.hostname}`);
-
- await sandbox.kill();
- green("Sandbox killed — preview URL should be auto-cleaned");
- passed++;
- sandbox = null; // prevent double-kill in finally
- console.log();
-
- } catch (err: any) {
- if (err.message.includes("400")) {
- yellow("Preview URL creation failed (400) — likely no verified custom domain.");
- dim(`Error: ${err.message}`);
- dim("");
- dim("This is expected if the org has no verified custom domain or Cloudflare is not configured.");
- dim("The API endpoints are working correctly (they validated the preconditions).");
- console.log();
-
- // Still verify the endpoint returned a proper error
- check("Server validated preconditions (returned 400)", true);
-
- // Test that GET returns null for a sandbox with no preview
- const noPreview2 = await sandbox!.getPreviewURL();
- check("GET returns null when no preview URL", noPreview2 === null);
-
- // Test that DELETE is idempotent (no error on 404)
- await sandbox!.deletePreviewURL();
- green("DELETE on non-existent preview URL is idempotent");
- passed++;
- console.log();
- } else {
- throw err;
- }
- }
-
- } catch (err: any) {
- red(`Fatal error: ${err.message}`);
- if (err.stack) dim(err.stack);
- failed++;
- } finally {
- if (sandbox) {
- await sandbox.kill();
- green("Sandbox killed (cleanup)");
- }
- }
-
- // --- Summary ---
- console.log();
- bold("═══════════════════════════════════════════");
- bold(` Results: ${passed} passed, ${failed} failed`);
- bold("═══════════════════════════════════════════\n");
- if (failed > 0) process.exit(1);
-}
-
-main().catch((err) => {
- console.error("Fatal error:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/test-python-sdk.ts b/sdks/typescript/examples/test-python-sdk.ts
deleted file mode 100644
index f34feb23..00000000
--- a/sdks/typescript/examples/test-python-sdk.ts
+++ /dev/null
@@ -1,151 +0,0 @@
-/**
- * Python SDK Production Test
- *
- * Validates the Python SDK works end-to-end against production by running
- * the Python test script inside a sandbox (meta: using TS SDK to test Python SDK).
- *
- * Usage:
- * npx tsx examples/test-python-sdk.ts
- */
-
-import { Sandbox } from "../src/index";
-
-function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }
-function red(msg: string) { console.log(`\x1b[31m✗ ${msg}\x1b[0m`); }
-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-
-let passed = 0;
-let failed = 0;
-
-function check(desc: string, condition: boolean, detail?: string) {
- if (condition) {
- green(desc);
- passed++;
- } else {
- red(`${desc}${detail ? ` (${detail})` : ""}`);
- failed++;
- }
-}
-
-// Python test script that exercises all SDK operations and prints JSON results
-const PYTHON_TEST_SCRIPT = `
-import json
-import os
-
-results = {}
-
-# Test 1: Basic echo
-import subprocess
-r = subprocess.run(["echo", "hello-from-python"], capture_output=True, text=True)
-results["echo"] = r.stdout.strip()
-
-# Test 2: File write + read
-with open("/tmp/py-test.txt", "w") as f:
- f.write("python-sdk-data")
-with open("/tmp/py-test.txt", "r") as f:
- results["file_content"] = f.read()
-
-# Test 3: Environment variables
-results["home"] = os.environ.get("HOME", "unknown")
-results["path_exists"] = "PATH" in os.environ
-
-# Test 4: Nested directory
-os.makedirs("/tmp/py-nested/deep/dir", exist_ok=True)
-with open("/tmp/py-nested/deep/dir/file.txt", "w") as f:
- f.write("nested-content")
-with open("/tmp/py-nested/deep/dir/file.txt", "r") as f:
- results["nested"] = f.read()
-
-# Test 5: Python-specific features
-import sys
-results["python_version"] = sys.version.split()[0]
-results["platform"] = sys.platform
-
-# Test 6: Math/stdlib
-import math
-results["pi"] = str(round(math.pi, 5))
-
-# Test 7: JSON handling
-data = {"key": "value", "number": 42, "nested": {"a": True}}
-results["json_roundtrip"] = json.loads(json.dumps(data)) == data
-
-print(json.dumps(results))
-`;
-
-async function main() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Python SDK Production Test ║");
- bold("╚══════════════════════════════════════════════════╝\n");
-
- let sandbox: Sandbox | null = null;
-
- try {
- // --- Create sandbox with Python template ---
- bold("[1/4] Creating Python sandbox...");
- sandbox = await Sandbox.create({
- template: "base",
- timeout: 120,
- });
- green(`Created: ${sandbox.sandboxId}`);
- dim(`Domain: ${sandbox.domain}`);
- console.log();
-
- // --- Write and run Python test script ---
- bold("[2/4] Writing Python test script...");
- await sandbox.files.write("/tmp/test_sdk.py", PYTHON_TEST_SCRIPT);
- green("Script written to /tmp/test_sdk.py");
- console.log();
-
- bold("[3/4] Running Python tests inside sandbox...");
- const result = await sandbox.commands.run("python3 /tmp/test_sdk.py", { timeout: 30 });
- check("Python script exited cleanly", result.exitCode === 0, `exit code: ${result.exitCode}`);
-
- if (result.exitCode !== 0) {
- dim(`stderr: ${result.stderr}`);
- dim(`stdout: ${result.stdout}`);
- } else {
- const data = JSON.parse(result.stdout.trim());
- check("Echo command works", data.echo === "hello-from-python", data.echo);
- check("File write/read works", data.file_content === "python-sdk-data", data.file_content);
- check("HOME env var present", data.home !== "unknown", data.home);
- check("PATH env var exists", data.path_exists === true);
- check("Nested directory file works", data.nested === "nested-content", data.nested);
- check("Python version detected", data.python_version.startsWith("3."), data.python_version);
- check("Platform is Linux", data.platform === "linux", data.platform);
- check("Math.pi correct", data.pi === "3.14159", data.pi);
- check("JSON roundtrip works", data.json_roundtrip === true);
- dim(`Python ${data.python_version} on ${data.platform}`);
- }
- console.log();
-
- // --- Verify file ops from SDK side ---
- bold("[4/4] Verifying files from TypeScript SDK...");
- const content = await sandbox.files.read("/tmp/py-test.txt");
- check("TS SDK can read Python-written file", content === "python-sdk-data", content);
-
- const entries = await sandbox.files.list("/tmp/py-nested/deep/dir");
- check("TS SDK can list Python-created directory", entries.some(e => e.name === "file.txt"));
- console.log();
-
- } catch (err: any) {
- red(`Fatal error: ${err.message}`);
- failed++;
- } finally {
- if (sandbox) {
- await sandbox.kill();
- green("Sandbox killed");
- }
- }
-
- // --- Summary ---
- bold("========================================");
- bold(` Results: ${passed} passed, ${failed} failed`);
- bold("========================================\n");
- if (failed > 0) process.exit(1);
-}
-
-main().catch((err) => {
- console.error("Fatal error:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/test-reconnect.ts b/sdks/typescript/examples/test-reconnect.ts
deleted file mode 100644
index e8cbb719..00000000
--- a/sdks/typescript/examples/test-reconnect.ts
+++ /dev/null
@@ -1,185 +0,0 @@
-/**
- * SDK Connect/Reconnect Test
- *
- * Tests:
- * 1. Create sandbox, disconnect, reconnect via Sandbox.connect()
- * 2. Verify state persists across connections
- * 3. Multiple connect() calls to same sandbox
- * 4. Operations work on reconnected instance
- *
- * Usage:
- * npx tsx examples/test-reconnect.ts
- */
-
-import { Sandbox } from "../src/index";
-
-function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }
-function red(msg: string) { console.log(`\x1b[31m✗ ${msg}\x1b[0m`); }
-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-
-let passed = 0;
-let failed = 0;
-
-function check(desc: string, condition: boolean, detail?: string) {
- if (condition) {
- green(desc);
- passed++;
- } else {
- red(`${desc}${detail ? ` (${detail})` : ""}`);
- failed++;
- }
-}
-
-async function main() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ SDK Connect/Reconnect Test ║");
- bold("╚══════════════════════════════════════════════════╝\n");
-
- let sandboxId = "";
-
- try {
- // ── Test 1: Create and store ID ─────────────────────────────────
- bold("━━━ Test 1: Create sandbox and store ID ━━━\n");
-
- const original = await Sandbox.create({ template: "base", timeout: 120 });
- sandboxId = original.sandboxId;
- green(`Created: ${sandboxId}`);
- dim(`Domain: ${original.domain}`);
-
- // Write state
- await original.files.write("/tmp/reconnect-test.txt", "original-data");
- await original.commands.run("echo 'state-marker' > /tmp/marker.txt");
- green("State written to sandbox");
- console.log();
-
- // ── Test 2: Reconnect via Sandbox.connect() ─────────────────────
- bold("━━━ Test 2: Reconnect via Sandbox.connect() ━━━\n");
-
- const reconnected = await Sandbox.connect(sandboxId);
- check("Reconnect succeeded", !!reconnected);
- check("Same sandbox ID", reconnected.sandboxId === sandboxId);
- check("Domain matches", reconnected.domain === original.domain, reconnected.domain);
- check("Status is running", reconnected.status === "running", reconnected.status);
- console.log();
-
- // ── Test 3: Read state from reconnected instance ────────────────
- bold("━━━ Test 3: State persists across connections ━━━\n");
-
- const fileContent = await reconnected.files.read("/tmp/reconnect-test.txt");
- check("File from original instance readable", fileContent === "original-data", fileContent);
-
- const markerContent = await reconnected.files.read("/tmp/marker.txt");
- check("Command output file persisted", markerContent.trim() === "state-marker");
-
- // Write new data from reconnected instance
- await reconnected.files.write("/tmp/reconnect-new.txt", "from-reconnected");
- const newContent = await reconnected.files.read("/tmp/reconnect-new.txt");
- check("Write from reconnected instance works", newContent === "from-reconnected");
- console.log();
-
- // ── Test 4: Commands work on reconnected instance ───────────────
- bold("━━━ Test 4: Commands work on reconnected instance ━━━\n");
-
- const echo = await reconnected.commands.run("echo reconnected-echo");
- check("Echo command works", echo.stdout.trim() === "reconnected-echo");
- check("Exit code is 0", echo.exitCode === 0);
-
- const uname = await reconnected.commands.run("uname -s");
- check("Uname returns Linux", uname.stdout.trim() === "Linux");
-
- // Env vars
- const envResult = await reconnected.commands.run("echo $TEST_VAR", {
- env: { TEST_VAR: "reconnected-env" },
- });
- check("Env vars work on reconnected instance", envResult.stdout.trim() === "reconnected-env");
-
- // File list
- const entries = await reconnected.files.list("/tmp");
- check("File listing works", entries.some(e => e.name === "reconnect-test.txt"));
- check("New file visible in listing", entries.some(e => e.name === "reconnect-new.txt"));
- console.log();
-
- // ── Test 5: Multiple simultaneous connections ───────────────────
- bold("━━━ Test 5: Multiple simultaneous connections ━━━\n");
-
- const conn1 = await Sandbox.connect(sandboxId);
- const conn2 = await Sandbox.connect(sandboxId);
- const conn3 = await Sandbox.connect(sandboxId);
-
- check("3 connections to same sandbox succeeded", !!conn1 && !!conn2 && !!conn3);
-
- // All should be able to read
- const [read1, read2, read3] = await Promise.all([
- conn1.files.read("/tmp/reconnect-test.txt"),
- conn2.files.read("/tmp/reconnect-test.txt"),
- conn3.files.read("/tmp/reconnect-test.txt"),
- ]);
-
- check("All connections read same data",
- read1 === "original-data" && read2 === "original-data" && read3 === "original-data");
-
- // Write from conn1, read from conn2
- await conn1.files.write("/tmp/cross-conn.txt", "from-conn1");
- const crossRead = await conn2.files.read("/tmp/cross-conn.txt");
- check("Write from conn1 visible to conn2", crossRead === "from-conn1");
- console.log();
-
- // ── Test 6: isRunning on reconnected instance ───────────────────
- bold("━━━ Test 6: isRunning on reconnected instance ━━━\n");
-
- const running = await reconnected.isRunning();
- check("isRunning returns true", running);
- console.log();
-
- // ── Test 7: Kill from reconnected instance ──────────────────────
- bold("━━━ Test 7: Kill from reconnected instance ━━━\n");
-
- await reconnected.kill();
- green("Killed from reconnected instance");
-
- await new Promise(r => globalThis.setTimeout(r, 500));
-
- // Verify from original reference
- const stillRunning = await original.isRunning();
- check("Original ref sees sandbox as stopped", !stillRunning);
-
- // Verify connect fails for killed sandbox
- try {
- const deadConn = await Sandbox.connect(sandboxId);
- const deadRunning = await deadConn.isRunning();
- check("Connect to killed sandbox: isRunning=false", !deadRunning);
- } catch (err: any) {
- check("Connect to killed sandbox: throws or returns not running", true);
- dim(`Error: ${err.message}`);
- }
- console.log();
-
- // Clear sandboxId so cleanup doesn't try to kill again
- sandboxId = "";
-
- } catch (err: any) {
- red(`Fatal error: ${err.message}`);
- if (err.stack) dim(err.stack);
- failed++;
- } finally {
- if (sandboxId) {
- try {
- const cleanup = await Sandbox.connect(sandboxId);
- await cleanup.kill();
- green("Sandbox killed in cleanup");
- } catch {}
- }
- }
-
- // --- Summary ---
- bold("========================================");
- bold(` Results: ${passed} passed, ${failed} failed`);
- bold("========================================\n");
- if (failed > 0) process.exit(1);
-}
-
-main().catch((err) => {
- console.error("Fatal error:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/test-secret-seal-e2e.ts b/sdks/typescript/examples/test-secret-seal-e2e.ts
deleted file mode 100644
index e7a1b2b4..00000000
--- a/sdks/typescript/examples/test-secret-seal-e2e.ts
+++ /dev/null
@@ -1,286 +0,0 @@
-/**
- * End-to-end secret-seal verification.
- *
- * Single script covering all the things that have silently broken before:
- * 1. Secrets land in the guest as `osb_sealed_*` tokens, never plaintext
- * (echo, file write+read, hex roundtrip).
- * 2. Per-secret `allowedHosts` is honored on outbound: a secret marked
- * allowed for httpbin.org IS substituted when curling httpbin.org;
- * a secret NOT allowed for httpbin.org is left as the literal token.
- * 3. Store-level `egressAllowlist` blocks connections to disallowed hosts
- * entirely (regardless of any secret).
- *
- * Usage:
- * OPENCOMPUTER_API_URL=... OPENCOMPUTER_API_KEY=... npx tsx examples/test-secret-seal-e2e.ts
- */
-
-import { Sandbox, SecretStore } from "../src/index";
-import { randomBytes } from "node:crypto";
-
-const ALLOWED_VAL = `allowed_${randomBytes(12).toString("hex")}`;
-const DENIED_VAL = `denied_${randomBytes(12).toString("hex")}`;
-
-let storeId: string | null = null;
-let sandbox: Sandbox | null = null;
-let forkedSandbox: Sandbox | null = null;
-let passed = 0;
-let failed = 0;
-
-const green = (s: string) => console.log(`\x1b[32m\u2713 ${s}\x1b[0m`);
-const red = (s: string, detail?: string) =>
- console.log(`\x1b[31m\u2717 ${s}${detail ? ` — ${detail}` : ""}\x1b[0m`);
-const bold = (s: string) => console.log(`\x1b[1m${s}\x1b[0m`);
-const dim = (s: string) => console.log(`\x1b[2m ${s}\x1b[0m`);
-
-function check(desc: string, condition: boolean, detail?: string) {
- if (condition) {
- green(desc);
- passed++;
- } else {
- red(desc, detail);
- failed++;
- }
-}
-
-async function execStdout(cmd: string): Promise<string> {
- const r = await sandbox!.exec.run(cmd);
- return r.stdout;
-}
-
-async function main() {
- const storeName = `seal-e2e-${Date.now()}`;
- try {
- bold("\n=== 1. Setup: store + secrets ===\n");
-
- // Store-level egressAllowlist: only httpbin.org reachable.
- // example.com is intentionally OUT of the allowlist to test blocking.
- const store = await SecretStore.create({
- name: storeName,
- egressAllowlist: ["httpbin.org"],
- });
- storeId = store.id;
- dim(`Store: ${storeName} (id=${store.id})`);
-
- // Two secrets with different per-secret allowedHosts:
- // ALLOWED — should be substituted ONLY on httpbin.org
- // DENIED — allowed on a host the sandbox can't reach, so should
- // never be substituted on httpbin.org
- await SecretStore.setSecret(storeId, "SECRET_ALLOWED", ALLOWED_VAL, {
- allowedHosts: ["httpbin.org"],
- });
- await SecretStore.setSecret(storeId, "SECRET_DENIED", DENIED_VAL, {
- allowedHosts: ["api.example.com"],
- });
- green("Created 2 secrets with distinct allowedHosts");
-
- bold("\n=== 2. Create sandbox bound to store ===\n");
- sandbox = await Sandbox.create({ secretStore: storeName, timeout: 180 });
- dim(`Sandbox: ${sandbox.sandboxId}`);
- green("Sandbox created");
-
- bold("\n=== 3. In-guest: secrets must be sealed tokens ===\n");
-
- const allowedEcho = (await execStdout("printf %s \"$SECRET_ALLOWED\"")).trim();
- const deniedEcho = (await execStdout("printf %s \"$SECRET_DENIED\"")).trim();
-
- check(
- "SECRET_ALLOWED is sealed in env",
- allowedEcho.startsWith("osb_sealed_") && !allowedEcho.includes(ALLOWED_VAL),
- `got "${allowedEcho}"`,
- );
- check(
- "SECRET_DENIED is sealed in env",
- deniedEcho.startsWith("osb_sealed_") && !deniedEcho.includes(DENIED_VAL),
- `got "${deniedEcho}"`,
- );
-
- // file roundtrip — different agent code path than env echo
- await sandbox.exec.run('printf %s "$SECRET_ALLOWED" > /tmp/s.txt');
- const fileBuf = await sandbox.files.read("/tmp/s.txt");
- const fileVal = (typeof fileBuf === "string" ? fileBuf : Buffer.from(fileBuf).toString("utf-8")).trim();
- check(
- "file write+read of secret stays sealed",
- fileVal.startsWith("osb_sealed_") && !fileVal.includes(ALLOWED_VAL),
- `got "${fileVal}"`,
- );
-
- bold("\n=== 4. Egress: per-secret allowedHosts on httpbin.org ===\n");
-
- // Single httpbin call carries BOTH headers. httpbin echoes them back in
- // its JSON response. Expected behavior:
- // X-Allowed → real value (proxy substituted, host matches allowedHosts)
- // X-Denied → still the sealed token (proxy did NOT substitute)
- const httpbinOut = await execStdout(
- `curl -sS -m 10 https://httpbin.org/headers -H "X-Allowed: $SECRET_ALLOWED" -H "X-Denied: $SECRET_DENIED"`,
- );
- dim(`httpbin response (first 400 chars):`);
- dim(httpbinOut.replace(/\s+/g, " ").slice(0, 400));
-
- check(
- "httpbin echoed REAL value for SECRET_ALLOWED (substituted on allowed host)",
- httpbinOut.includes(ALLOWED_VAL),
- "expected substitution on httpbin.org since it's in SECRET_ALLOWED.allowedHosts",
- );
- check(
- "httpbin did NOT echo real value for SECRET_DENIED",
- !httpbinOut.includes(DENIED_VAL),
- "real DENIED value leaked to httpbin even though it's not in SECRET_DENIED.allowedHosts",
- );
- check(
- "httpbin echoed sealed token literal for SECRET_DENIED",
- httpbinOut.includes("osb_sealed_") && /X-Denied[^\n]*osb_sealed_/i.test(httpbinOut),
- "expected literal osb_sealed_* token in X-Denied header",
- );
-
- bold("\n=== 5. Egress: store-level egressAllowlist blocks unrelated hosts ===\n");
-
- // example.com is NOT in egressAllowlist=["httpbin.org"], so the proxy
- // should refuse the CONNECT entirely. Curl exits non-zero / no body.
- const blockedOut = await sandbox.exec.run(
- `curl -sS -m 10 -o /tmp/blocked.body -w '%{http_code}\\n' https://example.com/ ; echo "exit=$?"`,
- );
- const blockedBody = await sandbox.exec.run("cat /tmp/blocked.body 2>/dev/null || true");
- dim(`curl status line: ${blockedOut.stdout.trim().replace(/\n/g, " | ")}`);
- dim(`body bytes: ${blockedBody.stdout.length}`);
-
- const reachedExample = /<title>Example Domain<\/title>/i.test(blockedBody.stdout);
- check(
- "example.com (not in egressAllowlist) is BLOCKED",
- !reachedExample,
- "fetched example.com despite it not being in the store's egressAllowlist",
- );
-
- // Sanity: an allowed host still works (proves we didn't just kill all egress)
- const sanity = await execStdout(`curl -sS -m 10 -o /dev/null -w '%{http_code}' https://httpbin.org/get`);
- check("sanity: httpbin.org (in egressAllowlist) is reachable", sanity.trim() === "200", `got "${sanity.trim()}"`);
-
- bold("\n=== 6. Snapshot/fork inheritance: secret store binds at first creation ===\n");
-
- // Take a checkpoint of the running sandbox, wait for it to be ready,
- // then fork. The fork must inherit the secret store binding without the
- // user passing secretStore again — and the seal/proxy semantics must
- // continue to hold on the fork.
- dim("Creating checkpoint of running sandbox...");
- const cp = await sandbox.createCheckpoint(`seal-e2e-cp-${Date.now()}`);
- dim(`Checkpoint id: ${cp.id}`);
-
- // Poll until ready — generous timeout because S3 upload can be slow on
- // dev boxes. Print status periodically so a hang is visible.
- let cpReady = false;
- let lastStatus: string | undefined;
- for (let i = 0; i < 180; i++) {
- const list = await sandbox.listCheckpoints();
- const found = list.find((c) => c.id === cp.id);
- if (found?.status !== lastStatus) {
- dim(` [t=${i}s] checkpoint status: ${found?.status ?? "(missing)"}`);
- lastStatus = found?.status;
- }
- if (found?.status === "ready") { cpReady = true; break; }
- if (found?.status === "failed") break;
- await new Promise((r) => setTimeout(r, 1000));
- }
- check("checkpoint reached ready state", cpReady, `last status: ${lastStatus}`);
- if (!cpReady) throw new Error(`checkpoint never became ready (last status: ${lastStatus})`);
-
- // Mutate the secret store BETWEEN snapshot and fork. The fork should see
- // the new value because we re-resolve the store name fresh on fork load.
- const ROTATED_VAL = `rotated_${randomBytes(12).toString("hex")}`;
- await SecretStore.setSecret(storeId!, "SECRET_ALLOWED", ROTATED_VAL, {
- allowedHosts: ["httpbin.org"],
- });
- dim(`Rotated SECRET_ALLOWED to ${ROTATED_VAL}`);
-
- // Fork. The SDK's createFromCheckpoint takes no secretStore — inheritance
- // is the only contract.
- forkedSandbox = await Sandbox.createFromCheckpoint(cp.id, { timeout: 180 });
- dim(`Forked sandbox: ${forkedSandbox.sandboxId}`);
- check("forked sandbox created without re-passing secretStore", !!forkedSandbox.sandboxId);
-
- // In-guest: the inherited secret must still be sealed (token, not value)
- const forkEcho = (await forkedSandbox.exec.run('printf %s "$SECRET_ALLOWED"')).stdout.trim();
- check(
- "forked sandbox: SECRET_ALLOWED is sealed (inherited)",
- forkEcho.startsWith("osb_sealed_") && !forkEcho.includes(ROTATED_VAL) && !forkEcho.includes(ALLOWED_VAL),
- `got "${forkEcho}"`,
- );
-
- // The DENIED secret must also have inherited
- const forkDeniedEcho = (await forkedSandbox.exec.run('printf %s "$SECRET_DENIED"')).stdout.trim();
- check(
- "forked sandbox: SECRET_DENIED is sealed (inherited)",
- forkDeniedEcho.startsWith("osb_sealed_") && !forkDeniedEcho.includes(DENIED_VAL),
- `got "${forkDeniedEcho}"`,
- );
-
- // Egress on the fork: hit httpbin and assert
- // - SECRET_ALLOWED is substituted with the *ROTATED* value (proves we
- // re-resolved the store fresh, instead of replaying baked-in values)
- // - SECRET_DENIED is left as the literal sealed token (per-host filter still active)
- const forkHttpbinOut = (await forkedSandbox.exec.run(
- `curl -sS -m 10 https://httpbin.org/headers -H "X-Allowed: $SECRET_ALLOWED" -H "X-Denied: $SECRET_DENIED"`,
- )).stdout;
- dim(`forked httpbin response (first 400 chars):`);
- dim(forkHttpbinOut.replace(/\s+/g, " ").slice(0, 400));
-
- check(
- "forked sandbox: httpbin sees ROTATED value for SECRET_ALLOWED",
- forkHttpbinOut.includes(ROTATED_VAL),
- "fork should re-resolve the store fresh, picking up the rotated secret value",
- );
- check(
- "forked sandbox: httpbin does NOT see old (pre-rotation) value",
- !forkHttpbinOut.includes(ALLOWED_VAL),
- "fork served stale baked-in value instead of re-resolving",
- );
- check(
- "forked sandbox: SECRET_DENIED still not substituted on httpbin",
- !forkHttpbinOut.includes(DENIED_VAL),
- "per-secret allowedHosts filter regressed on the fork path",
- );
-
- // Egress allowlist still enforced on the fork
- const forkBlocked = await forkedSandbox.exec.run(
- `curl -sS -m 10 -o /tmp/blocked.body -w '%{http_code}' https://example.com/ ; cat /tmp/blocked.body 2>/dev/null || true`,
- );
- check(
- "forked sandbox: example.com still blocked by inherited egressAllowlist",
- !/<title>Example Domain<\/title>/i.test(forkBlocked.stdout),
- "egress allowlist not inherited on fork",
- );
- } catch (err: any) {
- red(`Fatal: ${err.message}`);
- if (err.stack) dim(err.stack);
- failed++;
- } finally {
- bold("\n=== Cleanup ===\n");
- if (forkedSandbox) {
- try { await forkedSandbox.kill(); green("Forked sandbox killed"); } catch (e: any) { red(`fork kill failed: ${e.message}`); }
- }
- if (sandbox) {
- try {
- await sandbox.kill();
- green("Sandbox killed");
- } catch (e: any) {
- red(`kill failed: ${e.message}`);
- }
- }
- if (storeId) {
- try {
- await SecretStore.delete(storeId);
- green("Store deleted");
- } catch (e: any) {
- red(`store delete failed: ${e.message}`);
- }
- }
- }
-
- bold("\n========================================");
- bold(` Results: ${passed} passed, ${failed} failed`);
- bold("========================================\n");
- if (failed > 0) process.exit(1);
-}
-
-main().catch((err) => {
- console.error("Unhandled:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/test-secret-store-fork.ts b/sdks/typescript/examples/test-secret-store-fork.ts
deleted file mode 100644
index 135771c7..00000000
--- a/sdks/typescript/examples/test-secret-store-fork.ts
+++ /dev/null
@@ -1,436 +0,0 @@
-/**
- * Test secret store inheritance on fork / createFromCheckpoint.
- *
- * Creates two secret stores, a sandbox with store A, checkpoints it,
- * then forks with store B attached. Verifies:
- * 1. Secret env vars from both stores are present (layered merge)
- * 2. Secrets are sealed in-guest (osb_sealed_* tokens, not plaintext)
- * 3. Actual secret VALUES resolve correctly through the proxy (httpbin echo)
- * 4. Store B's value wins on collision (SHARED_KEY override)
- * 5. Egress allowlists aggregate across layers
- *
- * Usage:
- * OPENCOMPUTER_API_URL=... OPENCOMPUTER_API_KEY=... npx tsx examples/test-secret-store-fork.ts
- */
-
-import { Sandbox, SecretStore } from "../src/index";
-import { Snapshots, Image } from "../src/node";
-import { randomBytes } from "node:crypto";
-
-// Random values so we can verify exact substitution via httpbin
-const GIT_TOKEN_VAL = `git_${randomBytes(12).toString("hex")}`;
-const SHARED_KEY_A_VAL = `shared_a_${randomBytes(12).toString("hex")}`;
-const SHARED_KEY_B_VAL = `shared_b_${randomBytes(12).toString("hex")}`;
-const API_KEY_VAL = `api_${randomBytes(12).toString("hex")}`;
-
-let storeAId: string | null = null;
-let storeBId: string | null = null;
-let baseSandbox: Sandbox | null = null;
-let forkedSandbox: Sandbox | null = null;
-let snapshotSandbox: Sandbox | null = null;
-let snapshotName: string | null = null;
-let passed = 0;
-let failed = 0;
-
-const green = (s: string) => console.log(`\x1b[32m✓ ${s}\x1b[0m`);
-const red = (s: string, detail?: string) =>
- console.log(`\x1b[31m✗ ${s}${detail ? ` — ${detail}` : ""}\x1b[0m`);
-const bold = (s: string) => console.log(`\x1b[1m${s}\x1b[0m`);
-const dim = (s: string) => console.log(`\x1b[2m ${s}\x1b[0m`);
-
-function check(desc: string, condition: boolean, detail?: string) {
- if (condition) {
- green(desc);
- passed++;
- } else {
- red(desc, detail);
- failed++;
- }
-}
-
-async function main() {
- const suffix = Date.now();
- const storeAName = `fork-test-a-${suffix}`;
- const storeBName = `fork-test-b-${suffix}`;
-
- try {
- // ── Setup: two secret stores ──────────────────────────────────────
- bold("\n=== 1. Setup: create two secret stores ===\n");
-
- // Store A: egress to httpbin.org (for value verification) + github.com
- const storeA = await SecretStore.create({
- name: storeAName,
- egressAllowlist: ["github.com", "httpbin.org"],
- });
- storeAId = storeA.id;
- console.log(` Store A: ${storeAId} (${storeAName})`);
-
- await SecretStore.setSecret(storeAId, "GIT_TOKEN", GIT_TOKEN_VAL, {
- allowedHosts: ["github.com", "httpbin.org"],
- });
- await SecretStore.setSecret(storeAId, "SHARED_KEY", SHARED_KEY_A_VAL, {
- allowedHosts: ["httpbin.org"],
- });
- dim(`GIT_TOKEN = ${GIT_TOKEN_VAL}`);
- dim(`SHARED_KEY(A) = ${SHARED_KEY_A_VAL}`);
- green(
- "Store A created: GIT_TOKEN + SHARED_KEY, egress=[github.com, httpbin.org]",
- );
-
- // Store B: egress to httpbin.org (for value verification) + api.anthropic.com
- const storeB = await SecretStore.create({
- name: storeBName,
- egressAllowlist: ["api.anthropic.com", "httpbin.org"],
- });
- storeBId = storeB.id;
- console.log(` Store B: ${storeBId} (${storeBName})`);
-
- await SecretStore.setSecret(storeBId, "API_KEY", API_KEY_VAL, {
- allowedHosts: ["api.anthropic.com", "httpbin.org"],
- });
- await SecretStore.setSecret(storeBId, "SHARED_KEY", SHARED_KEY_B_VAL, {
- allowedHosts: ["httpbin.org"],
- });
- dim(`API_KEY = ${API_KEY_VAL}`);
- dim(`SHARED_KEY(B) = ${SHARED_KEY_B_VAL} (should override A)`);
- green(
- "Store B created: API_KEY + SHARED_KEY(override), egress=[api.anthropic.com, httpbin.org]",
- );
-
- // ── Layer 1: sandbox with store A ─────────────────────────────────
- bold("\n=== 2. Create base sandbox with store A ===\n");
-
- baseSandbox = await Sandbox.create({
- secretStore: storeAName,
- timeout: 120,
- });
- console.log(` Base sandbox: ${baseSandbox.sandboxId}`);
- await new Promise((r) => setTimeout(r, 5000));
-
- const envBase = (await baseSandbox.exec.run("env")).stdout;
- check("Base has GIT_TOKEN", envBase.includes("GIT_TOKEN"));
- check("Base has SHARED_KEY", envBase.includes("SHARED_KEY"));
- check("Base does NOT have API_KEY", !envBase.includes("API_KEY"));
-
- // Verify secrets are sealed (not plaintext) in base
- const baseGitEcho = (
- await baseSandbox.exec.run('printf %s "$GIT_TOKEN"')
- ).stdout.trim();
- check(
- "Base: GIT_TOKEN is sealed (not plaintext)",
- baseGitEcho.startsWith("osb_sealed_") &&
- !baseGitEcho.includes(GIT_TOKEN_VAL),
- `got "${baseGitEcho.slice(0, 40)}..."`,
- );
-
- // Verify actual value via httpbin
- const baseHttpbin = (
- await baseSandbox.exec.run(
- `curl -sS -m 10 https://httpbin.org/headers -H "X-Git: $GIT_TOKEN" -H "X-Shared: $SHARED_KEY"`,
- )
- ).stdout;
- check(
- "Base: GIT_TOKEN value resolves correctly via httpbin",
- baseHttpbin.includes(GIT_TOKEN_VAL),
- `httpbin did not echo back ${GIT_TOKEN_VAL}`,
- );
- check(
- "Base: SHARED_KEY(A) value resolves correctly via httpbin",
- baseHttpbin.includes(SHARED_KEY_A_VAL),
- `httpbin did not echo back ${SHARED_KEY_A_VAL}`,
- );
-
- // ── Checkpoint ────────────────────────────────────────────────────
- bold("\n=== 3. Create checkpoint from base ===\n");
-
- const cp = await baseSandbox.createCheckpoint("fork-test-cp");
- console.log(` Checkpoint: ${cp.id}`);
-
- for (let i = 0; i < 30; i++) {
- const cps = await baseSandbox.listCheckpoints();
- const found = cps.find((c: { id: string }) => c.id === cp.id);
- if (found && (found as any).status === "ready") break;
- await new Promise((r) => setTimeout(r, 2000));
- }
- green("Checkpoint ready");
-
- // ── Layer 2: fork with store B ────────────────────────────────────
- bold(
- "\n=== 4. Fork from checkpoint with store B (secretStore inheritance) ===\n",
- );
-
- forkedSandbox = await Sandbox.createFromCheckpoint(cp.id, {
- secretStore: storeBName,
- timeout: 120,
- });
- console.log(` Forked sandbox: ${forkedSandbox.sandboxId}`);
- await new Promise((r) => setTimeout(r, 5000));
-
- // ── Network debug for checkpoint fork ──────────────────────────────
- bold("\n=== 4-debug. Network state inside checkpoint fork ===\n");
-
- const netDebug = await forkedSandbox.exec.run(
- 'echo "=== IP ===" && ip addr show eth0 2>&1 && ' +
- 'echo "=== ROUTE ===" && ip route 2>&1 && ' +
- 'echo "=== ARP ===" && ip neigh 2>&1 && ' +
- 'echo "=== HTTP_PROXY ===" && echo "$HTTP_PROXY" && ' +
- 'echo "=== PROXY REACH ===" && curl -sS --connect-timeout 5 -o /dev/null -w "http_code=%{http_code}" "$HTTP_PROXY" 2>&1 || echo "UNREACHABLE" && ' +
- 'echo "=== PING GW ===" && ping -c 1 -W 2 $(ip route | grep default | awk "{print \\$3}") 2>&1 || echo "PING_FAIL"',
- );
- dim("Network debug output:");
- for (const line of netDebug.stdout.split("\n")) {
- dim(line);
- }
- if (netDebug.stderr) {
- dim("stderr: " + netDebug.stderr);
- }
-
- // ── 4a. Check env vars exist ──────────────────────────────────────
- bold("\n=== 4a. Verify secret env vars present ===\n");
-
- const envFork = (await forkedSandbox.exec.run("env")).stdout;
- check(
- "Fork has GIT_TOKEN (inherited from store A)",
- envFork.includes("GIT_TOKEN"),
- );
- check("Fork has API_KEY (from store B)", envFork.includes("API_KEY"));
- check("Fork has SHARED_KEY (merged)", envFork.includes("SHARED_KEY"));
- check(
- "Fork has HTTP_PROXY (secrets proxy active)",
- envFork.includes("HTTP_PROXY"),
- );
-
- const sealedCount = (envFork.match(/osb_sealed_/g) || []).length;
- check(
- `Fork has 3 sealed secrets (got ${sealedCount})`,
- sealedCount === 3,
- "expected GIT_TOKEN(A) + SHARED_KEY(B override) + API_KEY(B)",
- );
-
- // ── 4b. Verify secrets are sealed (not plaintext) ─────────────────
- bold("\n=== 4b. Verify secrets are sealed in-guest ===\n");
-
- const forkGitEcho = (
- await forkedSandbox.exec.run('printf %s "$GIT_TOKEN"')
- ).stdout.trim();
- check(
- "Fork: GIT_TOKEN is sealed",
- forkGitEcho.startsWith("osb_sealed_") &&
- !forkGitEcho.includes(GIT_TOKEN_VAL),
- `got "${forkGitEcho.slice(0, 40)}..."`,
- );
-
- const forkApiEcho = (
- await forkedSandbox.exec.run('printf %s "$API_KEY"')
- ).stdout.trim();
- check(
- "Fork: API_KEY is sealed",
- forkApiEcho.startsWith("osb_sealed_") &&
- !forkApiEcho.includes(API_KEY_VAL),
- `got "${forkApiEcho.slice(0, 40)}..."`,
- );
-
- const forkSharedEcho = (
- await forkedSandbox.exec.run('printf %s "$SHARED_KEY"')
- ).stdout.trim();
- check(
- "Fork: SHARED_KEY is sealed",
- forkSharedEcho.startsWith("osb_sealed_") &&
- !forkSharedEcho.includes(SHARED_KEY_B_VAL),
- `got "${forkSharedEcho.slice(0, 40)}..."`,
- );
-
- // ── 4c. Verify actual VALUES via httpbin ──────────────────────────
- bold(
- "\n=== 4c. Verify actual secret values via httpbin (proxy substitution) ===\n",
- );
-
- const forkHttpbin = (
- await forkedSandbox.exec.run(
- `curl -sS -m 10 https://httpbin.org/headers ` +
- `-H "X-Git: $GIT_TOKEN" ` +
- `-H "X-Api: $API_KEY" ` +
- `-H "X-Shared: $SHARED_KEY"`,
- )
- ).stdout;
- dim(`httpbin response (first 500 chars):`);
- dim(forkHttpbin.replace(/\s+/g, " ").slice(0, 500));
-
- check(
- "Fork: GIT_TOKEN value correct (inherited from A)",
- forkHttpbin.includes(GIT_TOKEN_VAL),
- `httpbin did not echo back ${GIT_TOKEN_VAL}`,
- );
- check(
- "Fork: API_KEY value correct (from B)",
- forkHttpbin.includes(API_KEY_VAL),
- `httpbin did not echo back ${API_KEY_VAL}`,
- );
- check(
- "Fork: SHARED_KEY has B's value (B override wins on collision)",
- forkHttpbin.includes(SHARED_KEY_B_VAL),
- `httpbin did not echo back B's value ${SHARED_KEY_B_VAL}`,
- );
- check(
- "Fork: SHARED_KEY does NOT have A's value (overridden by B)",
- !forkHttpbin.includes(SHARED_KEY_A_VAL),
- `httpbin echoed A's value ${SHARED_KEY_A_VAL} — override did not work`,
- );
-
- // ── 4d. Verify egress aggregation ─────────────────────────────────
- bold("\n=== 4d. Verify egress allowlist aggregation ===\n");
-
- // github.com (from A) and api.anthropic.com (from B) should both be reachable
- const githubResult = await forkedSandbox.exec.run(
- `curl -sS -m 10 -o /dev/null -w '%{http_code}' https://github.com/ 2>&1 || echo "BLOCKED"`,
- );
- check(
- "Fork: github.com reachable (from store A egress)",
- !githubResult.stdout.includes("BLOCKED") &&
- !githubResult.stdout.includes("000"),
- `got "${githubResult.stdout.trim()}"`,
- );
-
- const anthropicResult = await forkedSandbox.exec.run(
- `curl -sS -m 10 -o /dev/null -w '%{http_code}' https://api.anthropic.com/ 2>&1 || echo "BLOCKED"`,
- );
- check(
- "Fork: api.anthropic.com reachable (from store B egress)",
- !anthropicResult.stdout.includes("BLOCKED") &&
- !anthropicResult.stdout.includes("000"),
- `got "${anthropicResult.stdout.trim()}"`,
- );
-
- // ── 5. Snapshot/template path: create snapshot, fork with secretStore ──
- bold("\n=== 5. Create snapshot template, fork with secretStore ===\n");
-
- const snapshots = new Snapshots();
- snapshotName = `fork-secret-test-${suffix}`;
- dim(`Creating snapshot "${snapshotName}" from base image...`);
- await snapshots.create({
- name: snapshotName,
- image: Image.base().runCommands(
- "echo 'template-ready' > /home/sandbox/marker.txt",
- ),
- });
-
- // Poll until snapshot is ready
- for (let i = 0; i < 30; i++) {
- const info = await snapshots.get(snapshotName);
- if (info.status === "ready") break;
- await new Promise((r) => setTimeout(r, 2000));
- }
- green(`Snapshot "${snapshotName}" ready`);
-
- // Fork from snapshot with store B attached
- snapshotSandbox = await Sandbox.create({
- snapshot: snapshotName,
- secretStore: storeBName,
- timeout: 120,
- });
- console.log(` Snapshot-forked sandbox: ${snapshotSandbox.sandboxId}`);
- await new Promise((r) => setTimeout(r, 5000));
-
- // Verify the template content survived
- const marker = (
- await snapshotSandbox.exec.run("cat /home/sandbox/marker.txt")
- ).stdout.trim();
- check(
- "Snapshot fork: template content present (/home/sandbox/marker.txt)",
- marker === "template-ready",
- `got "${marker}"`,
- );
-
- // Verify secrets from store B are available
- const envSnap = (await snapshotSandbox.exec.run("env")).stdout;
- check(
- "Snapshot fork: has API_KEY (from store B)",
- envSnap.includes("API_KEY"),
- );
- check(
- "Snapshot fork: has SHARED_KEY (from store B)",
- envSnap.includes("SHARED_KEY"),
- );
- check(
- "Snapshot fork: has HTTP_PROXY (secrets proxy active)",
- envSnap.includes("HTTP_PROXY"),
- );
-
- // Verify secrets are sealed
- const snapApiEcho = (
- await snapshotSandbox.exec.run('printf %s "$API_KEY"')
- ).stdout.trim();
- check(
- "Snapshot fork: API_KEY is sealed",
- snapApiEcho.startsWith("osb_sealed_") &&
- !snapApiEcho.includes(API_KEY_VAL),
- `got "${snapApiEcho.slice(0, 40)}..."`,
- );
-
- // Verify actual values via httpbin
- const snapHttpbin = (
- await snapshotSandbox.exec.run(
- `curl -sS -m 10 https://httpbin.org/headers ` +
- `-H "X-Api: $API_KEY" ` +
- `-H "X-Shared: $SHARED_KEY"`,
- )
- ).stdout;
- dim(`httpbin response (first 500 chars):`);
- dim(snapHttpbin.replace(/\s+/g, " ").slice(0, 500));
-
- check(
- "Snapshot fork: API_KEY value correct via httpbin",
- snapHttpbin.includes(API_KEY_VAL),
- `httpbin did not echo back ${API_KEY_VAL}`,
- );
- check(
- "Snapshot fork: SHARED_KEY has B's value via httpbin",
- snapHttpbin.includes(SHARED_KEY_B_VAL),
- `httpbin did not echo back ${SHARED_KEY_B_VAL}`,
- );
-
- // ── Summary ───────────────────────────────────────────────────────
- bold(`\n=== Results: ${passed} passed, ${failed} failed ===\n`);
- } finally {
- bold("=== Cleanup ===");
- if (snapshotSandbox) {
- try {
- await snapshotSandbox.shutdown();
- } catch {}
- }
- if (forkedSandbox) {
- try {
- await forkedSandbox.shutdown();
- } catch {}
- }
- if (baseSandbox) {
- try {
- await baseSandbox.shutdown();
- } catch {}
- }
- if (snapshotName) {
- try {
- const snapshots = new Snapshots();
- await snapshots.delete(snapshotName);
- } catch {}
- }
- if (storeBId) {
- try {
- await SecretStore.delete(storeBId);
- } catch {}
- }
- if (storeAId) {
- try {
- await SecretStore.delete(storeAId);
- } catch {}
- }
- green("Cleanup done");
- }
-
- process.exit(failed > 0 ? 1 : 0);
-}
-
-main().catch((err) => {
- console.error("Fatal:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/test-secretstore.ts b/sdks/typescript/examples/test-secretstore.ts
deleted file mode 100644
index cb09079e..00000000
--- a/sdks/typescript/examples/test-secretstore.ts
+++ /dev/null
@@ -1,213 +0,0 @@
-/**
- * Secret Stores & Secrets Test
- *
- * Tests:
- * 1. Create a secret store
- * 2. List secret stores
- * 3. Get secret store by ID
- * 4. Update secret store
- * 5. Set secrets on a store
- * 6. List secrets (names only, values never returned)
- * 7. Create sandbox with secret store (inherits secrets)
- * 8. Verify secrets are injected as sealed env vars
- * 9. Delete secret
- * 10. Delete secret store
- *
- * Usage:
- * npx tsx examples/test-projects.ts
- */
-
-import { Sandbox, SecretStore } from "../src/index";
-
-function green(msg: string) { console.log(`\x1b[32m\u2713 ${msg}\x1b[0m`); }
-function red(msg: string) { console.log(`\x1b[31m\u2717 ${msg}\x1b[0m`); }
-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-
-let passed = 0;
-let failed = 0;
-
-function check(desc: string, condition: boolean, detail?: string) {
- if (condition) {
- green(desc);
- passed++;
- } else {
- red(`${desc}${detail ? ` (${detail})` : ""}`);
- failed++;
- }
-}
-
-async function main() {
- bold("\n\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557");
- bold("\u2551 Secret Stores & Secrets Test \u2551");
- bold("\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\n");
-
- let storeId: string | null = null;
- let sandbox: Sandbox | null = null;
- const storeName = `test-store-${Date.now()}`;
-
- try {
- // -- Test 1: Create secret store --
- bold("--- Test 1: Create secret store ---\n");
-
- const store = await SecretStore.create({
- name: storeName,
- egressAllowlist: ["api.anthropic.com"],
- });
-
- storeId = store.id;
- check("Store created", !!store.id);
- check("Name matches", store.name === storeName);
- check("Egress allowlist set", store.egressAllowlist?.length === 1);
- dim(`Store ID: ${store.id}`);
- console.log();
-
- // -- Test 2: List secret stores --
- bold("--- Test 2: List secret stores ---\n");
-
- const stores = await SecretStore.list();
- check("List returns array", Array.isArray(stores));
- const found = stores.find((s) => s.id === storeId);
- check("Created store in list", !!found);
- dim(`Total stores: ${stores.length}`);
- console.log();
-
- // -- Test 3: Get secret store --
- bold("--- Test 3: Get secret store by ID ---\n");
-
- const fetched = await SecretStore.get(storeId!);
- check("Get returns correct store", fetched.id === storeId);
- check("Get has correct name", fetched.name === storeName);
- console.log();
-
- // -- Test 4: Update secret store --
- bold("--- Test 4: Update secret store ---\n");
-
- const updatedName = `${storeName}-updated`;
- const updated = await SecretStore.update(storeId!, {
- name: updatedName,
- egressAllowlist: ["api.anthropic.com", "*.openai.com"],
- });
- check("Name updated", updated.name === updatedName);
- check("Egress allowlist updated", updated.egressAllowlist?.length === 2);
- console.log();
-
- // -- Test 5: Set secrets --
- bold("--- Test 5: Set secrets ---\n");
-
- await SecretStore.setSecret(storeId!, "TEST_API_KEY", "sk-test-12345");
- green("Set TEST_API_KEY");
-
- await SecretStore.setSecret(storeId!, "DATABASE_URL", "postgres://localhost/test");
- green("Set DATABASE_URL");
-
- await SecretStore.setSecret(storeId!, "TEMP_SECRET", "will-be-deleted");
- green("Set TEMP_SECRET");
- console.log();
-
- // -- Test 6: List secrets --
- bold("--- Test 6: List secret entries ---\n");
-
- const entries = await SecretStore.listSecrets(storeId!);
- check("Returns array", Array.isArray(entries));
- const names = entries.map((e) => e.name);
- check("Has TEST_API_KEY", names.includes("TEST_API_KEY"));
- check("Has DATABASE_URL", names.includes("DATABASE_URL"));
- check("Has TEMP_SECRET", names.includes("TEMP_SECRET"));
- check("3 secrets total", entries.length === 3, `got ${entries.length}`);
- dim(`Secret names: ${names.join(", ")}`);
- console.log();
-
- // -- Test 7: Create sandbox with secret store --
- bold("--- Test 7: Create sandbox with secret store ---\n");
-
- sandbox = await Sandbox.create({
- secretStore: updatedName,
- timeout: 120,
- });
- check("Sandbox created", !!sandbox.sandboxId);
- dim(`Sandbox ID: ${sandbox.sandboxId}`);
- console.log();
-
- // -- Test 8: Verify secrets are sealed in sandbox --
- bold("--- Test 8: Verify secrets sealed in sandbox ---\n");
-
- // Secrets should be sealed tokens (osb_sealed_*) inside the VM.
- // The MITM proxy replaces sealed tokens with real values on outbound HTTPS requests,
- // so the real secret never exists in VM memory.
- const apiKeyResult = await sandbox.commands.run("echo $TEST_API_KEY");
- const apiKeyVal = apiKeyResult.stdout.trim();
- check("TEST_API_KEY is sealed", apiKeyVal.startsWith("osb_sealed_"),
- `got "${apiKeyVal}"`);
-
- const dbUrlResult = await sandbox.commands.run("echo $DATABASE_URL");
- const dbUrlVal = dbUrlResult.stdout.trim();
- check("DATABASE_URL is sealed", dbUrlVal.startsWith("osb_sealed_"),
- `got "${dbUrlVal}"`);
-
- const tempResult = await sandbox.commands.run("echo $TEMP_SECRET");
- const tempVal = tempResult.stdout.trim();
- check("TEMP_SECRET is sealed", tempVal.startsWith("osb_sealed_"),
- `got "${tempVal}"`);
- console.log();
-
- // -- Test 9: Delete secret --
- bold("--- Test 9: Delete secret ---\n");
-
- await SecretStore.deleteSecret(storeId!, "TEMP_SECRET");
- green("Deleted TEMP_SECRET");
-
- const afterDelete = await SecretStore.listSecrets(storeId!);
- const afterNames = afterDelete.map((e) => e.name);
- check("TEMP_SECRET removed", !afterNames.includes("TEMP_SECRET"));
- check("2 secrets remaining", afterDelete.length === 2, `got ${afterDelete.length}`);
- console.log();
-
- // -- Test 10: Delete secret store --
- bold("--- Test 10: Delete secret store ---\n");
-
- // Kill sandbox first
- await sandbox.kill();
- green("Sandbox killed");
- sandbox = null;
-
- await SecretStore.delete(storeId!);
- green("Secret store deleted");
-
- // Verify it's gone
- try {
- await SecretStore.get(storeId!);
- red("Store should not exist after delete");
- failed++;
- } catch {
- green("Store not found after delete (expected)");
- passed++;
- }
- storeId = null;
- console.log();
-
- } catch (err: any) {
- red(`Fatal error: ${err.message}`);
- if (err.stack) dim(err.stack);
- failed++;
- } finally {
- // Cleanup
- if (sandbox) {
- try { await sandbox.kill(); } catch {}
- }
- if (storeId) {
- try { await SecretStore.delete(storeId); } catch {}
- }
- }
-
- // --- Summary ---
- bold("========================================");
- bold(` Results: ${passed} passed, ${failed} failed`);
- bold("========================================\n");
- if (failed > 0) process.exit(1);
-}
-
-main().catch((err) => {
- console.error("Fatal error:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/test-shell.ts b/sdks/typescript/examples/test-shell.ts
deleted file mode 100644
index 7338d705..00000000
--- a/sdks/typescript/examples/test-shell.ts
+++ /dev/null
@@ -1,231 +0,0 @@
-/**
- * test-shell.ts — End-to-end test for exec.shell() (stateful shell sessions)
- *
- * Usage:
- * cd sdks/typescript
- * npx tsx examples/test-shell.ts
- *
- * Environment:
- * OPENCOMPUTER_API_URL (default: http://localhost:8080)
- * OPENCOMPUTER_API_KEY (default: opensandbox-dev)
- */
-
-import { Sandbox, ShellBusyError, ShellClosedError } from "../src/index.js";
-
-const API_URL = process.env.OPENCOMPUTER_API_URL || "http://localhost:8080";
-const API_KEY = process.env.OPENCOMPUTER_API_KEY || "opensandbox-dev";
-
-const decoder = new TextDecoder();
-let passed = 0;
-let failed = 0;
-
-function assert(condition: boolean, msg: string) {
- if (condition) {
- passed++;
- console.log(` ✓ ${msg}`);
- } else {
- failed++;
- console.log(` ✗ ${msg}`);
- }
-}
-
-async function main() {
- console.log("=== OpenSandbox Shell API Test ===\n");
- console.log(`API: ${API_URL}`);
-
- console.log("\n--- 1. Creating sandbox ---");
- const sandbox = await Sandbox.create({
- apiUrl: API_URL,
- apiKey: API_KEY,
- template: "base",
- });
- console.log(` Sandbox: ${sandbox.sandboxId} (${sandbox.status})`);
- assert(sandbox.status === "running", "sandbox is running");
-
- // 2. basic run + exit code
- console.log("\n--- 2. shell.run('echo hello') ---");
- const sh = await sandbox.exec.shell();
- const r1 = await sh.run("echo hello");
- console.log(` stdout: "${r1.stdout.trim()}" exit=${r1.exitCode}`);
- assert(r1.exitCode === 0, "exit 0");
- assert(r1.stdout.trim() === "hello", "stdout matches");
- assert(r1.stderr === "", "stderr empty");
-
- // 3. cwd persists across calls
- console.log("\n--- 3. cwd persists across run() calls ---");
- await sh.run("cd /tmp");
- const pwd = await sh.run("pwd");
- console.log(` pwd: "${pwd.stdout.trim()}"`);
- assert(pwd.stdout.trim() === "/tmp", "cwd persisted");
-
- // 4. exported env persists
- console.log("\n--- 4. exported env persists ---");
- await sh.run("export MY_SHELL_VAR=persistence-works");
- const envR = await sh.run("echo $MY_SHELL_VAR");
- console.log(` echo: "${envR.stdout.trim()}"`);
- assert(envR.stdout.trim() === "persistence-works", "env persisted");
-
- // 5. non-zero exit — subshell so it doesn't kill the outer shell
- console.log("\n--- 5. non-zero exit code ---");
- const rFail = await sh.run("( exit 7 )");
- console.log(` exit: ${rFail.exitCode}`);
- assert(rFail.exitCode === 7, `exit 7 (got ${rFail.exitCode})`);
- const rFail2 = await sh.run("false && echo nope");
- assert(rFail2.exitCode === 1, `exit 1 from false (got ${rFail2.exitCode})`);
-
- // 6. stderr vs stdout separation
- console.log("\n--- 6. stderr separated from stdout ---");
- const rErr = await sh.run("echo to-out; echo to-err >&2");
- console.log(` stdout="${rErr.stdout.trim()}" stderr="${rErr.stderr.trim()}"`);
- assert(rErr.stdout.trim() === "to-out", "stdout is to-out");
- assert(rErr.stderr.trim() === "to-err", "stderr is to-err");
-
- // 7. streaming callbacks — print live so interleaving is visible, then
- // assert the chunks were spaced out in time (not buffered to the end).
- console.log("\n--- 7. streaming callbacks ---");
- const outChunks: string[] = [];
- const errChunks: string[] = [];
- const outTimes: number[] = [];
- const errTimes: number[] = [];
- const t0 = Date.now();
- const stamp = () => ((Date.now() - t0) / 1000).toFixed(2).padStart(5, " ");
- // Use /bin/echo (external) rather than bash's builtin — the builtin
- // goes through glibc stdio which block-buffers when stdout is a pipe,
- // so output lands in one chunk at the end. Each /bin/echo is a fresh
- // process that flushes on exit, making the streaming observable.
- const rStream = await sh.run(
- "for i in 1 2 3; do /bin/echo stdout-$i; /bin/echo stderr-$i >&2; sleep 0.2; done",
- {
- onStdout: (b) => {
- const s = decoder.decode(b);
- outChunks.push(s);
- outTimes.push(Date.now());
- process.stdout.write(` [+${stamp()}s OUT] ${JSON.stringify(s)}\n`);
- },
- onStderr: (b) => {
- const s = decoder.decode(b);
- errChunks.push(s);
- errTimes.push(Date.now());
- process.stdout.write(` [+${stamp()}s ERR] ${JSON.stringify(s)}\n`);
- },
- },
- );
- const joinedOut = outChunks.join("");
- const joinedErr = errChunks.join("");
- assert(joinedOut.includes("stdout-1") && joinedOut.includes("stdout-3"), "stdout stream callbacks fired");
- assert(joinedErr.includes("stderr-1") && joinedErr.includes("stderr-3"), "stderr stream callbacks fired");
- assert(!joinedErr.includes("__OC_"), "sentinel token hidden from onStderr");
- assert(!rStream.stderr.includes("__OC_"), "sentinel token hidden from returned stderr");
- // Command sleeps 0.2s × 3 = 0.6s. Ideally chunks stream as they are
- // produced. In practice, frames may be coalesced by upstream proxies
- // (CF/ALB) or gRPC flow control, so a single-chunk delivery is legal —
- // we log the span for visibility but don't fail on it.
- const stdoutSpanMs = outTimes.length >= 2 ? outTimes[outTimes.length - 1] - outTimes[0] : 0;
- console.log(` (stdout span across ${outTimes.length} chunks: ${stdoutSpanMs}ms)`);
-
- // 8. concurrent run rejects
- console.log("\n--- 8. concurrent run rejects ---");
- const slowP = sh.run("sleep 0.3; echo done");
- let busyErr: unknown;
- try {
- await sh.run("echo should-not-run");
- } catch (e) {
- busyErr = e;
- }
- assert(busyErr instanceof ShellBusyError, "got ShellBusyError on concurrent run");
- const slowR = await slowP;
- assert(slowR.stdout.trim() === "done", "original run still completes");
-
- // 9. shell.run with multi-line cmd
- console.log("\n--- 9. multi-line cmd ---");
- const multiR = await sh.run("echo a\necho b\necho c");
- const lines = multiR.stdout.trim().split("\n");
- assert(lines.length === 3 && lines[0] === "a" && lines[2] === "c", "multi-line executes in order");
-
- // 10. shell.run with a function defined earlier
- console.log("\n--- 10. shell functions persist ---");
- await sh.run("greet() { echo hi-$1; }");
- const fnR = await sh.run("greet world");
- assert(fnR.stdout.trim() === "hi-world", "defined function callable in later run");
-
- // 11. close
- console.log("\n--- 11. close ---");
- await sh.close();
- let closedErr: unknown;
- try {
- await sh.run("echo after-close");
- } catch (e) {
- closedErr = e;
- }
- assert(closedErr instanceof ShellClosedError, "run after close rejects with ShellClosedError");
-
- // 12. shell with cwd/env at construction
- console.log("\n--- 12. shell({ cwd, env }) initial state ---");
- const sh2 = await sandbox.exec.shell({
- cwd: "/etc",
- env: { SHELL_INIT_VAR: "from-init" },
- });
- const r12a = await sh2.run("pwd");
- assert(r12a.stdout.trim() === "/etc", "initial cwd honored");
- const r12b = await sh2.run("echo $SHELL_INIT_VAR");
- assert(r12b.stdout.trim() === "from-init", "initial env honored");
- await sh2.close();
-
- // 13. terminal-tab semantic: `exit` in user command closes the shell
- console.log("\n--- 13. exit N closes the shell (terminal-tab semantic) ---");
- const shExit = await sandbox.exec.shell();
- let exitErr: unknown;
- try {
- await shExit.run("exit 42");
- } catch (e) {
- exitErr = e;
- }
- assert(exitErr instanceof ShellClosedError, "exit 42 rejects the pending run with ShellClosedError");
- let afterExitErr: unknown;
- try {
- await shExit.run("echo after");
- } catch (e) {
- afterExitErr = e;
- }
- assert(afterExitErr instanceof ShellClosedError, "subsequent run rejects once shell is closed");
-
- // 14. reattach to an open shell by sessionId
- console.log("\n--- 14. reattachShell revisits an open shell ---");
- const shA = await sandbox.exec.shell();
- await shA.run("cd /tmp");
- await shA.run("export REATTACH_VAR=round-trip");
- const reattachId = shA.sessionId;
- // Drop the reference without closing — server-side bash keeps running.
- const shB = await sandbox.exec.reattachShell(reattachId);
- assert(shB.sessionId === reattachId, "reattached shell has the same sessionId");
- const rPwd = await shB.run("pwd");
- assert(rPwd.stdout.trim() === "/tmp", `reattach preserves cwd (got "${rPwd.stdout.trim()}")`);
- const rEnv = await shB.run("echo $REATTACH_VAR");
- assert(rEnv.stdout.trim() === "round-trip", `reattach preserves env (got "${rEnv.stdout.trim()}")`);
- await shB.close();
-
- // 15. shell alongside exec.background
- console.log("\n--- 15. exec.background alias ---");
- let bgExitCode = -999;
- const bgSession = await sandbox.exec.background("sh", {
- args: ["-c", "echo bg-ok; sleep 0.2"],
- onExit: (c) => {
- bgExitCode = c;
- },
- });
- await bgSession.done;
- assert(bgExitCode === 0, `exec.background returns exit code (got ${bgExitCode})`);
-
- // Cleanup
- console.log("\n--- 14. Killing sandbox ---");
- await sandbox.kill();
- assert(sandbox.status === "stopped", "sandbox stopped");
-
- console.log(`\n=== Results: ${passed} passed, ${failed} failed ===`);
- if (failed > 0) process.exit(1);
-}
-
-main().catch((err) => {
- console.error("\nTest failed:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/test-signed-urls.ts b/sdks/typescript/examples/test-signed-urls.ts
deleted file mode 100644
index 41bc0202..00000000
--- a/sdks/typescript/examples/test-signed-urls.ts
+++ /dev/null
@@ -1,220 +0,0 @@
-/**
- * Signed Download/Upload URL Test
- *
- * Tests:
- * 1. Generate a signed download URL and fetch file content without API key
- * 2. Modify file after URL generation — verify URL serves live content
- * 3. Generate a signed upload URL and PUT new content without API key
- * 4. Verify uploaded content via SDK read
- * 5. Expired URL returns 403
- * 6. Tampered signature returns 403
- *
- * Usage:
- * npx tsx examples/test-signed-urls.ts
- */
-
-import { Sandbox } from "../src/index";
-
-function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }
-function red(msg: string) { console.log(`\x1b[31m✗ ${msg}\x1b[0m`); }
-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-
-let passed = 0;
-let failed = 0;
-
-function check(desc: string, condition: boolean, detail?: string) {
- if (condition) {
- green(desc);
- passed++;
- } else {
- red(`${desc}${detail ? ` (${detail})` : ""}`);
- failed++;
- }
-}
-
-async function main() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Signed Download/Upload URL Test ║");
- bold("╚══════════════════════════════════════════════════╝\n");
-
- let sandbox: Sandbox | null = null;
-
- try {
- sandbox = await Sandbox.create({ template: "base", timeout: 120 });
- green(`Created sandbox: ${sandbox.sandboxId}`);
- console.log();
-
- // ── Test 1: Signed download URL ────────────────────────────────
- bold("━━━ Test 1: Signed download URL ━━━\n");
-
- const originalContent = "ORIGINAL CONTENT - written before signed URL generation";
- await sandbox.files.write("/tmp/hello.txt", originalContent);
- dim("Wrote /tmp/hello.txt with original content");
-
- const downloadUrl = await sandbox.downloadUrl("/tmp/hello.txt");
- dim(`Download URL: ${downloadUrl}`);
-
- // Inspect URL structure
- const urlObj = new URL(downloadUrl);
- dim(`Host: ${urlObj.host}`);
- dim(`Path: ${urlObj.pathname}`);
- check("URL contains sandbox ID", downloadUrl.includes(sandbox.sandboxId));
- check("URL contains signature param", urlObj.searchParams.has("signature"));
- check("URL contains expires param", urlObj.searchParams.has("expires"));
-
- // Fetch without API key — just a plain GET
- const res1 = await fetch(downloadUrl);
- const body1 = await res1.text();
- dim(`Status: ${res1.status}`);
- dim(`Body: "${body1.trim()}"`);
- check("Download URL returns 200", res1.status === 200);
- check("Content matches original", body1 === originalContent);
- console.log();
-
- // ── Test 2: URL serves live content (not a snapshot) ───────────
- bold("━━━ Test 2: Live content (not snapshot) ━━━\n");
-
- const modifiedContent = "MODIFIED CONTENT - written AFTER signed URL generation";
- await sandbox.files.write("/tmp/hello.txt", modifiedContent);
- dim("Overwrote /tmp/hello.txt with modified content");
-
- // Fetch the SAME URL again
- const res2 = await fetch(downloadUrl);
- const body2 = await res2.text();
- dim(`Same URL body: "${body2.trim()}"`);
-
- check("Same URL returns modified content (live, not snapshot)", body2 === modifiedContent);
-
- // Generate a new URL — should also work
- const downloadUrl2 = await sandbox.downloadUrl("/tmp/hello.txt");
- const res3 = await fetch(downloadUrl2);
- const body3 = await res3.text();
- check("New URL also returns modified content", body3 === modifiedContent);
- console.log();
-
- // ── Test 3: Signed upload URL ──────────────────────────────────
- bold("━━━ Test 3: Signed upload URL ━━━\n");
-
- const uploadUrl = await sandbox.uploadUrl("/tmp/uploaded.txt");
- dim(`Upload URL: ${uploadUrl}`);
-
- const uploadContent = "UPLOADED VIA SIGNED URL - no API key needed";
- const uploadRes = await fetch(uploadUrl, {
- method: "PUT",
- body: uploadContent,
- });
- dim(`Upload status: ${uploadRes.status}`);
- check("Upload returns 204", uploadRes.status === 204);
-
- // Verify via SDK read
- const readBack = await sandbox.files.read("/tmp/uploaded.txt");
- dim(`Readback: "${readBack}"`);
- check("Uploaded content readable via SDK", readBack === uploadContent);
- console.log();
-
- // ── Test 4: Upload overwrite via signed URL ────────────────────
- bold("━━━ Test 4: Upload overwrite ━━━\n");
-
- const overwriteContent = "OVERWRITTEN VIA SIGNED URL";
- const uploadUrl2 = await sandbox.uploadUrl("/tmp/uploaded.txt");
- const overwriteRes = await fetch(uploadUrl2, {
- method: "PUT",
- body: overwriteContent,
- });
- check("Overwrite upload returns 204", overwriteRes.status === 204);
-
- const readBack2 = await sandbox.files.read("/tmp/uploaded.txt");
- check("Overwritten content correct", readBack2 === overwriteContent);
- console.log();
-
- // ── Test 5: Download uploaded file via signed URL ───────────────
- bold("━━━ Test 5: Round-trip: upload then download via signed URLs ━━━\n");
-
- const roundtripContent = "round-trip test content 🎉";
- const upUrl = await sandbox.uploadUrl("/tmp/roundtrip.txt");
- await fetch(upUrl, { method: "PUT", body: roundtripContent });
-
- const dlUrl = await sandbox.downloadUrl("/tmp/roundtrip.txt");
- const dlRes = await fetch(dlUrl);
- const dlBody = await dlRes.text();
- check("Round-trip content intact", dlBody === roundtripContent);
- console.log();
-
- // ── Test 6: Expired URL ────────────────────────────────────────
- bold("━━━ Test 6: Expired URL ━━━\n");
-
- const shortUrl = await sandbox.downloadUrl("/tmp/hello.txt", { expiresIn: 1 });
- dim("Generated URL with 1s expiry, waiting 2s...");
- await new Promise((r) => setTimeout(r, 2000));
-
- const expiredRes = await fetch(shortUrl);
- dim(`Expired URL status: ${expiredRes.status}`);
- check("Expired URL returns 403", expiredRes.status === 403);
-
- if (expiredRes.status === 403) {
- const errBody = await expiredRes.json();
- dim(`Error: ${JSON.stringify(errBody)}`);
- check("Error message mentions expiry", errBody.error?.includes("expired"));
- }
- console.log();
-
- // ── Test 7: Tampered signature ─────────────────────────────────
- bold("━━━ Test 7: Tampered signature ━━━\n");
-
- const validUrl = await sandbox.downloadUrl("/tmp/hello.txt");
- const tampered = validUrl.replace(/signature=[^&]+/, "signature=deadbeef0000");
- const tamperedRes = await fetch(tampered);
- dim(`Tampered URL status: ${tamperedRes.status}`);
- check("Tampered signature returns 403", tamperedRes.status === 403);
- console.log();
-
- // ── Test 8: Tampered path ──────────────────────────────────────
- bold("━━━ Test 8: Tampered path ━━━\n");
-
- // Write a secret file, then try to access it by tampering the path param
- await sandbox.files.write("/tmp/secret.txt", "TOP SECRET");
- const legitUrl = await sandbox.downloadUrl("/tmp/hello.txt");
- const pathTampered = legitUrl.replace(
- /path=[^&]+/,
- `path=${encodeURIComponent("/tmp/secret.txt")}`,
- );
- const pathTamperedRes = await fetch(pathTampered);
- dim(`Path-tampered URL status: ${pathTamperedRes.status}`);
- check("Path-tampered URL returns 403 (signature mismatch)", pathTamperedRes.status === 403);
- console.log();
-
- // ── Test 9: Custom expiry ──────────────────────────────────────
- bold("━━━ Test 9: Custom expiry (5 min) ━━━\n");
-
- const customUrl = await sandbox.downloadUrl("/tmp/hello.txt", { expiresIn: 300 });
- const customUrlObj = new URL(customUrl);
- const expires = parseInt(customUrlObj.searchParams.get("expires") || "0");
- const now = Math.floor(Date.now() / 1000);
- const diff = expires - now;
- dim(`Expires in ${diff}s (expected ~300s)`);
- check("Expiry is approximately 5 minutes", diff >= 295 && diff <= 305, `${diff}s`);
- console.log();
-
- } catch (err: any) {
- red(`Fatal error: ${err.message}`);
- if (err.stack) dim(err.stack);
- failed++;
- } finally {
- if (sandbox) {
- await sandbox.kill();
- green("Sandbox killed");
- }
- }
-
- // --- Summary ---
- bold("========================================");
- bold(` Results: ${passed} passed, ${failed} failed`);
- bold("========================================\n");
- if (failed > 0) process.exit(1);
-}
-
-main().catch((err) => {
- console.error("Fatal error:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/test-snapshot-envs.ts b/sdks/typescript/examples/test-snapshot-envs.ts
deleted file mode 100644
index 8345516c..00000000
--- a/sdks/typescript/examples/test-snapshot-envs.ts
+++ /dev/null
@@ -1,210 +0,0 @@
-/**
- * Snapshot Envs & Secret-Sealing Test
- *
- * Regression coverage for two bugs that previously interacted around
- * Sandbox.create({ envs }):
- *
- * 1. The snapshot/fork path silently dropped user-supplied envs because
- * createFromCheckpointCore re-bound only `Timeout` from the request body
- * and forwarded `originalCfg.Envs` from the checkpoint instead.
- *
- * 2. Every env var was tokenized into an `osb_sealed_…` value by the
- * secrets proxy regardless of source, so `echo $TEST_VAR` inside the
- * guest returned the sealed token rather than the plaintext the user
- * passed. Sealing should only apply to envs that originated from a
- * SecretStore — those are the ones the MITM proxy needs to swap on
- * outbound HTTPS.
- *
- * What this test asserts:
- * - Plain `Sandbox.create({ envs })` → guest sees plaintext.
- * - `Sandbox.create({ snapshot, envs })` → user envs survive the fork AND
- * reach the guest as plaintext.
- * - `Sandbox.create({ secretStore, envs })` → user-supplied envs are
- * plaintext, store-derived envs are sealed (`osb_sealed_…`).
- *
- * Usage:
- * npx tsx examples/test-snapshot-envs.ts
- */
-
-import { Sandbox, SecretStore } from "../src/index";
-import { Snapshots, Image } from "../src/node";
-
-function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }
-function red(msg: string) { console.log(`\x1b[31m✗ ${msg}\x1b[0m`); }
-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-
-let passed = 0;
-let failed = 0;
-
-function check(desc: string, condition: boolean, detail?: string) {
- if (condition) {
- green(desc);
- passed++;
- } else {
- red(`${desc}${detail ? ` (${detail})` : ""}`);
- failed++;
- }
-}
-
-// Unique names so concurrent runs / reruns don't collide.
-const RUN_ID = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
-const SNAPSHOT_NAME = `test-snapshot-envs-${RUN_ID}`;
-const STORE_NAME = `test-snapshot-envs-store-${RUN_ID}`;
-const USER_VALUE = "plaintext-from-user";
-const SECRET_VALUE = "plaintext-from-store";
-
-async function readVar(sb: Sandbox, name: string): Promise<string> {
- // -n to avoid trailing newline; printenv would also work but echo matches
- // the original repro and is universally available in the base image.
- const out = await sb.commands.run(`echo -n "$${name}"`);
- return out.stdout;
-}
-
-async function main() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Snapshot Envs & Secret Sealing Test ║");
- bold("╚══════════════════════════════════════════════════╝\n");
-
- const snapshots = new Snapshots();
- let storeId: string | null = null;
- let createdSnapshot = false;
- const sandboxes: Sandbox[] = [];
-
- try {
- // ── Test 1: Plain create — user envs reach guest as plaintext ──
- bold("━━━ Test 1: envs without snapshot or secret store ━━━\n");
-
- const a = await Sandbox.create({ timeout: 60, envs: { TEST_VAR: USER_VALUE } });
- sandboxes.push(a);
- const aVal = await readVar(a, "TEST_VAR");
- dim(`TEST_VAR=${JSON.stringify(aVal)}`);
- check("plain create: user env is plaintext", aVal === USER_VALUE,
- `expected ${JSON.stringify(USER_VALUE)}, got ${JSON.stringify(aVal)}`);
- check("plain create: user env is NOT sealed", !aVal.startsWith("osb_sealed_"));
- console.log();
-
- // ── Test 2: Snapshot fork preserves user envs as plaintext ──
- // Bug #1 regression: this returned "" before the fix because the fork
- // path dropped envs from the request body.
- // Bug #2 regression: even after #1 was fixed it returned an osb_sealed_
- // token because every env was tokenized unconditionally.
- bold("━━━ Test 2: envs survive snapshot fork as plaintext ━━━\n");
-
- dim(`creating snapshot ${SNAPSHOT_NAME}...`);
- await snapshots.create({ name: SNAPSHOT_NAME, image: Image.base() });
- createdSnapshot = true;
-
- const b = await Sandbox.create({
- snapshot: SNAPSHOT_NAME,
- timeout: 60,
- envs: { TEST_VAR: USER_VALUE },
- });
- sandboxes.push(b);
- const bVal = await readVar(b, "TEST_VAR");
- dim(`TEST_VAR=${JSON.stringify(bVal)}`);
- check("snapshot fork: user env survives the fork", bVal.length > 0,
- "got empty string — bug #1 (createFromCheckpointCore drops req body)");
- check("snapshot fork: user env is NOT sealed", !bVal.startsWith("osb_sealed_"),
- "bug #2 (CreateSealedEnvs tokenizes every env)");
- check("snapshot fork: user env equals plaintext", bVal === USER_VALUE,
- `expected ${JSON.stringify(USER_VALUE)}, got ${JSON.stringify(bVal)}`);
- console.log();
-
- // ── Test 3: Secret store envs are still sealed; user envs are not ──
- // Selective sealing: passing both a SecretStore *and* explicit envs in
- // the same create should produce mixed plaintext/sealed values.
- bold("━━━ Test 3: secret store envs sealed, user envs plaintext ━━━\n");
-
- const store = await SecretStore.create({ name: STORE_NAME });
- storeId = store.id;
- await SecretStore.setSecret(storeId, "STORE_VAR", SECRET_VALUE);
-
- const c = await Sandbox.create({
- timeout: 60,
- secretStore: STORE_NAME,
- envs: { USER_VAR: USER_VALUE },
- });
- sandboxes.push(c);
- const userVal = await readVar(c, "USER_VAR");
- const storeVal = await readVar(c, "STORE_VAR");
- dim(`USER_VAR=${JSON.stringify(userVal)}`);
- dim(`STORE_VAR=${JSON.stringify(storeVal)}`);
- check("mixed: user env is plaintext", userVal === USER_VALUE,
- `expected ${JSON.stringify(USER_VALUE)}, got ${JSON.stringify(userVal)}`);
- check("mixed: user env is NOT sealed", !userVal.startsWith("osb_sealed_"));
- check("mixed: store env IS sealed", storeVal.startsWith("osb_sealed_"),
- `store-derived env should be tokenized by secrets proxy, got ${JSON.stringify(storeVal)}`);
- console.log();
-
- // ── Test 4: secretStore + snapshot must NOT silently leak secrets ──
- // Regression guard. The combination used to silently drop the user's
- // secret store on fork; the bug-#1 fix turned that silent drop into a
- // silent plaintext leak (the parent handler eagerly resolved the store
- // into cfg.Envs, which the fix then merged into the fork — but the
- // seal-set is computed from the snapshot's *original* store, so the
- // smuggled values reached the guest unsealed).
- //
- // The supported semantics are: a fork inherits the snapshot's secret
- // store and cannot override it. The API must reject the combination
- // explicitly so users can't trip the leak by accident.
- bold("━━━ Test 4: secretStore + snapshot is rejected (no leak) ━━━\n");
-
- let rejected = false;
- let leaked = false;
- let leakedValue = "";
- let d: Sandbox | null = null;
- try {
- d = await Sandbox.create({
- snapshot: SNAPSHOT_NAME,
- timeout: 60,
- secretStore: STORE_NAME,
- });
- // Reached this point: API accepted the combo. Verify it didn't leak.
- sandboxes.push(d);
- leakedValue = await readVar(d, "STORE_VAR");
- leaked = leakedValue === SECRET_VALUE;
- } catch (err: any) {
- rejected = true;
- dim(`API rejected combo: ${err.message}`);
- }
- check(
- "secretStore + snapshot is rejected at the API edge",
- rejected,
- leaked
- ? `LEAK: STORE_VAR reached the guest as plaintext (${JSON.stringify(leakedValue)})`
- : "API accepted the combo without leaking, but the supported contract is rejection",
- );
- check(
- "secretStore + snapshot does not leak plaintext into the guest",
- !leaked,
- `STORE_VAR=${JSON.stringify(leakedValue)} — secret-store value reached the guest unsealed`,
- );
- console.log();
-
- } catch (err: any) {
- red(`Fatal error: ${err.message}`);
- if (err.stack) dim(err.stack);
- failed++;
- } finally {
- for (const sb of sandboxes) {
- await sb.kill().catch(() => {});
- }
- if (createdSnapshot) {
- await snapshots.delete(SNAPSHOT_NAME).catch(() => {});
- }
- if (storeId) {
- await SecretStore.delete(storeId).catch(() => {});
- }
- }
-
- bold("========================================");
- bold(` Results: ${passed} passed, ${failed} failed`);
- bold("========================================\n");
- if (failed > 0) process.exit(1);
-}
-
-main().catch((err) => {
- console.error("Fatal error:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/test-timeout.ts b/sdks/typescript/examples/test-timeout.ts
deleted file mode 100644
index 40163af7..00000000
--- a/sdks/typescript/examples/test-timeout.ts
+++ /dev/null
@@ -1,151 +0,0 @@
-/**
- * Timeout Behavior Test
- *
- * Tests:
- * 1. Activity resets the rolling timeout (sandbox stays alive with pokes)
- * 2. Sandbox with short timeout eventually auto-hibernates when idle
- * 3. HTTP server sandbox + timeout behavior
- *
- * Known Limitations:
- * - Worker JWT tokens have a fixed TTL. If the token expires before the
- * sandbox timeout, commands via the direct worker URL will fail with 403.
- * The SDK should refresh tokens or use a longer TTL.
- * - setTimeout() is a worker-direct API that doesn't proxy through the
- * control plane yet.
- *
- * Usage:
- * npx tsx examples/test-timeout.ts
- */
-
-import { Sandbox } from "../src/index";
-
-function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }
-function red(msg: string) { console.log(`\x1b[31m✗ ${msg}\x1b[0m`); }
-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-function cyan(msg: string) { console.log(`\x1b[36m→ ${msg}\x1b[0m`); }
-function yellow(msg: string) { console.log(`\x1b[33m⚠ ${msg}\x1b[0m`); }
-
-function sleep(ms: number) {
- return new Promise((r) => globalThis.setTimeout(r, ms));
-}
-
-let passed = 0;
-let failed = 0;
-
-function check(desc: string, condition: boolean, detail?: string) {
- if (condition) {
- green(desc);
- passed++;
- } else {
- red(`${desc}${detail ? ` (${detail})` : ""}`);
- failed++;
- }
-}
-
-async function main() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Timeout Behavior Test ║");
- bold("╚══════════════════════════════════════════════════╝\n");
-
- // ── Test 1: Activity resets rolling timeout ───────────────────────
- bold("━━━ Test 1: Activity resets rolling timeout ━━━\n");
- dim("Timeout=60s, pokes every 15s × 8 = 120s total elapsed");
- dim("Without rolling reset, sandbox would die at 60s");
- {
- const sb = await Sandbox.create({ template: "base", timeout: 60 });
- green(`Created: ${sb.sandboxId} (timeout: 60s)`);
-
- // Run commands at 15s intervals for 120s total.
- // With a 60s timeout, the sandbox would die at t=60s without rolling reset.
- // Each poke resets the timer, so the sandbox should survive all 8 pokes.
- for (let i = 0; i < 8; i++) {
- dim(`Poke ${i + 1}/8: waiting 15s then running command...`);
- await sleep(15000);
- try {
- const result = await sb.commands.run(`echo poke-${i + 1}`);
- check(`Poke ${i + 1} at ${(i + 1) * 15}s: sandbox still alive`, result.stdout.trim() === `poke-${i + 1}`, `got: "${result.stdout.trim()}"`);
- } catch (err: any) {
- check(`Poke ${i + 1} at ${(i + 1) * 15}s: sandbox still alive`, false, err.message);
- }
- }
-
- dim("Total elapsed: ~120s (2× the 60s timeout, proving rolling reset)");
- const running = await sb.isRunning();
- check("Sandbox alive after 120s with activity (rolling timeout proven)", running);
-
- await sb.kill();
- green("Sandbox killed");
- console.log();
- }
-
- // ── Test 2: Idle sandbox eventually times out ─────────────────────
- bold("━━━ Test 2: Idle sandbox times out ━━━\n");
- {
- const sb = await Sandbox.create({ template: "base", timeout: 30 });
- green(`Created: ${sb.sandboxId} (timeout: 30s)`);
-
- // Verify it's alive
- const result = await sb.commands.run("echo alive");
- check("Commands work while alive", result.stdout.trim() === "alive");
-
- // Now do absolutely nothing for 40s
- dim("Leaving sandbox completely idle for 40 seconds...");
- await sleep(40000);
-
- // After idle timeout, the sandbox should have auto-hibernated.
- // isRunning() goes through control plane which doesn't touch the worker router.
- const running = await sb.isRunning();
- dim(`isRunning after 40s idle: ${running}`);
-
- // If the sandbox is still "running" per the control plane, the timeout may
- // have hibernated it locally on the worker (the CP doesn't always sync state).
- // Try to reconnect and run a command to see what happens.
- if (running) {
- try {
- const reconnected = await Sandbox.connect(sb.sandboxId);
- const afterResult = await reconnected.commands.run("echo after-timeout");
- dim(`Command after idle: "${afterResult.stdout.trim()}"`);
- yellow("Sandbox still responds after idle — timeout may auto-hibernate + auto-wake on command");
- } catch (err: any) {
- dim(`Command after idle failed: ${err.message}`);
- green("Sandbox appears to have timed out (command failed)");
- }
- } else {
- green("Sandbox no longer running after idle period");
- }
-
- check("Idle timeout test completed", true);
-
- // Clean up
- try { await sb.kill(); } catch {}
- green("Sandbox cleaned up");
- console.log();
- }
-
- // ── Test 3: Create → use → verify timeout config works ────────────
- bold("━━━ Test 3: Different timeout values accepted ━━━\n");
- {
- // Create with various timeout values
- const timeouts = [30, 60, 300, 600];
- for (const t of timeouts) {
- const sb = await Sandbox.create({ template: "base", timeout: t });
- check(`Sandbox created with timeout=${t}s`, sb.status === "running");
- const result = await sb.commands.run("echo ok");
- check(`Commands work with timeout=${t}s`, result.stdout.trim() === "ok");
- await sb.kill();
- }
- console.log();
- }
-
- // --- Summary ---
- bold("========================================");
- bold(` Results: ${passed} passed, ${failed} failed`);
- bold("========================================\n");
- if (failed > 0) process.exit(1);
-}
-
-main().catch((err) => {
- console.error("Fatal error:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/examples/webhook-demo.ts b/sdks/typescript/examples/webhook-demo.ts
deleted file mode 100644
index 03be5848..00000000
--- a/sdks/typescript/examples/webhook-demo.ts
+++ /dev/null
@@ -1,212 +0,0 @@
-/**
- * OpenSandbox Webhook Demo
- *
- * Demonstrates:
- * 1. Create a sandbox with a webhook server
- * 2. Send a webhook while sandbox is AWAKE → instant response
- * 3. Hibernate the sandbox (sandbox goes to sleep)
- * 4. Send a webhook while sandbox is ASLEEP → auto-wakes and responds
- * 5. Verify data persisted across the sleep/wake cycle
- *
- * Usage:
- * OPENCOMPUTER_API_KEY=osb_... npx tsx examples/webhook-demo.ts
- */
-
-import { Sandbox } from "../src/index";
-
-// ── Helpers ─────────────────────────────────────────────────────────────────
-
-function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }
-function red(msg: string) { console.log(`\x1b[31m✗ ${msg}\x1b[0m`); }
-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }
-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }
-function cyan(msg: string) { console.log(`\x1b[36m→ ${msg}\x1b[0m`); }
-
-function sleep(ms: number) {
- return new Promise((r) => globalThis.setTimeout(r, ms));
-}
-
-async function sendWebhook(
- domain: string,
- payload: Record<string, unknown>,
-): Promise<{ status: number; body: string; latencyMs: number }> {
- const url = `https://${domain}/webhook`;
- const start = Date.now();
- const resp = await fetch(url, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(payload),
- });
- const latencyMs = Date.now() - start;
- const body = await resp.text();
- return { status: resp.status, body, latencyMs };
-}
-
-// ── Webhook server (runs inside the sandbox on port 80) ─────────────────
-
-const WEBHOOK_SERVER = `
-const http = require('http');
-const fs = require('fs');
-
-const LOG_FILE = '/tmp/webhooks.log';
-
-const server = http.createServer((req, res) => {
- if (req.method === 'POST' && req.url === '/webhook') {
- let body = '';
- req.on('data', chunk => body += chunk);
- req.on('end', () => {
- const entry = { timestamp: new Date().toISOString(), payload: JSON.parse(body) };
- fs.appendFileSync(LOG_FILE, JSON.stringify(entry) + '\\n');
-
- const response = {
- received: true,
- event: entry.payload.event,
- processedAt: entry.timestamp,
- sandboxUptime: process.uptime().toFixed(1) + 's',
- };
-
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(response));
- });
- } else if (req.method === 'GET' && req.url === '/health') {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ status: 'ok', uptime: process.uptime().toFixed(1) + 's' }));
- } else {
- res.writeHead(404);
- res.end('not found');
- }
-});
-
-server.listen(80, '0.0.0.0', () => {
- console.log('Webhook server listening on port 80');
-});
-`;
-
-// ── Main Demo ───────────────────────────────────────────────────────────────
-
-async function main() {
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ OpenSandbox Webhook Demo ║");
- bold("║ Webhooks that survive sleep ║");
- bold("╚══════════════════════════════════════════════════╝\n");
-
- // ── Step 1: Create sandbox ────────────────────────────────────────────
- bold("━━━ Step 1: Create sandbox with webhook server ━━━\n");
- cyan("Creating sandbox...");
-
- const sandbox = await Sandbox.create({
- timeout: 300,
- });
-
- green(`Sandbox created: ${sandbox.sandboxId}`);
- dim(`Domain: ${sandbox.domain}`);
- console.log();
-
- // Write and start the webhook server
- cyan("Starting webhook server...");
- await sandbox.files.write("/tmp/server.js", WEBHOOK_SERVER);
- await sandbox.commands.run("nohup node /tmp/server.js > /tmp/server.log 2>&1 &");
-
- // Wait for server to bind
- await sleep(1000);
-
- // Verify it's running via the subdomain
- const healthResp = await fetch(`https://${sandbox.domain}/health`);
- if (healthResp.ok) {
- const health = await healthResp.json();
- green(`Webhook server is running (uptime: ${health.uptime})`);
- } else {
- red(`Webhook server failed to start (${healthResp.status})`);
- const serverLog = await sandbox.commands.run("cat /tmp/server.log");
- dim("Server log: " + serverLog.stdout + serverLog.stderr);
- await sandbox.kill();
- return;
- }
- console.log();
-
- // ── Step 2: Webhook while AWAKE ───────────────────────────────────────
- bold("━━━ Step 2: Send webhook while sandbox is AWAKE ━━━\n");
- cyan('Sending webhook: { event: "payment.completed" }');
-
- const awakeResult = await sendWebhook(sandbox.domain, {
- event: "payment.completed",
- amount: 99.99,
- customer: "cust_12345",
- });
-
- green(`Response (${awakeResult.latencyMs}ms): ${awakeResult.body}`);
- console.log();
-
- // ── Step 3: Hibernate ─────────────────────────────────────────────────
- bold("━━━ Step 3: Hibernate sandbox (sleep) ━━━\n");
- cyan("Hibernating...");
-
- const hibStart = Date.now();
- await sandbox.hibernate();
- const hibMs = Date.now() - hibStart;
-
- green(`Sandbox is now sleeping (took ${hibMs}ms)`);
- dim("Container checkpointed to S3, all processes frozen");
- dim("Domain still assigned: " + sandbox.domain);
- console.log();
-
- // Pause to make the sleep visible
- await sleep(2000);
-
- // ── Step 4: Webhook while ASLEEP ──────────────────────────────────────
- bold("━━━ Step 4: Send webhook while sandbox is ASLEEP ━━━\n");
- cyan("Sending webhook to sleeping sandbox...");
- dim("Sandbox will auto-wake from checkpoint and process the request");
- console.log();
-
- const sleepResult = await sendWebhook(sandbox.domain, {
- event: "invoice.created",
- invoiceId: "inv_67890",
- total: 250.0,
- });
-
- if (sleepResult.status === 200) {
- green(`Response (${sleepResult.latencyMs}ms): ${sleepResult.body}`);
- dim(`Latency includes: S3 download → container restore → request forwarded`);
- } else {
- red(`Unexpected status ${sleepResult.status}: ${sleepResult.body}`);
- }
- console.log();
-
- // ── Step 5: Verify logs persisted across sleep ────────────────────────
- bold("━━━ Step 5: Verify webhook logs survived hibernation ━━━\n");
-
- // Reconnect to get fresh worker token
- const reconnected = await Sandbox.connect(sandbox.sandboxId);
- const logs = await reconnected.commands.run("cat /tmp/webhooks.log");
-
- cyan("Webhook log (/tmp/webhooks.log):");
- for (const line of logs.stdout.trim().split("\n")) {
- const entry = JSON.parse(line);
- dim(`${entry.timestamp} → ${entry.payload.event}`);
- }
- green("Both webhooks logged — data persisted across sleep/wake cycle");
- console.log();
-
- // ── Cleanup ───────────────────────────────────────────────────────────
- bold("━━━ Cleanup ━━━\n");
- await reconnected.kill();
- green("Sandbox killed");
-
- bold("\n╔══════════════════════════════════════════════════╗");
- bold("║ Demo complete! ║");
- bold("║ ║");
- bold("║ What happened: ║");
- bold("║ 1. Created sandbox with Node.js webhook server ║");
- bold("║ 2. Sent webhook while awake → instant response ║");
- bold("║ 3. Hibernated sandbox to S3 checkpoint ║");
- bold("║ 4. Sent webhook to sleeping sandbox ║");
- bold("║ → auto-woke and processed the request ║");
- bold("║ 5. Both webhook logs persisted across sleep ║");
- bold("╚══════════════════════════════════════════════════╝\n");
-}
-
-main().catch((err) => {
- console.error("Fatal error:", err);
- process.exit(1);
-});
diff --git a/sdks/typescript/package-lock.json b/sdks/typescript/package-lock.json
index bc2a1d6e..35eb843a 100644
--- a/sdks/typescript/package-lock.json
+++ b/sdks/typescript/package-lock.json
@@ -1,16 +1,13 @@
{
"name": "@opencomputer/sdk",
- "version": "2.3.1",
+ "version": "3.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@opencomputer/sdk",
- "version": "2.3.1",
+ "version": "3.0.0",
"license": "MIT",
- "dependencies": {
- "undici": "^6.0.0 || ^7.0.0"
- },
"devDependencies": {
"@types/node": "^25.3.0",
"tsx": "^4.21.0",
@@ -2173,15 +2170,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/undici": {
- "version": "7.29.0",
- "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.0.tgz",
- "integrity": "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==",
- "license": "MIT",
- "engines": {
- "node": ">=20.18.1"
- }
- },
"node_modules/undici-types": {
"version": "7.18.2",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz",
diff --git a/sdks/typescript/package.json b/sdks/typescript/package.json
index 21ba04fd..86e0ef1c 100644
--- a/sdks/typescript/package.json
+++ b/sdks/typescript/package.json
@@ -1,23 +1,14 @@
{
"name": "@opencomputer/sdk",
- "version": "2.3.1",
- "description": "TypeScript SDK for OpenComputer - cloud sandboxes and the Serverless Agents management API",
+ "version": "3.0.0",
+ "description": "TypeScript client for the OpenComputer Serverless Agents management API (@opencomputer/sdk/agents)",
"type": "module",
- "main": "dist/index.js",
- "types": "dist/index.d.ts",
"exports": {
- ".": {
- "types": "./dist/index.d.ts",
- "import": "./dist/index.js"
- },
"./agents": {
"types": "./dist/agents/index.d.ts",
"import": "./dist/agents/index.js"
},
- "./node": {
- "types": "./dist/node.d.ts",
- "import": "./dist/node.js"
- }
+ "./package.json": "./package.json"
},
"files": [
"dist"
@@ -29,12 +20,10 @@
"prepublishOnly": "npm run build"
},
"keywords": [
- "sandbox",
"opencomputer",
- "e2b",
- "cloud",
- "containers",
- "code-execution"
+ "serverless-agents",
+ "agents",
+ "management-api"
],
"author": "OpenComputer",
"license": "MIT",
@@ -58,8 +47,5 @@
"tsx": "^4.21.0",
"typescript": "^5.4.0",
"vitest": "^1.6.0"
- },
- "dependencies": {
- "undici": "^6.0.0 || ^7.0.0"
}
}
diff --git a/sdks/typescript/src/agent.ts b/sdks/typescript/src/agent.ts
deleted file mode 100644
index 47674b54..00000000
--- a/sdks/typescript/src/agent.ts
+++ /dev/null
@@ -1,256 +0,0 @@
-import { apiFetch } from "./http2.js";
-import { openWebSocket } from "./websocket.js";
-export interface SandboxAgentEvent {
- type:
- | "ready"
- | "configured"
- | "assistant"
- | "result"
- | "system"
- | "tool_use_summary"
- | "turn_complete"
- | "interrupted"
- | "error"
- | string;
- [key: string]: unknown;
-}
-
-export interface McpServerConfig {
- command: string;
- args?: string[];
- env?: Record<string, string>;
-}
-
-export interface SandboxAgentConfig {
- model?: string;
- systemPrompt?: string;
- allowedTools?: string[];
- permissionMode?: string;
- maxTurns?: number;
- cwd?: string;
- mcpServers?: Record<string, McpServerConfig>;
- resume?: string;
-}
-
-export interface SandboxAgentStartOpts extends SandboxAgentConfig {
- prompt?: string;
- onEvent?: (event: SandboxAgentEvent) => void;
- onError?: (data: string) => void;
- onExit?: (exitCode: number) => void;
- onScrollbackEnd?: () => void;
-}
-
-export interface SandboxAgentSession {
- sessionId: string;
- done: Promise<number>;
- sendPrompt(text: string): void;
- interrupt(): void;
- configure(config: SandboxAgentConfig): void;
- kill(signal?: number): Promise<void>;
- close(): void;
-}
-
-/**
- * @deprecated The in-sandbox agent is a low-level primitive and is being phased out.
- * Prefer managed agents via the `OpenComputer` client — durable, streamable sessions.
- */
-export class SandboxAgent {
- constructor(
- private apiUrl: string,
- private apiKey: string,
- private sandboxId: string,
- private token: string = "",
- ) {}
-
- private get headers(): Record<string, string> {
- const h: Record<string, string> = { "Content-Type": "application/json" };
- if (this.token) {
- h["Authorization"] = `Bearer ${this.token}`;
- } else if (this.apiKey) {
- h["X-API-Key"] = this.apiKey;
- }
- return h;
- }
-
- async start(opts: SandboxAgentStartOpts = {}): Promise<SandboxAgentSession> {
- const body: Record<string, unknown> = {};
- if (opts.prompt) body.prompt = opts.prompt;
- if (opts.model) body.model = opts.model;
- if (opts.systemPrompt) body.systemPrompt = opts.systemPrompt;
- if (opts.allowedTools) body.allowedTools = opts.allowedTools;
- if (opts.permissionMode) body.permissionMode = opts.permissionMode;
- if (opts.maxTurns != null) body.maxTurns = opts.maxTurns;
- if (opts.cwd) body.cwd = opts.cwd;
- if (opts.mcpServers) body.mcpServers = opts.mcpServers;
- if (opts.resume) body.resume = opts.resume;
-
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/agent`, {
- method: "POST",
- headers: this.headers,
- body: JSON.stringify(body),
- });
-
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to create agent session: ${resp.status} ${text}`);
- }
-
- const data = await resp.json();
- const sessionId: string = data.sessionID;
-
- return this.attach(sessionId, opts);
- }
-
- async attach(sessionId: string, opts: Omit<SandboxAgentStartOpts, "prompt" | keyof SandboxAgentConfig> = {}): Promise<SandboxAgentSession> {
- // Connect via the existing exec session WebSocket endpoint
- const wsUrl = this.apiUrl
- .replace("http://", "ws://")
- .replace("https://", "wss://");
- const authParam = this.token
- ? `?token=${encodeURIComponent(this.token)}`
- : this.apiKey
- ? `?api_key=${encodeURIComponent(this.apiKey)}`
- : "";
- const wsEndpoint = `${wsUrl}/sandboxes/${this.sandboxId}/exec/${sessionId}${authParam}`;
-
- const ws = await openWebSocket(wsEndpoint);
-
- let gotExit = false;
- let resolveDone: (code: number) => void;
- const done = new Promise<number>((resolve) => { resolveDone = resolve; });
-
- // Line buffer for JSON-line parsing from stdout
- let lineBuf = "";
-
- const parseLines = (text: string) => {
- lineBuf += text;
- const lines = lineBuf.split("\n");
- // Keep incomplete last line in buffer
- lineBuf = lines.pop() ?? "";
- for (const line of lines) {
- const trimmed = line.trim();
- if (!trimmed) continue;
- try {
- const event: SandboxAgentEvent = JSON.parse(trimmed);
- opts.onEvent?.(event);
- } catch {
- // Not JSON — treat as raw output
- opts.onError?.(`non-JSON stdout: ${trimmed}`);
- }
- }
- };
-
- const decoder = new TextDecoder();
-
- ws.onmessage = (event) => {
- const buf = new Uint8Array(event.data as ArrayBuffer);
- if (buf.length < 1) return;
-
- const streamId = buf[0];
- const payload = buf.slice(1);
-
- switch (streamId) {
- case 0x01: // stdout — JSON lines from wrapper
- parseLines(decoder.decode(payload, { stream: true }));
- break;
- case 0x02: // stderr — wrapper's own logs
- opts.onError?.(decoder.decode(payload, { stream: true }));
- break;
- case 0x03: // exit
- gotExit = true;
- if (payload.length >= 4) {
- const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
- const exitCode = view.getInt32(0, false);
- opts.onExit?.(exitCode);
- resolveDone(exitCode);
- } else {
- opts.onExit?.(0);
- resolveDone(0);
- }
- break;
- case 0x04: // scrollback_end
- opts.onScrollbackEnd?.();
- break;
- }
- };
-
- ws.onclose = () => {
- // Flush remaining line buffer
- if (lineBuf.trim()) {
- try {
- const event: SandboxAgentEvent = JSON.parse(lineBuf.trim());
- opts.onEvent?.(event);
- } catch {
- opts.onError?.(`non-JSON stdout: ${lineBuf.trim()}`);
- }
- lineBuf = "";
- }
- if (!gotExit) {
- opts.onExit?.(-1);
- resolveDone(-1);
- }
- };
-
- ws.onerror = () => {
- if (!gotExit) {
- opts.onExit?.(-1);
- resolveDone(-1);
- }
- };
-
- const agent = this;
-
- const sendStdin = (data: string) => {
- if (ws.readyState !== WebSocket.OPEN) return;
- const payload = new TextEncoder().encode(data);
- const msg = new Uint8Array(1 + payload.length);
- msg[0] = 0x00;
- msg.set(payload, 1);
- ws.send(msg);
- };
-
- return {
- sessionId,
- done,
- sendPrompt(text: string): void {
- sendStdin(JSON.stringify({ type: "prompt", text }) + "\n");
- },
- interrupt(): void {
- sendStdin(JSON.stringify({ type: "interrupt" }) + "\n");
- },
- configure(config: SandboxAgentConfig): void {
- sendStdin(JSON.stringify({ type: "configure", ...config }) + "\n");
- },
- async kill(signal?: number): Promise<void> {
- const body: Record<string, unknown> = {};
- if (signal != null) body.signal = signal;
-
- const resp = await apiFetch(`${agent.apiUrl}/sandboxes/${agent.sandboxId}/agent/${sessionId}/kill`, {
- method: "POST",
- headers: agent.headers,
- body: JSON.stringify(body),
- });
-
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to kill agent session: ${resp.status} ${text}`);
- }
- },
- close(): void {
- ws.close();
- },
- };
- }
-
- async list(): Promise<Array<{ sessionID: string; sandboxID: string; running: boolean; startedAt: string }>> {
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/agent`, {
- headers: this.headers,
- });
-
- if (!resp.ok) {
- throw new Error(`Failed to list agent sessions: ${resp.status}`);
- }
-
- return resp.json();
- }
-}
diff --git a/sdks/typescript/src/agents/index.ts b/sdks/typescript/src/agents/index.ts
index a15c0fce..401ea0ed 100644
--- a/sdks/typescript/src/agents/index.ts
+++ b/sdks/typescript/src/agents/index.ts
@@ -2,8 +2,8 @@
//
// This module graph is portable: fetch, URL, Headers and Web Crypto only, no
// Node built-ins, nothing run at import. It loads the same in a Cloudflare
-// Worker without Node compatibility, on Vercel, on Deno and on Node. The
-// sandbox client at the package root is Node-only and lives apart on purpose.
+// Worker without Node compatibility, on Vercel, on Deno and on Node. Since
+// 3.0.0 it is the package's only entry: the sandbox client is gone.
export {
OpenComputer,
diff --git a/sdks/typescript/src/browser.test.ts b/sdks/typescript/src/browser.test.ts
deleted file mode 100644
index 448a01a8..00000000
--- a/sdks/typescript/src/browser.test.ts
+++ /dev/null
@@ -1,234 +0,0 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
-import { Browser } from "./browser.js";
-import { BrowserProfile } from "./browser.js";
-import { BrowserProfileAuthCheck } from "./browser.js";
-
-const browserResponse = {
- id: "br_1",
- provider: "kernel",
- provider_session_id: "kernel_1",
- status: "active",
- cdp_ws_url: "wss://proxy.example.onkernel.com/browser/cdp?jwt=abc",
- webdriver_ws_url: "wss://proxy.example.onkernel.com/browser/webdriver/session?jwt=abc",
- live_view_url: "https://proxy.example.onkernel.com/browser/live?jwt=abc",
- base_url: "https://proxy.example.onkernel.com/browser/kernel",
- headless: false,
- stealth: true,
- timeout_seconds: 60,
-};
-
-describe("Browser", () => {
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
- it("creates a browser with OpenComputer browser API shape", async () => {
- const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(
- Response.json(browserResponse, { status: 201 }),
- );
-
- const browser = await Browser.create({
- apiKey: "osb_test",
- apiUrl: "https://browser.example.test/",
- stealth: true,
- timeoutSeconds: 120,
- startUrl: "https://example.com",
- telemetry: false,
- recording: false,
- viewport: { width: 1280, height: 800, refreshRate: 60 },
- profile: { name: "default", saveChanges: true },
- });
-
- expect(browser.id).toBe("br_1");
- expect(browser.providerSessionId).toBe("kernel_1");
- expect(browser.cdpWsUrl).toContain("onkernel.com");
- expect(fetchMock).toHaveBeenCalledWith(
- "https://browser.example.test/v1/browsers",
- expect.objectContaining({
- method: "POST",
- headers: expect.objectContaining({ "X-API-Key": "osb_test" }),
- body: JSON.stringify({
- stealth: true,
- timeout_seconds: 120,
- profile: { name: "default", save_changes: true },
- viewport: { width: 1280, height: 800, refresh_rate: 60 },
- start_url: "https://example.com",
- telemetry: false,
- recording: false,
- }),
- }),
- );
- });
-
- it("connects and deletes a browser", async () => {
- const fetchMock = vi.spyOn(globalThis, "fetch")
- .mockResolvedValueOnce(Response.json(browserResponse))
- .mockResolvedValueOnce(Response.json({ id: "br_1", status: "deleted" }));
-
- const browser = await Browser.connect("br_1", {
- apiKey: "osb_test",
- apiUrl: "https://browser.example.test",
- });
- await browser.delete();
-
- expect(fetchMock).toHaveBeenNthCalledWith(
- 1,
- "https://browser.example.test/v1/browsers/br_1",
- expect.objectContaining({ headers: expect.objectContaining({ "X-API-Key": "osb_test" }) }),
- );
- expect(fetchMock).toHaveBeenNthCalledWith(
- 2,
- "https://browser.example.test/v1/browsers/br_1",
- expect.objectContaining({ method: "DELETE" }),
- );
- });
-
- it("creates, lists, connects, and deletes browser profiles", async () => {
- const profileResponse = {
- id: "prof_1",
- provider: "kernel",
- provider_profile_id: "kernel_profile_1",
- name: "github-login",
- created_at: "2026-06-27T00:00:00.000Z",
- updated_at: "2026-06-27T00:00:00.000Z",
- };
- const fetchMock = vi.spyOn(globalThis, "fetch")
- .mockResolvedValueOnce(Response.json(profileResponse, { status: 201 }))
- .mockResolvedValueOnce(Response.json({ profiles: [profileResponse] }))
- .mockResolvedValueOnce(Response.json(profileResponse))
- .mockResolvedValueOnce(Response.json({ id: "prof_1", status: "deleted" }));
-
- const profile = await BrowserProfile.create({
- apiKey: "osb_test",
- apiUrl: "https://browser.example.test",
- name: "github-login",
- });
- expect(profile.id).toBe("prof_1");
- expect(profile.providerProfileId).toBe("kernel_profile_1");
-
- const profiles = await BrowserProfile.list({
- apiKey: "osb_test",
- apiUrl: "https://browser.example.test",
- });
- expect(profiles).toHaveLength(1);
-
- await BrowserProfile.connect("github-login", {
- apiKey: "osb_test",
- apiUrl: "https://browser.example.test",
- });
- await profile.delete();
-
- expect(fetchMock).toHaveBeenNthCalledWith(
- 1,
- "https://browser.example.test/v1/profiles",
- expect.objectContaining({
- method: "POST",
- body: JSON.stringify({ name: "github-login" }),
- }),
- );
- expect(fetchMock).toHaveBeenNthCalledWith(
- 4,
- "https://browser.example.test/v1/profiles/prof_1",
- expect.objectContaining({ method: "DELETE" }),
- );
- });
-
- it("creates and polls browser profile auth checks", async () => {
- const profileResponse = {
- id: "prof_1",
- provider: "kernel",
- provider_profile_id: "kernel_profile_1",
- name: "linkedin",
- };
- const runningResponse = {
- id: "authchk_1",
- status: "running",
- profile_id: "prof_1",
- provider_profile_id: "kernel_profile_1",
- homepage: "https://www.linkedin.com/feed/",
- user: "motatoes",
- mode: "vision",
- compare_fresh: true,
- trigger_run_id: "run_1",
- };
- const completedResponse = {
- ...runningResponse,
- status: "completed",
- result: { outcome: "authenticated", confidence: 0.99 },
- completed_at: "2026-07-17T00:00:00.000Z",
- };
- const fetchMock = vi.spyOn(globalThis, "fetch")
- .mockResolvedValueOnce(Response.json(profileResponse))
- .mockResolvedValueOnce(Response.json(runningResponse, { status: 202 }))
- .mockResolvedValueOnce(Response.json(completedResponse));
-
- const profile = await BrowserProfile.connect("linkedin", {
- apiKey: "osb_test",
- apiUrl: "https://browser.example.test",
- });
- const run = await profile.checkAuth({
- homepage: "https://www.linkedin.com/feed/",
- user: "motatoes",
- mode: "vision",
- compareFresh: true,
- });
- const refreshed = await run.refresh();
-
- expect(run.id).toBe("authchk_1");
- expect(run.done).toBe(false);
- expect(refreshed.done).toBe(true);
- expect(refreshed.result).toEqual({ outcome: "authenticated", confidence: 0.99 });
- expect(fetchMock).toHaveBeenNthCalledWith(
- 2,
- "https://browser.example.test/v1/profiles/prof_1/auth-checks",
- expect.objectContaining({
- method: "POST",
- body: JSON.stringify({
- homepage: "https://www.linkedin.com/feed/",
- user: "motatoes",
- mode: "vision",
- compare_fresh: true,
- }),
- }),
- );
- expect(fetchMock).toHaveBeenNthCalledWith(
- 3,
- "https://browser.example.test/v1/profile-auth-checks/authchk_1",
- expect.objectContaining({ headers: expect.objectContaining({ "X-API-Key": "osb_test" }) }),
- );
- });
-
- it("waits for browser profile auth checks by polling", async () => {
- vi.useFakeTimers();
- const runningResponse = {
- id: "authchk_1",
- status: "running",
- profile_id: "prof_1",
- homepage: "https://mail.google.com/",
- };
- const completedResponse = {
- ...runningResponse,
- status: "completed",
- result: { outcome: "authenticated" },
- };
- const fetchMock = vi.spyOn(globalThis, "fetch")
- .mockResolvedValueOnce(Response.json(runningResponse))
- .mockResolvedValueOnce(Response.json(completedResponse));
-
- try {
- const run = await BrowserProfileAuthCheck.connect("authchk_1", {
- apiKey: "osb_test",
- apiUrl: "https://browser.example.test",
- });
- const waitPromise = run.wait({ intervalMs: 10, timeoutMs: 1000 });
- await vi.advanceTimersByTimeAsync(10);
- const done = await waitPromise;
-
- expect(done.status).toBe("completed");
- expect(done.result).toEqual({ outcome: "authenticated" });
- expect(fetchMock).toHaveBeenCalledTimes(2);
- } finally {
- vi.useRealTimers();
- }
- });
-});
diff --git a/sdks/typescript/src/browser.ts b/sdks/typescript/src/browser.ts
deleted file mode 100644
index 394916b8..00000000
--- a/sdks/typescript/src/browser.ts
+++ /dev/null
@@ -1,392 +0,0 @@
-import { apiFetch } from "./http2.js";
-const DEFAULT_BROWSER_API_URL = "https://browser.opencomputer.dev";
-
-function resolveBrowserApiUrl(url?: string): string {
- return (url || process.env.OPENCOMPUTER_BROWSER_API_URL || DEFAULT_BROWSER_API_URL).replace(/\/+$/, "");
-}
-
-export interface BrowserCreateOpts {
- apiKey?: string;
- apiUrl?: string;
- name?: string;
- tags?: Record<string, string>;
- stealth?: boolean;
- headless?: boolean;
- gpu?: boolean;
- timeoutSeconds?: number;
- profile?: { id?: string; name?: string; saveChanges?: boolean };
- extensions?: Array<{ id?: string; name?: string }>;
- proxyId?: string;
- viewport?: { width: number; height: number; refreshRate?: number };
- kioskMode?: boolean;
- startUrl?: string;
- chromePolicy?: Record<string, unknown>;
- telemetry?: boolean | Record<string, unknown> | null;
- recording?: boolean;
-}
-
-export interface BrowserData {
- id: string;
- provider: "kernel";
- provider_session_id: string;
- status: string;
- cdp_ws_url: string;
- webdriver_ws_url: string;
- live_view_url?: string | null;
- base_url?: string | null;
- headless?: boolean;
- stealth?: boolean;
- gpu?: boolean;
- timeout_seconds?: number;
- created_at?: string;
- updated_at?: string;
- deleted_at?: string | null;
-}
-
-export interface BrowserProfileCreateOpts {
- apiKey?: string;
- apiUrl?: string;
- name?: string;
-}
-
-export interface BrowserProfileData {
- id: string;
- provider: "kernel";
- provider_profile_id: string;
- name?: string | null;
- created_at?: string;
- updated_at?: string;
- deleted_at?: string | null;
- provider_created_at?: string;
- provider_updated_at?: string;
- provider_last_used_at?: string;
-}
-
-export interface BrowserProfileAuthCheckCreateOpts {
- homepage: string;
- user?: string;
- mode?: "vision" | "playwright" | "hybrid";
- compareFresh?: boolean;
-}
-
-export interface BrowserProfileAuthCheckData {
- id: string;
- status: "queued" | "running" | "completed" | "failed" | string;
- profile_id: string;
- provider_profile_id?: string;
- homepage: string;
- user?: string | null;
- mode?: "vision" | "playwright" | "hybrid" | string;
- compare_fresh?: boolean;
- trigger_run_id?: string | null;
- result?: unknown;
- error?: unknown;
- created_at?: string;
- updated_at?: string;
- completed_at?: string | null;
-}
-
-export interface BrowserProfileAuthCheckWaitOpts {
- intervalMs?: number;
- timeoutMs?: number;
-}
-
-export class Browser {
- readonly id: string;
- readonly provider: "kernel";
- readonly providerSessionId: string;
- readonly status: string;
- readonly cdpWsUrl: string;
- readonly webdriverWsUrl: string;
- readonly liveViewUrl: string | null;
- readonly baseUrl: string | null;
- readonly headless?: boolean;
- readonly stealth?: boolean;
- readonly gpu?: boolean;
- readonly timeoutSeconds?: number;
- readonly createdAt?: string;
- readonly updatedAt?: string;
- readonly deletedAt?: string | null;
-
- private readonly apiUrl: string;
- private readonly apiKey: string;
-
- constructor(data: BrowserData, apiUrl: string, apiKey: string) {
- this.id = data.id;
- this.provider = data.provider;
- this.providerSessionId = data.provider_session_id;
- this.status = data.status;
- this.cdpWsUrl = data.cdp_ws_url;
- this.webdriverWsUrl = data.webdriver_ws_url;
- this.liveViewUrl = data.live_view_url ?? null;
- this.baseUrl = data.base_url ?? null;
- this.headless = data.headless;
- this.stealth = data.stealth;
- this.gpu = data.gpu;
- this.timeoutSeconds = data.timeout_seconds;
- this.createdAt = data.created_at;
- this.updatedAt = data.updated_at;
- this.deletedAt = data.deleted_at;
- this.apiUrl = apiUrl;
- this.apiKey = apiKey;
- }
-
- static async create(opts: BrowserCreateOpts = {}): Promise<Browser> {
- const apiUrl = resolveBrowserApiUrl(opts.apiUrl);
- const apiKey = opts.apiKey || process.env.OPENCOMPUTER_API_KEY || "";
- const resp = await apiFetch(`${apiUrl}/v1/browsers`, {
- method: "POST",
- headers: headers(apiKey),
- body: JSON.stringify(toCreateBody(opts)),
- });
- if (!resp.ok) {
- throw await browserError(resp, "create browser");
- }
- return new Browser(await resp.json() as BrowserData, apiUrl, apiKey);
- }
-
- static async connect(id: string, opts: { apiKey?: string; apiUrl?: string } = {}): Promise<Browser> {
- const apiUrl = resolveBrowserApiUrl(opts.apiUrl);
- const apiKey = opts.apiKey || process.env.OPENCOMPUTER_API_KEY || "";
- const resp = await apiFetch(`${apiUrl}/v1/browsers/${encodeURIComponent(id)}`, {
- headers: headers(apiKey),
- });
- if (!resp.ok) {
- throw await browserError(resp, "connect browser");
- }
- return new Browser(await resp.json() as BrowserData, apiUrl, apiKey);
- }
-
- async delete(): Promise<void> {
- const resp = await apiFetch(`${this.apiUrl}/v1/browsers/${encodeURIComponent(this.id)}`, {
- method: "DELETE",
- headers: headers(this.apiKey),
- });
- if (!resp.ok) {
- throw await browserError(resp, "delete browser");
- }
- }
-}
-
-export class BrowserProfile {
- readonly id: string;
- readonly provider: "kernel";
- readonly providerProfileId: string;
- readonly name: string | null;
- readonly createdAt?: string;
- readonly updatedAt?: string;
- readonly deletedAt?: string | null;
- readonly providerCreatedAt?: string;
- readonly providerUpdatedAt?: string;
- readonly providerLastUsedAt?: string;
-
- private readonly apiUrl: string;
- private readonly apiKey: string;
-
- constructor(data: BrowserProfileData, apiUrl: string, apiKey: string) {
- this.id = data.id;
- this.provider = data.provider;
- this.providerProfileId = data.provider_profile_id;
- this.name = data.name ?? null;
- this.createdAt = data.created_at;
- this.updatedAt = data.updated_at;
- this.deletedAt = data.deleted_at;
- this.providerCreatedAt = data.provider_created_at;
- this.providerUpdatedAt = data.provider_updated_at;
- this.providerLastUsedAt = data.provider_last_used_at;
- this.apiUrl = apiUrl;
- this.apiKey = apiKey;
- }
-
- static async create(opts: BrowserProfileCreateOpts = {}): Promise<BrowserProfile> {
- const apiUrl = resolveBrowserApiUrl(opts.apiUrl);
- const apiKey = opts.apiKey || process.env.OPENCOMPUTER_API_KEY || "";
- const body: Record<string, unknown> = {};
- if (opts.name !== undefined) body.name = opts.name;
- const resp = await apiFetch(`${apiUrl}/v1/profiles`, {
- method: "POST",
- headers: headers(apiKey),
- body: JSON.stringify(body),
- });
- if (!resp.ok) {
- throw await browserError(resp, "create browser profile");
- }
- return new BrowserProfile(await resp.json() as BrowserProfileData, apiUrl, apiKey);
- }
-
- static async list(opts: { apiKey?: string; apiUrl?: string } = {}): Promise<BrowserProfile[]> {
- const apiUrl = resolveBrowserApiUrl(opts.apiUrl);
- const apiKey = opts.apiKey || process.env.OPENCOMPUTER_API_KEY || "";
- const resp = await apiFetch(`${apiUrl}/v1/profiles`, {
- headers: headers(apiKey),
- });
- if (!resp.ok) {
- throw await browserError(resp, "list browser profiles");
- }
- const data = await resp.json() as { profiles: BrowserProfileData[] };
- return (data.profiles ?? []).map((profile) => new BrowserProfile(profile, apiUrl, apiKey));
- }
-
- static async connect(idOrName: string, opts: { apiKey?: string; apiUrl?: string } = {}): Promise<BrowserProfile> {
- const apiUrl = resolveBrowserApiUrl(opts.apiUrl);
- const apiKey = opts.apiKey || process.env.OPENCOMPUTER_API_KEY || "";
- const resp = await apiFetch(`${apiUrl}/v1/profiles/${encodeURIComponent(idOrName)}`, {
- headers: headers(apiKey),
- });
- if (!resp.ok) {
- throw await browserError(resp, "connect browser profile");
- }
- return new BrowserProfile(await resp.json() as BrowserProfileData, apiUrl, apiKey);
- }
-
- async delete(): Promise<void> {
- const resp = await apiFetch(`${this.apiUrl}/v1/profiles/${encodeURIComponent(this.id)}`, {
- method: "DELETE",
- headers: headers(this.apiKey),
- });
- if (!resp.ok) {
- throw await browserError(resp, "delete browser profile");
- }
- }
-
- async checkAuth(opts: BrowserProfileAuthCheckCreateOpts): Promise<BrowserProfileAuthCheck> {
- const resp = await apiFetch(`${this.apiUrl}/v1/profiles/${encodeURIComponent(this.id)}/auth-checks`, {
- method: "POST",
- headers: headers(this.apiKey),
- body: JSON.stringify(toAuthCheckBody(opts)),
- });
- if (!resp.ok) {
- throw await browserError(resp, "create browser profile auth check");
- }
- return new BrowserProfileAuthCheck(await resp.json() as BrowserProfileAuthCheckData, this.apiUrl, this.apiKey);
- }
-}
-
-export class BrowserProfileAuthCheck {
- readonly id: string;
- readonly status: string;
- readonly profileId: string;
- readonly providerProfileId?: string;
- readonly homepage: string;
- readonly user: string | null;
- readonly mode?: string;
- readonly compareFresh?: boolean;
- readonly triggerRunId: string | null;
- readonly result: unknown;
- readonly error: unknown;
- readonly createdAt?: string;
- readonly updatedAt?: string;
- readonly completedAt?: string | null;
-
- private readonly apiUrl: string;
- private readonly apiKey: string;
-
- constructor(data: BrowserProfileAuthCheckData, apiUrl: string, apiKey: string) {
- this.id = data.id;
- this.status = data.status;
- this.profileId = data.profile_id;
- this.providerProfileId = data.provider_profile_id;
- this.homepage = data.homepage;
- this.user = data.user ?? null;
- this.mode = data.mode;
- this.compareFresh = data.compare_fresh;
- this.triggerRunId = data.trigger_run_id ?? null;
- this.result = data.result ?? null;
- this.error = data.error ?? null;
- this.createdAt = data.created_at;
- this.updatedAt = data.updated_at;
- this.completedAt = data.completed_at;
- this.apiUrl = apiUrl;
- this.apiKey = apiKey;
- }
-
- get done(): boolean {
- return this.status === "completed" || this.status === "failed";
- }
-
- static async connect(id: string, opts: { apiKey?: string; apiUrl?: string } = {}): Promise<BrowserProfileAuthCheck> {
- const apiUrl = resolveBrowserApiUrl(opts.apiUrl);
- const apiKey = opts.apiKey || process.env.OPENCOMPUTER_API_KEY || "";
- const resp = await apiFetch(`${apiUrl}/v1/profile-auth-checks/${encodeURIComponent(id)}`, {
- headers: headers(apiKey),
- });
- if (!resp.ok) {
- throw await browserError(resp, "connect browser profile auth check");
- }
- return new BrowserProfileAuthCheck(await resp.json() as BrowserProfileAuthCheckData, apiUrl, apiKey);
- }
-
- async refresh(): Promise<BrowserProfileAuthCheck> {
- return BrowserProfileAuthCheck.connect(this.id, { apiUrl: this.apiUrl, apiKey: this.apiKey });
- }
-
- async wait(opts: BrowserProfileAuthCheckWaitOpts = {}): Promise<BrowserProfileAuthCheck> {
- const intervalMs = opts.intervalMs ?? 2000;
- const timeoutMs = opts.timeoutMs ?? 120000;
- const startedAt = Date.now();
- let current: BrowserProfileAuthCheck = this;
- while (!current.done) {
- if (Date.now() - startedAt > timeoutMs) {
- throw new Error(`Timed out waiting for browser profile auth check ${this.id}`);
- }
- await sleep(intervalMs);
- current = await current.refresh();
- }
- return current;
- }
-}
-
-function headers(apiKey: string): HeadersInit {
- const h: Record<string, string> = { "Content-Type": "application/json" };
- if (apiKey) h["X-API-Key"] = apiKey;
- return h;
-}
-
-function toCreateBody(opts: BrowserCreateOpts): Record<string, unknown> {
- const body: Record<string, unknown> = {};
- if (opts.name !== undefined) body.name = opts.name;
- if (opts.tags !== undefined) body.tags = opts.tags;
- if (opts.stealth !== undefined) body.stealth = opts.stealth;
- if (opts.headless !== undefined) body.headless = opts.headless;
- if (opts.gpu !== undefined) body.gpu = opts.gpu;
- if (opts.timeoutSeconds !== undefined) body.timeout_seconds = opts.timeoutSeconds;
- if (opts.profile !== undefined) {
- body.profile = {
- ...(opts.profile.id !== undefined ? { id: opts.profile.id } : {}),
- ...(opts.profile.name !== undefined ? { name: opts.profile.name } : {}),
- ...(opts.profile.saveChanges !== undefined ? { save_changes: opts.profile.saveChanges } : {}),
- };
- }
- if (opts.extensions !== undefined) body.extensions = opts.extensions;
- if (opts.proxyId !== undefined) body.proxy_id = opts.proxyId;
- if (opts.viewport !== undefined) {
- body.viewport = {
- width: opts.viewport.width,
- height: opts.viewport.height,
- ...(opts.viewport.refreshRate !== undefined ? { refresh_rate: opts.viewport.refreshRate } : {}),
- };
- }
- if (opts.kioskMode !== undefined) body.kiosk_mode = opts.kioskMode;
- if (opts.startUrl !== undefined) body.start_url = opts.startUrl;
- if (opts.chromePolicy !== undefined) body.chrome_policy = opts.chromePolicy;
- if (opts.telemetry !== undefined) body.telemetry = opts.telemetry;
- if (opts.recording !== undefined) body.recording = opts.recording;
- return body;
-}
-
-function toAuthCheckBody(opts: BrowserProfileAuthCheckCreateOpts): Record<string, unknown> {
- const body: Record<string, unknown> = { homepage: opts.homepage };
- if (opts.user !== undefined) body.user = opts.user;
- if (opts.mode !== undefined) body.mode = opts.mode;
- if (opts.compareFresh !== undefined) body.compare_fresh = opts.compareFresh;
- return body;
-}
-
-function sleep(ms: number): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, ms));
-}
-
-async function browserError(resp: Response, action: string): Promise<Error> {
- const text = await resp.text();
- return new Error(`Failed to ${action}: ${resp.status} ${text}`);
-}
diff --git a/sdks/typescript/src/exec.ts b/sdks/typescript/src/exec.ts
deleted file mode 100644
index 81162899..00000000
--- a/sdks/typescript/src/exec.ts
+++ /dev/null
@@ -1,442 +0,0 @@
-import { apiFetch } from "./http2.js";
-import { openWebSocket } from "./websocket.js";
-import { ShellImpl, type Shell, type ShellOpts } from "./shell.js";
-
-export interface ProcessResult {
- exitCode: number;
- stdout: string;
- stderr: string;
-}
-
-export interface RunOpts {
- /** Server-side command timeout in seconds (default 60). */
- timeout?: number;
- env?: Record<string, string>;
- cwd?: string;
- /**
- * Abort the client-side wait for the result. The command keeps running on the
- * worker and stays retrievable by execId (exposed on the thrown error).
- */
- signal?: AbortSignal;
- /**
- * Max time to wait client-side for the command to finish, in milliseconds.
- * On expiry, run() throws an ExecTimeoutError but the command keeps running.
- */
- timeoutMs?: number;
-}
-
-/**
- * Thrown when run()'s client-side wait is aborted or times out. The command is
- * still running on the worker; re-poll or attach via execId to recover it.
- */
-export class ExecTimeoutError extends Error {
- constructor(public readonly execId: string, message: string) {
- super(message);
- this.name = "ExecTimeoutError";
- }
-}
-
-interface ExecRunHandle {
- execId?: string;
- running?: boolean;
- startedAt?: string;
- // Back-compat: a pre-async origin returns the full result synchronously.
- exitCode?: number;
- stdout?: string;
- stderr?: string;
-}
-
-interface ExecRunResult {
- running: boolean;
- waking?: boolean;
- exitCode?: number;
- stdout?: string;
- stderr?: string;
- truncated?: boolean;
- error?: string;
- // Timing breakdown (524 attribution), observable per-request.
- wakeMs?: number;
- createMs?: number;
- commandMs?: number;
-}
-
-/** Sleep that resolves early (does not reject) when the signal aborts. */
-function sleep(ms: number, signal?: AbortSignal): Promise<void> {
- return new Promise((resolve) => {
- if (signal?.aborted) return resolve();
- const onAbort = () => {
- clearTimeout(timer);
- signal?.removeEventListener("abort", onAbort);
- resolve();
- };
- const timer = setTimeout(() => {
- signal?.removeEventListener("abort", onAbort);
- resolve();
- }, ms);
- signal?.addEventListener("abort", onAbort);
- });
-}
-
-export interface ExecStartOpts {
- args?: string[];
- env?: Record<string, string>;
- cwd?: string;
- timeout?: number;
- maxRunAfterDisconnect?: number;
- onStdout?: (data: Uint8Array) => void;
- onStderr?: (data: Uint8Array) => void;
- onExit?: (exitCode: number) => void;
- onScrollbackEnd?: () => void;
-}
-
-export interface ExecAttachOpts {
- onStdout?: (data: Uint8Array) => void;
- onStderr?: (data: Uint8Array) => void;
- onExit?: (exitCode: number) => void;
- onScrollbackEnd?: () => void;
-}
-
-export interface ExecSessionInfo {
- sessionID: string;
- sandboxID: string;
- command: string;
- args: string[];
- running: boolean;
- exitCode?: number;
- startedAt: string;
- attachedClients: number;
-}
-
-export interface ExecSession {
- sessionId: string;
- /** Resolves with the exit code when the process exits. */
- done: Promise<number>;
- sendStdin(data: string | Uint8Array): void;
- kill(signal?: number): Promise<void>;
- close(): void;
-}
-
-export class Exec {
- constructor(
- private apiUrl: string,
- private apiKey: string,
- private sandboxId: string,
- private token: string = "",
- ) {}
-
- private get headers(): Record<string, string> {
- const h: Record<string, string> = { "Content-Type": "application/json" };
- if (this.token) {
- h["Authorization"] = `Bearer ${this.token}`;
- } else if (this.apiKey) {
- h["X-API-Key"] = this.apiKey;
- }
- return h;
- }
-
- async start(command: string, opts: ExecStartOpts = {}): Promise<ExecSession> {
- const body: Record<string, unknown> = { cmd: command };
- if (opts.args) body.args = opts.args;
- if (opts.env) body.envs = opts.env;
- if (opts.cwd) body.cwd = opts.cwd;
- if (opts.timeout != null) body.timeout = opts.timeout;
- if (opts.maxRunAfterDisconnect != null) body.maxRunAfterDisconnect = opts.maxRunAfterDisconnect;
-
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/exec`, {
- method: "POST",
- headers: this.headers,
- body: JSON.stringify(body),
- });
-
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to create exec session: ${resp.status} ${text}`);
- }
-
- const data = await resp.json();
- const sessionId: string = data.sessionID;
-
- return this.attach(sessionId, {
- onStdout: opts.onStdout,
- onStderr: opts.onStderr,
- onExit: opts.onExit,
- onScrollbackEnd: opts.onScrollbackEnd,
- });
- }
-
- async attach(sessionId: string, opts: ExecAttachOpts = {}): Promise<ExecSession> {
- const wsUrl = this.apiUrl
- .replace("http://", "ws://")
- .replace("https://", "wss://");
- // WebSocket can't set custom headers, so pass credentials as query params.
- // Prefer JWT token (direct worker access); fall back to API key (control plane).
- const authParam = this.token
- ? `?token=${encodeURIComponent(this.token)}`
- : this.apiKey
- ? `?api_key=${encodeURIComponent(this.apiKey)}`
- : "";
- const wsEndpoint = `${wsUrl}/sandboxes/${this.sandboxId}/exec/${sessionId}${authParam}`;
-
- const ws = await openWebSocket(wsEndpoint);
-
- let gotExit = false;
- let resolveDone: (code: number) => void;
- const done = new Promise<number>((resolve) => { resolveDone = resolve; });
-
- ws.onmessage = (event) => {
- const buf = new Uint8Array(event.data as ArrayBuffer);
- if (buf.length < 1) return;
-
- const streamId = buf[0];
- const payload = buf.slice(1);
-
- switch (streamId) {
- case 0x01: // stdout
- opts.onStdout?.(payload);
- break;
- case 0x02: // stderr
- opts.onStderr?.(payload);
- break;
- case 0x03: // exit
- gotExit = true;
- if (payload.length >= 4) {
- const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
- const exitCode = view.getInt32(0, false); // big-endian
- opts.onExit?.(exitCode);
- resolveDone(exitCode);
- } else {
- opts.onExit?.(0);
- resolveDone(0);
- }
- break;
- case 0x04: // scrollback_end
- opts.onScrollbackEnd?.();
- break;
- }
- };
-
- ws.onclose = () => {
- if (!gotExit) {
- opts.onExit?.(-1);
- resolveDone(-1);
- }
- };
-
- ws.onerror = () => {
- // Post-open errors are followed by onclose, which handles exit.
- };
-
- const exec = this;
-
- return {
- sessionId,
- done,
- sendStdin(data: string | Uint8Array): void {
- if (ws.readyState !== WebSocket.OPEN) return;
- const payload = typeof data === "string"
- ? new TextEncoder().encode(data)
- : data;
- const msg = new Uint8Array(1 + payload.length);
- msg[0] = 0x00; // stdin stream ID
- msg.set(payload, 1);
- ws.send(msg);
- },
- async kill(signal?: number): Promise<void> {
- await exec.kill(sessionId, signal);
- },
- close(): void {
- ws.close();
- },
- };
- }
-
- async list(): Promise<ExecSessionInfo[]> {
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/exec`, {
- headers: this.headers,
- });
-
- if (!resp.ok) {
- throw new Error(`Failed to list exec sessions: ${resp.status}`);
- }
-
- return resp.json();
- }
-
- async kill(sessionId: string, signal?: number): Promise<void> {
- const body: Record<string, unknown> = {};
- if (signal != null) body.signal = signal;
-
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/exec/${sessionId}/kill`, {
- method: "POST",
- headers: this.headers,
- body: JSON.stringify(body),
- });
-
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to kill exec session: ${resp.status} ${text}`);
- }
- }
-
- /**
- * Alias for {@link start}. Use when the intent is "run this command in the
- * background and observe it" rather than the more ambiguous "start". Same
- * options, same return type.
- */
- async background(command: string, opts: ExecStartOpts = {}): Promise<ExecSession> {
- return this.start(command, opts);
- }
-
- /**
- * Open a stateful shell session. Subsequent `.run()` calls share the same
- * bash process, so `cwd`, exported env vars, and shell functions persist
- * across calls — the ergonomics of a terminal tab.
- *
- * Backed by a long-running exec session running `bash --noprofile --norc`.
- * Foreground-only: concurrent `.run()` rejects. Use `exec.background()` for
- * fire-and-forget processes. If the user command calls `exit`, the shell
- * closes (same as closing a terminal tab) and subsequent `.run()` rejects.
- */
- async shell(opts: ShellOpts = {}): Promise<Shell> {
- let impl: ShellImpl | null = null;
- const session = await this.start("bash", {
- args: ["--noprofile", "--norc", "+m"],
- env: opts.env,
- cwd: opts.cwd,
- onStdout: (chunk) => impl?.onStdoutChunk(chunk),
- onStderr: (chunk) => impl?.onStderrChunk(chunk),
- onScrollbackEnd: () => impl?.onScrollbackEnd(),
- });
- impl = new ShellImpl(session);
- return impl;
- }
-
- /**
- * Re-attach to a shell session that was previously opened by `shell()` and
- * whose sessionId you've kept. Useful for revisiting a long-lived terminal
- * tab from a different process invocation.
- *
- * Assumes the shell is idle (no in-flight `.run()` from another client).
- * If another client has a run in flight, output will interleave and the
- * results are undefined — coordinate at the application level.
- */
- async reattachShell(sessionId: string): Promise<Shell> {
- let impl: ShellImpl | null = null;
- const session = await this.attach(sessionId, {
- onStdout: (chunk) => impl?.onStdoutChunk(chunk),
- onStderr: (chunk) => impl?.onStderrChunk(chunk),
- onScrollbackEnd: () => impl?.onScrollbackEnd(),
- });
- impl = new ShellImpl(session);
- return impl;
- }
-
- /**
- * Run a command and wait for it to finish, returning its result.
- *
- * Transparently async: POSTs to /exec/run-async (which returns a handle
- * immediately) then polls /exec/:execId/result until the command exits. Each
- * HTTP request is sub-second, so there is no proxy 524 regardless of how long
- * the command runs, and a dropped poll simply retries — the result persists
- * on the worker independent of the connection.
- *
- * Pass `timeoutMs`/`signal` to bound the client-side wait; on expiry an
- * {@link ExecTimeoutError} is thrown (carrying execId) while the command
- * keeps running. For live output instead of wait-for-result, use
- * {@link start}/{@link background} + {@link attach}.
- */
- async run(command: string, opts: RunOpts = {}): Promise<ProcessResult> {
- const body: Record<string, unknown> = {
- cmd: "sh",
- args: ["-c", command],
- };
- if (opts.env) body.envs = opts.env;
- if (opts.cwd) body.cwd = opts.cwd;
- body.timeout = opts.timeout != null ? opts.timeout : 60;
-
- let resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/exec/run-async`, {
- method: "POST",
- headers: this.headers,
- body: JSON.stringify(body),
- });
-
- // Graceful degradation: a server (CP or worker) that predates the async
- // endpoint returns 404. Fall back to the legacy synchronous /exec/run, which
- // returns the full result directly — what older SDKs always used. (A genuine
- // "sandbox not found" 404s here too and re-404s below, surfacing the same
- // error.)
- if (resp.status === 404) {
- resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/exec/run`, {
- method: "POST",
- headers: this.headers,
- body: JSON.stringify(body),
- });
- }
-
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to run command: ${resp.status} ${text}`);
- }
-
- const handle = (await resp.json()) as ExecRunHandle;
-
- // Legacy synchronous origin (the 404 fallback above) returns the full result
- // directly, with no execId to poll.
- if (handle.execId == null && handle.exitCode != null) {
- return {
- exitCode: handle.exitCode,
- stdout: handle.stdout ?? "",
- stderr: handle.stderr ?? "",
- };
- }
-
- const execId = handle.execId!;
- const deadline = opts.timeoutMs != null ? Date.now() + opts.timeoutMs : null;
- // First poll is short (the common fast command is already answered inline by
- // the server hold, so this ladder only runs for commands that outlive the
- // hold or for a waking box); a 50ms first delay reclaims up to ~150ms there
- // before backing off. Cheap insurance; the server /result long-poll absorbs
- // the extra request.
- let delay = 50;
- const maxDelay = 2000;
-
- for (;;) {
- if (opts.signal?.aborted) {
- throw new ExecTimeoutError(execId, `exec.run aborted; command still running (execId=${execId})`);
- }
- if (deadline != null && Date.now() >= deadline) {
- throw new ExecTimeoutError(execId, `exec.run timed out after ${opts.timeoutMs}ms; command still running (execId=${execId})`);
- }
-
- const result = await this.result(execId);
- if (!result.running) {
- if (result.error) {
- // Wake/restore or session creation failed on the worker.
- throw new Error(`exec.run failed: ${result.error}`);
- }
- return {
- exitCode: result.exitCode ?? 0,
- stdout: result.stdout ?? "",
- stderr: result.stderr ?? "",
- };
- }
-
- await sleep(delay, opts.signal);
- delay = Math.min(delay * 2, maxDelay);
- }
- }
-
- /** Fetch the current result of an exec session (poll target for run()). */
- private async result(execId: string): Promise<ExecRunResult> {
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/exec/${execId}/result`, {
- headers: this.headers,
- });
-
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to fetch exec result: ${resp.status} ${text}`);
- }
-
- return resp.json();
- }
-}
diff --git a/sdks/typescript/src/filesystem.ts b/sdks/typescript/src/filesystem.ts
deleted file mode 100644
index cba88e4d..00000000
--- a/sdks/typescript/src/filesystem.ts
+++ /dev/null
@@ -1,128 +0,0 @@
-import { apiFetch } from "./http2.js";
-export interface EntryInfo {
- name: string;
- isDir: boolean;
- path: string;
- size: number;
-}
-
-export class Filesystem {
- constructor(
- private apiUrl: string,
- private apiKey: string,
- private sandboxId: string,
- private token: string = "",
- ) {}
-
- private get headers(): Record<string, string> {
- // X-OSB-Async-Wake opts into the control plane's background-wake + 503
- // {waking} flow on a cold sandbox (wfetch retries it), instead of the inline
- // synchronous wake older SDKs get — which can hold the connection past the
- // edge's ~100s and 524. Harmless when the box is already warm.
- const h: Record<string, string> = { "X-OSB-Async-Wake": "1" };
- if (this.token) h["Authorization"] = `Bearer ${this.token}`;
- else if (this.apiKey) h["X-API-Key"] = this.apiKey;
- return h;
- }
-
- // wfetch transparently rides out a cold-start wake. If the sandbox is
- // hibernated, the control plane wakes it in the background and returns
- // 503 { waking: true } immediately (rather than restoring on the connection
- // and risking a proxy 524). We retry until the box is up. Bounded so a wake
- // that can't complete eventually surfaces the 503 instead of hanging forever.
- private async wfetch(url: string, init?: RequestInit): Promise<Response> {
- const deadline = Date.now() + 120_000;
- let delay = 500;
- for (;;) {
- const resp = await apiFetch(url, init);
- if (resp.status !== 503) return resp;
- let waking = false;
- try { waking = (await resp.clone().json())?.waking === true; } catch { /* not JSON */ }
- if (!waking || Date.now() >= deadline) return resp;
- await new Promise((r) => setTimeout(r, delay));
- delay = Math.min(delay * 2, 3000);
- }
- }
-
- async read(path: string): Promise<string> {
- const resp = await this.wfetch(
- `${this.apiUrl}/sandboxes/${this.sandboxId}/files?path=${encodeURIComponent(path)}`,
- { headers: this.headers },
- );
- if (!resp.ok) throw new Error(`Failed to read ${path}: ${resp.status}`);
- return resp.text();
- }
-
- async readBytes(path: string): Promise<Uint8Array> {
- const resp = await this.wfetch(
- `${this.apiUrl}/sandboxes/${this.sandboxId}/files?path=${encodeURIComponent(path)}`,
- { headers: this.headers },
- );
- if (!resp.ok) throw new Error(`Failed to read ${path}: ${resp.status}`);
- return new Uint8Array(await resp.arrayBuffer());
- }
-
- async write(path: string, content: string | Uint8Array | ReadableStream<Uint8Array>): Promise<void> {
- const isStream = content instanceof ReadableStream;
- const headers = { ...this.headers };
- if (isStream) {
- // A stream body can't be replayed across a 503-waking retry, so opt out of
- // the async-wake flow (drop X-OSB-Async-Wake): on a cold box the control
- // plane wakes synchronously on this connection, as it did before, rather
- // than returning a 503 we couldn't retry.
- delete headers["X-OSB-Async-Wake"];
- }
- const opts: RequestInit & Record<string, unknown> = {
- method: "PUT",
- headers,
- body: content as BodyInit,
- };
- // duplex: "half" is required for ReadableStream bodies in Node.js fetch,
- // but must NOT be set for Uint8Array/Buffer/string bodies.
- if (isStream) {
- opts.duplex = "half";
- }
- const url = `${this.apiUrl}/sandboxes/${this.sandboxId}/files?path=${encodeURIComponent(path)}`;
- // A stream body can't be replayed across a wake retry; string/bytes can.
- const resp = isStream ? await apiFetch(url, opts) : await this.wfetch(url, opts);
- if (!resp.ok) throw new Error(`Failed to write ${path}: ${resp.status}`);
- }
-
- async list(path: string = "/"): Promise<EntryInfo[]> {
- const resp = await this.wfetch(
- `${this.apiUrl}/sandboxes/${this.sandboxId}/files/list?path=${encodeURIComponent(path)}`,
- { headers: this.headers },
- );
- if (!resp.ok) throw new Error(`Failed to list ${path}: ${resp.status}`);
- const data = await resp.json();
- return data ?? [];
- }
-
- async makeDir(path: string): Promise<void> {
- const resp = await this.wfetch(
- `${this.apiUrl}/sandboxes/${this.sandboxId}/files/mkdir?path=${encodeURIComponent(path)}`,
- { method: "POST", headers: this.headers },
- );
- if (!resp.ok) throw new Error(`Failed to mkdir ${path}: ${resp.status}`);
- }
-
- async remove(path: string): Promise<void> {
- const resp = await this.wfetch(
- `${this.apiUrl}/sandboxes/${this.sandboxId}/files?path=${encodeURIComponent(path)}`,
- { method: "DELETE", headers: this.headers },
- );
- if (!resp.ok) throw new Error(`Failed to remove ${path}: ${resp.status}`);
- }
-
- async exists(path: string): Promise<boolean> {
- try {
- const resp = await this.wfetch(
- `${this.apiUrl}/sandboxes/${this.sandboxId}/files?path=${encodeURIComponent(path)}`,
- { headers: this.headers },
- );
- return resp.ok;
- } catch {
- return false;
- }
- }
-}
diff --git a/sdks/typescript/src/http2.ts b/sdks/typescript/src/http2.ts
deleted file mode 100644
index 0f6fb188..00000000
--- a/sdks/typescript/src/http2.ts
+++ /dev/null
@@ -1,171 +0,0 @@
-// The sandbox client's transport: an HTTP/2 connection pool it owns and
-// passes to every request it makes, plus the pre-warming of that pool.
-//
-// Client-owned, not global. The pool is an undici Agent handed to fetch as the
-// per-request `dispatcher`; the process's global dispatcher is never touched,
-// so an application's own fetch traffic, and any other library's, keeps its
-// own settings. Nothing here runs at import: the Agent is created on the
-// first request the sandbox client makes, and the pool is warmed on the
-// first `Sandbox.create` (or on an explicit `prewarmConnections` call from a
-// program that wants the cost paid before its timing loop).
-//
-// WHY a warm pool: under a concurrent burst, the dominant cost of a sandbox
-// create is not our API but opening ~100 TLS connections at once from one
-// process. Measured against prod from an in-region client, 100 concurrent
-// creates:
-//
-// cold connections min 686 median 716 p95 731 (flat: all pay the same)
-// warm connections min 390 median 412 p95 436 (-304ms, -42%)
-//
-// The flatness is the tell: every request in the burst pays the same fixed
-// cost, so it is admission/setup, not queueing behind our server. A raw TLS
-// test measured 100 concurrent handshakes at ~301ms (a single handshake is
-// ~27ms), and the server-side phases sum to ~20ms against a ~350ms
-// client-observed create. The ~300ms gap is the handshakes.
-//
-// WHAT: hold a pool of already-established connections open so a later burst
-// reuses them instead of negotiating TLS inside the latency it is measuring.
-// Two parts, both required:
-// - keepAliveTimeout well above undici's 4s default, so idle connections are
-// not reaped between phases of a workload.
-// - a low-rate keepalive ping, so the connections stay live across long idle
-// gaps. (An earlier version warmed connections and then idled 60s; they had
-// all been closed by then and the burst was SLOWER than cold, because
-// undici tried the dead sockets first. The warm pool must be kept alive.)
-//
-// `allowH2` negotiates per-origin via ALPN, so HTTP/1.1-only origins keep
-// working unchanged. Outside Node (browsers, Workers) there is no undici and
-// requests go to the global fetch untouched. Opt out of HTTP/2 with
-// OPENCOMPUTER_DISABLE_HTTP2=1, or of warming with
-// OPENCOMPUTER_DISABLE_PREWARM=1 / OPENCOMPUTER_PREWARM_CONNECTIONS=0.
-
-// How many connections to hold open, and how often to keep them alive.
-//
-// 48. Swept against prod from an IAD runner (4 vCPU) at burst-100, TTI p50:
-//
-// prewarm=100 23,990ms opening 100 TLS connections while 100 creates are
-// in flight starves the event loop; everything
-// unblocks together at the end
-// prewarm=0 624ms the opposite failure: undici marks an h2 session
-// busy per in-flight POST, so 100 concurrent creates
-// queue behind each other on one connection
-// prewarm=32 338ms
-// prewarm=48 301ms / 328ms (two runs)
-// prewarm=64 312ms
-//
-// The curve is flat between 32 and 64 (run-to-run variance on TTI p50 is
-// ~27ms) and turns back up past that because establishing the pool starts
-// costing more than it saves (424ms to open 64 versus 153ms for 48, paid
-// inside the measured window). 48 sits at the bottom with margin on both sides.
-const DEFAULT_PREWARM = 48;
-const KEEPALIVE_INTERVAL_MS = 30_000;
-// Above undici's 4s default so an idle connection survives between phases of a
-// workload; still far below any sane server-side idle close.
-const KEEP_ALIVE_TIMEOUT_MS = 600_000;
-
-const DEFAULT_API_URL = "https://app.opencomputer.dev";
-
-/** The non-standard init undici's fetch reads: which pool serves the request. */
-type DispatchedInit = RequestInit & { dispatcher?: unknown };
-
-const isNode = (): boolean => typeof process !== "undefined" && !!process.versions?.node;
-
-function intFromEnv(name: string, fallback: number): number {
- const raw = process.env?.[name];
- if (raw === undefined || raw === "") return fallback;
- const n = Number.parseInt(raw, 10);
- return Number.isFinite(n) && n >= 0 ? n : fallback;
-}
-
-let dispatcherPromise: Promise<unknown> | null = null;
-
-// The pool, created once on first use. Resolves to `undefined` outside Node,
-// when HTTP/2 is disabled, or when undici cannot be loaded; requests then use
-// the global fetch as it is. Never rejects.
-function dispatcher(): Promise<unknown> {
- if (dispatcherPromise) return dispatcherPromise;
- dispatcherPromise = (async () => {
- if (!isNode()) return undefined;
- if (process.env?.OPENCOMPUTER_DISABLE_HTTP2) return undefined;
- try {
- // Dynamic import so browser bundlers never pull undici into the graph.
- // undici is a hard dependency on Node (see package.json) so this resolves;
- // the catch keeps a stripped-down install on the default transport.
- const { Agent } = await import("undici");
- return new Agent({
- allowH2: true,
- keepAliveTimeout: KEEP_ALIVE_TIMEOUT_MS,
- keepAliveMaxTimeout: KEEP_ALIVE_TIMEOUT_MS,
- });
- } catch {
- return undefined;
- }
- })();
- return dispatcherPromise;
-}
-
-/**
- * fetch over the sandbox client's own connection pool. The global fetch is
- * called (so a test that replaces it sees every request) with the pool as the
- * per-request dispatcher; the global dispatcher is left alone.
- */
-export async function apiFetch(input: string | URL, init?: RequestInit): Promise<Response> {
- const pool = await dispatcher();
- if (!pool) return fetch(input, init);
- const dispatched: DispatchedInit = { ...init, dispatcher: pool };
- return fetch(input, dispatched);
-}
-
-let warmPromise: Promise<void> | null = null;
-let keepAliveTimer: ReturnType<typeof setInterval> | null = null;
-
-/**
- * Opens `count` connections to the API and keeps them alive, so a later burst
- * reuses them instead of paying ~300ms of concurrent TLS handshakes inside
- * its own latency. Idempotent, never rejects, and safe to call on a hot path:
- * `Sandbox.create` fires it on first use and callers may fire-and-forget it
- * earlier, before a timing loop.
- *
- * `apiUrl` defaults to `OPENCOMPUTER_API_URL` or `https://app.opencomputer.dev`.
- * The keepalive timer is unref'd: a warm pool is never the reason a process
- * stays alive.
- */
-export function prewarmConnections(apiUrl?: string, count?: number): Promise<void> {
- if (warmPromise) return warmPromise;
- warmPromise = (async () => {
- if (!isNode()) return;
- if (process.env?.OPENCOMPUTER_DISABLE_PREWARM) return;
- const n = count ?? intFromEnv("OPENCOMPUTER_PREWARM_CONNECTIONS", DEFAULT_PREWARM);
- if (n <= 0) return;
- const origin = (apiUrl ?? process.env?.OPENCOMPUTER_API_URL ?? DEFAULT_API_URL)
- .replace(/\/+$/, "")
- .replace(/\/api$/, "");
-
- // The warm MUST use the same method class as the traffic it is warming for.
- // undici refuses to multiplex non-idempotent requests over one HTTP/2
- // session (client-h2.js marks the client busy while any request is in
- // flight), so N concurrent POSTs need N separate connections, while N
- // concurrent GETs happily share ONE h2 session. Warming with GET therefore
- // warms a single connection and leaves a POST burst to pay ~100 handshakes
- // anyway. POST to a path that costs the server nothing (405/404 is fine;
- // only the socket matters).
- const ping = (): Promise<unknown> =>
- apiFetch(`${origin}/health`, { method: "POST" })
- .then((r) => r.arrayBuffer())
- .catch(() => undefined);
-
- // Fire them together: a connection is only created while another is still
- // busy, so the pings must overlap; sequential pings would reuse one socket.
- await Promise.all(Array.from({ length: n }, ping));
-
- if (keepAliveTimer === null) {
- keepAliveTimer = setInterval(() => {
- // Same reasoning as the initial warm: these must be concurrent, or the
- // pool collapses back to one connection between bursts.
- void Promise.all(Array.from({ length: n }, ping));
- }, KEEPALIVE_INTERVAL_MS);
- keepAliveTimer.unref?.();
- }
- })();
- return warmPromise;
-}
diff --git a/sdks/typescript/src/image.ts b/sdks/typescript/src/image.ts
deleted file mode 100644
index 31ef543d..00000000
--- a/sdks/typescript/src/image.ts
+++ /dev/null
@@ -1,179 +0,0 @@
-import { createHash } from "crypto";
-import { readFileSync, readdirSync, statSync } from "fs";
-import { join, relative } from "path";
-
-export interface ImageStep {
- type: "apt_install" | "pip_install" | "run" | "env" | "workdir" | "add_file" | "add_dir";
- args: Record<string, unknown>;
-}
-
-export interface ImageManifest {
- base: string;
- steps: ImageStep[];
- /** RAM (MB) for the build phase (apt/pip). Omit for the server default. Does
- * NOT pin the output — the server re-snapshots at the default 1 GB floor, and
- * you size the actual sandbox at create time via memoryMB. */
- builderMemoryMB?: number;
-}
-
-/**
- * Declarative image builder for OpenSandbox.
- *
- * Defines a reproducible sandbox environment via a fluent API.
- * Under the hood, the manifest is sent to the server which boots a base sandbox,
- * executes each step, checkpoints the result, and caches it by content hash.
- *
- * @example
- * ```typescript
- * const image = Image.base()
- * .aptInstall(['curl', 'git'])
- * .pipInstall(['requests', 'pandas'])
- * .addFile('/workspace/config.json', '{"key": "value"}')
- * .env({ PROJECT_ROOT: '/workspace' })
- * .workdir('/workspace')
- *
- * // Heavy build that should still fork down to the default floor:
- * const big = Image.base().aptInstall(['build-essential']).builderMemory(8192)
- *
- * // On-demand: cached by content hash
- * const sandbox = await Sandbox.create({ image })
- *
- * // Pre-built snapshot
- * const snapshots = new Snapshots()
- * await snapshots.create({ name: 'data-science', image })
- * ```
- */
-export class Image {
- private readonly manifest: ImageManifest;
-
- private constructor(manifest: ImageManifest) {
- this.manifest = manifest;
- }
-
- /**
- * Create a new image starting from the default OpenSandbox environment
- * (Ubuntu 22.04 with Python, Node.js, build tools, and common utilities).
- * Customize by chaining steps like `.aptInstall()`, `.pipInstall()`, `.runCommands()`, etc.
- */
- static base(): Image {
- return new Image({ base: "base", steps: [] });
- }
-
- /** Append a step, preserving base + memory settings. */
- private withStep(step: ImageStep): Image {
- return new Image({ ...this.manifest, steps: [...this.manifest.steps, step] });
- }
-
- /**
- * Install system packages via apt-get.
- */
- aptInstall(packages: string[]): Image {
- return this.withStep({ type: "apt_install", args: { packages } });
- }
-
- /**
- * Install Python packages via pip.
- */
- pipInstall(packages: string[]): Image {
- return this.withStep({ type: "pip_install", args: { packages } });
- }
-
- /**
- * Run one or more shell commands.
- */
- runCommands(...commands: string[]): Image {
- return this.withStep({ type: "run", args: { commands } });
- }
-
- /**
- * Set environment variables (written to /etc/environment).
- */
- env(vars: Record<string, string>): Image {
- return this.withStep({ type: "env", args: { vars } });
- }
-
- /**
- * Set the default working directory.
- */
- workdir(path: string): Image {
- return this.withStep({ type: "workdir", args: { path } });
- }
-
- /**
- * Add a file with inline content to the image.
- * @param remotePath - Absolute path inside the sandbox where the file will be written.
- * @param content - String content of the file.
- */
- addFile(remotePath: string, content: string): Image {
- const encoded = Buffer.from(content).toString("base64");
- return this.withStep({ type: "add_file", args: { path: remotePath, content: encoded, encoding: "base64" } });
- }
-
- /**
- * Add a local file into the image.
- * Reads the file from disk and embeds its content in the manifest.
- * @param localPath - Path to the file on the local machine.
- * @param remotePath - Absolute path inside the sandbox where the file will be written.
- */
- addLocalFile(localPath: string, remotePath: string): Image {
- const content = readFileSync(localPath);
- const encoded = content.toString("base64");
- return this.withStep({ type: "add_file", args: { path: remotePath, content: encoded, encoding: "base64" } });
- }
-
- /**
- * Add a local directory into the image.
- * Recursively reads all files and embeds them in the manifest.
- * @param localPath - Path to the directory on the local machine.
- * @param remotePath - Absolute path inside the sandbox where the directory will be created.
- */
- addLocalDir(localPath: string, remotePath: string): Image {
- const files: Array<{ relativePath: string; content: string }> = [];
- collectFiles(localPath, localPath, files);
- return this.withStep({ type: "add_dir", args: { path: remotePath, files } });
- }
-
- /**
- * Set the RAM (MB) for the build phase. Use this when a build OOMs at the
- * default 4 GB (e.g. heavy `apt`/`pip`/`npm`). Does not affect the resulting
- * image's memory — size the sandbox at create time via `memoryMB`.
- */
- builderMemory(mb: number): Image {
- return new Image({ ...this.manifest, builderMemoryMB: mb });
- }
-
- /**
- * Returns the manifest as a plain object (for JSON serialization).
- */
- toJSON(): ImageManifest {
- return this.manifest;
- }
-
- /**
- * Compute a deterministic content hash for caching. Memory knobs are resource
- * params, not image content, so they're excluded (matches the server).
- */
- cacheKey(): string {
- const canonical = JSON.stringify({ base: this.manifest.base, steps: this.manifest.steps });
- return createHash("sha256").update(canonical).digest("hex");
- }
-}
-
-function collectFiles(
- basePath: string,
- currentPath: string,
- out: Array<{ relativePath: string; content: string }>
-): void {
- for (const entry of readdirSync(currentPath)) {
- const full = join(currentPath, entry);
- const stat = statSync(full);
- if (stat.isDirectory()) {
- collectFiles(basePath, full, out);
- } else if (stat.isFile()) {
- out.push({
- relativePath: relative(basePath, full),
- content: readFileSync(full).toString("base64"),
- });
- }
- }
-}
diff --git a/sdks/typescript/src/index.ts b/sdks/typescript/src/index.ts
deleted file mode 100644
index 372256ee..00000000
--- a/sdks/typescript/src/index.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-// @opencomputer/sdk: the sandbox client. Node-only: the image builder reads
-// the filesystem and the transport pools HTTP/2 connections through undici.
-// Nothing runs at import; the connection pool is created on the first
-// request and warmed on the first `Sandbox.create`.
-//
-// The management API client for Serverless Agents lives on its own portable
-// subpath, `@opencomputer/sdk/agents`, whose module graph has no Node
-// dependency. It is not re-exported here so that importing it never drags
-// this graph along.
-
-export {
- Sandbox,
- ScalingLockedError,
- PlanLimitError,
- SandboxFamilyLimitError,
- type SandboxOpts,
- type CheckpointInfo,
- type CheckpointRetentionPolicy,
- type CreateCheckpointOptions,
- type PatchInfo,
- type PatchResult,
- type ScaleResult,
- type AutoscaleConfig,
- type AutoscaleStatus,
- type ScalingLockStatus,
- type AllowedHostsInfo,
- type SandboxKillOptions,
-} from "./sandbox.js";
-export {
- Browser,
- BrowserProfile,
- BrowserProfileAuthCheck,
- type BrowserCreateOpts,
- type BrowserData,
- type BrowserProfileAuthCheckCreateOpts,
- type BrowserProfileAuthCheckData,
- type BrowserProfileAuthCheckWaitOpts,
- type BrowserProfileCreateOpts,
- type BrowserProfileData
-} from "./browser.js";
-export { SandboxAgent, type SandboxAgentEvent, type SandboxAgentConfig, type SandboxAgentStartOpts, type SandboxAgentSession, type McpServerConfig } from "./agent.js";
-export { Filesystem, type EntryInfo } from "./filesystem.js";
-export { Exec, ExecTimeoutError, type ProcessResult, type RunOpts, type ExecSession, type ExecSessionInfo, type ExecStartOpts, type ExecAttachOpts } from "./exec.js";
-export { Mounts, type AddMountOpts, type MountInfo, type MountBackend } from "./mounts.js";
-export { type Shell, type ShellOpts, type ShellRunOpts, ShellBusyError, ShellClosedError } from "./shell.js";
-export { Pty, type PtySession, type PtyOpts } from "./pty.js";
-export { Templates, type TemplateInfo } from "./template.js";
-export { SDK_VERSION, SDK_VERSION_HEADER } from "./version.js";
-// Warm the sandbox client's connection pool ahead of a burst. `Sandbox.create`
-// does this on first use; a program that measures creates calls it earlier.
-export { prewarmConnections } from "./http2.js";
-export {
- Webhooks,
- WebhookDeliveries,
- type WebhooksOptions,
- type CreateWebhookParams,
- type CreateWebhookResult,
- type UpdateWebhookParams,
- type WebhookDestination,
- type WebhookDeliveryRecord,
- type WebhookDeliveryStatus,
- type WebhookTestResult,
- type ListPage,
- type SandboxWebhookDelivery,
- type SandboxLifecycleEvent,
- type SandboxLifecycleEventBase,
- type SandboxStopReason,
- type SandboxWebhookEventType,
-} from "./webhooks.js";
-export {
- verifyWebhook,
- WebhookVerificationError,
- type WebhookDelivery,
- type WebhookEvent,
- type VerifyWebhookOptions,
-} from "./verify-webhook.js";
-export { SecretStore, type SecretStoreInfo, type SecretEntryInfo, type SecretStoreOpts, type CreateSecretStoreOpts, type UpdateSecretStoreOpts } from "./project.js";
-export {
- Usage,
- Tags,
- type UsageSandboxItem,
- type UsageTagItem,
- type UsageTotals,
- type UsageUntaggedBucket,
- type UsageBySandboxResponse,
- type UsageByTagResponse,
- type UsageQueryOpts,
- type UsageFilterMap,
- type SandboxUsageResponse,
- type SandboxUsagePoint,
- type SandboxUsageTotals,
- type TagKeyInfo,
-} from "./usage.js";
-// Node.js-only modules (use crypto, fs, path) — also exported via "@opencomputer/sdk/node".
-// The Image builder and the Snapshots client are exported as VALUES, not only
-// as types. Both were type-only, so `import { Image } from "@opencomputer/sdk"`
-// — which the Image reference documents — failed at runtime with "does not
-// provide an export named 'Image'", and there was no supported way to define a
-// template through the SDK at all.
-export { Image } from "./image.js";
-export type { ImageManifest, ImageStep } from "./image.js";
-export { Snapshots } from "./snapshot.js";
-export type { SnapshotInfo, CreateSnapshotOpts, WaitForReadyOpts } from "./snapshot.js";
diff --git a/sdks/typescript/src/mounts.ts b/sdks/typescript/src/mounts.ts
deleted file mode 100644
index 7066dbd0..00000000
--- a/sdks/typescript/src/mounts.ts
+++ /dev/null
@@ -1,186 +0,0 @@
-import { apiFetch } from "./http2.js";
-/**
- * Backends supported by the typed `creds` shape. For any backend not in this
- * list (or for advanced rclone tuning), pass `rcloneConfig` instead — the raw
- * string is dropped into the in-VM config file unchanged.
- */
-export type MountBackend =
- | "s3"
- | "gcs"
- | "azureblob"
- | "sftp"
- | "webdav"
- | "dropbox";
-
-/**
- * rclone-driver mount — the easy path. Wraps any of rclone's ~40 backends
- * behind a simple remote+creds shape.
- */
-export interface RcloneMountOpts {
- /** Absolute path inside the sandbox where the remote will be mounted. */
- path: string;
- /** Driver. Defaults to `"rclone"`. */
- driver?: "rclone";
- /** rclone remote spec — `<name>:<path>` (e.g. `"s3:my-bucket/prefix"`). */
- remote: string;
- /**
- * Backend type. Determines how `creds` are templated into the rclone
- * config. Omit and pass `rcloneConfig` directly for backends not listed.
- */
- backend?: MountBackend;
- /**
- * Backend-specific credential / config keys (rclone config field names —
- * e.g. for S3: `access_key_id`, `secret_access_key`, `region`).
- *
- * Creds are written to a tmpfs file inside the VM (mode 0600) and never
- * persisted on the worker.
- */
- creds?: Record<string, string>;
- /**
- * Raw rclone config to use verbatim. Overrides `backend`+`creds`. Useful
- * for backends not in the typed list, or for advanced tuning.
- */
- rcloneConfig?: string;
- /** Default `true`. Object-store FUSE mounts have well-known write footguns. */
- readOnly?: boolean;
- /** Extra args appended to `rclone mount` (e.g. `["--dir-cache-time", "1m"]`). */
- mountOptions?: string[];
-}
-
-/**
- * Command-driver mount — run your own FUSE daemon / mount command. Use this
- * when you already have a FUSE-ready filesystem (your own VFS, gcsfuse, s3fs,
- * …) and don't want rclone as a middle layer. The platform manages the
- * mountpoint, env/secret injection, and teardown; your command establishes the
- * mount.
- */
-export interface CommandMountOpts {
- /** Absolute path inside the sandbox where the filesystem will be mounted. */
- path: string;
- driver: "command";
- /**
- * argv for the FUSE daemon / mount command. Any `"{mountpoint}"` token is
- * replaced with `path` (so you can template where the mount lands).
- * @example ["gcsfuse", "my-bucket", "{mountpoint}"]
- */
- command: string[];
- /** Env vars for the command. Returned by `list()`. */
- env?: Record<string, string>;
- /**
- * Secret env vars — injected into the daemon's process environment (never
- * the command line, so they don't leak via `ps`), and never recorded or
- * returned by `list()`.
- */
- secrets?: Record<string, string>;
- /**
- * Advisory for this driver — your command must honor it. Also exported to
- * the daemon as `OC_MOUNT_READONLY=1`. Default `true`.
- */
- readOnly?: boolean;
-}
-
-export type AddMountOpts = RcloneMountOpts | CommandMountOpts;
-
-export interface MountInfo {
- path: string;
- driver: "rclone" | "command";
- readOnly: boolean;
- /** rclone driver: the remote spec. */
- remote?: string;
- /** rclone driver: the backend type. */
- backend?: string;
- /**
- * rclone driver: rclone version inside the sandbox at add time (e.g.
- * `"v1.65.2"`). Captured for ops triage — rclone is baked into the rootfs,
- * so different sandboxes may carry different versions.
- */
- rcloneVersion?: string;
- /** command driver: the resolved argv. */
- command?: string[];
- /** command driver: non-secret env vars (secrets are omitted). */
- env?: Record<string, string>;
-}
-
-export class Mounts {
- constructor(
- private apiUrl: string,
- private apiKey: string,
- private sandboxId: string,
- private token: string = "",
- ) {}
-
- private get headers(): Record<string, string> {
- if (this.token) return { "Authorization": `Bearer ${this.token}` };
- return this.apiKey ? { "X-API-Key": this.apiKey } : {};
- }
-
- /**
- * Mount a filesystem inside the sandbox. Two drivers:
- *
- * - `rclone` (default): wrap any rclone backend behind remote+creds.
- * - `command`: run your own FUSE daemon / mount command.
- *
- * @example rclone driver
- * ```ts
- * await sandbox.mounts.add({
- * path: "/mnt/data",
- * remote: "s3:my-bucket",
- * backend: "s3",
- * creds: { access_key_id: "...", secret_access_key: "...", region: "us-east-1" },
- * });
- * ```
- *
- * @example command driver (bring your own FUSE)
- * ```ts
- * await sandbox.mounts.add({
- * path: "/mnt/data",
- * driver: "command",
- * command: ["my-vfs-fuse", "--bucket", "gs://my-bucket", "{mountpoint}"],
- * secrets: { GOOGLE_APPLICATION_CREDENTIALS_JSON: saJson },
- * });
- * ```
- */
- async add(opts: AddMountOpts): Promise<MountInfo> {
- const resp = await apiFetch(
- `${this.apiUrl}/sandboxes/${this.sandboxId}/mounts`,
- {
- method: "POST",
- headers: { "Content-Type": "application/json", ...this.headers },
- body: JSON.stringify(opts),
- },
- );
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to add mount: ${resp.status} ${text}`);
- }
- return resp.json();
- }
-
- /**
- * List the mounts this worker is tracking for the sandbox. Returns empty
- * after hibernate/wake — re-issue `add()` for any mounts you need back.
- */
- async list(): Promise<MountInfo[]> {
- const resp = await apiFetch(
- `${this.apiUrl}/sandboxes/${this.sandboxId}/mounts`,
- { headers: this.headers },
- );
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to list mounts: ${resp.status} ${text}`);
- }
- return resp.json();
- }
-
- /** Unmount a path previously passed to `add()`. No-op if not mounted. */
- async remove(path: string): Promise<void> {
- const resp = await apiFetch(
- `${this.apiUrl}/sandboxes/${this.sandboxId}/mounts?path=${encodeURIComponent(path)}`,
- { method: "DELETE", headers: this.headers },
- );
- if (!resp.ok && resp.status !== 404) {
- const text = await resp.text();
- throw new Error(`Failed to remove mount: ${resp.status} ${text}`);
- }
- }
-}
diff --git a/sdks/typescript/src/node.ts b/sdks/typescript/src/node.ts
deleted file mode 100644
index 31b5e66b..00000000
--- a/sdks/typescript/src/node.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export * from "./index.js";
-export { Image, type ImageManifest, type ImageStep } from "./image.js";
-export { Snapshots, type SnapshotInfo, type CreateSnapshotOpts } from "./snapshot.js";
diff --git a/sdks/typescript/src/normalize.test.ts b/sdks/typescript/src/normalize.test.ts
deleted file mode 100644
index 97c9a443..00000000
--- a/sdks/typescript/src/normalize.test.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { normalize } from "./normalize.js";
-
-describe("normalize (API response → idiomatic TS)", () => {
- it("camelCases nested keys — last_turn → lastTurn, and the field is `id`", () => {
- const out = normalize<{ lastTurn?: { id?: string; yieldReason?: string; resultEventId?: string } }>({
- last_turn: { id: "trn_1", yield_reason: "completed", result_event_id: "evt_9" },
- });
- expect(out.lastTurn?.id).toBe("trn_1");
- expect(out.lastTurn?.yieldReason).toBe("completed");
- expect(out.lastTurn?.resultEventId).toBe("evt_9");
- });
-
- it("coerces known stringified-bigint numerics", () => {
- const out = normalize<{ seq?: number; head?: number }>({ seq: "12", head: "3" });
- expect(out.seq).toBe(12);
- expect(out.head).toBe(3);
- });
-
- it("normalizes the canonical nested usage shape", () => {
- const out = normalize<{
- usage?: {
- activeSeconds?: number;
- reportedTurns?: number;
- complete?: boolean;
- totalCostUsd?: number;
- cacheReadInputTokens?: number;
- };
- }>({
- usage: {
- active_seconds: 12,
- reported_turns: 2,
- complete: false,
- total_cost_usd: 0.42,
- cache_read_input_tokens: 17,
- },
- });
-
- expect(out.usage).toEqual({
- activeSeconds: 12,
- reportedTurns: 2,
- complete: false,
- totalCostUsd: 0.42,
- cacheReadInputTokens: 17,
- });
- });
-
- it("passes `metadata` through verbatim — opaque, inner keys untouched", () => {
- const out = normalize<{ metadata?: Record<string, unknown> }>({
- metadata: { pull_number: 42, owner_repo: "acme/widgets", nested: { keep_me: true } },
- });
- // Caller's routing JSON must round-trip exactly as set (no snake→camel mangling).
- expect(out.metadata).toEqual({ pull_number: 42, owner_repo: "acme/widgets", nested: { keep_me: true } });
- });
-
- it("passes event refs through verbatim — opaque, inner keys untouched", () => {
- const out = normalize<{ refs?: Record<string, unknown> }>({
- refs: { pull_number: 42, owner_repo: "acme/widgets", nested: { keep_me: true } },
- });
- expect(out.refs).toEqual({ pull_number: 42, owner_repo: "acme/widgets", nested: { keep_me: true } });
- });
-
- it("passes manifest vars through verbatim", () => {
- const out = normalize<{ vars?: Record<string, unknown> }>({
- vars: { api_url: "https://example.test", nested_value: { keep_me: true } },
- });
- expect(out.vars).toEqual({ api_url: "https://example.test", nested_value: { keep_me: true } });
- });
-});
diff --git a/sdks/typescript/src/normalize.ts b/sdks/typescript/src/normalize.ts
deleted file mode 100644
index b93253cc..00000000
--- a/sdks/typescript/src/normalize.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-// Normalize a delivered webhook envelope to idiomatic TS: snake_case keys → camelCase,
-// and a known set of numeric fields that the wire serializes as strings (bigints) →
-// numbers. Opaque subtrees are passed through untouched: `raw` (source-specific adapter
-// data), `metadata`, `refs`, and `vars` (caller/source-owned maps — must round-trip
-// verbatim, keys included). Used by `verifyWebhook` only; the management client speaks
-// camelCase on the wire and needs no normalization.
-
-const NUMERIC = new Set([
- "seq", "head", "inputCursor", "inputFromSeq", "inputToSeq", "exitCode", "bytes", "port",
- "numTurns", "revision", "tokens", "turnSeconds", "turns",
- "attempts", "responseCode",
-]);
-
-const camel = (k: string): string => k.replace(/_([a-z0-9])/g, (_, c: string) => c.toUpperCase());
-
-export function normalize<T = any>(value: unknown): T {
- if (Array.isArray(value)) return value.map((v) => normalize(v)) as T;
- if (value && typeof value === "object") {
- const out: Record<string, unknown> = {};
- for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
- const ck = camel(k);
- if (ck === "raw" || ck === "metadata" || ck === "refs" || ck === "vars") { out[ck] = v; continue; } // opaque: verbatim, keys untouched
- let nv: unknown = normalize(v);
- if (NUMERIC.has(ck) && typeof nv === "string" && nv !== "" && !Number.isNaN(Number(nv))) {
- nv = Number(nv);
- }
- out[ck] = nv;
- }
- return out as T;
- }
- return value as T;
-}
diff --git a/sdks/typescript/src/project.ts b/sdks/typescript/src/project.ts
deleted file mode 100644
index fe56a85a..00000000
--- a/sdks/typescript/src/project.ts
+++ /dev/null
@@ -1,173 +0,0 @@
-import { apiFetch } from "./http2.js";
-function resolveApiUrl(url: string): string {
- const base = url.replace(/\/+$/, "");
- return base.endsWith("/api") ? base : `${base}/api`;
-}
-
-export interface SecretStoreInfo {
- id: string;
- orgId: string;
- name: string;
- egressAllowlist: string[];
- createdAt: string;
- updatedAt: string;
-}
-
-export interface SecretEntryInfo {
- id: string;
- storeId: string;
- name: string;
- allowedHosts: string[];
- createdAt: string;
- updatedAt: string;
-}
-
-export interface SecretStoreOpts {
- apiKey?: string;
- apiUrl?: string;
-}
-
-export interface CreateSecretStoreOpts extends SecretStoreOpts {
- name: string;
- egressAllowlist?: string[];
-}
-
-export interface UpdateSecretStoreOpts extends SecretStoreOpts {
- name?: string;
- egressAllowlist?: string[];
-}
-
-function getConfig(opts: SecretStoreOpts) {
- const apiUrl = resolveApiUrl(opts.apiUrl ?? process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev");
- const apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";
- const headers: Record<string, string> = { "Content-Type": "application/json" };
- if (apiKey) headers["X-API-Key"] = apiKey;
- return { apiUrl, headers };
-}
-
-export class SecretStore {
- private constructor() {}
-
- static async create(opts: CreateSecretStoreOpts): Promise<SecretStoreInfo> {
- const { apiUrl, headers } = getConfig(opts);
-
- const body: Record<string, unknown> = { name: opts.name };
- if (opts.egressAllowlist) body.egressAllowlist = opts.egressAllowlist;
-
- const resp = await apiFetch(`${apiUrl}/secret-stores`, {
- method: "POST",
- headers,
- body: JSON.stringify(body),
- });
-
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to create secret store: ${resp.status} ${text}`);
- }
-
- return resp.json();
- }
-
- static async list(opts: SecretStoreOpts = {}): Promise<SecretStoreInfo[]> {
- const { apiUrl, headers } = getConfig(opts);
-
- const resp = await apiFetch(`${apiUrl}/secret-stores`, { headers });
-
- if (!resp.ok) {
- throw new Error(`Failed to list secret stores: ${resp.status}`);
- }
-
- return resp.json();
- }
-
- static async get(storeId: string, opts: SecretStoreOpts = {}): Promise<SecretStoreInfo> {
- const { apiUrl, headers } = getConfig(opts);
-
- const resp = await apiFetch(`${apiUrl}/secret-stores/${storeId}`, { headers });
-
- if (!resp.ok) {
- throw new Error(`Failed to get secret store: ${resp.status}`);
- }
-
- return resp.json();
- }
-
- static async update(storeId: string, opts: UpdateSecretStoreOpts): Promise<SecretStoreInfo> {
- const { apiUrl, headers } = getConfig(opts);
-
- const body: Record<string, unknown> = {};
- if (opts.name) body.name = opts.name;
- if (opts.egressAllowlist) body.egressAllowlist = opts.egressAllowlist;
-
- const resp = await apiFetch(`${apiUrl}/secret-stores/${storeId}`, {
- method: "PUT",
- headers,
- body: JSON.stringify(body),
- });
-
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to update secret store: ${resp.status} ${text}`);
- }
-
- return resp.json();
- }
-
- static async delete(storeId: string, opts: SecretStoreOpts = {}): Promise<void> {
- const { apiUrl, headers } = getConfig(opts);
-
- const resp = await apiFetch(`${apiUrl}/secret-stores/${storeId}`, {
- method: "DELETE",
- headers,
- });
-
- if (!resp.ok) {
- throw new Error(`Failed to delete secret store: ${resp.status}`);
- }
- }
-
- // ── Secret Entries ──────────────────────────────────────────────────────
-
- static async setSecret(storeId: string, name: string, value: string, opts: SecretStoreOpts & { allowedHosts?: string[] } = {}): Promise<void> {
- const { apiUrl, headers } = getConfig(opts);
-
- const body: Record<string, unknown> = { value };
- if (opts.allowedHosts) body.allowedHosts = opts.allowedHosts;
-
- const resp = await apiFetch(`${apiUrl}/secret-stores/${storeId}/secrets/${name}`, {
- method: "PUT",
- headers,
- body: JSON.stringify(body),
- });
-
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to set secret: ${resp.status} ${text}`);
- }
- }
-
- static async deleteSecret(storeId: string, name: string, opts: SecretStoreOpts = {}): Promise<void> {
- const { apiUrl, headers } = getConfig(opts);
-
- const resp = await apiFetch(`${apiUrl}/secret-stores/${storeId}/secrets/${name}`, {
- method: "DELETE",
- headers,
- });
-
- if (!resp.ok && resp.status !== 404) {
- throw new Error(`Failed to delete secret: ${resp.status}`);
- }
- }
-
- static async listSecrets(storeId: string, opts: SecretStoreOpts = {}): Promise<SecretEntryInfo[]> {
- const { apiUrl, headers } = getConfig(opts);
-
- const resp = await apiFetch(`${apiUrl}/secret-stores/${storeId}/secrets`, { headers });
-
- if (!resp.ok) {
- throw new Error(`Failed to list secrets: ${resp.status}`);
- }
-
- return resp.json();
- }
-}
diff --git a/sdks/typescript/src/pty.ts b/sdks/typescript/src/pty.ts
deleted file mode 100644
index ac004f68..00000000
--- a/sdks/typescript/src/pty.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-import { apiFetch } from "./http2.js";
-import { openWebSocket } from "./websocket.js";
-export interface PtyOpts {
- cols?: number;
- rows?: number;
- onOutput?: (data: Uint8Array) => void;
-}
-
-export interface PtySession {
- sessionId: string;
- send(data: string | Uint8Array): void;
- close(): void;
-}
-
-export class Pty {
- constructor(
- private apiUrl: string,
- private apiKey: string,
- private sandboxId: string,
- private token: string = "",
- ) {}
-
- private get headers(): Record<string, string> {
- const h: Record<string, string> = { "Content-Type": "application/json" };
- if (this.token) {
- h["Authorization"] = `Bearer ${this.token}`;
- } else if (this.apiKey) {
- h["X-API-Key"] = this.apiKey;
- }
- return h;
- }
-
- async create(opts: PtyOpts = {}): Promise<PtySession> {
- // Create session via REST
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/pty`, {
- method: "POST",
- headers: this.headers,
- body: JSON.stringify({
- cols: opts.cols ?? 80,
- rows: opts.rows ?? 24,
- }),
- });
-
- if (!resp.ok) {
- throw new Error(`Failed to create PTY: ${resp.status}`);
- }
-
- const data = await resp.json();
- const sessionId: string = data.sessionID;
-
- // Connect via WebSocket
- const wsUrl = this.apiUrl
- .replace("http://", "ws://")
- .replace("https://", "wss://");
- const authParam = this.token
- ? `?token=${encodeURIComponent(this.token)}`
- : this.apiKey
- ? `?api_key=${encodeURIComponent(this.apiKey)}`
- : "";
- const wsEndpoint = `${wsUrl}/sandboxes/${this.sandboxId}/pty/${sessionId}${authParam}`;
-
- const ws = await openWebSocket(wsEndpoint);
-
- if (opts.onOutput) {
- const onOutput = opts.onOutput;
- ws.onmessage = (event) => {
- const data = event.data instanceof ArrayBuffer
- ? new Uint8Array(event.data)
- : new TextEncoder().encode(event.data as string);
- onOutput(data);
- };
- }
-
- return {
- sessionId,
- send(data: string | Uint8Array): void {
- if (typeof data === "string") {
- ws.send(data);
- } else {
- ws.send(data);
- }
- },
- close(): void {
- ws.close();
- },
- };
- }
-}
diff --git a/sdks/typescript/src/retry.ts b/sdks/typescript/src/retry.ts
deleted file mode 100644
index c017eed3..00000000
--- a/sdks/typescript/src/retry.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { apiFetch } from "./http2.js";
-// Transient-failure retry for SDK HTTP calls.
-//
-// One retry, short fixed delay, and a deliberately narrow predicate: network
-// errors (fetch rejected — DNS, reset, TLS) and proxy-level 5xx (502/503/504,
-// plus 500) that almost always mean the request never reached — or never
-// finished in — the origin handler. Anything else (4xx, app-level errors)
-// surfaces immediately. Callers on non-idempotent paths (exec submission)
-// still qualify: a 502/503/504 is emitted by an intermediary before or
-// instead of origin processing, so re-sending does not double-run work in
-// any case we have observed; genuinely ambiguous statuses are not retried.
-
-const RETRY_STATUSES = new Set([500, 502, 503, 504]);
-const RETRY_DELAY_MS = 250;
-
-function sleep(ms: number): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, ms));
-}
-
-/**
- * apiFetch() with a single retry on transient transport failures.
- * Non-retryable responses (including 4xx) are returned as-is for the caller's
- * normal error handling.
- */
-export async function transientFetch(url: string, init?: RequestInit): Promise<Response> {
- try {
- const resp = await apiFetch(url, init);
- if (!RETRY_STATUSES.has(resp.status)) return resp;
- } catch {
- // network-level failure — retry below
- }
- await sleep(RETRY_DELAY_MS);
- return apiFetch(url, init);
-}
diff --git a/sdks/typescript/src/sandbox.test.ts b/sdks/typescript/src/sandbox.test.ts
deleted file mode 100644
index 5a604c43..00000000
--- a/sdks/typescript/src/sandbox.test.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
-import { Sandbox } from "./sandbox.js";
-
-describe("Sandbox checkpoint requests", () => {
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
- it("sends delete_oldest retention policy when creating a checkpoint", async () => {
- const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(
- new Response(JSON.stringify({
- id: "cp_1",
- sandboxId: "sb_1",
- orgId: "org_1",
- name: "autosave",
- sandboxConfig: {},
- status: "processing",
- sizeBytes: 0,
- createdAt: "2026-01-01T00:00:00Z",
- }), { status: 201, headers: { "content-type": "application/json" } }),
- );
-
- const sandbox = Object.create(Sandbox.prototype) as Sandbox;
- const sandboxState = sandbox as unknown as Record<string, unknown>;
- sandboxState.apiUrl = "https://api.example.test/api";
- sandboxState.apiKey = "osb_test";
- sandboxState.sandboxId = "sb_1";
-
- await sandbox.createCheckpoint("autosave", {
- retentionPolicy: { mode: "delete_oldest", maxCount: 3 },
- });
-
- const [, init] = fetchMock.mock.calls[0];
- expect(JSON.parse(init?.body as string)).toEqual({
- name: "autosave",
- retentionPolicy: { mode: "delete_oldest", maxCount: 3 },
- });
- });
-
- it("preserves explicit false for disk-only promotion override", async () => {
- const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(
- new Response(JSON.stringify({
- id: "cp_1",
- sandboxId: "sb_1",
- orgId: "org_1",
- name: "manual",
- sandboxConfig: {},
- kind: "disk_only",
- status: "processing",
- sizeBytes: 0,
- createdAt: "2026-01-01T00:00:00Z",
- }), { status: 201, headers: { "content-type": "application/json" } }),
- );
-
- const sandbox = Object.create(Sandbox.prototype) as Sandbox;
- const sandboxState = sandbox as unknown as Record<string, unknown>;
- sandboxState.apiUrl = "https://api.example.test/api";
- sandboxState.apiKey = "osb_test";
- sandboxState.sandboxId = "sb_1";
-
- await sandbox.createCheckpoint("manual", {
- kind: "disk_only",
- promoteToFull: false,
- });
-
- const [, init] = fetchMock.mock.calls[0];
- expect(JSON.parse(init?.body as string)).toEqual({
- name: "manual",
- kind: "disk_only",
- promoteToFull: false,
- });
- });
-});
-
-describe("Sandbox.destroy", () => {
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
- // The bug this exists to prevent: connect()+kill() reads a 404 from the GET
- // as "already gone" and never issues the DELETE, leaking a live sandbox while
- // reporting success. destroy() must go straight to the DELETE.
- it("issues DELETE without a preceding GET", async () => {
- const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(
- new Response(null, { status: 204 }),
- );
-
- await Sandbox.destroy("sb_1", { apiUrl: "https://api.example.test/api", apiKey: "osb_test" });
-
- expect(fetchMock).toHaveBeenCalledTimes(1);
- const [url, init] = fetchMock.mock.calls[0];
- expect(String(url)).toBe("https://api.example.test/api/sandboxes/sb_1");
- expect(init?.method).toBe("DELETE");
- });
-
- // A 404 from the DELETE means the sandbox really is gone, which is the
- // caller's desired end state.
- it("treats a 404 from the DELETE as success", async () => {
- vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(null, { status: 404 }));
-
- await expect(
- Sandbox.destroy("sb_missing", { apiUrl: "https://api.example.test/api", apiKey: "osb_test" }),
- ).resolves.toBeUndefined();
- });
-
- // Anything else must throw: a delete that did not happen must never look
- // like one that did.
- it("throws when the delete genuinely failed", async () => {
- vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(null, { status: 500 }));
-
- await expect(
- Sandbox.destroy("sb_1", { apiUrl: "https://api.example.test/api", apiKey: "osb_test" }),
- ).rejects.toThrow(/Failed to destroy sandbox sb_1: 500/);
- });
-
- it("forwards deleteSecretStore", async () => {
- const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(null, { status: 204 }));
-
- await Sandbox.destroy("sb_1", {
- apiUrl: "https://api.example.test/api",
- apiKey: "osb_test",
- deleteSecretStore: true,
- });
-
- expect(String(fetchMock.mock.calls[0][0])).toBe(
- "https://api.example.test/api/sandboxes/sb_1?deleteSecretStore=true",
- );
- });
-});
diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.ts
deleted file mode 100644
index 0f0f5985..00000000
--- a/sdks/typescript/src/sandbox.ts
+++ /dev/null
@@ -1,1064 +0,0 @@
-import { SandboxAgent } from "./agent.js";
-import { sdkVersionHeaders } from "./version.js";
-import { apiFetch, prewarmConnections } from "./http2.js";
-import { Filesystem } from "./filesystem.js";
-import { Exec } from "./exec.js";
-import { Mounts } from "./mounts.js";
-import { Pty } from "./pty.js";
-import { Image } from "./image.js";
-import { parseSSEStream } from "./sse.js";
-
-function resolveApiUrl(url: string): string {
- const base = url.replace(/\/+$/, "");
- return base.endsWith("/api") ? base : `${base}/api`;
-}
-
-
-export interface SandboxOpts {
- template?: string;
- /** Create a Burst Sandbox. Disk is preserved across infrastructure restarts; processes may restart. */
- burst?: boolean;
- /** Internal/legacy placement family. Prefer `burst: true` for public API usage. */
- sandboxFamily?: "spot";
- /**
- * Idle timeout in seconds after which the sandbox auto-hibernates.
- * Default: `0` (persistent — never auto-hibernate).
- */
- timeout?: number;
- apiKey?: string;
- apiUrl?: string;
- envs?: Record<string, string>;
- metadata?: Record<string, string>;
- cpuCount?: number;
- memoryMB?: number;
- /**
- * Workspace disk size in MB (default 20480 = 20GB). Any additional GB above
- * 20GB is metered at a per-second rate comparable to EBS gp3.
- *
- * Closed beta: requests above 20GB require the org's `max_disk_mb` to be
- * raised. Contact us: https://cal.com/team/digger/opencomputer-founder-chat
- */
- diskMB?: number;
- /** Secret store name — resolves encrypted secrets and egress allowlist. */
- secretStore?: string;
- /** Declarative image definition. The server builds and caches it as a checkpoint. */
- image?: Image;
- /** Name of a pre-built snapshot to create the sandbox from. */
- snapshot?: string;
- /** Callback for build log streaming when using `image`. Called with each build step message. */
- onBuildLog?: (log: string) => void;
- /**
- * Require a bearer token on the sandbox's preview URLs.
- *
- * When set, every request to `https://sb-{id}-p{port}.<domain>` must include
- * the token in an `Authorization: Bearer <token>` or `X-OC-Preview-Token`
- * header. The check happens at the edge before traffic reaches the VM —
- * bad tokens never touch your sandbox.
- *
- * Pass `{ token: "auto" }` (or omit `token`) to have the server generate a
- * 256-bit random token; pass an explicit string (≥16 chars) to bring your
- * own. The plaintext is returned exactly once on the create response as
- * `previewAuthToken`. Use `Sandbox.rotatePreviewAuthToken()` to issue a new
- * one (the old one stops working immediately).
- */
- previewAuth?: { scheme?: "bearer"; token?: "auto" | string };
- /**
- * Register webhook destination(s) for this sandbox's lifecycle events, atomically with
- * create — so you receive `sandbox.created` / `sandbox.ready`, which fire before a separate
- * `webhooks.create` call could know the sandbox id. Each is pinned to this sandbox and
- * receives its full lifecycle. A generated signing secret is returned once on the create
- * response (`webhooks[].secret`). For fleet-wide subscriptions, use a standalone org
- * destination (`new Webhooks().create(...)`) instead.
- */
- webhooks?: Array<{ url: string; secret?: string; eventTypes?: string[] }>;
-}
-
-interface SandboxData {
- sandboxID: string;
- status: string;
- templateID?: string;
- sandboxFamily?: string;
- burst?: boolean;
- connectURL?: string;
- token?: string;
- sandboxDomain?: string;
- /**
- * RFC3339 instant at which the provider will destroy this sandbox's host.
- *
- * Present only when the runtime imposes one. A sandbox on the QEMU fleet has
- * no provider-imposed lifetime and omits the field entirely, so its presence
- * is also how you tell which runtime served a create.
- *
- * Read this rather than computing a deadline from the create time: sandboxes
- * are served from a warm pool, so the host is usually older than the create.
- */
- endAt?: string;
- /** Plaintext preview-URL bearer token. Returned exactly once on the create
- * or rotate response when `previewAuth` was requested. */
- previewAuthToken?: string;
- /** Destinations registered via `create({ webhooks })`. A generated `secret` (`whsec_…`)
- * is present once here — store it; it isn't returned again. */
- webhooks?: Array<{ id: string; url: string; secret?: string }>;
-}
-
-export interface CheckpointInfo {
- id: string;
- sandboxId: string;
- orgId: string;
- name: string;
- rootfsS3Key?: string;
- workspaceS3Key?: string;
- sandboxConfig: Record<string, unknown>;
- status: string;
- sizeBytes: number;
- createdAt: string;
-}
-
-export type CheckpointRetentionPolicy =
- | { mode: "none" }
- | { mode: "delete_oldest"; maxCount?: number };
-
-export interface CreateCheckpointOptions {
- kind?: "full" | "disk_only";
- promoteToFull?: boolean;
- retentionPolicy?: CheckpointRetentionPolicy;
-}
-
-export interface PatchInfo {
- id: string;
- checkpointId: string;
- sequence: number;
- script: string;
- description: string;
- strategy: string;
- createdAt: string;
-}
-
-export interface PatchResult {
- patch: PatchInfo;
-}
-
-export interface PreviewURLResult {
- id: string;
- sandboxId: string;
- orgId: string;
- hostname: string;
- customHostname?: string;
- port: number;
- cfHostnameId?: string;
- sslStatus: string;
- authConfig: Record<string, unknown>;
- createdAt: string;
-}
-
-/**
- * Thrown by `scale`, `setAutoscale`, and resource-changing calls when the
- * sandbox has a scaling lock active. Catch this to handle the lock case
- * specifically — typically by surfacing a clear message to the user, or
- * unlocking via `sandbox.setScalingLock(false)` first.
- */
-export class ScalingLockedError extends Error {
- readonly code = "scaling_locked";
- constructor(message?: string) {
- super(message ?? "scaling is locked on this sandbox");
- this.name = "ScalingLockedError";
- }
-}
-
-/**
- * Thrown by `scale` and `setAutoscale` when the requested size exceeds the
- * organization's plan cap (e.g. free tier blocks > 4 GB). The HTTP layer
- * returns 402 Payment Required for this case.
- */
-export class PlanLimitError extends Error {
- constructor(message?: string) {
- super(message ?? "plan limit exceeded for requested resources");
- this.name = "PlanLimitError";
- }
-}
-
-/**
- * Thrown when a resource-changing call is blocked by the sandbox's family.
- * Kept for compatibility with older API responses.
- */
-export class SandboxFamilyLimitError extends Error {
- readonly code = "sandbox_family_scale_disabled";
- constructor(message?: string) {
- super(message ?? "sandbox family does not allow scaling");
- this.name = "SandboxFamilyLimitError";
- }
-}
-
-/**
- * Inspect a non-OK response from a scaling endpoint and throw the most
- * specific error type. Falls back to a generic Error when the response
- * doesn't match a known shape so callers still see the status + body.
- */
-async function throwScalingError(resp: Response, action: string): Promise<never> {
- const text = await resp.text();
- let body: { error?: string; code?: string } = {};
- try {
- body = JSON.parse(text);
- } catch {
- // Non-JSON body — fall through to generic Error below.
- }
- if (resp.status === 403 && body.code === "scaling_locked") {
- throw new ScalingLockedError(body.error);
- }
- if (resp.status === 403 && body.code === "sandbox_family_scale_disabled") {
- throw new SandboxFamilyLimitError(body.error);
- }
- if (resp.status === 402) {
- throw new PlanLimitError(body.error);
- }
- throw new Error(`Failed to ${action}: ${resp.status} ${text}`);
-}
-
-export interface ScaleResult {
- sandboxID: string;
- memoryMB: number;
- cpuPercent: number;
-}
-
-export interface AutoscaleConfig {
- enabled: boolean;
- /** Minimum tier the autoscaler will shrink to. Must be an allowed memory tier (1024, 4096, 8192, 16384, 32768, 65536). */
- minMemoryMB?: number;
- /** Maximum tier the autoscaler will grow to. Must be an allowed memory tier and ≥ minMemoryMB. */
- maxMemoryMB?: number;
-}
-
-export interface AutoscaleStatus {
- sandboxID: string;
- enabled: boolean;
- minMemoryMB: number;
- maxMemoryMB: number;
-}
-
-export interface ScalingLockStatus {
- sandboxID: string;
- locked: boolean;
-}
-
-/**
- * Result of `sandbox.getAllowedHosts()`. Describes the egress-allowlist that
- * a sandbox's secrets proxy enforces.
- *
- * - `egressAllowlist` is the cluster-wide list of hosts the sandbox can
- * reach via the secrets proxy. Comes from the secret store the sandbox
- * was created with.
- * - `perSecretAllowedHosts` is an optional finer restriction per individual
- * secret. When the sandbox uses one of these secrets in a request, only
- * the listed hosts are reachable for that request.
- * - `secretStore` is the name of the store the sandbox is bound to. Empty
- * when the sandbox was created without a `secretStore` option.
- */
-export interface AllowedHostsInfo {
- sandboxID: string;
- secretStore?: string;
- egressAllowlist: string[];
- perSecretAllowedHosts: Record<string, string[]>;
-}
-
-export interface SandboxKillOptions {
- /**
- * Also delete the secret store currently attached to this sandbox.
- *
- * Defaults to false. Only set this for single-use stores that should not
- * outlive the sandbox.
- */
- deleteSecretStore?: boolean;
-}
-
-export class Sandbox {
- readonly sandboxId: string;
- readonly id: string;
- /** @deprecated The in-sandbox agent is legacy — prefer managed agents (the `OpenComputer` client). */
- readonly agent: SandboxAgent;
- readonly files: Filesystem;
- readonly exec: Exec;
- readonly mounts: Mounts;
- readonly pty: Pty;
- /** @deprecated Use `sandbox.exec` instead. This alias exists for backwards compatibility. */
- readonly commands: Exec;
-
- private apiUrl: string;
- private apiKey: string;
- private connectUrl: string;
- private token: string;
- private _status: string;
- private _sandboxDomain: string;
- /**
- * Plaintext preview-URL bearer token, available immediately after a
- * `Sandbox.create({ previewAuth: ... })` call. Read it once and store
- * it somewhere durable — the server will not return it again. After
- * a successful `rotatePreviewAuthToken()` this value is replaced
- * with the new token.
- *
- * Empty string when the sandbox was created without `previewAuth`,
- * or when reconnecting via `Sandbox.connect()` (the server-side hash
- * is still in effect; only the plaintext is gone). In that case use
- * `rotatePreviewAuthToken()` to mint a new one.
- */
- previewAuthToken: string;
-
- /**
- * Webhook destinations registered inline via `Sandbox.create({ webhooks: [...] })`. Each
- * generated signing `secret` (`whsec_…`) is present here exactly once — read and store it
- * now; the server won't return it again. Empty when none were requested or after `connect()`.
- */
- readonly webhooks: Array<{ id: string; url: string; secret?: string }>;
-
- /**
- * RFC3339 instant at which the provider destroys this sandbox's host, or
- * `undefined` when the runtime imposes no lifetime.
- *
- * Two uses. It is the deadline to plan against — checkpoint and roll over
- * before it, because the disk goes with the host. And because only some
- * runtimes have one, its presence identifies which runtime served the
- * create, which is what the upgrade guide's smoke test checks.
- *
- * ```ts
- * const sandbox = await Sandbox.create();
- * if (sandbox.endAt) {
- * const msLeft = Date.parse(sandbox.endAt) - Date.now();
- * }
- * ```
- */
- readonly endAt?: string;
-
- private constructor(data: SandboxData, apiUrl: string, apiKey: string) {
- this.sandboxId = data.sandboxID;
- this.id = this.sandboxId;
- this._status = data.status;
- this.apiUrl = apiUrl;
- this.apiKey = apiKey;
- this.connectUrl = data.connectURL || "";
- this.token = data.token || "";
- this.previewAuthToken = data.previewAuthToken || "";
- this.webhooks = data.webhooks ?? [];
- this.endAt = data.endAt;
- this._sandboxDomain = data.sandboxDomain || "";
-
- // Always route through the CP — it handles readiness waiting and proxies to workers.
- this.agent = new SandboxAgent(apiUrl, apiKey, this.sandboxId, "");
- this.files = new Filesystem(apiUrl, apiKey, this.sandboxId, "");
- this.exec = new Exec(apiUrl, apiKey, this.sandboxId, "");
- this.commands = this.exec; // backwards-compatible alias
- this.mounts = new Mounts(apiUrl, apiKey, this.sandboxId, "");
- this.pty = new Pty(apiUrl, apiKey, this.sandboxId, "");
- }
-
- get status(): string {
- return this._status;
- }
-
- /** Preview URL domain for port 80 (e.g., "sb-xxx-p80.workers.opencomputer.dev"). */
- get domain(): string {
- if (!this._sandboxDomain) return "";
- return `${this.sandboxId}-p80.${this._sandboxDomain}`;
- }
-
- /** Get the preview URL domain for a specific port. */
- getPreviewDomain(port: number): string {
- if (!this._sandboxDomain) return "";
- return `${this.sandboxId}-p${port}.${this._sandboxDomain}`;
- }
-
- static async create(opts: SandboxOpts = {}): Promise<Sandbox> {
- const apiUrl = resolveApiUrl(opts.apiUrl ?? process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev");
- const apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";
- // Kick connection pre-warming on the first create (fire-and-forget, memoized
- // — see http2.ts). A concurrent burst otherwise opens ~100 TLS connections
- // inside the latency it is measuring: ~300ms, more than the entire
- // server-side cost of a create. Deliberately NOT awaited: the first create
- // should not wait on the pool, it just seeds it for the ones behind it.
- void prewarmConnections(apiUrl.replace(/\/api$/, ""));
-
- const body: Record<string, unknown> = {
- templateID: opts.template ?? "base",
- // Default to 0 (persistent). Callers who want auto-hibernate must opt in.
- timeout: opts.timeout ?? 0,
- };
- if (opts.envs) body.envs = opts.envs;
- if (opts.metadata) body.metadata = opts.metadata;
- if (opts.burst != null) body.burst = opts.burst;
- if (opts.sandboxFamily) body.sandboxFamily = opts.sandboxFamily;
- if (opts.cpuCount != null) body.cpuCount = opts.cpuCount;
- if (opts.memoryMB != null) body.memoryMB = opts.memoryMB;
- if (opts.diskMB != null) body.diskMB = opts.diskMB;
- if (opts.secretStore) body.secretStore = opts.secretStore;
- if (opts.image) body.image = opts.image.toJSON();
- if (opts.snapshot) body.snapshot = opts.snapshot;
- if (opts.webhooks?.length) body.webhooks = opts.webhooks;
- if (opts.previewAuth) {
- body.previewAuth = {
- scheme: opts.previewAuth.scheme ?? "bearer",
- token: opts.previewAuth.token ?? "auto",
- };
- }
-
- // Always use SSE for image/snapshot creation to keep the connection alive
- // through proxies (Cloudflare has a 100s idle timeout).
- const useSSE = !!(opts.image || opts.snapshot);
-
- const headers: Record<string, string> = {
- "Content-Type": "application/json",
- // Which runtime serves this create. See version.ts: an org that has not
- // been pinned is routed by the calling SDK's major version, so this
- // header is how upgrading the dependency performs the migration.
- ...sdkVersionHeaders(),
- ...(apiKey ? { "X-API-Key": apiKey } : {}),
- };
- if (useSSE) {
- headers["Accept"] = "text/event-stream";
- }
-
- const resp = await apiFetch(`${apiUrl}/sandboxes`, {
- method: "POST",
- headers,
- body: JSON.stringify(body),
- });
-
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to create sandbox: ${resp.status} ${text}`);
- }
-
- if (useSSE && resp.headers.get("content-type")?.includes("text/event-stream")) {
- const onLog = opts.onBuildLog ?? (() => {});
- const data = await parseSSEStream<SandboxData>(resp, onLog);
- return new Sandbox(data, apiUrl, apiKey);
- }
-
- const data: SandboxData = await resp.json();
- return new Sandbox(data, apiUrl, apiKey);
- }
-
- static async connect(sandboxId: string, opts: Pick<SandboxOpts, "apiKey" | "apiUrl"> = {}): Promise<Sandbox> {
- const apiUrl = resolveApiUrl(opts.apiUrl ?? process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev");
- const apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";
-
- const resp = await apiFetch(`${apiUrl}/sandboxes/${sandboxId}`, {
- headers: apiKey ? { "X-API-Key": apiKey } : {},
- });
-
- if (!resp.ok) {
- throw new Error(`Failed to connect to sandbox ${sandboxId}: ${resp.status}`);
- }
-
- const data: SandboxData = await resp.json();
- return new Sandbox(data, apiUrl, apiKey);
- }
-
- /**
- * Delete a sandbox by id, without connecting to it first.
- *
- * `connect()` + `kill()` is the obvious way to do this and it is subtly
- * wrong, because `connect()` is a GET whose result `kill()` never uses —
- * killing needs only the id, the URL and the key. So the GET is a
- * precondition that can fail on its own: during the create→finalize window,
- * against a stale route cache, or on any transient miss it answers 404, and
- * a caller that reads "404" as "already gone" skips the DELETE entirely and
- * leaks a running sandbox that nothing will ever collect. That failure is
- * silent by construction — the caller sees success.
- *
- * This issues the DELETE directly, so there is no GET to misread.
- *
- * Idempotent: a 404 from the DELETE itself means the sandbox is genuinely
- * gone, which is the caller's desired end state, so it resolves rather than
- * throwing. Every other non-2xx throws — a delete that did not happen must
- * never look like one that did.
- */
- static async destroy(
- sandboxId: string,
- opts: Pick<SandboxOpts, "apiKey" | "apiUrl"> & SandboxKillOptions = {},
- ): Promise<void> {
- const apiUrl = resolveApiUrl(opts.apiUrl ?? process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev");
- const apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";
- const query = opts.deleteSecretStore ? "?deleteSecretStore=true" : "";
-
- const resp = await apiFetch(`${apiUrl}/sandboxes/${sandboxId}${query}`, {
- method: "DELETE",
- headers: apiKey ? { "X-API-Key": apiKey } : {},
- });
-
- if (!resp.ok && resp.status !== 404) {
- throw new Error(`Failed to destroy sandbox ${sandboxId}: ${resp.status}`);
- }
- }
-
- /**
- * Issue a new preview-URL bearer token and invalidate the previous one.
- *
- * Returns the new plaintext token (also written to `sandbox.previewAuthToken`).
- * The old token stops working immediately — there is no zero-downtime
- * dual-token mode in v1, so coordinate the rollover with whoever is calling
- * your preview URL.
- *
- * If the sandbox was created without `previewAuth`, calling this enables the
- * auth gate from that point on.
- */
- async rotatePreviewAuthToken(): Promise<string> {
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/preview/rotate`, {
- method: "POST",
- headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
- });
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to rotate preview auth token: ${resp.status} ${text}`);
- }
- const data = await resp.json() as { previewAuthToken: string };
- this.previewAuthToken = data.previewAuthToken;
- return this.previewAuthToken;
- }
-
- async kill(opts: SandboxKillOptions = {}): Promise<void> {
- const query = opts.deleteSecretStore ? "?deleteSecretStore=true" : "";
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}${query}`, {
- method: "DELETE",
- headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
- });
-
- if (!resp.ok) {
- throw new Error(`Failed to kill sandbox: ${resp.status}`);
- }
- this._status = "stopped";
- }
-
- async isRunning(): Promise<boolean> {
- try {
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}`, {
- headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
- });
- if (!resp.ok) return false;
- const data: SandboxData = await resp.json();
- this._status = data.status;
- return data.status === "running";
- } catch {
- return false;
- }
- }
-
- async hibernate(): Promise<void> {
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/hibernate`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- ...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),
- },
- });
-
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to hibernate sandbox: ${resp.status} ${text}`);
- }
- this._status = "hibernated";
- }
-
- async wake(opts: { timeout?: number } = {}): Promise<void> {
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/wake`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- ...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),
- },
- // Default to 0 (persistent) — matches create() default.
- body: JSON.stringify({ timeout: opts.timeout ?? 0 }),
- });
-
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to wake sandbox: ${resp.status} ${text}`);
- }
-
- const data: SandboxData = await resp.json();
- this._status = data.status;
- this.connectUrl = data.connectURL || "";
- this.token = data.token || "";
-
- // Always route through the CP
- (this as any).agent = new SandboxAgent(this.apiUrl, this.apiKey, this.sandboxId, "");
- (this as any).files = new Filesystem(this.apiUrl, this.apiKey, this.sandboxId, "");
- (this as any).exec = new Exec(this.apiUrl, this.apiKey, this.sandboxId, "");
- (this as any).mounts = new Mounts(this.apiUrl, this.apiKey, this.sandboxId, "");
- (this as any).pty = new Pty(this.apiUrl, this.apiKey, this.sandboxId, "");
- }
-
- /**
- * Soft restart of the running sandbox. The guest CPU is reset and the
- * kernel reboots — equivalent to running `reboot` inside the box. The
- * QEMU process, network mapping, and persistent disks all stay; only
- * in-memory state (running processes, page caches) is wiped.
- *
- * Use to recover from in-guest wedges: zombie pile-ups, OOM-killed
- * agents, runaway processes, broken-but-isolated systemd state.
- *
- * For the rare case where the VMM itself is wedged (e.g. QMP
- * unresponsive), use `powerCycle()` instead.
- */
- async reboot(): Promise<void> {
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/reboot`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- ...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),
- },
- });
-
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to reboot sandbox: ${resp.status} ${text}`);
- }
- }
-
- /**
- * Hard restart of the sandbox. The QEMU process is killed and a fresh
- * one is started with the same on-disk drives. Sandbox keeps its ID,
- * project, secrets, env, and persistent workspace data; gets a new
- * external host port and TAP. Use when the VMM itself is wedged or a
- * `reboot()` doesn't recover.
- */
- async powerCycle(): Promise<void> {
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/power-cycle`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- ...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),
- },
- });
-
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to power-cycle sandbox: ${resp.status} ${text}`);
- }
- }
-
- /**
- * Manually resize the sandbox to a specific memory tier. CPU is bundled
- * with memory per the platform's tier table (e.g. 8 GB → 4 vCPU). Allowed
- * tiers: 1024, 4096, 8192, 16384, 32768, 65536 MB.
- *
- * Side effect: a manual scale disables autoscale on this sandbox. If you
- * want size to track load again, call `setAutoscale({ enabled: true, ... })`
- * after.
- *
- * Throws `ScalingLockedError` if the sandbox has a scaling lock; throws
- * `PlanLimitError` if the requested size exceeds your plan cap.
- *
- * [HTTP API →](/api-reference/sandboxes/scale)
- */
- async scale(opts: { memoryMB: number }): Promise<ScaleResult> {
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/scale`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- ...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),
- },
- body: JSON.stringify({ memoryMB: opts.memoryMB }),
- });
-
- if (!resp.ok) {
- await throwScalingError(resp, "scale sandbox");
- }
-
- return resp.json();
- }
-
- /**
- * Enable or disable per-sandbox autoscale. When enabled, the platform
- * resizes the sandbox between `minMemoryMB` and `maxMemoryMB` based on
- * observed memory pressure — scaling up fast on a 1-min spike, down
- * slowly after sustained idle.
- *
- * Both bounds must be allowed memory tiers (1024, 4096, 8192, 16384,
- * 32768, 65536). Pass `enabled: false` to turn autoscale off (bounds
- * are ignored in that case).
- *
- * Throws `ScalingLockedError` if the sandbox has a scaling lock; throws
- * `PlanLimitError` if `maxMemoryMB` exceeds your plan cap.
- */
- async setAutoscale(opts: AutoscaleConfig): Promise<AutoscaleStatus> {
- const body: Record<string, unknown> = { enabled: opts.enabled };
- if (opts.minMemoryMB != null) body.minMemoryMB = opts.minMemoryMB;
- if (opts.maxMemoryMB != null) body.maxMemoryMB = opts.maxMemoryMB;
-
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/autoscale`, {
- method: "PUT",
- headers: {
- "Content-Type": "application/json",
- ...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),
- },
- body: JSON.stringify(body),
- });
-
- if (!resp.ok) {
- await throwScalingError(resp, "set autoscale");
- }
-
- return resp.json();
- }
-
- /**
- * Get the current autoscale configuration for the sandbox.
- */
- async getAutoscale(): Promise<AutoscaleStatus> {
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/autoscale`, {
- headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
- });
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to get autoscale: ${resp.status} ${text}`);
- }
- return resp.json();
- }
-
- /**
- * Lock or unlock the sandbox's resources against scaling. When locked:
- *
- * - `scale()` rejects with `ScalingLockedError`.
- * - `setAutoscale({ enabled: true })` rejects with `ScalingLockedError`.
- * - The platform autoscaler skips this sandbox entirely.
- *
- * Locking ALSO disables autoscale as a side effect (single-knob
- * semantics — "I don't want this scaling, period"). Unlocking does NOT
- * re-enable autoscale; call `setAutoscale({ enabled: true, ... })`
- * explicitly if you want it back.
- */
- async setScalingLock(locked: boolean): Promise<ScalingLockStatus> {
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/scaling-lock`, {
- method: "PUT",
- headers: {
- "Content-Type": "application/json",
- ...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),
- },
- body: JSON.stringify({ locked }),
- });
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to set scaling lock: ${resp.status} ${text}`);
- }
- return resp.json();
- }
-
- /**
- * Get the current scaling-lock state for the sandbox.
- */
- async getScalingLock(): Promise<ScalingLockStatus> {
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/scaling-lock`, {
- headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
- });
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to get scaling lock: ${resp.status} ${text}`);
- }
- return resp.json();
- }
-
- /**
- * Get the egress-allowlist + per-secret allowed hosts the sandbox's
- * secrets proxy enforces. Useful for debugging "why is my outbound HTTP
- * call being blocked" without having to cross-reference the secret store
- * config separately.
- *
- * Sandboxes created without a `secretStore` option return an empty
- * allowlist and `secretStore` is undefined — the sandbox has no
- * per-store egress restriction.
- */
- async getAllowedHosts(): Promise<AllowedHostsInfo> {
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/allowed-hosts`, {
- headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
- });
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to get allowed hosts: ${resp.status} ${text}`);
- }
- return resp.json();
- }
-
- async setTimeout(timeout: number): Promise<void> {
- const headers: Record<string, string> = { "Content-Type": "application/json" };
- if (this.apiKey) {
- headers["X-API-Key"] = this.apiKey;
- }
-
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/timeout`, {
- method: "POST",
- headers,
- body: JSON.stringify({ timeout }),
- });
-
- if (!resp.ok) {
- throw new Error(`Failed to set timeout: ${resp.status}`);
- }
- }
-
- async createCheckpoint(name: string, opts: CreateCheckpointOptions = {}): Promise<CheckpointInfo> {
- const body: Record<string, unknown> = { name };
- if (opts.kind) {
- body.kind = opts.kind;
- }
- if (opts.promoteToFull !== undefined) {
- body.promoteToFull = opts.promoteToFull;
- }
- if (opts.retentionPolicy) {
- body.retentionPolicy = opts.retentionPolicy;
- }
-
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/checkpoints`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- ...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),
- },
- body: JSON.stringify(body),
- });
-
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to create checkpoint: ${resp.status} ${text}`);
- }
-
- return resp.json();
- }
-
- async listCheckpoints(): Promise<CheckpointInfo[]> {
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/checkpoints`, {
- headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
- });
-
- if (!resp.ok) {
- throw new Error(`Failed to list checkpoints: ${resp.status}`);
- }
-
- return resp.json();
- }
-
- async restoreCheckpoint(checkpointId: string): Promise<void> {
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/checkpoints/${checkpointId}/restore`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- ...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),
- },
- });
-
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to restore checkpoint: ${resp.status} ${text}`);
- }
-
- // After restore, rebuild ops clients since the VM was rebooted
- const data: SandboxData = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}`, {
- headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
- }).then((r) => r.json());
-
- this.connectUrl = data.connectURL || "";
- this.token = data.token || "";
-
- // Always route through the CP
- (this as any).agent = new SandboxAgent(this.apiUrl, this.apiKey, this.sandboxId, "");
- (this as any).files = new Filesystem(this.apiUrl, this.apiKey, this.sandboxId, "");
- (this as any).exec = new Exec(this.apiUrl, this.apiKey, this.sandboxId, "");
- (this as any).mounts = new Mounts(this.apiUrl, this.apiKey, this.sandboxId, "");
- (this as any).pty = new Pty(this.apiUrl, this.apiKey, this.sandboxId, "");
- }
-
- static async createFromCheckpoint(checkpointId: string, opts: Pick<SandboxOpts, "apiKey" | "apiUrl" | "timeout" | "envs" | "secretStore"> = {}): Promise<Sandbox> {
- const apiUrl = resolveApiUrl(opts.apiUrl ?? process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev");
- const apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";
-
- const body: Record<string, unknown> = {};
- if (opts.timeout != null) body.timeout = opts.timeout;
- if (opts.envs) body.envs = opts.envs;
- if (opts.secretStore) body.secretStore = opts.secretStore;
-
- const resp = await apiFetch(`${apiUrl}/sandboxes/from-checkpoint/${checkpointId}`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- ...(apiKey ? { "X-API-Key": apiKey } : {}),
- },
- body: JSON.stringify(body),
- });
-
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to create sandbox from checkpoint: ${resp.status} ${text}`);
- }
-
- const data: SandboxData = await resp.json();
- return new Sandbox(data, apiUrl, apiKey);
- }
-
- async deleteCheckpoint(checkpointId: string): Promise<void> {
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/checkpoints/${checkpointId}`, {
- method: "DELETE",
- headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
- });
-
- if (!resp.ok && resp.status !== 404) {
- throw new Error(`Failed to delete checkpoint: ${resp.status}`);
- }
- }
-
- static async createCheckpointPatch(
- checkpointId: string,
- opts: { script: string; description?: string; apiKey?: string; apiUrl?: string }
- ): Promise<PatchResult> {
- const apiUrl = resolveApiUrl(opts.apiUrl ?? process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev");
- const apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";
-
- const resp = await apiFetch(`${apiUrl}/sandboxes/checkpoints/${checkpointId}/patches`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- ...(apiKey ? { "X-API-Key": apiKey } : {}),
- },
- body: JSON.stringify({
- script: opts.script,
- description: opts.description ?? "",
- }),
- });
-
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to create checkpoint patch: ${resp.status} ${text}`);
- }
-
- return resp.json();
- }
-
- static async listCheckpointPatches(
- checkpointId: string,
- opts: { apiKey?: string; apiUrl?: string } = {}
- ): Promise<PatchInfo[]> {
- const apiUrl = resolveApiUrl(opts.apiUrl ?? process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev");
- const apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";
-
- const resp = await apiFetch(`${apiUrl}/sandboxes/checkpoints/${checkpointId}/patches`, {
- headers: apiKey ? { "X-API-Key": apiKey } : {},
- });
-
- if (!resp.ok) {
- throw new Error(`Failed to list checkpoint patches: ${resp.status}`);
- }
-
- return resp.json();
- }
-
- static async deleteCheckpointPatch(
- checkpointId: string,
- patchId: string,
- opts: { apiKey?: string; apiUrl?: string } = {}
- ): Promise<void> {
- const apiUrl = resolveApiUrl(opts.apiUrl ?? process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev");
- const apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";
-
- const resp = await apiFetch(`${apiUrl}/sandboxes/checkpoints/${checkpointId}/patches/${patchId}`, {
- method: "DELETE",
- headers: apiKey ? { "X-API-Key": apiKey } : {},
- });
-
- if (!resp.ok && resp.status !== 404) {
- throw new Error(`Failed to delete checkpoint patch: ${resp.status}`);
- }
- }
-
- /**
- * Generate a signed download URL for a file in the sandbox.
- * The URL can be used by anyone (e.g. in a browser) without an API key.
- * @param path - absolute path inside the sandbox
- * @param opts.expiresIn - URL validity in seconds (default: 3600, max: 86400)
- */
- async downloadUrl(path: string, opts?: { expiresIn?: number }): Promise<string> {
- const resp = await apiFetch(
- `${this.apiUrl}/sandboxes/${this.sandboxId}/files/download-url`,
- {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- ...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),
- },
- body: JSON.stringify({ path, expiresIn: opts?.expiresIn ?? 3600 }),
- },
- );
-
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to get download URL: ${resp.status} ${text}`);
- }
-
- const data: { url: string } = await resp.json();
- return data.url;
- }
-
- /**
- * Generate a signed upload URL for a file in the sandbox.
- * The URL can be used by anyone (e.g. in a browser) to PUT file content without an API key.
- * @param path - absolute path inside the sandbox
- * @param opts.expiresIn - URL validity in seconds (default: 3600, max: 86400)
- */
- async uploadUrl(path: string, opts?: { expiresIn?: number }): Promise<string> {
- const resp = await apiFetch(
- `${this.apiUrl}/sandboxes/${this.sandboxId}/files/upload-url`,
- {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- ...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),
- },
- body: JSON.stringify({ path, expiresIn: opts?.expiresIn ?? 3600 }),
- },
- );
-
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to get upload URL: ${resp.status} ${text}`);
- }
-
- const data: { url: string } = await resp.json();
- return data.url;
- }
-
- async createPreviewURL(opts: { port: number; domain?: string; authConfig?: Record<string, unknown> }): Promise<PreviewURLResult> {
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/preview`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- ...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),
- },
- body: JSON.stringify({ port: opts.port, ...(opts.domain ? { domain: opts.domain } : {}), authConfig: opts.authConfig ?? {} }),
- });
-
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to create preview URL: ${resp.status} ${text}`);
- }
-
- return resp.json();
- }
-
- async listPreviewURLs(): Promise<PreviewURLResult[]> {
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/preview`, {
- headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
- });
-
- if (!resp.ok) {
- throw new Error(`Failed to list preview URLs: ${resp.status}`);
- }
-
- return resp.json();
- }
-
- async deletePreviewURL(port: number): Promise<void> {
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/preview/${port}`, {
- method: "DELETE",
- headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
- });
-
- if (!resp.ok && resp.status !== 404) {
- throw new Error(`Failed to delete preview URL: ${resp.status}`);
- }
- }
-}
diff --git a/sdks/typescript/src/shell.ts b/sdks/typescript/src/shell.ts
deleted file mode 100644
index 3c965855..00000000
--- a/sdks/typescript/src/shell.ts
+++ /dev/null
@@ -1,291 +0,0 @@
-import type { ExecSession, ProcessResult } from "./exec.js";
-
-export interface ShellOpts {
- cwd?: string;
- env?: Record<string, string>;
-}
-
-export interface ShellRunOpts {
- onStdout?: (data: Uint8Array) => void;
- onStderr?: (data: Uint8Array) => void;
-}
-
-export interface Shell {
- readonly sessionId: string;
- /**
- * Run a command inside the shell and wait for it to complete.
- *
- * State set by previous calls (cwd, exported variables, shell functions)
- * persists into this call. Rejects with `ShellBusyError` if another run is
- * in flight, or `ShellClosedError` if the shell has exited (including when
- * the user command calls `exit` — same as closing a terminal tab).
- *
- * Per-call `cwd`/`env`/`timeout` are intentionally not supported in v1 —
- * use shell syntax inline (`cd /x && cmd`, `FOO=bar cmd`). Timeouts will
- * land once we have a "signal foreground job" primitive.
- */
- run(cmd: string, opts?: ShellRunOpts): Promise<ProcessResult>;
- /**
- * Write `exit` to the shell and wait for bash to terminate.
- */
- close(): Promise<void>;
-}
-
-export class ShellBusyError extends Error {
- constructor() {
- super("shell is already running a command; shell.run is foreground-only");
- this.name = "ShellBusyError";
- }
-}
-
-export class ShellClosedError extends Error {
- constructor(reason?: string) {
- super(reason ? `shell is closed: ${reason}` : "shell is closed");
- this.name = "ShellClosedError";
- }
-}
-
-type State = "idle" | "running" | "closed";
-
-interface PendingRun {
- token: string;
- stdoutDoneMarker: string; // "\n__OC_<TOK>_DONE__\n"
- stderrExitPrefix: string; // "\n__OC_<TOK>_EXIT_"
- stdoutBuf: string;
- stderrBuf: string;
- stdoutScanIdx: number; // bytes emitted to onStdout
- stderrScanIdx: number; // bytes emitted to onStderr
- stdoutDoneIdx: number | null; // index of DONE marker in stdoutBuf, once found
- stderrExitCode: number | null; // parsed exit code, once EXIT sentinel found
- stderrExitIdx: number | null; // index of EXIT sentinel start in stderrBuf
- onStdout?: (data: Uint8Array) => void;
- onStderr?: (data: Uint8Array) => void;
- resolve: (r: ProcessResult) => void;
- reject: (e: Error) => void;
-}
-
-const encoder = new TextEncoder();
-
-/**
- * Hex-ish 128-bit token; `crypto.randomUUID` is Node 18+ / browser standard.
- * Fallback uses `Math.random` only if the global `crypto` is absent.
- */
-function newToken(): string {
- const g = globalThis as { crypto?: { randomUUID?: () => string } };
- if (g.crypto?.randomUUID) return g.crypto.randomUUID().replace(/-/g, "");
- let s = "";
- for (let i = 0; i < 32; i++) s += Math.floor(Math.random() * 16).toString(16);
- return s;
-}
-
-export class ShellImpl implements Shell {
- readonly sessionId: string;
- private session: ExecSession;
- private state: State = "idle";
- private pending: PendingRun | null = null;
- private stdoutDecoder = new TextDecoder("utf-8", { fatal: false });
- private stderrDecoder = new TextDecoder("utf-8", { fatal: false });
- // Chunks arriving before scrollback_end (0x04) are historical replay of
- // the session's prior output. Drop them — our sentinel protocol only
- // matches per-call tokens, but the caller's onStdout/onStderr callbacks
- // should not see stale data either.
- private scrollbackDone = false;
-
- constructor(session: ExecSession) {
- this.session = session;
- this.sessionId = session.sessionId;
-
- // If bash exits while a run is pending, fail the pending run.
- this.session.done.then((exitCode) => {
- const prev = this.state;
- this.state = "closed";
- if (this.pending) {
- const p = this.pending;
- this.pending = null;
- if (prev !== "idle") {
- p.reject(new ShellClosedError(`bash exited with code ${exitCode}`));
- }
- }
- });
- }
-
- onScrollbackEnd(): void {
- this.scrollbackDone = true;
- }
-
- onStdoutChunk(chunk: Uint8Array): void {
- if (!this.scrollbackDone) return;
- const p = this.pending;
- if (!p) return;
- p.stdoutBuf += this.stdoutDecoder.decode(chunk, { stream: true });
- this.scanStdout();
- }
-
- onStderrChunk(chunk: Uint8Array): void {
- if (!this.scrollbackDone) return;
- const p = this.pending;
- if (!p) return;
- p.stderrBuf += this.stderrDecoder.decode(chunk, { stream: true });
- this.scanStderr();
- }
-
- /** Extract user stdout up to the DONE marker; emit incremental chunks. */
- private scanStdout(): void {
- const p = this.pending;
- if (!p || p.stdoutDoneIdx !== null) return;
-
- const idx = p.stdoutBuf.indexOf(p.stdoutDoneMarker, p.stdoutScanIdx);
-
- if (idx === -1) {
- // Hold back a tail that could be a partial marker.
- const hold = p.stdoutDoneMarker.length - 1;
- const safe = Math.max(p.stdoutScanIdx, p.stdoutBuf.length - hold);
- if (safe > p.stdoutScanIdx) {
- const chunk = p.stdoutBuf.slice(p.stdoutScanIdx, safe);
- p.onStdout?.(encoder.encode(chunk));
- p.stdoutScanIdx = safe;
- }
- return;
- }
-
- // Emit any un-emitted bytes before the marker.
- if (idx > p.stdoutScanIdx) {
- const chunk = p.stdoutBuf.slice(p.stdoutScanIdx, idx);
- p.onStdout?.(encoder.encode(chunk));
- p.stdoutScanIdx = idx;
- }
-
- p.stdoutDoneIdx = idx;
- this.tryComplete();
- }
-
- /** Extract user stderr up to the EXIT sentinel; parse the exit code. */
- private scanStderr(): void {
- const p = this.pending;
- if (!p || p.stderrExitCode !== null) return;
-
- const idx = p.stderrBuf.indexOf(p.stderrExitPrefix, p.stderrScanIdx);
-
- if (idx === -1) {
- const hold = p.stderrExitPrefix.length - 1;
- const safe = Math.max(p.stderrScanIdx, p.stderrBuf.length - hold);
- if (safe > p.stderrScanIdx) {
- const chunk = p.stderrBuf.slice(p.stderrScanIdx, safe);
- p.onStderr?.(encoder.encode(chunk));
- p.stderrScanIdx = safe;
- }
- return;
- }
-
- if (idx > p.stderrScanIdx) {
- const chunk = p.stderrBuf.slice(p.stderrScanIdx, idx);
- p.onStderr?.(encoder.encode(chunk));
- p.stderrScanIdx = idx;
- }
-
- const afterPrefix = idx + p.stderrExitPrefix.length;
- const closeIdx = p.stderrBuf.indexOf("__", afterPrefix);
- if (closeIdx === -1) return; // wait for more bytes
-
- const exitStr = p.stderrBuf.slice(afterPrefix, closeIdx);
- const exitCode = parseInt(exitStr, 10);
- if (!Number.isFinite(exitCode)) {
- this.state = "closed";
- this.pending = null;
- p.reject(new ShellClosedError(`corrupt sentinel: "${exitStr}"`));
- return;
- }
-
- p.stderrExitCode = exitCode;
- p.stderrExitIdx = idx;
- this.tryComplete();
- }
-
- /** Resolve once both markers are in — guarantees both pipes are drained. */
- private tryComplete(): void {
- const p = this.pending;
- if (!p) return;
- if (p.stdoutDoneIdx === null || p.stderrExitCode === null) return;
-
- const result: ProcessResult = {
- exitCode: p.stderrExitCode,
- stdout: p.stdoutBuf.slice(0, p.stdoutDoneIdx),
- stderr: p.stderrBuf.slice(0, p.stderrExitIdx ?? p.stderrBuf.length),
- };
-
- this.pending = null;
- if (this.state !== "closed") this.state = "idle";
- p.resolve(result);
- }
-
- async run(cmd: string, opts: ShellRunOpts = {}): Promise<ProcessResult> {
- if (this.state === "closed") throw new ShellClosedError();
- if (this.state === "running") throw new ShellBusyError();
-
- const token = newToken();
- const stdoutDoneMarker = `\n__OC_${token}_DONE__\n`;
- const stderrExitPrefix = `\n__OC_${token}_EXIT_`;
-
- // `{ cmd\n}` groups the user command so `$?` captures its exit. The
- // newline before `}` is required — `{ cmd\n; }` is a bash syntax error.
- //
- // Two markers, one per stream: DONE to stdout, EXIT to stderr. We
- // resolve only when both are seen, which prevents a race where the
- // stderr sentinel arrives before the user's stdout is drained (the
- // agent reads stdout and stderr on separate goroutines, so wire
- // ordering isn't guaranteed). Empty command becomes `:` (POSIX no-op).
- const inner = cmd.trim() === "" ? ":" : cmd;
- const wrapped =
- `{ ${inner}\n} ; __oc_ec=$? ; ` +
- `printf '\\n__OC_%s_DONE__\\n' '${token}' ; ` +
- `printf '\\n__OC_%s_EXIT_%d__\\n' '${token}' "$__oc_ec" >&2\n`;
-
- this.state = "running";
- const run: PendingRun = {
- token,
- stdoutDoneMarker,
- stderrExitPrefix,
- stdoutBuf: "",
- stderrBuf: "",
- stdoutScanIdx: 0,
- stderrScanIdx: 0,
- stdoutDoneIdx: null,
- stderrExitCode: null,
- stderrExitIdx: null,
- onStdout: opts.onStdout,
- onStderr: opts.onStderr,
- resolve: () => {},
- reject: () => {},
- };
- const promise = new Promise<ProcessResult>((resolve, reject) => {
- run.resolve = resolve;
- run.reject = reject;
- });
- this.pending = run;
-
- try {
- this.session.sendStdin(wrapped);
- } catch (err) {
- this.pending = null;
- this.state = "closed";
- throw err;
- }
-
- return promise;
- }
-
- async close(): Promise<void> {
- if (this.state === "closed") return;
- this.state = "closed";
- try {
- this.session.sendStdin("exit\n");
- } catch {
- // session already dead
- }
- try {
- await this.session.done;
- } finally {
- this.session.close();
- }
- }
-}
diff --git a/sdks/typescript/src/snapshot.ts b/sdks/typescript/src/snapshot.ts
deleted file mode 100644
index 13f8d4e2..00000000
--- a/sdks/typescript/src/snapshot.ts
+++ /dev/null
@@ -1,203 +0,0 @@
-import { apiFetch } from "./http2.js";
-import { Image } from "./image.js";
-import { sdkVersionHeaders } from "./version.js";
-import { parseSSEStream } from "./sse.js";
-
-function resolveApiUrl(url: string): string {
- const base = url.replace(/\/+$/, "");
- return base.endsWith("/api") ? base : `${base}/api`;
-}
-
-export interface SnapshotInfo {
- id: string;
- orgId: string;
- name: string;
- contentHash: string;
- checkpointId: string;
- status: string;
- manifest: Record<string, unknown>;
- createdAt: string;
- lastUsedAt: string;
-}
-
-export interface CreateSnapshotOpts {
- name: string;
- image: Image;
- onBuildLogs?: (log: string) => void;
-}
-
-export interface SnapshotOpts {
- apiKey?: string;
- apiUrl?: string;
-}
-
-export interface WaitForReadyOpts {
- /** Abort the wait. */
- signal?: AbortSignal;
- /** Max time to wait before throwing, in milliseconds. */
- timeoutMs?: number;
- /** Initial poll interval in ms (default 1000, backs off to 5000). */
- pollIntervalMs?: number;
-}
-
-/** Sleep that resolves early (does not reject) when the signal aborts. */
-function sleep(ms: number, signal?: AbortSignal): Promise<void> {
- return new Promise((resolve) => {
- if (signal?.aborted) return resolve();
- const onAbort = () => {
- clearTimeout(timer);
- signal?.removeEventListener("abort", onAbort);
- resolve();
- };
- const timer = setTimeout(() => {
- signal?.removeEventListener("abort", onAbort);
- resolve();
- }, ms);
- signal?.addEventListener("abort", onAbort);
- });
-}
-
-/**
- * Manage pre-built snapshots (named, persistent image checkpoints).
- */
-export class Snapshots {
- private apiUrl: string;
- private apiKey: string;
-
- constructor(opts: SnapshotOpts = {}) {
- this.apiUrl = resolveApiUrl(
- opts.apiUrl ?? process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev"
- );
- this.apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";
- }
-
- private get headers(): Record<string, string> {
- // Template builds are runtime-specific — a v1 template is a whole-disk
- // checkpoint, a v2 template is a machine image — so the same version header
- // the create path sends has to ride along here, or a v2 caller would build
- // a checkpoint their sandboxes cannot use. See version.ts.
- const h: Record<string, string> = { "Content-Type": "application/json", ...sdkVersionHeaders() };
- if (this.apiKey) h["X-API-Key"] = this.apiKey;
- return h;
- }
-
- /**
- * Create a pre-built snapshot from a declarative image.
- * The server boots a sandbox, runs the image steps, checkpoints it, and stores it under the given name.
- */
- async create(opts: CreateSnapshotOpts): Promise<SnapshotInfo> {
- const headers: Record<string, string> = {
- ...this.headers,
- Accept: "text/event-stream",
- };
-
- const resp = await apiFetch(`${this.apiUrl}/snapshots`, {
- method: "POST",
- headers,
- body: JSON.stringify({
- name: opts.name,
- image: opts.image.toJSON(),
- }),
- });
-
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`Failed to create snapshot: ${resp.status} ${text}`);
- }
-
- if (resp.headers.get("content-type")?.includes("text/event-stream")) {
- const onLog = opts.onBuildLogs ?? (() => {});
- return parseSSEStream<SnapshotInfo>(resp, onLog);
- }
-
- return resp.json();
- }
-
- /**
- * List all named snapshots for the current org.
- */
- async list(): Promise<SnapshotInfo[]> {
- const resp = await apiFetch(`${this.apiUrl}/snapshots`, {
- headers: this.headers,
- });
-
- if (!resp.ok) {
- throw new Error(`Failed to list snapshots: ${resp.status}`);
- }
-
- return resp.json();
- }
-
- /**
- * Get a snapshot by name.
- */
- async get(name: string): Promise<SnapshotInfo> {
- const resp = await apiFetch(`${this.apiUrl}/snapshots/${encodeURIComponent(name)}`, {
- headers: this.headers,
- });
-
- if (!resp.ok) {
- throw new Error(`Failed to get snapshot: ${resp.status}`);
- }
-
- return resp.json();
- }
-
- /**
- * Poll a snapshot until its build reaches a terminal state, resolving with
- * the ready SnapshotInfo. Throws if the build fails or the wait times out.
- *
- * Useful when a snapshot was created via the async (non-SSE) endpoint, which
- * returns a `building` row immediately. The SSE `create()` already waits for
- * completion via the build-log stream, so this is not needed after it.
- *
- * Note: a still-building snapshot is not yet mirrored to the read store, so
- * `get()` 404s until it reaches a terminal state. We treat that 404 as
- * "still building" and keep polling; `failed` is mirrored, so it surfaces as
- * a thrown error rather than a poll-to-timeout.
- */
- async waitUntilReady(name: string, opts: WaitForReadyOpts = {}): Promise<SnapshotInfo> {
- const deadline = opts.timeoutMs != null ? Date.now() + opts.timeoutMs : null;
- let delay = opts.pollIntervalMs ?? 1000;
- const maxDelay = 5000;
-
- for (;;) {
- if (opts.signal?.aborted) {
- throw new Error(`waitUntilReady aborted for snapshot ${name}`);
- }
- if (deadline != null && Date.now() >= deadline) {
- throw new Error(`Snapshot ${name} not ready after ${opts.timeoutMs}ms`);
- }
-
- const resp = await apiFetch(`${this.apiUrl}/snapshots/${encodeURIComponent(name)}`, {
- headers: this.headers,
- });
- if (resp.ok) {
- const snap = (await resp.json()) as SnapshotInfo;
- if (snap.status === "ready") return snap;
- if (snap.status === "failed") throw new Error(`Snapshot ${name} build failed`);
- // any other status (e.g. "building") → keep polling
- } else if (resp.status !== 404) {
- // 404 = not yet mirrored (still building); anything else is a real error
- throw new Error(`Failed to get snapshot ${name}: ${resp.status}`);
- }
-
- await sleep(delay, opts.signal);
- delay = Math.min(delay * 2, maxDelay);
- }
- }
-
- /**
- * Delete a named snapshot.
- */
- async delete(name: string): Promise<void> {
- const resp = await apiFetch(`${this.apiUrl}/snapshots/${encodeURIComponent(name)}`, {
- method: "DELETE",
- headers: this.headers,
- });
-
- if (!resp.ok && resp.status !== 404) {
- throw new Error(`Failed to delete snapshot: ${resp.status}`);
- }
- }
-}
diff --git a/sdks/typescript/src/sse.ts b/sdks/typescript/src/sse.ts
deleted file mode 100644
index dc821005..00000000
--- a/sdks/typescript/src/sse.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-/**
- * Parse an SSE stream from the server.
- *
- * The server emits three event types:
- * - `build_log`: streamed during image build, contains `{ step, type, message }`
- * - `error`: build failed, contains `{ error: string }`
- * - `result`: final result JSON (sandbox data, snapshot info, etc.)
- *
- * @param resp - Fetch Response with content-type text/event-stream
- * @param onLog - Callback for build log messages
- * @returns The parsed result from the "result" event
- */
-export async function parseSSEStream<T>(resp: Response, onLog: (msg: string) => void): Promise<T> {
- const reader = resp.body?.getReader();
- if (!reader) throw new Error("No response body for SSE stream");
-
- const decoder = new TextDecoder();
- let buffer = "";
- let result: T | null = null;
-
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
-
- buffer += decoder.decode(value, { stream: true });
- const parts = buffer.split("\n\n");
- buffer = parts.pop() ?? "";
-
- for (const part of parts) {
- if (!part.trim()) continue;
-
- let eventType = "";
- let data = "";
- for (const line of part.split("\n")) {
- if (line.startsWith("event: ")) eventType = line.slice(7);
- else if (line.startsWith("data: ")) data = line.slice(6);
- }
-
- if (!data) continue;
-
- switch (eventType) {
- case "build_log": {
- try {
- onLog(JSON.parse(data).message ?? data);
- } catch {
- onLog(data);
- }
- break;
- }
- case "error": {
- let msg = data;
- try { msg = JSON.parse(data).error ?? data; } catch {}
- throw new Error(`Build failed: ${msg}`);
- }
- case "result": {
- result = JSON.parse(data);
- break;
- }
- }
- }
- }
-
- if (!result) throw new Error("No result received from build stream");
- return result;
-}
diff --git a/sdks/typescript/src/template.ts b/sdks/typescript/src/template.ts
deleted file mode 100644
index 91da6ab9..00000000
--- a/sdks/typescript/src/template.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-import { apiFetch } from "./http2.js";
-import { sdkVersionHeaders } from "./version.js";
-
-export interface TemplateInfo {
- templateID: string;
- name: string;
- tag: string;
- status: string;
-}
-
-export class Templates {
- constructor(
- private apiUrl: string,
- private apiKey: string,
- ) {}
-
- private get headers(): Record<string, string> {
- // Same reason as Snapshots.headers — a build is runtime-specific, so the
- // server has to know which SDK asked for it. See version.ts.
- const h: Record<string, string> = { "Content-Type": "application/json", ...sdkVersionHeaders() };
- if (this.apiKey) h["X-API-Key"] = this.apiKey;
- return h;
- }
-
- async build(name: string, dockerfile: string): Promise<TemplateInfo> {
- const resp = await apiFetch(`${this.apiUrl}/templates`, {
- method: "POST",
- headers: this.headers,
- body: JSON.stringify({ name, dockerfile }),
- });
-
- if (!resp.ok) {
- throw new Error(`Failed to build template: ${resp.status}`);
- }
-
- return resp.json();
- }
-
- async list(): Promise<TemplateInfo[]> {
- const resp = await apiFetch(`${this.apiUrl}/templates`, {
- headers: this.headers,
- });
-
- if (!resp.ok) {
- throw new Error(`Failed to list templates: ${resp.status}`);
- }
-
- return resp.json();
- }
-
- async get(name: string): Promise<TemplateInfo> {
- const resp = await apiFetch(`${this.apiUrl}/templates/${name}`, {
- headers: this.headers,
- });
-
- if (!resp.ok) {
- throw new Error(`Failed to get template: ${resp.status}`);
- }
-
- return resp.json();
- }
-
- async delete(name: string): Promise<void> {
- const resp = await apiFetch(`${this.apiUrl}/templates/${name}`, {
- method: "DELETE",
- headers: this.headers,
- });
-
- if (!resp.ok) {
- throw new Error(`Failed to delete template: ${resp.status}`);
- }
- }
-}
diff --git a/sdks/typescript/src/transport.test.ts b/sdks/typescript/src/transport.test.ts
deleted file mode 100644
index d891a5d4..00000000
--- a/sdks/typescript/src/transport.test.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-// The root's transport contract: importing the package installs nothing and
-// opens nothing; a sandbox request goes to the global fetch with the client's
-// own undici Agent as its per-request dispatcher; the process's global
-// dispatcher is the one Node started with, before and after.
-
-import { afterEach, describe, expect, it, vi } from "vitest";
-import { Agent, getGlobalDispatcher } from "undici";
-
-afterEach(() => {
- vi.restoreAllMocks();
-});
-
-describe("sandbox client transport", () => {
- it("leaves the global dispatcher alone and passes its own pool per request", async () => {
- const before = getGlobalDispatcher();
- const fetchMock = vi.spyOn(globalThis, "fetch");
- const { Sandbox } = await import("./index.js");
- expect(fetchMock).not.toHaveBeenCalled();
- expect(getGlobalDispatcher()).toBe(before);
-
- fetchMock.mockResolvedValue(
- new Response(JSON.stringify({ sandboxID: "sb_1", status: "running" }), { status: 200 }),
- );
- const sandbox = await Sandbox.connect("sb_1", { apiKey: "k", apiUrl: "https://api.example.test" });
- expect(sandbox.sandboxId).toBe("sb_1");
-
- const [, init] = fetchMock.mock.calls[0] as [unknown, { dispatcher?: unknown }];
- expect(init.dispatcher).toBeInstanceOf(Agent);
- expect(init.dispatcher).not.toBe(before);
- expect(getGlobalDispatcher()).toBe(before);
- });
-
- it("reuses one pool across requests", async () => {
- const fetchMock = vi
- .spyOn(globalThis, "fetch")
- .mockImplementation(async () => new Response(JSON.stringify({ sandboxID: "sb_2", status: "running" }), { status: 200 }));
- const { Sandbox } = await import("./index.js");
- await Sandbox.connect("sb_2", { apiKey: "k", apiUrl: "https://api.example.test" });
- await Sandbox.connect("sb_2", { apiKey: "k", apiUrl: "https://api.example.test" });
- const pools = fetchMock.mock.calls.map(([, init]) => (init as { dispatcher?: unknown }).dispatcher);
- expect(pools[0]).toBeInstanceOf(Agent);
- expect(pools[1]).toBe(pools[0]);
- });
-});
diff --git a/sdks/typescript/src/usage.ts b/sdks/typescript/src/usage.ts
deleted file mode 100644
index d4c60286..00000000
--- a/sdks/typescript/src/usage.ts
+++ /dev/null
@@ -1,246 +0,0 @@
-import { apiFetch } from "./http2.js";
-// Usage + tags — TypeScript SDK surface.
-//
-// All numeric fields are GB-seconds. Dollars live in Stripe; the SDK
-// intentionally mirrors the server's "physical quantity" model so
-// the invoice stays the source of truth for currency.
-
-function resolveApiUrl(url: string): string {
- const base = url.replace(/\/+$/, "");
- return base.endsWith("/api") ? base : `${base}/api`;
-}
-
-async function throwApiError(resp: Response, action: string): Promise<never> {
- const body = await resp.text();
- const detail = body ? ` ${body}` : "";
- throw new Error(`Failed to ${action}: ${resp.status}${detail}`);
-}
-
-export interface UsageSandboxItem {
- sandboxId: string;
- alias?: string;
- status?: string;
- tags: Record<string, string>;
- tagsLastUpdatedAt: string | null;
- memoryGbSeconds: number;
- diskOverageGbSeconds: number;
-}
-
-export interface UsageTagItem {
- tagKey: string;
- tagValue: string;
- memoryGbSeconds: number;
- diskOverageGbSeconds: number;
- sandboxCount: number;
-}
-
-export interface UsageTotals {
- memoryGbSeconds: number;
- diskOverageGbSeconds: number;
-}
-
-export interface UsageUntaggedBucket extends UsageTotals {
- sandboxCount: number;
-}
-
-export interface UsageBySandboxResponse {
- from: string;
- to: string;
- groupBy: "sandbox";
- total: UsageTotals;
- items: UsageSandboxItem[];
- nextCursor: string | null;
-}
-
-export interface UsageByTagResponse {
- from: string;
- to: string;
- groupBy: string; // "tag:<key>"
- total: UsageTotals;
- untagged: UsageUntaggedBucket;
- items: UsageTagItem[];
- nextCursor: string | null;
-}
-
-export interface UsageFilterMap {
- /**
- * One entry per dimension. Comma-separated values within an entry are
- * OR'd; entries across different dimensions are AND'd. Empty string
- * matches "key absent." Repeating the same dimension is rejected by
- * the server — put multiple values in one comma-separated string.
- */
- [tagFilter: string]: string;
-}
-
-export interface UsageQueryOpts {
- from?: string; // ISO date (YYYY-MM-DD) or RFC3339; default: now - 30d
- to?: string; // ISO date (YYYY-MM-DD) or RFC3339
- filter?: UsageFilterMap;
- sort?: "-memoryGbSeconds" | "-diskOverageGbSeconds";
- limit?: number;
- cursor?: string;
-}
-
-/**
- * One 1-minute bucket of memory usage for a sandbox. Integrals
- * (`*GbSeconds`, `uptimeSeconds`) compose by summation; snapshot scalars
- * (`allocatedMemoryMb`, `usedMemoryMb*`) are for chart rendering.
- *
- * v1 is memory only. CPU fields will be added symmetrically once the
- * server-side collector starts populating cgroup cpu.stat.
- */
-export interface SandboxUsagePoint {
- ts: string; // RFC3339, bucket start, minute-aligned in UTC
- memoryAllocatedGbSeconds: number;
- memoryUsedGbSeconds: number;
- uptimeSeconds: number;
- allocatedMemoryMb: number;
- usedMemoryMbAvg: number;
- usedMemoryMbPeak: number;
-}
-
-/**
- * Envelope totals over `[from, to)`. Server-side invariant: summing
- * the matching field across `points[]` reproduces the value here.
- */
-export interface SandboxUsageTotals {
- memoryAllocatedGbSeconds: number;
- memoryUsedGbSeconds: number;
- uptimeSeconds: number;
- memoryAllocatedPeakMb: number;
- memoryUsedPeakMb: number;
-}
-
-/**
- * Response shape for `GET /api/sandboxes/:id/usage`. Default window is
- * last 1 hour; max window is 30 days (server returns 400 beyond that).
- * Allocation comes from scale events; used memory from cgroup samples.
- *
- * Charts read `points[]`; programmatic consumers usually want `totals`.
- */
-export interface SandboxUsageResponse {
- sandboxId: string;
- alias?: string;
- from: string;
- to: string;
- totals: SandboxUsageTotals;
- points: SandboxUsagePoint[];
-}
-
-export interface TagKeyInfo {
- key: string;
- sandboxCount: number;
- valueCount: number;
-}
-
-export class Usage {
- private apiUrl: string;
-
- constructor(
- apiUrl: string,
- private apiKey: string,
- ) {
- this.apiUrl = resolveApiUrl(apiUrl);
- }
-
- private get headers(): Record<string, string> {
- const h: Record<string, string> = { "Content-Type": "application/json" };
- if (this.apiKey) h["X-API-Key"] = this.apiKey;
- return h;
- }
-
- private buildQueryString(params: Record<string, string | undefined>, filter?: UsageFilterMap): string {
- const u = new URLSearchParams();
- for (const [k, v] of Object.entries(params)) {
- if (v !== undefined && v !== "") u.set(k, v);
- }
- if (filter) {
- for (const [k, v] of Object.entries(filter)) {
- u.append(`filter[${k}]`, v);
- }
- }
- const s = u.toString();
- return s ? `?${s}` : "";
- }
-
- /** `GET /usage?groupBy=sandbox` — top sandboxes by usage. */
- async bySandbox(opts: UsageQueryOpts = {}): Promise<UsageBySandboxResponse> {
- const qs = this.buildQueryString({
- groupBy: "sandbox",
- from: opts.from,
- to: opts.to,
- sort: opts.sort,
- limit: opts.limit?.toString(),
- cursor: opts.cursor,
- }, opts.filter);
- const resp = await apiFetch(`${this.apiUrl}/usage${qs}`, { headers: this.headers });
- if (!resp.ok) await throwApiError(resp, "fetch usage");
- return resp.json();
- }
-
- /** `GET /usage?groupBy=tag:<key>` — usage per tag value, plus untagged sibling bucket. */
- async byTag(tagKey: string, opts: UsageQueryOpts = {}): Promise<UsageByTagResponse> {
- const qs = this.buildQueryString({
- groupBy: `tag:${tagKey}`,
- from: opts.from,
- to: opts.to,
- sort: opts.sort,
- limit: opts.limit?.toString(),
- cursor: opts.cursor,
- }, opts.filter);
- const resp = await apiFetch(`${this.apiUrl}/usage${qs}`, { headers: this.headers });
- if (!resp.ok) await throwApiError(resp, "fetch usage");
- return resp.json();
- }
-
- /** `GET /sandboxes/:id/usage` — per-sandbox drilldown. */
- async forSandbox(sandboxId: string, opts: Pick<UsageQueryOpts, "from" | "to"> = {}): Promise<SandboxUsageResponse> {
- const qs = this.buildQueryString({ from: opts.from, to: opts.to });
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${sandboxId}/usage${qs}`, { headers: this.headers });
- if (!resp.ok) await throwApiError(resp, "fetch sandbox usage");
- return resp.json();
- }
-}
-
-export class Tags {
- private apiUrl: string;
-
- constructor(
- apiUrl: string,
- private apiKey: string,
- ) {
- this.apiUrl = resolveApiUrl(apiUrl);
- }
-
- private get headers(): Record<string, string> {
- const h: Record<string, string> = { "Content-Type": "application/json" };
- if (this.apiKey) h["X-API-Key"] = this.apiKey;
- return h;
- }
-
- /** `GET /tags` — discovery of all tag keys across the org. */
- async listKeys(): Promise<TagKeyInfo[]> {
- const resp = await apiFetch(`${this.apiUrl}/tags`, { headers: this.headers });
- if (!resp.ok) await throwApiError(resp, "list tag keys");
- const body = await resp.json();
- return body.keys;
- }
-
- /** `GET /sandboxes/:id/tags` — current tag set. */
- async get(sandboxId: string): Promise<{ tags: Record<string, string>; tagsLastUpdatedAt: string | null }> {
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${sandboxId}/tags`, { headers: this.headers });
- if (!resp.ok) await throwApiError(resp, "get tags");
- return resp.json();
- }
-
- /** `PUT /sandboxes/:id/tags` — full replace. `{}` clears all tags. */
- async set(sandboxId: string, tags: Record<string, string>): Promise<{ tags: Record<string, string>; tagsLastUpdatedAt: string | null }> {
- const resp = await apiFetch(`${this.apiUrl}/sandboxes/${sandboxId}/tags`, {
- method: "PUT",
- headers: this.headers,
- body: JSON.stringify(tags),
- });
- if (!resp.ok) await throwApiError(resp, "set tags");
- return resp.json();
- }
-}
diff --git a/sdks/typescript/src/verify-webhook.test.ts b/sdks/typescript/src/verify-webhook.test.ts
deleted file mode 100644
index 5b940cdc..00000000
--- a/sdks/typescript/src/verify-webhook.test.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { verifyWebhook, WebhookVerificationError } from "./verify-webhook.js";
-
-const SECRET = "whsec_" + btoa("super-secret-key-bytes-123456");
-
-// Mirror the backend's key derivation (strip whsec_, base64 if it round-trips, else raw UTF-8).
-function keyBytesFor(secret: string): Uint8Array {
- const s = secret.startsWith("whsec_") ? secret.slice("whsec_".length) : secret;
- try {
- const bin = atob(s);
- const decoded = new Uint8Array(bin.length);
- for (let i = 0; i < bin.length; i++) decoded[i] = bin.charCodeAt(i);
- let re = "";
- for (let i = 0; i < decoded.length; i++) re += String.fromCharCode(decoded[i]);
- if (decoded.length > 0 && btoa(re).replace(/=+$/, "") === s.replace(/=+$/, "")) return decoded;
- } catch { /* not base64 */ }
- return new TextEncoder().encode(secret);
-}
-
-async function sign(id: string, ts: number, body: string, secret: string): Promise<string> {
- const key = await crypto.subtle.importKey("raw", new Uint8Array(keyBytesFor(secret)), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
- const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${id}.${ts}.${body}`)));
- let b = "";
- for (let i = 0; i < mac.length; i++) b += String.fromCharCode(mac[i]);
- return "v1," + btoa(b);
-}
-
-describe("verifyWebhook", () => {
- const id = "msg_1";
- const ts = 1_700_000_000;
- const body = JSON.stringify({
- type: "turn.completed", sessionId: "ses_1", eventId: "msg_1",
- metadata: { pull_number: 7 }, event: { id: "evt_1", type: "turn.completed", turn_id: "trn_1" },
- });
- const hdr = (sig: string) => ({ "webhook-id": id, "webhook-timestamp": String(ts), "webhook-signature": sig });
-
- it("accepts a valid signature and returns the parsed envelope (metadata verbatim)", async () => {
- const delivery = await verifyWebhook(body, hdr(await sign(id, ts, body, SECRET)), SECRET, { nowSeconds: ts });
- expect(delivery.type).toBe("turn.completed");
- expect(delivery.eventId).toBe("msg_1");
- expect(delivery.metadata).toEqual({ pull_number: 7 }); // opaque — verbatim
- expect((delivery.event as { turnId?: string }).turnId).toBe("trn_1"); // wire turn_id → camelCase
- });
-
- it("rejects a tampered body", async () => {
- const sig = await sign(id, ts, body, SECRET);
- await expect(verifyWebhook(body + " ", hdr(sig), SECRET, { nowSeconds: ts })).rejects.toThrow(WebhookVerificationError);
- });
-
- it("rejects an out-of-tolerance timestamp (replay)", async () => {
- const sig = await sign(id, ts, body, SECRET);
- await expect(verifyWebhook(body, hdr(sig), SECRET, { nowSeconds: ts + 10_000 })).rejects.toThrow(/tolerance/);
- });
-
- it("rejects a wrong secret", async () => {
- const sig = await sign(id, ts, body, SECRET);
- const wrong = "whsec_" + btoa("different-key-bytes-000000");
- await expect(verifyWebhook(body, hdr(sig), wrong, { nowSeconds: ts })).rejects.toThrow(WebhookVerificationError);
- });
-
- it("accepts when one of several rotated signatures matches", async () => {
- const good = await sign(id, ts, body, SECRET);
- const delivery = await verifyWebhook(body, hdr(`v1,bogus ${good}`), SECRET, { nowSeconds: ts });
- expect(delivery.sessionId).toBe("ses_1");
- });
-
- it("throws on missing headers", async () => {
- await expect(verifyWebhook(body, {}, SECRET, { nowSeconds: ts })).rejects.toThrow(/missing/);
- });
-
- it("verifies a raw (non-base64) secret — backend signs with UTF-8 bytes", async () => {
- const raw = "testsecret"; // not a whsec_/base64 secret → both sides use UTF-8 key bytes
- const delivery = await verifyWebhook(body, hdr(await sign(id, ts, body, raw)), raw, { nowSeconds: ts });
- expect(delivery.type).toBe("turn.completed");
- });
-
- it("sandbox dialect: deliveryId + dedupeId both come from svix-id", async () => {
- const svixId = "msg_svix_1";
- const sbBody = JSON.stringify({
- type: "sandbox.created", sandboxId: "sb_1", eventId: "sb_1:sandbox.created",
- event: { id: "sb_1:sandbox.created", type: "sandbox.created", data: {} },
- });
- const sig = await sign(svixId, ts, sbBody, SECRET);
- const headers = { "svix-id": svixId, "svix-timestamp": String(ts), "svix-signature": sig };
- const delivery = await verifyWebhook(sbBody, headers, SECRET, { nowSeconds: ts });
- expect(delivery.deliveryId).toBe(svixId);
- expect(delivery.dedupeId).toBe(svixId);
- });
-
- it("session dialect: deliveryId = X-OC-Delivery-ID, dedupeId = eventId (webhook-id is the eventId)", async () => {
- const sig = await sign(id, ts, body, SECRET); // id == eventId == "msg_1"
- const headers = {
- "webhook-id": id, "webhook-timestamp": String(ts), "webhook-signature": sig,
- "x-oc-delivery-id": "dlv_99",
- };
- const delivery = await verifyWebhook(body, headers, SECRET, { nowSeconds: ts });
- expect(delivery.deliveryId).toBe("dlv_99"); // the delivery-row id, NOT webhook-id
- expect(delivery.dedupeId).toBe("msg_1"); // eventId
- });
-});
diff --git a/sdks/typescript/src/verify-webhook.ts b/sdks/typescript/src/verify-webhook.ts
deleted file mode 100644
index 3fe70b5a..00000000
--- a/sdks/typescript/src/verify-webhook.ts
+++ /dev/null
@@ -1,191 +0,0 @@
-// Webhook verification for OpenComputer destinations: **sandbox lifecycle** webhooks, and
-// **session** webhooks delivered under the `webhook-` header dialect. One verifier, one envelope.
-//
-// Deliveries are signed with the Standard Webhooks scheme (https://www.standardwebhooks.com).
-// Sandbox webhooks are delivered by Svix, which uses the same scheme under `svix-`-prefixed
-// headers; session webhooks use the `webhook-`-prefixed names. This verifier accepts EITHER:
-// {svix,webhook}-id, {svix,webhook}-timestamp, {svix,webhook}-signature, where
-// signature = "v1,<base64(HMAC-SHA256(secret, `${id}.${timestamp}.${rawBody}`))>"
-// and the secret is the destination's `whsec_…` value. The header may carry several
-// space-separated signatures (key rotation); any match passes.
-//
-// Implemented with Web Crypto (no Node-only deps) so it runs in Cloudflare Workers,
-// browsers, Deno, and Node 16+ — the same places the SDK runs. Verify against the RAW
-// request body, BEFORE JSON-parsing it.
-
-import { normalize } from "./normalize.js";
-
-/** The nested event when the caller names no type: whatever the delivery carried, keyed by `type`. */
-export type WebhookEvent = { type: string; [key: string]: unknown };
-
-/**
- * The envelope OpenComputer POSTs to a destination (camelCase). One shape for both products;
- * the product-specific id is set accordingly. `E` is the nested event type — pass
- * `SandboxLifecycleEvent` for sandbox webhooks.
- */
-export interface WebhookDelivery<E = WebhookEvent> {
- /** The event type — route on this (e.g. `turn.completed`, `sandbox.stopped`). */
- type: string;
- /** Set on **session** webhooks. */
- sessionId?: string;
- /** Set on **sandbox lifecycle** webhooks. */
- sandboxId?: string;
- /** The underlying event id — app-level correlation. */
- eventId: string;
- /**
- * The delivery id, set by {@link verifyWebhook}. **Sandbox** webhooks: the Svix message id
- * (`svix-id`). **Session** webhooks: the delivery-row id (`X-OC-Delivery-ID` header) — note the
- * session `webhook-id` header is the *eventId*, not a delivery id, so it is NOT used here.
- */
- deliveryId?: string;
- /**
- * The idempotency key to dedupe on — stable across retries and redelivery. **Sandbox**: the
- * Svix message id (`svix-id`). **Session**: the `eventId`. Prefer this over {@link deliveryId}
- * for "have I already processed this?" checks.
- */
- dedupeId?: string;
- /**
- * Opaque routing metadata. On **session** webhooks this is carried in the body. On **sandbox**
- * webhooks, per-destination metadata is delivered as custom HTTP **headers** (set at
- * registration), not in the body, so this is absent — read it from the request headers.
- */
- metadata?: Record<string, unknown> | null;
- /** The full event — the same shape the SSE stream emits (session) or the lifecycle event (sandbox). */
- event: E;
-}
-
-export interface VerifyWebhookOptions {
- /** Max allowed clock skew between now and `webhook-timestamp`, in seconds (default 300). */
- toleranceSeconds?: number;
- /** Override "now" (unix seconds) — for testing. */
- nowSeconds?: number;
-}
-
-export class WebhookVerificationError extends Error {
- constructor(message: string) {
- super(message);
- this.name = "WebhookVerificationError";
- }
-}
-
-type HeaderBag = Record<string, string | string[] | undefined>;
-
-function header(headers: HeaderBag | Headers, name: string): string | undefined {
- if (typeof (headers as Headers).get === "function") {
- return (headers as Headers).get(name) ?? undefined; // Headers.get is case-insensitive
- }
- const bag = headers as HeaderBag;
- const v = bag[name] ?? bag[name.toLowerCase()];
- return Array.isArray(v) ? v[0] : v;
-}
-
-function base64ToBytes(b64: string): Uint8Array<ArrayBuffer> {
- const bin = atob(b64);
- const out = new Uint8Array(bin.length);
- for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
- return out;
-}
-
-function bytesToBase64(bytes: Uint8Array): string {
- let bin = "";
- for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
- return btoa(bin);
-}
-
-/**
- * Derive the HMAC key bytes EXACTLY as the backend does (delivery signing): strip the
- * `whsec_` prefix, use the base64-decoded bytes if the remainder round-trips as base64,
- * otherwise fall back to the raw UTF-8 bytes of the ORIGINAL secret. So a destination made
- * with a non-base64 secret (e.g. `"testsecret"`) verifies, matching what the server signed.
- */
-function secretKeyBytes(secret: string): Uint8Array<ArrayBuffer> {
- const s = secret.startsWith("whsec_") ? secret.slice("whsec_".length) : secret;
- try {
- const decoded = base64ToBytes(s);
- if (decoded.length > 0 && bytesToBase64(decoded).replace(/=+$/, "") === s.replace(/=+$/, "")) return decoded;
- } catch {
- /* not base64 → raw bytes below */
- }
- return new Uint8Array(new TextEncoder().encode(secret));
-}
-
-/** Constant-time string compare (equal length → no early-exit on content). */
-function timingSafeEqual(a: string, b: string): boolean {
- if (a.length !== b.length) return false;
- let diff = 0;
- for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
- return diff === 0;
-}
-
-/**
- * Verify a webhook delivery and return its parsed envelope. Throws
- * {@link WebhookVerificationError} on a missing/expired/invalid signature.
- *
- * ```ts
- * import { verifyWebhook } from "@opencomputer/sdk";
- * // in your handler — pass the RAW body string, not a parsed object:
- * const delivery = await verifyWebhook(rawBody, request.headers, process.env.OC_WEBHOOK_SECRET!);
- * if (delivery.type === "turn.completed") { /* route via delivery.metadata *\/ }
- * ```
- */
-export async function verifyWebhook<E = WebhookEvent>(
- rawBody: string,
- headers: HeaderBag | Headers,
- secret: string,
- opts: VerifyWebhookOptions = {},
-): Promise<WebhookDelivery<E>> {
- const id = header(headers, "svix-id") ?? header(headers, "webhook-id");
- const ts = header(headers, "svix-timestamp") ?? header(headers, "webhook-timestamp");
- const sigHeader = header(headers, "svix-signature") ?? header(headers, "webhook-signature");
- if (!id || !ts || !sigHeader) {
- throw new WebhookVerificationError("missing {svix,webhook}-id / -timestamp / -signature header");
- }
-
- const tolerance = opts.toleranceSeconds ?? 300;
- const now = opts.nowSeconds ?? Math.floor(Date.now() / 1000);
- const tsNum = Number(ts);
- if (!Number.isFinite(tsNum)) throw new WebhookVerificationError("invalid webhook-timestamp");
- if (Math.abs(now - tsNum) > tolerance) {
- throw new WebhookVerificationError("webhook-timestamp outside tolerance (possible replay)");
- }
-
- let expected: string;
- try {
- const cryptoKey = await crypto.subtle.importKey("raw", secretKeyBytes(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
- const msg = new Uint8Array(new TextEncoder().encode(`${id}.${ts}.${rawBody}`));
- expected = bytesToBase64(new Uint8Array(await crypto.subtle.sign("HMAC", cryptoKey, msg)));
- } catch (err) {
- throw new WebhookVerificationError(`could not compute signature: ${err instanceof Error ? err.message : String(err)}`);
- }
-
- // Header is space-separated "v1,<sig>" entries (multiple during secret rotation).
- const matched = sigHeader.split(" ").some((entry) => {
- const comma = entry.indexOf(",");
- if (comma < 0) return false;
- return entry.slice(0, comma) === "v1" && timingSafeEqual(entry.slice(comma + 1), expected);
- });
- if (!matched) throw new WebhookVerificationError("no matching webhook signature");
-
- try {
- // Normalize so the returned envelope + nested event match the SDK's camelCase types
- // (the wire event is snake-cased, e.g. `turn_id`). The two products use different header
- // dialects + delivery-id ownership, so resolve deliveryId/dedupeId by dialect:
- // - Sandbox (Svix): `svix-id` is BOTH the stable delivery id and the dedupe key.
- // - Session: the signed `webhook-id` is the *eventId* (dedupe on it); the delivery-row id
- // rides separately in `X-OC-Delivery-ID`.
- const delivery = normalize(JSON.parse(rawBody)) as WebhookDelivery<E>;
- const svixId = header(headers, "svix-id");
- if (svixId) {
- delivery.deliveryId = svixId;
- delivery.dedupeId = svixId;
- } else {
- const deliveryRowId = header(headers, "x-oc-delivery-id");
- if (deliveryRowId) delivery.deliveryId = deliveryRowId;
- // webhook-id == eventId for sessions; prefer the body's eventId, fall back to the header.
- delivery.dedupeId = delivery.eventId ?? id;
- }
- return delivery;
- } catch {
- throw new WebhookVerificationError("signature valid but body is not JSON");
- }
-}
diff --git a/sdks/typescript/src/version.test.ts b/sdks/typescript/src/version.test.ts
deleted file mode 100644
index b54a02ce..00000000
--- a/sdks/typescript/src/version.test.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { SDK_VERSION, SDK_VERSION_HEADER, sdkVersionHeaders } from "./version.js";
-
-describe("SDK version", () => {
- // The server routes creates by the MAJOR of this value. If the constant drifts
- // from the published version, a v2 release goes out still announcing whatever
- // was hardcoded — and every customer who upgrades stays on the old runtime
- // with no error anywhere.
- it("matches package.json", () => {
- const pkgPath = fileURLToPath(new URL("../package.json", import.meta.url));
- const pkg = JSON.parse(readFileSync(pkgPath, "utf8")) as { version: string };
- expect(SDK_VERSION).toBe(pkg.version);
- });
-
- // HTTP/2 rejects upper-case header names outright, and this SDK speaks h2.
- it("uses a lower-case header name", () => {
- expect(SDK_VERSION_HEADER).toBe(SDK_VERSION_HEADER.toLowerCase());
- });
-
- // Every previously published version is 0.x, so a major of at least 1 is what
- // separates a caller routed to MicroVM from one that is not.
- it("announces a stable major", () => {
- expect(Number(SDK_VERSION.split(".")[0])).toBeGreaterThanOrEqual(1);
- expect(sdkVersionHeaders()[SDK_VERSION_HEADER]).toBe(SDK_VERSION);
- });
-});
diff --git a/sdks/typescript/src/version.ts b/sdks/typescript/src/version.ts
deleted file mode 100644
index d91c9a6a..00000000
--- a/sdks/typescript/src/version.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-// The SDK's own identity, sent on the two requests that decide which runtime
-// serves a customer: creating a sandbox and creating a template.
-//
-// This is what makes self-service migration possible. An org that has not been
-// pinned to a runtime lands on the MicroVM backend when it calls with a 1.x SDK
-// and on the QEMU fleet when it calls with an older one — so upgrading the
-// dependency IS the migration, and pinning the old version is the rollback.
-// Nothing has to be changed in our database for either direction.
-//
-// 1.0.0, not 2.0.0, even though the docs call this platform generation "v2":
-// every version this package has ever published is 0.x, so 1.0.0 is both the
-// first stable release and a clean major break from all of them. The product
-// generation and the package major are not the same number.
-//
-// Only the MAJOR is load-bearing: the server compares it against a minimum, so
-// patch and minor releases never move anyone.
-
-/** Header carrying the version below. Lower-case: HTTP/2 requires it. */
-export const SDK_VERSION_HEADER = "x-oc-sdk-version";
-
-/**
- * This package's version.
- *
- * Kept as a literal rather than read from package.json, because the SDK ships
- * as an ESM bundle that may be consumed by bundlers where a JSON import is not
- * resolvable. version.test.ts asserts it matches package.json, which is the
- * only failure mode that matters — a stale constant here would silently route a
- * v2 caller to the old runtime.
- */
-export const SDK_VERSION = "2.3.1";
-
-/** The identifying header, as a spreadable object. */
-export function sdkVersionHeaders(): Record<string, string> {
- return { [SDK_VERSION_HEADER]: SDK_VERSION };
-}
diff --git a/sdks/typescript/src/webhooks.ts b/sdks/typescript/src/webhooks.ts
deleted file mode 100644
index 41c40a29..00000000
--- a/sdks/typescript/src/webhooks.ts
+++ /dev/null
@@ -1,326 +0,0 @@
-import { apiFetch } from "./http2.js";
-// Sandbox lifecycle webhooks — the account-level control surface.
-//
-// PREVIEW: newly available functionality; the surface may change.
-//
-// Register a destination and OpenComputer delivers sandbox lifecycle events to it as a small,
-// signed envelope — at-least-once, retried with managed backoff, and redeliverable (delivery is
-// handled by Svix). This is the management client (org API key, server-side); to VERIFY an
-// incoming delivery in your handler use `verifyWebhook` (exported from the package root, shared
-// with session webhooks).
-//
-// import { Webhooks } from "@opencomputer/sdk";
-// const webhooks = new Webhooks({ apiKey: process.env.OPENCOMPUTER_API_KEY });
-// const { id, secret } = await webhooks.create({ url: "https://app.example.com/oc" });
-// // `secret` verifies deliveries; it's returned here and re-fetchable via webhooks.getSecret(id).
-
-import type { WebhookDelivery } from "./verify-webhook.js";
-
-function resolveApiUrl(url: string): string {
- const base = url.replace(/\/+$/, "");
- return base.endsWith("/api") ? base : `${base}/api`;
-}
-
-// ---- the delivered envelope (what your endpoint receives; verify with `verifyWebhook`) ----
-
-export type SandboxWebhookEventType =
- | "sandbox.created"
- | "sandbox.ready"
- | "sandbox.hibernated"
- | "sandbox.resumed"
- | "sandbox.stopped"
- | "sandbox.migrated"
- | "sandbox.checkpoint.created"
- | "sandbox.forked"
- | "sandbox.scaled"
- | "sandbox.preview_url.changed"
- | "sandbox.test";
-
-/** Why a sandbox stopped (`sandbox.stopped` → `event.data.reason`). */
-export type SandboxStopReason = "user_requested" | "expired" | "crash";
-
-/** Fields common to every lifecycle event (nested under `event` in a delivery). */
-export interface SandboxLifecycleEventBase {
- id: string;
- ts: string;
- orgId: string;
- sandboxId: string;
-}
-
-/**
- * The lifecycle event nested under `event` in a delivery — a discriminated union
- * on `type`, so `event.data` is typed per event (e.g. narrow on
- * `event.type === "sandbox.stopped"` to get `event.data.reason`).
- */
-export type SandboxLifecycleEvent = SandboxLifecycleEventBase &
- (
- | { type: "sandbox.created"; data: { template?: string } }
- | { type: "sandbox.ready"; data: Record<string, never> }
- | { type: "sandbox.hibernated"; data: Record<string, never> }
- | { type: "sandbox.resumed"; data: Record<string, never> }
- | { type: "sandbox.stopped"; data: { reason: SandboxStopReason } }
- | { type: "sandbox.migrated"; data: Record<string, never> }
- | { type: "sandbox.checkpoint.created"; data: { checkpointId: string } }
- | { type: "sandbox.forked"; data: { parentId: string } }
- | { type: "sandbox.scaled"; data: { cpuCount: number; memoryMB: number } }
- | { type: "sandbox.preview_url.changed"; data: { port: number; url: string | null } }
- | { type: "sandbox.test"; data: Record<string, unknown> }
- );
-
-/**
- * The delivered envelope for sandbox webhooks: the shared {@link WebhookDelivery} carrying a
- * {@link SandboxLifecycleEvent} under `event`. Delivered by Svix; `sandboxId`, `deliveryId`, and
- * `dedupeId` are always set, and all equal the `svix-id` header (stable across retries — dedupe on
- * `dedupeId`). Per-destination registration metadata arrives as custom HTTP headers, not in the body.
- *
- * Verify an incoming request with: `verifyWebhook<SandboxLifecycleEvent>(rawBody, headers, secret)`.
- */
-export type SandboxWebhookDelivery = WebhookDelivery<SandboxLifecycleEvent>;
-
-// ---- destinations ----
-
-export interface WebhookDestination {
- id: string;
- name: string | null;
- url: string;
- /** Event-type allow-list (exact or `prefix.*`); empty = all. */
- eventTypes: string[];
- /** Scoped to one sandbox, or `null` for all of the org's sandboxes. */
- sandboxId: string | null;
- enabled: boolean;
- /** Whether a signing secret is set; fetch the value any time with {@link Webhooks.getSecret}. */
- hasSecret: boolean;
- createdAt: string;
- updatedAt: string;
-}
-
-export interface CreateWebhookParams {
- url: string;
- /** Optional display name for the destination. */
- name?: string;
- /** Signing secret. Omit and OpenComputer generates a `whsec_…` one (re-fetchable via {@link Webhooks.getSecret}). */
- secret?: string;
- /** Event-type allow-list (exact, e.g. `sandbox.stopped`, or `prefix.*`); default all. Unknown types are rejected. */
- eventTypes?: string[];
- /** Scope to one sandbox; omit for all of the org's sandboxes. */
- sandboxId?: string;
- enabled?: boolean;
- /** Idempotency-Key: a retried create with the same key returns the same destination (200), never a duplicate. */
- idempotencyKey?: string;
-}
-
-/** The create response — includes the signing `secret` (also re-fetchable later via {@link Webhooks.getSecret}). */
-export interface CreateWebhookResult extends WebhookDestination {
- /** The signing secret (`whsec_…`). Returned here on create, and re-fetchable any time via {@link Webhooks.getSecret}. */
- secret?: string;
-}
-
-export interface UpdateWebhookParams {
- url?: string;
- /** Pass `null` to clear the allow-list (deliver all types). Unknown types are rejected. */
- eventTypes?: string[] | null;
- enabled?: boolean;
- /**
- * Rotate to a NEW Svix-generated signing secret — returned on the response (see
- * {@link CreateWebhookResult}). The previous secret stays valid for a short rollover window so
- * in-flight deliveries still verify. (To set a specific secret, create a new destination.)
- */
- rotateSecret?: boolean;
- name?: string;
-}
-
-/** Scope (`sandboxId`) is immutable — set it at create; it can't be changed by update. */
-
-// ---- deliveries (the control surface behind a deliveries dashboard) ----
-
-export type WebhookDeliveryStatus = "success" | "pending" | "failed";
-
-/** One Svix delivery attempt to the endpoint (from `deliveries.list`). */
-export interface WebhookDeliveryRecord {
- /** The message id — the key for `get` / `redeliver`; equals the `svix-id` header. */
- id: string;
- status: WebhookDeliveryStatus;
- /** The consumer's HTTP response code, when the attempt reached it. */
- responseStatusCode?: number;
- timestamp?: string;
-}
-
-/** A delivered message (from `deliveries.get`). */
-export interface WebhookMessage {
- id: string;
- eventType?: string;
- eventId?: string;
- payload?: unknown;
- timestamp?: string;
-}
-
-export interface WebhookTestResult {
- /** The test message was accepted by Svix for delivery (delivery itself is async). */
- ok: boolean;
- /** The event type sent — a type the destination is subscribed to. */
- eventType?: string;
- /** The Svix message id; find its attempt under `deliveries`. */
- messageId?: string;
-}
-
-export interface ListPage<T> {
- data: T[];
- nextCursor: string | null;
- hasMore: boolean;
-}
-
-export interface WebhooksOptions {
- /** Defaults to `process.env.OPENCOMPUTER_API_KEY`. */
- apiKey?: string;
- /** Defaults to `process.env.OPENCOMPUTER_API_URL` or `https://app.opencomputer.dev`. */
- apiUrl?: string;
-}
-
-async function fail(resp: Response, what: string): Promise<never> {
- let detail = "";
- try {
- const body = (await resp.json()) as { error?: { message?: string } | string };
- detail = typeof body.error === "string" ? body.error : body.error?.message ?? "";
- } catch {
- /* no JSON body */
- }
- throw new Error(`${what}: HTTP ${resp.status}${detail ? ` — ${detail}` : ""}`);
-}
-
-/** Delivery records for the org's webhook destinations. Reached via `webhooks.deliveries`. */
-export class WebhookDeliveries {
- constructor(
- private readonly apiUrl: string,
- private readonly apiKey: string,
- ) {}
-
- private get headers(): Record<string, string> {
- const h: Record<string, string> = { "Content-Type": "application/json" };
- if (this.apiKey) h["X-API-Key"] = this.apiKey;
- return h;
- }
-
- /** List recent delivery attempts for a destination. */
- async list(destinationId: string): Promise<WebhookDeliveryRecord[]> {
- const resp = await apiFetch(`${this.apiUrl}/webhooks/${destinationId}/deliveries`, {
- headers: this.headers,
- });
- if (!resp.ok) return fail(resp, "list deliveries");
- const body = (await resp.json()) as { data?: WebhookDeliveryRecord[] };
- return body.data ?? [];
- }
-
- /** Fetch one delivered message by id. */
- async get(destinationId: string, deliveryId: string): Promise<WebhookMessage> {
- const resp = await apiFetch(`${this.apiUrl}/webhooks/${destinationId}/deliveries/${deliveryId}`, {
- headers: this.headers,
- });
- if (!resp.ok) return fail(resp, "get delivery");
- return resp.json();
- }
-
- /**
- * Re-send a message to the endpoint. The redelivery carries the **same** `svix-id`, so a
- * receiver that dedupes treats it as the same message — for when the original never landed.
- */
- async redeliver(destinationId: string, deliveryId: string): Promise<{ ok: boolean }> {
- const resp = await apiFetch(`${this.apiUrl}/webhooks/${destinationId}/deliveries/${deliveryId}/redeliver`, {
- method: "POST",
- headers: this.headers,
- });
- if (!resp.ok) return fail(resp, "redeliver");
- return resp.json();
- }
-}
-
-/**
- * Manage webhook destinations for sandbox lifecycle events. Server-side only — uses the org
- * API key. To verify an incoming delivery, use `verifyWebhook` (package root).
- *
- * **Preview:** newly available; the surface may change.
- */
-export class Webhooks {
- readonly deliveries: WebhookDeliveries;
- private readonly apiUrl: string;
- private readonly apiKey: string;
-
- constructor(opts: WebhooksOptions = {}) {
- this.apiUrl = resolveApiUrl(opts.apiUrl ?? process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev");
- this.apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";
- this.deliveries = new WebhookDeliveries(this.apiUrl, this.apiKey);
- }
-
- private headers(extra?: Record<string, string>): Record<string, string> {
- const h: Record<string, string> = { "Content-Type": "application/json", ...extra };
- if (this.apiKey) h["X-API-Key"] = this.apiKey;
- return h;
- }
-
- /**
- * Register a destination (HTTP 201). Without an `idempotencyKey`, each call creates a new
- * destination — there is no get-or-create. With one, a retried call returns the same destination
- * (HTTP 200) instead of a duplicate. The response includes the signing `secret` (also re-fetchable
- * later via {@link getSecret}). Unknown `eventTypes` are rejected with a 400.
- */
- async create(params: CreateWebhookParams): Promise<CreateWebhookResult> {
- const { idempotencyKey, ...body } = params;
- const resp = await apiFetch(`${this.apiUrl}/webhooks`, {
- method: "POST",
- headers: this.headers(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : undefined),
- body: JSON.stringify(body),
- });
- if (!resp.ok) return fail(resp, "create webhook");
- return resp.json();
- }
-
- async list(): Promise<WebhookDestination[]> {
- const resp = await apiFetch(`${this.apiUrl}/webhooks`, { headers: this.headers() });
- if (!resp.ok) return fail(resp, "list webhooks");
- const body = (await resp.json()) as { data?: WebhookDestination[] } | WebhookDestination[];
- return Array.isArray(body) ? body : body.data ?? [];
- }
-
- async get(id: string): Promise<WebhookDestination> {
- const resp = await apiFetch(`${this.apiUrl}/webhooks/${id}`, { headers: this.headers() });
- if (!resp.ok) return fail(resp, "get webhook");
- return resp.json();
- }
-
- /**
- * Fetch the destination's current signing secret (`whsec_…`). Re-fetchable any time by the
- * owner (API key) — use it to verify deliveries. Rotate with `update(id, { rotateSecret: true })`.
- */
- async getSecret(id: string): Promise<string> {
- const resp = await apiFetch(`${this.apiUrl}/webhooks/${id}/secret`, { headers: this.headers() });
- if (!resp.ok) return fail(resp, "get webhook secret");
- const body = (await resp.json()) as { secret: string };
- return body.secret;
- }
-
- /** Update a destination — pause/resume (`enabled`), retune `eventTypes`, change `url`, or rotate `secret`. */
- async update(id: string, params: UpdateWebhookParams): Promise<CreateWebhookResult> {
- const resp = await apiFetch(`${this.apiUrl}/webhooks/${id}`, {
- method: "PATCH",
- headers: this.headers(),
- body: JSON.stringify(params),
- });
- if (!resp.ok) return fail(resp, "update webhook");
- return resp.json();
- }
-
- /** Delete a destination (removes its Svix endpoint). Delivery history for a deleted destination is no longer queryable. */
- async delete(id: string): Promise<void> {
- const resp = await apiFetch(`${this.apiUrl}/webhooks/${id}`, { method: "DELETE", headers: this.headers() });
- if (!resp.ok) return fail(resp, "delete webhook");
- }
-
- /**
- * Send a sample event (of a type the destination is subscribed to) to exercise the endpoint.
- * Returns the queued Svix message; delivery is asynchronous — check `deliveries` for the result.
- */
- async test(id: string): Promise<WebhookTestResult> {
- const resp = await apiFetch(`${this.apiUrl}/webhooks/${id}/test`, { method: "POST", headers: this.headers() });
- if (!resp.ok) return fail(resp, "test webhook");
- return resp.json();
- }
-}
diff --git a/sdks/typescript/src/websocket.ts b/sdks/typescript/src/websocket.ts
deleted file mode 100644
index faded21c..00000000
--- a/sdks/typescript/src/websocket.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-// websocket.ts — opening a WebSocket without tripping over our own HTTP/2 agent.
-//
-// The REST surface runs on an undici Agent with `allowH2: true` (http2.ts):
-// h2 multiplexes a burst of creates down one connection. A WebSocket must not
-// use that agent: it would negotiate h2 via ALPN and then try to upgrade, and
-// a WebSocket over h2 needs RFC 8441 extended CONNECT, which the server's
-// WebSocket library does not implement (nor do most), so the upgrade simply
-// fails.
-//
-// Measured against dev, same URL, back to back:
-//
-// default dispatcher (no allowH2): OPEN
-// allowH2:true dispatcher : ERROR
-//
-// So WebSockets get their own dispatcher with h2 off, passed per connection.
-// The REST path keeps h2 and its prewarmed pool; only the upgrade is forced
-// down HTTP/1.1, which is what an upgrade requires anyway. Neither agent is
-// ever installed as the process's global dispatcher.
-
-let wsDispatcher: unknown | null = null;
-let wsCtor: typeof WebSocket | null = null;
-
-async function nodeWebSocket(): Promise<typeof WebSocket | null> {
- const isNode = typeof process !== "undefined" && !!process.versions?.node;
- if (!isNode) return null; // browsers speak WebSocket natively; nothing to fix
- try {
- const undici = await import("undici");
- if (!wsDispatcher) {
- // allowH2 omitted (defaults false) rather than set — an h1-only agent is
- // the point, and spelling it out invites someone to "align" it with the
- // global one later.
- wsDispatcher = new undici.Agent({ keepAliveTimeout: 60_000 });
- }
- return undici.WebSocket as unknown as typeof WebSocket;
- } catch {
- return null; // stripped-down install — fall back to whatever global exists
- }
-}
-
-// openWebSocket resolves once the socket is OPEN, and rejects if it errors or
-// closes first.
-//
-// Resolving early is its own bug: a CONNECTING socket throws "Sent before
-// connected" on the first send, and creating a PTY then immediately typing
-// into it is the normal way to use one.
-export async function openWebSocket(url: string): Promise<WebSocket> {
- if (!wsCtor) wsCtor = await nodeWebSocket();
- const Ctor = wsCtor ?? (globalThis as { WebSocket?: typeof WebSocket }).WebSocket;
- if (!Ctor) throw new Error("no WebSocket implementation available in this environment");
-
- const ws = wsDispatcher
- ? new (Ctor as unknown as new (u: string, o: unknown) => WebSocket)(url, { dispatcher: wsDispatcher })
- : new Ctor(url);
- ws.binaryType = "arraybuffer";
-
- await new Promise<void>((resolve, reject) => {
- let opened = false;
- ws.onopen = () => {
- opened = true;
- resolve();
- };
- ws.onerror = () => {
- if (!opened) reject(new Error(`WebSocket connection failed: ${url}`));
- };
- ws.onclose = () => {
- if (!opened) reject(new Error(`WebSocket closed before opening: ${url}`));
- };
- });
- // Handlers are cleared so a caller's own onerror/onclose are not shadowed by
- // the ones used to await the open.
- ws.onopen = null;
- ws.onerror = null;
- ws.onclose = null;
- return ws;
-}