@tangle-network/sandbox 0.13.0-develop.20260726140131.65bdb24 → 0.13.0-develop.20260726161607.1f7da8b
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +254 -1295
- package/dist/agent/index.d.ts +11 -11
- package/dist/auth/index.d.ts +1 -1
- package/dist/{client-BDejoJQR.d.ts → client-CdpU6vjj.d.ts} +23 -28
- package/dist/{client-DS8qSxCp.js → client-Cz6oQM1P.js} +86 -78
- package/dist/collaboration/index.d.ts +1 -1
- package/dist/core.d.ts +5 -5
- package/dist/core.js +3 -3
- package/dist/{index-DwjU-4s_.d.ts → index-Cl5Vyyz7.d.ts} +2 -2
- package/dist/index.d.ts +3323 -516
- package/dist/index.js +271 -328
- package/dist/intelligence/index.d.ts +2 -2
- package/dist/intelligence/index.js +3 -3
- package/dist/local-cli-auth-DHBoF3wi.js +35 -0
- package/dist/openai/index.d.ts +1 -1
- package/dist/{runtime-api-BFtk4_HK.js → runtime-api-fZ4UDwOY.js} +30 -17
- package/dist/runtime.d.ts +2 -3
- package/dist/runtime.js +1 -1
- package/dist/{sandbox-CxflW4z4.d.ts → sandbox-Bz7kCFtN.d.ts} +11 -78
- package/dist/{sandbox-DXuuroty.js → sandbox-kHfb3J4x.js} +36 -217
- package/dist/tangle/index.d.ts +1 -1
- package/dist/tangle/index.js +1 -1
- package/dist/{tangle-46aLycNc.js → tangle-BdbEHJRy.js} +9 -31
- package/dist/{types-DFYV3JSL.d.ts → types-Ch78hv3k.d.ts} +218 -331
- package/package.json +5 -3
- /package/dist/{errors-C8HMx78o.d.ts → errors-BzMmpmqU.d.ts} +0 -0
- /package/dist/{index-DKzapw-9.d.ts → index-Cp1KYanB.d.ts} +0 -0
- /package/dist/{index-CyHojkuA.d.ts → index-DtRFVx5U.d.ts} +0 -0
package/README.md
CHANGED
|
@@ -1,1449 +1,408 @@
|
|
|
1
1
|
# @tangle-network/sandbox
|
|
2
2
|
|
|
3
|
-
TypeScript SDK for creating and
|
|
4
|
-
|
|
5
|
-
agent tool adapters, streaming sessions, and trace intelligence.
|
|
3
|
+
TypeScript SDK for creating isolated development environments, running commands and agents, managing sessions, and coordinating fleets.
|
|
4
|
+
The package is ESM-only and works in Node.js, edge runtimes, and browsers through separate entrypoints.
|
|
6
5
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
## Agent quick start
|
|
10
|
-
|
|
11
|
-
Use this path when an AI coding agent needs real compute before editing code,
|
|
12
|
-
running tests, or executing user-provided programs.
|
|
6
|
+
## Install
|
|
13
7
|
|
|
14
8
|
```bash
|
|
15
9
|
npm install @tangle-network/sandbox
|
|
16
|
-
export TANGLE_API_KEY=sk-tan-...
|
|
17
|
-
export SANDBOX_BASE_URL=https://sandbox.tangle.tools
|
|
18
10
|
```
|
|
19
11
|
|
|
20
|
-
|
|
21
|
-
import { Sandbox } from "@tangle-network/sandbox";
|
|
22
|
-
|
|
23
|
-
const client = new Sandbox({
|
|
24
|
-
apiKey: process.env.TANGLE_API_KEY!,
|
|
25
|
-
baseUrl: process.env.SANDBOX_BASE_URL ?? "https://sandbox.tangle.tools",
|
|
26
|
-
});
|
|
27
|
-
|
|
28
|
-
const box = await client.create({
|
|
29
|
-
environment: "universal",
|
|
30
|
-
name: "agent-smoke",
|
|
31
|
-
});
|
|
32
|
-
|
|
33
|
-
try {
|
|
34
|
-
const result = await box.exec("node --version && npm --version");
|
|
35
|
-
console.log(result.stdout);
|
|
36
|
-
} finally {
|
|
37
|
-
await box.delete();
|
|
38
|
-
}
|
|
39
|
-
```
|
|
40
|
-
|
|
41
|
-
Discovery calls that are safe to run before creating a sandbox:
|
|
12
|
+
Set the customer API key and Sandbox API URL in your server environment.
|
|
42
13
|
|
|
43
14
|
```bash
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
curl -fsS https://sandbox.tangle.tools/v1/public-templates/featured
|
|
47
|
-
```
|
|
48
|
-
|
|
49
|
-
If sandbox creation hangs or times out, do not generate fallback code that
|
|
50
|
-
pretends to have run in a sandbox. Surface the failure, keep the `sandboxId` or
|
|
51
|
-
request id, and retry with the same idempotency key when available.
|
|
52
|
-
|
|
53
|
-
### Temporary GPU for evals
|
|
54
|
-
|
|
55
|
-
Keep the base sandbox cheap and attach a GPU only around the command that needs it.
|
|
56
|
-
Omit `provider` to let the platform choose the cheapest configured GPU cloud.
|
|
57
|
-
Every GPU lease needs a hard spend cap and lifetime.
|
|
58
|
-
|
|
59
|
-
```typescript
|
|
60
|
-
const lease = await box.gpu.attach({
|
|
61
|
-
accelerator: { kind: "nvidia-3090", count: 1, memoryMB: 24_000 },
|
|
62
|
-
maxSpendUsd: 1,
|
|
63
|
-
maxLifetimeSeconds: 900,
|
|
64
|
-
idleTimeoutSeconds: 120,
|
|
65
|
-
});
|
|
66
|
-
|
|
67
|
-
try {
|
|
68
|
-
const result = await box.gpu.exec(lease.id, {
|
|
69
|
-
command: "python eval.py",
|
|
70
|
-
timeoutMs: 15 * 60 * 1000,
|
|
71
|
-
});
|
|
72
|
-
console.log(result.result.stdout);
|
|
73
|
-
} finally {
|
|
74
|
-
await box.gpu.detach(lease.id);
|
|
75
|
-
}
|
|
15
|
+
export TANGLE_API_KEY=sk-tan-...
|
|
16
|
+
export SANDBOX_BASE_URL=https://sandbox.tangle.tools
|
|
76
17
|
```
|
|
77
18
|
|
|
78
|
-
|
|
79
|
-
See `examples/gpu-eval-lease.ts` for the full create, run, detach, and sandbox cleanup flow.
|
|
19
|
+
## Choose an entrypoint
|
|
80
20
|
|
|
81
|
-
|
|
21
|
+
| Need | Import |
|
|
22
|
+
|---|---|
|
|
23
|
+
| Full client, sandboxes, fleets, images, sessions, and trace utilities | `@tangle-network/sandbox` |
|
|
24
|
+
| Edge-safe client without `viem` | `@tangle-network/sandbox/core` |
|
|
25
|
+
| Browser or Worker access with a short-lived scoped token | `@tangle-network/sandbox/runtime` |
|
|
26
|
+
| Direct Tangle chain operations | `@tangle-network/sandbox/tangle` |
|
|
27
|
+
| Server-side token issuance and validation | `@tangle-network/sandbox/auth` |
|
|
28
|
+
| Collaborative document clients and file bridging | `@tangle-network/sandbox/collaboration` |
|
|
29
|
+
| Browser WebSocket session streaming and replay | `@tangle-network/sandbox/session-gateway` |
|
|
30
|
+
| OpenAI-compatible request and event translation | `@tangle-network/sandbox/openai` |
|
|
31
|
+
| Agent framework tool packs and the local MCP bridge | `@tangle-network/sandbox/agent` |
|
|
32
|
+
| Browser-safe trace reads from Tangle Intelligence | `@tangle-network/sandbox/intelligence` |
|
|
82
33
|
|
|
83
|
-
|
|
84
|
-
npm install @tangle-network/sandbox
|
|
85
|
-
# or
|
|
86
|
-
pnpm add @tangle-network/sandbox
|
|
87
|
-
# or
|
|
88
|
-
yarn add @tangle-network/sandbox
|
|
89
|
-
```
|
|
34
|
+
Install an optional peer dependency only when the selected integration requires it.
|
|
90
35
|
|
|
91
|
-
## Quick
|
|
36
|
+
## Quick start
|
|
92
37
|
|
|
93
38
|
```typescript
|
|
94
39
|
import { Sandbox } from "@tangle-network/sandbox";
|
|
95
|
-
|
|
96
40
|
const client = new Sandbox({
|
|
97
41
|
apiKey: process.env.TANGLE_API_KEY!,
|
|
98
|
-
baseUrl: process.env.SANDBOX_BASE_URL
|
|
99
|
-
});
|
|
100
|
-
|
|
101
|
-
// Create a sandbox
|
|
102
|
-
const box = await client.create({
|
|
103
|
-
name: "my-project",
|
|
104
|
-
environment: "node:20",
|
|
105
|
-
});
|
|
106
|
-
|
|
107
|
-
// Execute commands
|
|
108
|
-
const result = await box.exec("npm install && npm test");
|
|
109
|
-
console.log(result.stdout);
|
|
110
|
-
|
|
111
|
-
// Run an AI agent task
|
|
112
|
-
const task = await box.task("Fix any failing tests and commit the changes");
|
|
113
|
-
console.log(task.response);
|
|
114
|
-
|
|
115
|
-
// Clean up
|
|
116
|
-
await box.delete();
|
|
117
|
-
```
|
|
118
|
-
|
|
119
|
-
## Custom Images
|
|
120
|
-
|
|
121
|
-
Build a reusable image once, then create sandboxes from the returned image id.
|
|
122
|
-
The SDK sends the build to the public sandbox API, which forwards it to the
|
|
123
|
-
orchestrator image builder and cache.
|
|
124
|
-
|
|
125
|
-
```typescript
|
|
126
|
-
import { Image, Sandbox } from "@tangle-network/sandbox";
|
|
127
|
-
|
|
128
|
-
const client = new Sandbox({
|
|
129
|
-
apiKey: process.env.TANGLE_API_KEY!,
|
|
130
|
-
baseUrl: process.env.SANDBOX_BASE_URL ?? "https://sandbox.tangle.tools",
|
|
131
|
-
});
|
|
132
|
-
|
|
133
|
-
const image = await Image.create("python:3.12-slim")
|
|
134
|
-
.addPackages(["numpy", "pandas"])
|
|
135
|
-
.addCommands(["python - <<'PY'\nprint('image ready')\nPY"])
|
|
136
|
-
.build({ client });
|
|
137
|
-
|
|
138
|
-
const box = await client.create({ environment: image.id });
|
|
139
|
-
```
|
|
140
|
-
|
|
141
|
-
## Stream durability is platform-managed — do not build your own
|
|
142
|
-
|
|
143
|
-
> **If you are about to add a Cloudflare Durable Object, a KV bucket, an in-Worker
|
|
144
|
-
> ring buffer, or any other state store to "buffer agent stream events so the user
|
|
145
|
-
> survives a reload" — stop.** The Tangle orchestrator already buffers every event
|
|
146
|
-
> for every session to a Redis sorted-set keyed by `sessionId` with TTL, and the
|
|
147
|
-
> SDK ships a browser/Worker-safe client that reconnects, replays missed events,
|
|
148
|
-
> and persists `lastEventId` across tab reloads. The work is done. Use it.
|
|
149
|
-
|
|
150
|
-
The decision tree:
|
|
151
|
-
|
|
152
|
-
| You need… | Use |
|
|
153
|
-
|---|---|
|
|
154
|
-
| Fire-and-forget streaming from a server you control (CLI, cron, batch worker) | `box.streamPrompt()` / `box.streamTask()` — internal auto-reconnect handles transient drops within the same call |
|
|
155
|
-
| Survive **client process death** (Worker isolate eviction, laptop crash, deploy) and resume later | `box.dispatchPrompt(msg, { sessionId })` then `box.session(sessionId).events({ since })` / `.result()` from a fresh process |
|
|
156
|
-
| Survive **browser** disconnects (wifi flap, tab reload, mobile background) with `Last-Event-ID` replay | `SessionGatewayClient` from `@tangle-network/sandbox/session-gateway` |
|
|
157
|
-
| Retry a payment-triggered or webhook-triggered run safely | `box.dispatchPrompt(msg, { sessionId: deterministicKeyFromRequest })` — same `sessionId` is idempotent: a duplicate dispatch returns the in-flight or completed session, never re-executes |
|
|
158
|
-
| Inspect what happened to a turn that died mid-stream | `box.session(id).status()` (terminal state), `box.session(id).events({ since })` (replay buffered events) |
|
|
159
|
-
|
|
160
|
-
### Dispatch + reconnect (the "Worker restart" pattern)
|
|
161
|
-
|
|
162
|
-
```typescript
|
|
163
|
-
import { Sandbox } from "@tangle-network/sandbox/core";
|
|
164
|
-
|
|
165
|
-
const client = new Sandbox({ apiKey: process.env.TANGLE_API_KEY! });
|
|
166
|
-
|
|
167
|
-
// In your /chat handler, authenticate first. Derive this stable runtime
|
|
168
|
-
// session ID from the authenticated user, conversation, and turn with a
|
|
169
|
-
// server-side HMAC; never accept a caller-selected runtime session ID.
|
|
170
|
-
const turnId = requireStableTurnId(req);
|
|
171
|
-
const sessionId = await deriveOwnedTurnSessionId(
|
|
172
|
-
user.id,
|
|
173
|
-
conversationId,
|
|
174
|
-
turnId,
|
|
175
|
-
);
|
|
176
|
-
const { sessionId: id, alreadyExisted } = await box.dispatchPrompt(prompt, {
|
|
177
|
-
sessionId,
|
|
178
|
-
turnId,
|
|
179
|
-
});
|
|
180
|
-
|
|
181
|
-
// Stream to the browser; if the client comes back later with the same sessionId
|
|
182
|
-
// and a Last-Event-ID, hand them the replay path below.
|
|
183
|
-
for await (const event of box.session(id).events({
|
|
184
|
-
since: req.headers.get("last-event-id") ?? undefined,
|
|
185
|
-
})) {
|
|
186
|
-
res.write(`id: ${event.id}\ndata: ${JSON.stringify(event)}\n\n`);
|
|
187
|
-
}
|
|
188
|
-
```
|
|
189
|
-
|
|
190
|
-
### Browser-direct streaming (without proxying the stream through your server)
|
|
191
|
-
|
|
192
|
-
```typescript
|
|
193
|
-
import { SessionGatewayClient } from "@tangle-network/sandbox/session-gateway";
|
|
194
|
-
|
|
195
|
-
const sessionId =
|
|
196
|
-
localStorage.getItem("sandbox-browser-session") ?? crypto.randomUUID();
|
|
197
|
-
localStorage.setItem("sandbox-browser-session", sessionId);
|
|
198
|
-
|
|
199
|
-
// The browser sends only sessionId. Your authenticated backend looks up the
|
|
200
|
-
// owned runtime session and mints with both sessionId and runtimeSessionId:
|
|
201
|
-
// box.mintScopedToken({ scope: "session", sessionId, runtimeSessionId })
|
|
202
|
-
const scoped = await fetchScopedToken({ sessionId });
|
|
203
|
-
let client: SessionGatewayClient;
|
|
204
|
-
client = new SessionGatewayClient({
|
|
205
|
-
url: "wss://your-sandbox-api.example.com/session",
|
|
206
|
-
token: scoped.token,
|
|
207
|
-
sessionId,
|
|
208
|
-
onTokenRefresh: () => fetchScopedToken({ sessionId }),
|
|
209
|
-
autoReconnect: true,
|
|
210
|
-
enableReplayPersistence: true,
|
|
211
|
-
replayStorage: window.localStorage,
|
|
212
|
-
handlers: {
|
|
213
|
-
onAgentEvent: (_channel, event, seq) => render(event, seq),
|
|
214
|
-
onReplayStart: (total) => showSpinner(`replaying ${total} events`),
|
|
215
|
-
onReplayComplete: () => hideSpinner(),
|
|
216
|
-
onBackpressureWarning: (_droppedCount, since) => void client.replay(since),
|
|
217
|
-
},
|
|
218
|
-
});
|
|
219
|
-
client.connect();
|
|
220
|
-
```
|
|
221
|
-
|
|
222
|
-
`SessionGatewayClient` handles auto-reconnect with exponential backoff, event deduplication, replay-on-reconnect, and `lastEventId` persistence.
|
|
223
|
-
None of this requires a Durable Object.
|
|
224
|
-
The initial scoped token must be fetched before `connect()`; `onTokenRefresh` only handles later rotation.
|
|
225
|
-
Public operations reject if `connection.established` does not arrive within `connectionEstablishmentTimeoutMs` (10 seconds by default).
|
|
226
|
-
Use `handlers.onMessage` to observe every non-duplicate normalized frame after the client processes it; its `id` and canonical `seq` fields cover runtime, project, terminal, and control messages, while `onAgentEvent` is the agent-event convenience callback.
|
|
227
|
-
|
|
228
|
-
Server-originated product events can arrive before the browser connects:
|
|
229
|
-
|
|
230
|
-
```typescript
|
|
231
|
-
await client.broadcastSessionAgentEvent(sessionId, {
|
|
232
|
-
type: "project.provision_progress",
|
|
233
|
-
properties: { message: "Creating workspace" },
|
|
234
|
-
});
|
|
235
|
-
```
|
|
236
|
-
|
|
237
|
-
The public API binds that pending queue to the authenticated product and Sandbox account and commits it to Redis before returning `success: true`.
|
|
238
|
-
A later connection by the same owner leases and acknowledges the ordered queue; another owner receives none of it.
|
|
239
|
-
A gateway crash before acknowledgement redelivers the same event IDs, which the default `SessionGatewayClient` deduplicates before invoking handlers.
|
|
240
|
-
|
|
241
|
-
The Worker example authenticates before touching the account-key-backed Sandbox client and derives a user-owned runtime session ID from the user, conversation, and turn.
|
|
242
|
-
A retry with the same `x-conversation-id` and `x-turn-id` reuses one execution; a distinct turn gets a distinct execution.
|
|
243
|
-
The detached run survives a Worker or browser response ending; reconnect with the same conversation ID, turn ID, and `Last-Event-ID` to resume.
|
|
244
|
-
|
|
245
|
-
See `examples/cf-worker-chat.ts`, `examples/browser-streaming-resume.ts`, and
|
|
246
|
-
`examples/reconnect-from-last-event-id.ts` for end-to-end patterns.
|
|
247
|
-
|
|
248
|
-
### Browser-safe scoped runtime client
|
|
249
|
-
|
|
250
|
-
`@tangle-network/sandbox/runtime` is a browser- and Worker-safe entry point
|
|
251
|
-
(no `node:` imports) for talking directly to one sandbox's runtime with a
|
|
252
|
-
short-lived scoped token — never the account-level Sandbox API key — minted
|
|
253
|
-
server-side via `box.mintScopedToken({ scope: "session-runtime", sessionId })`
|
|
254
|
-
or `box.mintScopedToken({ scope: "read-only" })`.
|
|
255
|
-
|
|
256
|
-
```typescript
|
|
257
|
-
import { createSandboxRuntimeClient } from "@tangle-network/sandbox/runtime";
|
|
258
|
-
|
|
259
|
-
const runtime = createSandboxRuntimeClient({
|
|
260
|
-
baseUrl: scopedToken.sidecarProxyUrl, // browser-safe proxy base from box.mintScopedToken()
|
|
261
|
-
token: scopedToken.token,
|
|
262
|
-
});
|
|
263
|
-
|
|
264
|
-
await runtime.writeFile("/workspace/notes.md", "# from the browser");
|
|
265
|
-
|
|
266
|
-
// Binary-safe, chunked upload for payloads over ~1 MiB — same engine and
|
|
267
|
-
// size contract as SandboxInstance.fs.uploadData, wired to the scoped token
|
|
268
|
-
const blob = await fileInput.files[0].arrayBuffer();
|
|
269
|
-
await runtime.uploadData("/workspace/uploads/file.bin", blob, {
|
|
270
|
-
onProgress: (p) => console.log(`${p.percentage.toFixed(1)}%`),
|
|
271
|
-
});
|
|
272
|
-
```
|
|
273
|
-
|
|
274
|
-
Every method on the scoped client — `writeFile`, `readFiles`, `uploadData`,
|
|
275
|
-
terminals, sessions — carries the same `Authorization: Bearer <token>` header
|
|
276
|
-
and base URL prefix, so the request conventions match whether the token
|
|
277
|
-
scope allows the call or not; a denied call fails with the typed
|
|
278
|
-
`SandboxError`, not a silent no-op.
|
|
279
|
-
|
|
280
|
-
## Features
|
|
281
|
-
|
|
282
|
-
- **Sandbox Management** - Create, list, stop, resume, and delete sandboxes
|
|
283
|
-
- **Command Execution** - Run shell commands in isolated containers
|
|
284
|
-
- **AI Agent Tasks** - Multi-turn agent execution with automatic tool use
|
|
285
|
-
- **Snapshots** - Save and restore sandbox state
|
|
286
|
-
- **BYOS3** - Bring your own S3 storage for snapshots
|
|
287
|
-
- **Fleets** - Coordinated multi-machine workloads with policy, workspace snapshots, and parallel dispatch
|
|
288
|
-
- **Intelligence Reports** - Deterministic or agentic post-hoc analysis of sandbox or fleet evidence (fleet reports can refine to a single dispatch via `subject.dispatchId`)
|
|
289
|
-
- **Event Streaming** - Real-time SSE streams for agent events
|
|
290
|
-
- **Collaboration Foundations** - Token issuance and document identity helpers for collaborative editing
|
|
291
|
-
- **Trace Intelligence** - Export raw sandbox and fleet traces, embedded intelligence envelope, timing metrics, and OTEL JSON to customer-owned observability systems
|
|
292
|
-
|
|
293
|
-
## Collaboration Foundations
|
|
294
|
-
|
|
295
|
-
The SDK now includes the first collaboration primitives for product backends:
|
|
296
|
-
|
|
297
|
-
- collaboration token issuance from `@tangle-network/sandbox/auth`
|
|
298
|
-
- stable document identity helpers from `@tangle-network/sandbox/collaboration`
|
|
299
|
-
- a collaboration API client for bootstrap / token refresh / snapshot calls
|
|
300
|
-
- a headless file bridge for syncing document adapters with sandbox files
|
|
301
|
-
|
|
302
|
-
Example:
|
|
303
|
-
|
|
304
|
-
```typescript
|
|
305
|
-
import {
|
|
306
|
-
buildCollaborationDocumentId,
|
|
307
|
-
} from "@tangle-network/sandbox/collaboration";
|
|
308
|
-
import { ProductTokenIssuer } from "@tangle-network/sandbox/auth";
|
|
309
|
-
|
|
310
|
-
const issuer = new ProductTokenIssuer({
|
|
311
|
-
productId: "gtm-agent",
|
|
312
|
-
signingSecret: process.env.SANDBOX_SIGNING_SECRET!,
|
|
313
|
-
});
|
|
314
|
-
|
|
315
|
-
const documentId = buildCollaborationDocumentId({
|
|
316
|
-
workspaceId: "ws_123",
|
|
317
|
-
relativePath: "system/operating-system.md",
|
|
318
|
-
});
|
|
319
|
-
|
|
320
|
-
const { token, expiresAt } = issuer.issueCollaboration({
|
|
321
|
-
userId: "user_123",
|
|
322
|
-
sessionId: "sess_456",
|
|
323
|
-
projectId: "ws_123",
|
|
324
|
-
documentId,
|
|
325
|
-
access: "write",
|
|
326
|
-
});
|
|
327
|
-
```
|
|
328
|
-
|
|
329
|
-
Bootstrap and snapshot helpers:
|
|
330
|
-
|
|
331
|
-
```typescript
|
|
332
|
-
import { CollaborationClient } from "@tangle-network/sandbox/collaboration";
|
|
333
|
-
|
|
334
|
-
const collab = new CollaborationClient({
|
|
335
|
-
baseUrl: "https://app.example.com",
|
|
336
|
-
headers: () => ({
|
|
337
|
-
Authorization: `Bearer ${sessionToken}`,
|
|
338
|
-
}),
|
|
339
|
-
});
|
|
340
|
-
|
|
341
|
-
const bootstrap = await collab.bootstrap({
|
|
342
|
-
workspaceId: "ws_123",
|
|
343
|
-
relativePath: "system/operating-system.md",
|
|
344
|
-
});
|
|
345
|
-
```
|
|
346
|
-
|
|
347
|
-
The bridge and client are SDK-side primitives. Product/backend endpoints and CRDT runtime integration still need to be wired by the application.
|
|
348
|
-
|
|
349
|
-
## Trace Intelligence
|
|
350
|
-
|
|
351
|
-
The platform exposes two distinct intelligence primitives. Use the right one for the job.
|
|
352
|
-
|
|
353
|
-
| Primitive | What you get | Billable | API call |
|
|
354
|
-
|---|---|---|---|
|
|
355
|
-
| **Embedded envelope** | Inline summary in a trace/dispatch response: signals, recommended actions, fanout timings, dispatch failure classes | No (`billing.billable: false`) | `trace({ includeIntelligence: true })`, `intelligence()`, dispatch responses |
|
|
356
|
-
| **Intelligence Report** | A pollable job over sandbox or fleet evidence; fleet reports can refine to a single dispatch via `subject.dispatchId`. Runs in `deterministic` or `agentic` mode against a budget. | `deterministic`: free. `agentic`: billed against `budget.maxUsd` | `intelligence.createReport(...)`, see [Intelligence Reports](#intelligence-reports) |
|
|
357
|
-
|
|
358
|
-
### Embedded envelope (free)
|
|
359
|
-
|
|
360
|
-
The embedded envelope is opt-in on `trace()` calls (`includeIntelligence: true`) and always included on dispatch responses (because dispatch already pays the analysis cost as part of producing the result).
|
|
361
|
-
|
|
362
|
-
```typescript
|
|
363
|
-
const boxBundle = await box.trace(); // { trace } only
|
|
364
|
-
const boxInsights = await box.intelligence(); // envelope only
|
|
365
|
-
const boxBundleWithInsights = await box.trace({ includeIntelligence: true });
|
|
366
|
-
|
|
367
|
-
const run = await fleet.dispatchExecDetailed("pytest -q", {
|
|
368
|
-
machines: ["worker-1", "worker-2"],
|
|
369
|
-
});
|
|
370
|
-
console.log(run.results);
|
|
371
|
-
console.log(run.intelligence.signals); // always present on dispatch
|
|
372
|
-
console.log(run.intelligence.recommendedActions);
|
|
373
|
-
|
|
374
|
-
const fleetBundle = await fleet.trace(); // { trace } only
|
|
375
|
-
const fleetInsights = await fleet.intelligence(); // envelope only
|
|
376
|
-
const fleetBundleWithInsights = await fleet.trace({ includeIntelligence: true });
|
|
377
|
-
```
|
|
378
|
-
|
|
379
|
-
Sandbox traces cover lifecycle, runtime, usage, timing, and current health snapshots. Fleet traces add machine lifecycle, workspace state, dispatch results, fanout timings, and critical path. The embedded envelope tells you what to inspect next: reliability, parallelism efficiency for fleets, dispatch failure classes, resource attribution, timing bottlenecks, and recommended actions.
|
|
380
|
-
|
|
381
|
-
The embedded envelope is deterministic platform analysis. It reports `billing.billable: false` and `billing.costUsd: 0`; customers are not charged for generating these envelopes.
|
|
382
|
-
|
|
383
|
-
### Exporting traces to your observability stack
|
|
384
|
-
|
|
385
|
-
Use `format: "tangle"` to preserve the native envelope, or `format: "otel-json"` for OpenTelemetry-style collectors and platforms that accept OTLP JSON.
|
|
386
|
-
|
|
387
|
-
```typescript
|
|
388
|
-
await box.exportTrace({
|
|
389
|
-
url: "https://collector.example.com/traces",
|
|
390
|
-
headers: { Authorization: `Bearer ${process.env.OBSERVABILITY_TOKEN}` },
|
|
391
|
-
format: "otel-json",
|
|
392
|
-
serviceName: "research-agent",
|
|
42
|
+
baseUrl: process.env.SANDBOX_BASE_URL!,
|
|
393
43
|
});
|
|
394
|
-
|
|
395
|
-
await fleet.exportTrace({
|
|
396
|
-
url: "https://collector.example.com/traces",
|
|
397
|
-
headers: { Authorization: `Bearer ${process.env.OBSERVABILITY_TOKEN}` },
|
|
398
|
-
format: "otel-json",
|
|
399
|
-
serviceName: "research-agent",
|
|
400
|
-
});
|
|
401
|
-
```
|
|
402
|
-
|
|
403
|
-
For Braintrust, Lemma, Raindrop, Langfuse, Datadog, or a custom warehouse, keep this as a customer-owned sink or webhook. Tangle does not need their vendor credentials: fetch `box.trace()` or `fleet.trace()` and send the raw bundle through their SDK/API, or point `exportTrace()` at a small ingest endpoint that transforms it into the vendor's preferred schema.
|
|
404
|
-
|
|
405
|
-
Agent tools should expose both `trace` and `intelligence` actions on `manageSandboxes`. `trace` returns the full raw bundle for downstream analysis; `intelligence` returns the compact agent-readable next-step summary.
|
|
406
|
-
|
|
407
|
-
## Core Concepts
|
|
408
|
-
|
|
409
|
-
### Sandboxes
|
|
410
|
-
|
|
411
|
-
A sandbox is an isolated dev container with:
|
|
412
|
-
- A programmatic runtime API
|
|
413
|
-
- Optional SSH access
|
|
414
|
-
- Optional web terminal
|
|
415
|
-
- Persistent storage with snapshots
|
|
416
|
-
|
|
417
|
-
```typescript
|
|
418
44
|
const box = await client.create({
|
|
419
|
-
name: "
|
|
420
|
-
environment: "
|
|
421
|
-
env: { DEBUG: "true" },
|
|
422
|
-
sshEnabled: true,
|
|
423
|
-
maxLifetimeSeconds: 7200, // 2 hours
|
|
424
|
-
idleTimeoutSeconds: 1800, // 30 min idle timeout
|
|
45
|
+
name: "sdk-quick-start",
|
|
46
|
+
environment: "universal",
|
|
425
47
|
resources: {
|
|
426
48
|
cpuCores: 2,
|
|
427
49
|
memoryMB: 4096,
|
|
428
50
|
diskGB: 20,
|
|
429
51
|
},
|
|
430
52
|
});
|
|
431
|
-
```
|
|
432
53
|
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
```
|
|
436
|
-
pending -> provisioning -> running -> stopped -> deleted
|
|
437
|
-
|
|
|
438
|
-
v
|
|
439
|
-
failed
|
|
440
|
-
```
|
|
441
|
-
|
|
442
|
-
## API Reference
|
|
443
|
-
|
|
444
|
-
### Client
|
|
54
|
+
try {
|
|
55
|
+
await box.waitFor("running");
|
|
445
56
|
|
|
446
|
-
|
|
447
|
-
|
|
57
|
+
const result = await box.exec("node --version && npm --version");
|
|
58
|
+
if (result.exitCode !== 0) {
|
|
59
|
+
throw new Error(result.stderr);
|
|
60
|
+
}
|
|
448
61
|
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
});
|
|
62
|
+
console.log(result.stdout);
|
|
63
|
+
} finally {
|
|
64
|
+
await box.delete();
|
|
65
|
+
}
|
|
454
66
|
```
|
|
455
67
|
|
|
456
|
-
|
|
68
|
+
`apiKey` and `baseUrl` are required.
|
|
69
|
+
Keep `delete()` in `finally` unless the sandbox must outlive the process.
|
|
457
70
|
|
|
458
|
-
Create a
|
|
71
|
+
## Create a sandbox
|
|
72
|
+
|
|
73
|
+
`client.create()` accepts a named environment, container image, or published image ID.
|
|
74
|
+
The server chooses its default environment when `environment` is omitted.
|
|
459
75
|
|
|
460
76
|
```typescript
|
|
461
77
|
const box = await client.create({
|
|
462
|
-
name: "
|
|
463
|
-
environment: "node:
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
78
|
+
name: "repo-review",
|
|
79
|
+
environment: "node:22",
|
|
80
|
+
git: {
|
|
81
|
+
url: "https://github.com/acme/service.git",
|
|
82
|
+
ref: "main",
|
|
83
|
+
},
|
|
84
|
+
env: {
|
|
85
|
+
CI: "true",
|
|
86
|
+
},
|
|
471
87
|
resources: {
|
|
472
|
-
cpuCores:
|
|
473
|
-
memoryMB:
|
|
474
|
-
diskGB:
|
|
88
|
+
cpuCores: 4,
|
|
89
|
+
memoryMB: 8192,
|
|
90
|
+
diskGB: 40,
|
|
475
91
|
},
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
bucket: "my-snapshots",
|
|
481
|
-
region: "us-east-1",
|
|
482
|
-
credentials: {
|
|
483
|
-
accessKeyId: "AKIA...",
|
|
484
|
-
secretAccessKey: "...",
|
|
485
|
-
},
|
|
92
|
+
maxLifetimeSeconds: 3600,
|
|
93
|
+
idleTimeoutSeconds: 900,
|
|
94
|
+
metadata: {
|
|
95
|
+
project: "service",
|
|
486
96
|
},
|
|
487
|
-
fromSnapshot: "snap_abc123", // restore from snapshot
|
|
488
97
|
});
|
|
489
98
|
```
|
|
490
99
|
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
List all sandboxes.
|
|
100
|
+
List server-supported environments instead of hard-coding an internal catalog.
|
|
494
101
|
|
|
495
102
|
```typescript
|
|
496
|
-
const
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
offset: 0,
|
|
500
|
-
});
|
|
501
|
-
```
|
|
502
|
-
|
|
503
|
-
#### `client.get(id)`
|
|
504
|
-
|
|
505
|
-
Get a sandbox by ID.
|
|
506
|
-
|
|
507
|
-
```typescript
|
|
508
|
-
const box = await client.get("sandbox_abc123");
|
|
509
|
-
if (box) {
|
|
510
|
-
console.log(box.status);
|
|
103
|
+
const environments = await client.environments.list();
|
|
104
|
+
for (const environment of environments) {
|
|
105
|
+
console.log(environment.id, environment.description);
|
|
511
106
|
}
|
|
512
107
|
```
|
|
513
108
|
|
|
514
|
-
|
|
109
|
+
Use `bare: true` for a minimal container with command execution and lifecycle controls.
|
|
110
|
+
Use `agent: false` for managed files, processes, and telemetry without configuring an agent backend.
|
|
111
|
+
|
|
112
|
+
## Lifecycle
|
|
515
113
|
|
|
516
|
-
|
|
114
|
+
The active states are `pending`, `provisioning`, `running`, `stopped`, `failed`, and `expired`.
|
|
115
|
+
Deletion is permanent and is not a retained status.
|
|
517
116
|
|
|
518
117
|
```typescript
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
118
|
+
await box.waitFor("running", { timeoutMs: 120_000 });
|
|
119
|
+
await box.stop();
|
|
120
|
+
await box.waitFor("stopped");
|
|
121
|
+
await box.resume({ timeoutMs: 120_000 });
|
|
122
|
+
await box.waitFor("running");
|
|
123
|
+
await box.delete();
|
|
522
124
|
```
|
|
523
125
|
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
Run ad-hoc tasks across freshly-provisioned sandboxes in parallel. Use this when the work is one-shot and the sandboxes do not need to share a workspace or be addressable by stable `machineId`. For coordinated multi-machine workloads with policy enforcement, workspace sharing, dispatch buffering, and intelligence reports, see [Fleets](#fleets).
|
|
126
|
+
Create a snapshot when later sandboxes need the same filesystem state.
|
|
527
127
|
|
|
528
128
|
```typescript
|
|
529
|
-
const
|
|
530
|
-
|
|
531
|
-
{ id: "task-2", message: "Run security scan" },
|
|
532
|
-
{ id: "task-3", message: "Generate documentation" },
|
|
533
|
-
], {
|
|
534
|
-
timeoutMs: 300000,
|
|
535
|
-
scalingMode: "balanced", // "fastest" | "balanced" | "cheapest"
|
|
129
|
+
const snapshot = await box.snapshot({
|
|
130
|
+
tags: ["baseline"],
|
|
536
131
|
});
|
|
537
132
|
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
#### `client.fleets`
|
|
542
|
-
|
|
543
|
-
Fleet client — see [Fleets](#fleets) for the full surface (`create`, `createWithCoordinator`, `list`, `delete`, `estimateCost`, `capabilities`, `operations`, `reconcile`, `reapExpired`).
|
|
544
|
-
|
|
545
|
-
#### `client.intelligence`
|
|
546
|
-
|
|
547
|
-
Intelligence report client — see [Intelligence Reports](#intelligence-reports) for the full surface (`createReport`, `createAgenticReport`, `getReport`, `listReports`, `waitForReport`).
|
|
133
|
+
const restored = await client.create({
|
|
134
|
+
fromSnapshot: snapshot.snapshotId,
|
|
135
|
+
});
|
|
548
136
|
|
|
549
|
-
|
|
137
|
+
try {
|
|
138
|
+
await restored.waitFor("running");
|
|
139
|
+
} finally {
|
|
140
|
+
await restored.delete();
|
|
141
|
+
}
|
|
142
|
+
```
|
|
550
143
|
|
|
551
|
-
|
|
144
|
+
Use the same `idempotencyKey` only when retrying the same logical create request.
|
|
552
145
|
|
|
553
|
-
|
|
146
|
+
## Commands and files
|
|
554
147
|
|
|
555
|
-
|
|
148
|
+
`exec()` returns the exit code, standard output, standard error, and timing data.
|
|
556
149
|
|
|
557
150
|
```typescript
|
|
558
|
-
const
|
|
559
|
-
cwd: "/workspace",
|
|
151
|
+
const test = await box.exec("pnpm test", {
|
|
152
|
+
cwd: "/workspace/service",
|
|
560
153
|
env: { CI: "true" },
|
|
561
|
-
timeoutMs:
|
|
154
|
+
timeoutMs: 10 * 60 * 1000,
|
|
562
155
|
});
|
|
563
156
|
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
157
|
+
if (test.exitCode !== 0) {
|
|
158
|
+
throw new Error(test.stderr);
|
|
159
|
+
}
|
|
567
160
|
```
|
|
568
161
|
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
Build a Dockerfile from the sandbox workspace and publish the resulting image through the public Sandbox API.
|
|
572
|
-
Registry credentials are sent to the trusted publisher and are not exposed to sandbox processes.
|
|
573
|
-
Use the top-level `ImageBuilder` for an image specification needed before sandbox creation; use `box.images.publish()` for files already built or edited inside a live sandbox.
|
|
162
|
+
The direct file helpers cover common text operations.
|
|
163
|
+
The `fs` property exposes listing, metadata, upload, download, rename, and directory operations.
|
|
574
164
|
|
|
575
165
|
```typescript
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
dockerfilePath: "Dockerfile",
|
|
580
|
-
repository: "ghcr.io/acme/web",
|
|
581
|
-
auth: {
|
|
582
|
-
username: process.env.REGISTRY_USERNAME!,
|
|
583
|
-
password: process.env.REGISTRY_PASSWORD!,
|
|
584
|
-
},
|
|
585
|
-
platform: "linux/amd64",
|
|
586
|
-
},
|
|
587
|
-
{
|
|
588
|
-
idempotencyKey: "deploy-request-0184",
|
|
589
|
-
timeoutMs: 15 * 60 * 1000,
|
|
590
|
-
},
|
|
591
|
-
);
|
|
592
|
-
|
|
593
|
-
console.log(published.image); // ghcr.io/acme/web@sha256:...
|
|
594
|
-
console.log(published.taggedImage); // deterministic operation tag
|
|
166
|
+
await box.write("/workspace/service/config.json", '{"enabled":true}\n');
|
|
167
|
+
const config = await box.read("/workspace/service/config.json");
|
|
168
|
+
console.log(config);
|
|
595
169
|
```
|
|
596
170
|
|
|
597
|
-
|
|
598
|
-
The returned `image` is immutable and digest-addressed.
|
|
599
|
-
Operation tags are create-only: replaying identical content succeeds, while attempting to reuse a tag for different content fails.
|
|
600
|
-
The repository must omit the scheme, tag, and digest.
|
|
171
|
+
### File size contract
|
|
601
172
|
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
timeoutMs: 120000,
|
|
611
|
-
});
|
|
173
|
+
| Path | Limit | Constant | Use |
|
|
174
|
+
|---|---:|---|---|
|
|
175
|
+
| Decoded `write()` content | 5 MiB | `FILE_DECODED_WRITE_MAX_BYTES` | Common text and small binary writes |
|
|
176
|
+
| Public API request | 1 MiB | `SANDBOX_PROXY_REQUEST_MAX_BYTES` | Requests routed through the Sandbox API |
|
|
177
|
+
| Direct runtime file request | 32 MiB | `SANDBOX_DIRECT_FILE_REQUEST_MAX_BYTES` | Direct runtime requests |
|
|
178
|
+
| Multipart upload | 5 MiB | `FILE_MULTIPART_UPLOAD_MAX_BYTES` | One multipart upload |
|
|
179
|
+
| Chunked upload part | 768 KiB | `FILE_UPLOAD_PART_MAX_BYTES` | One `fs.uploadData()` part |
|
|
180
|
+
| Chunked upload session | 64 MiB | `FILE_UPLOAD_SESSION_MAX_BYTES` | One complete `fs.uploadData()` call |
|
|
612
181
|
|
|
613
|
-
|
|
614
|
-
console.log(result.usage); // { inputTokens, outputTokens }
|
|
615
|
-
```
|
|
182
|
+
Use `fs.uploadData()` when content is larger than the single-request limit.
|
|
616
183
|
|
|
617
|
-
|
|
184
|
+
The instance also exposes `git`, `tools`, `process`, `terminals`, `network`, `egress`, `previewLinks`, `images`, and `backend` capability clients.
|
|
185
|
+
Unsupported capabilities fail with a typed SDK error.
|
|
618
186
|
|
|
619
|
-
|
|
187
|
+
## Prompts
|
|
620
188
|
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
| `opencode` | [OpenCode](https://github.com/anomalyco/opencode) | Default. Multi-provider, profile system, MCP support |
|
|
624
|
-
| `claude-code` | [Claude Code](https://docs.anthropic.com/en/docs/claude-code) | Anthropic-native. Needs ANTHROPIC_API_KEY |
|
|
625
|
-
| `codex` | [Codex CLI](https://github.com/openai/codex) | OpenAI-native. Needs OPENAI_API_KEY |
|
|
626
|
-
| `cursor` | [Cursor Agent SDK](https://cursor.com/changelog/sdk-release) | Cursor-native local/cloud agent. Needs CURSOR_API_KEY |
|
|
627
|
-
| `amp` | [AMP](https://sourcegraph.com/amp) | Sourcegraph AMP agent |
|
|
628
|
-
| `factory-droids` | [Factory](https://factory.ai) | Factory Droid agent |
|
|
189
|
+
Configure the agent backend when creating the sandbox or override it for one prompt.
|
|
190
|
+
Provider credentials must come from your platform configuration or the backend model configuration.
|
|
629
191
|
|
|
630
192
|
```typescript
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
backend: { type: "claude-code" },
|
|
634
|
-
});
|
|
635
|
-
|
|
636
|
-
// Use Codex with a named profile
|
|
637
|
-
await box.prompt("Audit this repo", {
|
|
638
|
-
backend: { type: "codex", profile: "browser-codex-fast" },
|
|
639
|
-
});
|
|
640
|
-
|
|
641
|
-
// Use Cursor Agent SDK
|
|
642
|
-
await box.prompt("Implement this change", {
|
|
643
|
-
backend: {
|
|
644
|
-
type: "cursor",
|
|
645
|
-
model: {
|
|
646
|
-
model: "composer-2",
|
|
647
|
-
apiKey: process.env.CURSOR_API_KEY,
|
|
648
|
-
},
|
|
649
|
-
profile: {
|
|
650
|
-
name: "cursor-release-agent",
|
|
651
|
-
prompt: {
|
|
652
|
-
systemPrompt:
|
|
653
|
-
"Use repo rules, configured MCP servers, skills, and subagents when relevant.",
|
|
654
|
-
},
|
|
655
|
-
mcp: {
|
|
656
|
-
docs: { transport: "sse", url: "https://docs.example.com/sse" },
|
|
657
|
-
},
|
|
658
|
-
subagents: {
|
|
659
|
-
reviewer: {
|
|
660
|
-
description: "Reviews changes for correctness and missing tests.",
|
|
661
|
-
prompt: "Review the current diff. Return only blocking findings.",
|
|
662
|
-
model: "composer-2",
|
|
663
|
-
},
|
|
664
|
-
},
|
|
665
|
-
resources: {
|
|
666
|
-
instructions: "Run focused tests before reporting completion.",
|
|
667
|
-
skills: [
|
|
668
|
-
{
|
|
669
|
-
kind: "inline",
|
|
670
|
-
name: "release-check",
|
|
671
|
-
content:
|
|
672
|
-
"---\nname: release-check\ndescription: Validate release readiness.\n---\nRun typecheck and focused tests.",
|
|
673
|
-
},
|
|
674
|
-
],
|
|
675
|
-
},
|
|
676
|
-
extensions: {
|
|
677
|
-
cursor: {
|
|
678
|
-
runtime: "local",
|
|
679
|
-
local: { settingSources: ["project", "user"] },
|
|
680
|
-
force: true,
|
|
681
|
-
},
|
|
682
|
-
},
|
|
683
|
-
},
|
|
684
|
-
},
|
|
685
|
-
});
|
|
686
|
-
|
|
687
|
-
// Use OpenCode with an inline profile
|
|
688
|
-
await box.prompt("Audit this repo", {
|
|
689
|
-
backend: {
|
|
690
|
-
type: "opencode",
|
|
691
|
-
profile: {
|
|
692
|
-
name: "security-auditor",
|
|
693
|
-
prompt: {
|
|
694
|
-
systemPrompt: "Focus on authorization and sandbox boundary mistakes.",
|
|
695
|
-
},
|
|
696
|
-
tools: { bash: true },
|
|
697
|
-
permissions: { bash: "allow" },
|
|
698
|
-
},
|
|
699
|
-
},
|
|
700
|
-
});
|
|
701
|
-
|
|
702
|
-
// BYOK (Bring Your Own Key)
|
|
703
|
-
await box.prompt("Analyze this", {
|
|
193
|
+
const agentBox = await client.create({
|
|
194
|
+
environment: "universal",
|
|
704
195
|
backend: {
|
|
705
196
|
type: "opencode",
|
|
706
197
|
model: {
|
|
707
|
-
provider:
|
|
708
|
-
model:
|
|
709
|
-
apiKey: process.env.
|
|
198
|
+
provider: process.env.MODEL_PROVIDER!,
|
|
199
|
+
model: process.env.MODEL_NAME!,
|
|
200
|
+
apiKey: process.env.MODEL_API_KEY!,
|
|
710
201
|
},
|
|
711
202
|
},
|
|
712
203
|
});
|
|
713
204
|
|
|
714
|
-
|
|
715
|
-
await
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
"tangle.product": "blueprint-agent",
|
|
721
|
-
"tangle.partner": "acme",
|
|
722
|
-
"tangle.projectId": "project-42",
|
|
723
|
-
"tangle.domain": "web",
|
|
724
|
-
},
|
|
205
|
+
try {
|
|
206
|
+
const result = await agentBox.prompt(
|
|
207
|
+
"Run the tests, fix the failure, and explain the change.",
|
|
208
|
+
{
|
|
209
|
+
timeoutMs: 10 * 60 * 1000,
|
|
210
|
+
requireVisibleAssistantOutput: true,
|
|
725
211
|
},
|
|
726
|
-
|
|
727
|
-
});
|
|
728
|
-
```
|
|
729
|
-
|
|
730
|
-
The SDK serializes `backend.profile` into the required wire format automatically.
|
|
731
|
-
Trace attributes are labels only; supported backend metadata is limited to `containerType` and `traceAttributes`.
|
|
732
|
-
Sandbox configures the trace exporter; do not put collector endpoints, authorization headers, API keys, or user content in `traceAttributes`.
|
|
733
|
-
|
|
734
|
-
Cursor profiles map portable MCP, resources, skills, subagents, hooks, permissions,
|
|
735
|
-
and Cursor-native `extensions.cursor` fields into the Cursor Agent SDK. Local
|
|
736
|
-
Cursor runs materialize `.cursor/*` project files inside the sandbox workspace.
|
|
737
|
-
Cloud Cursor runs fail closed when given uncommitted local resources that cannot
|
|
738
|
-
be delivered to the remote Cursor workspace.
|
|
739
|
-
|
|
740
|
-
Provider-native metadata is available through `box.backend` when the backend
|
|
741
|
-
SDK exposes it:
|
|
742
|
-
|
|
743
|
-
```typescript
|
|
744
|
-
const account = await box.backend.account();
|
|
745
|
-
const models = await box.backend.models();
|
|
746
|
-
const repositories = await box.backend.repositories();
|
|
747
|
-
const agents = await box.backend.agents({ limit: 20 });
|
|
748
|
-
const agent = await box.backend.agent(agents.items[0].agentId);
|
|
749
|
-
const runs = await box.backend.runs(agent.agentId, { limit: 20 });
|
|
750
|
-
const run = await box.backend.run(runs.items[0].id, {
|
|
751
|
-
agentId: agent.agentId,
|
|
752
|
-
});
|
|
753
|
-
const messages = await box.backend.agentMessages(agent.agentId, { limit: 50 });
|
|
754
|
-
const artifacts = await box.backend.artifacts("active-session-id");
|
|
755
|
-
const bytes = await box.backend.downloadArtifact(
|
|
756
|
-
"active-session-id",
|
|
757
|
-
artifacts[0].path,
|
|
758
|
-
);
|
|
759
|
-
```
|
|
760
|
-
|
|
761
|
-
Unsupported provider-control methods return the backend error; the SDK does not
|
|
762
|
-
fabricate catalog, run, or artifact data for backends that do not expose it.
|
|
763
|
-
|
|
764
|
-
#### `box.task(message, options?)`
|
|
765
|
-
|
|
766
|
-
Run a multi-turn agent task. The agent keeps working until completion.
|
|
767
|
-
|
|
768
|
-
```typescript
|
|
769
|
-
const result = await box.task("Set up a REST API with authentication", {
|
|
770
|
-
maxTurns: 20, // limit turns (0 = unlimited)
|
|
771
|
-
sessionId: "...", // continue previous session
|
|
772
|
-
});
|
|
773
|
-
|
|
774
|
-
console.log(result.turnsUsed);
|
|
775
|
-
console.log(result.response);
|
|
776
|
-
```
|
|
777
|
-
|
|
778
|
-
#### `box.streamPrompt(message, options?)`
|
|
779
|
-
|
|
780
|
-
Stream agent events in real-time.
|
|
212
|
+
);
|
|
781
213
|
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
switch (event.type) {
|
|
785
|
-
case "message.part.updated": {
|
|
786
|
-
const part = event.data.part as { type?: string; text?: string };
|
|
787
|
-
if (part.type === "text" && event.data.delta) {
|
|
788
|
-
process.stdout.write(String(event.data.delta));
|
|
789
|
-
}
|
|
790
|
-
if (part.type === "reasoning" && event.data.delta) {
|
|
791
|
-
// Reasoning/thinking tokens from extended thinking models
|
|
792
|
-
process.stderr.write(`[thinking] ${String(event.data.delta)}`);
|
|
793
|
-
}
|
|
794
|
-
break;
|
|
795
|
-
}
|
|
796
|
-
case "result":
|
|
797
|
-
console.log("\nFinal:", event.data.finalText);
|
|
798
|
-
break;
|
|
799
|
-
case "done":
|
|
800
|
-
console.log("\nComplete!");
|
|
801
|
-
break;
|
|
214
|
+
if (!result.success) {
|
|
215
|
+
throw new Error(result.error ?? `Agent stopped with ${result.status}`);
|
|
802
216
|
}
|
|
803
|
-
}
|
|
804
|
-
```
|
|
805
|
-
|
|
806
|
-
#### `box.streamTask(message, options?)`
|
|
807
217
|
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
// Handle events...
|
|
218
|
+
console.log(result.response);
|
|
219
|
+
console.log(result.usage);
|
|
220
|
+
} finally {
|
|
221
|
+
await agentBox.delete();
|
|
813
222
|
}
|
|
814
223
|
```
|
|
815
224
|
|
|
816
|
-
|
|
225
|
+
Use `streamPrompt()` when the current process will stay attached to the event stream.
|
|
226
|
+
Use `dispatchPrompt()` when the run must continue after the caller disconnects.
|
|
817
227
|
|
|
818
|
-
|
|
228
|
+
## Resume a session
|
|
819
229
|
|
|
820
|
-
|
|
821
|
-
const directBox = box.direct();
|
|
822
|
-
const result = await directBox.exec("npm test");
|
|
823
|
-
```
|
|
824
|
-
|
|
825
|
-
#### `box.events(options?)`
|
|
826
|
-
|
|
827
|
-
Subscribe to sandbox lifecycle events.
|
|
230
|
+
A stable session ID preserves conversation context across prompts.
|
|
828
231
|
|
|
829
232
|
```typescript
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
```
|
|
834
|
-
|
|
835
|
-
### File I/O
|
|
836
|
-
|
|
837
|
-
| Method | Environment | Payload | Notes |
|
|
838
|
-
|---|---|---|---|
|
|
839
|
-
| `fs.read(path)` / `fs.write(path, content, options?)` | Node + browser | UTF-8 string, or base64 via `options.encoding` | Single request — see the size contract below for the cap |
|
|
840
|
-
| `fs.writeMany(files, options?)` | Node + browser | Same as `write`; per-file `encoding` | Paced, retry-aware batch through `fs.write`'s endpoint; fails loud on the first file that can't be written |
|
|
841
|
-
| `fs.upload(localPath, remotePath, options?)` | Node only | Local file path | Reads the local file with `node:fs`; not available in a browser tab |
|
|
842
|
-
| `fs.uploadData(remotePath, data, options?)` | Node + browser | `Blob \| ArrayBuffer \| ArrayBufferView \| string` | Browser/Worker-safe, binary-safe — the sanctioned path for payloads over ~1 MiB (see below) |
|
|
843
|
-
| `fs.download(remotePath, localPath, options?)` | Node only | — | Writes to a local path with `node:fs` |
|
|
844
|
-
| `fs.uploadDir` / `fs.downloadDir` | Node only | Local directory path | tar-based directory transfer |
|
|
845
|
-
| `fs.list` / `fs.stat` / `fs.mkdir` / `fs.delete` / `fs.rename` / `fs.exists` | Node + browser | — | Directory listing and file metadata operations |
|
|
846
|
-
| `fs.tree(path, options?)` / `fs.usage(path, options?)` | Node + browser | — | Filtered file browsing versus complete aggregate storage accounting |
|
|
847
|
-
|
|
848
|
-
```typescript
|
|
849
|
-
// Text write/read (UTF-8 by default)
|
|
850
|
-
await box.fs.write("/workspace/config.json", JSON.stringify(config));
|
|
851
|
-
const raw = await box.fs.read("/workspace/config.json");
|
|
852
|
-
|
|
853
|
-
// Base64 for binary content through the same single-shot endpoint
|
|
854
|
-
await box.fs.write("/workspace/icon.png", base64Png, { encoding: "base64" });
|
|
855
|
-
|
|
856
|
-
// Batch-write many small files (paced, retried)
|
|
857
|
-
await box.fs.writeMany([
|
|
858
|
-
{ path: "skills/review.md", content: reviewSkill },
|
|
859
|
-
{ path: "assets/logo.png", content: base64Logo, encoding: "base64" },
|
|
860
|
-
]);
|
|
861
|
-
|
|
862
|
-
// Node-only: upload a local file
|
|
863
|
-
await box.fs.upload("./model.bin", "/workspace/models/model.bin");
|
|
864
|
-
|
|
865
|
-
// Browser/Worker-safe: upload in-memory data over ~1 MiB (e.g. an
|
|
866
|
-
// <input type="file"> Blob) — chunked and verified end-to-end
|
|
867
|
-
const blob = await fetch("https://example.com/model.bin").then((r) => r.blob());
|
|
868
|
-
await box.fs.uploadData("/workspace/models/model.bin", blob, {
|
|
869
|
-
onProgress: (p) => console.log(`${p.percentage.toFixed(1)}%`),
|
|
233
|
+
const sessionId = "review-42";
|
|
234
|
+
await box.prompt("Inspect the authentication flow.", {
|
|
235
|
+
sessionId,
|
|
870
236
|
});
|
|
237
|
+
const resumed = await box
|
|
238
|
+
.session(sessionId)
|
|
239
|
+
.prompt("Now patch the highest-severity issue and run its tests.");
|
|
871
240
|
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
// Complete storage usage, including .git, dependencies, caches, and build output
|
|
875
|
-
const usage = await box.fs.usage("/workspace");
|
|
876
|
-
if (!usage.complete) throw new Error("Workspace usage scan was incomplete");
|
|
241
|
+
console.log(resumed.response);
|
|
877
242
|
```
|
|
878
243
|
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
upload-session and verifies the whole payload with a SHA-256 at commit, so
|
|
882
|
-
it's safe for arbitrarily-shaped binary content (video, model weights,
|
|
883
|
-
archives) up to the session cap. It works identically whether the sandbox is
|
|
884
|
-
reached through the gateway proxy or a direct sidecar connection
|
|
885
|
-
(`box.direct()`).
|
|
886
|
-
|
|
887
|
-
#### File size contract
|
|
888
|
-
|
|
889
|
-
| Surface | Cap | Constant | Failure |
|
|
890
|
-
|---|---|---|---|
|
|
891
|
-
| Single-shot decoded write (`fs.write`, `fs.writeMany`) | 5 MiB | `FILE_DECODED_WRITE_MAX_BYTES` | `FILE_TOO_LARGE` |
|
|
892
|
-
| Gateway proxy request (wire, any route) | 1 MiB | `SANDBOX_PROXY_REQUEST_MAX_BYTES` | `PAYLOAD_TOO_LARGE` |
|
|
893
|
-
| Direct-runtime write request (wire, `box.direct()` only) | 32 MiB | `SANDBOX_DIRECT_FILE_REQUEST_MAX_BYTES` | `PAYLOAD_TOO_LARGE` |
|
|
894
|
-
| Multipart upload (`fs.upload`) | 5 MiB | `FILE_MULTIPART_UPLOAD_MAX_BYTES` | `FILE_TOO_LARGE` |
|
|
895
|
-
| Chunked upload part (`fs.uploadData`, internal) | 768 KiB | `FILE_UPLOAD_PART_MAX_BYTES` | — (server-sized, transparent to callers) |
|
|
896
|
-
| Chunked upload session (`fs.uploadData`) | 64 MiB | `FILE_UPLOAD_SESSION_MAX_BYTES` | `PAYLOAD_TOO_LARGE` |
|
|
897
|
-
|
|
898
|
-
All constants are exported from `@tangle-network/runtime-contracts`. Use
|
|
899
|
-
`fs.uploadData` for anything above the single-shot caps. `PAYLOAD_TOO_LARGE`
|
|
900
|
-
means split the delivery (use `fs.uploadData` instead of one request);
|
|
901
|
-
`FILE_TOO_LARGE` means the content itself exceeds what that surface accepts,
|
|
902
|
-
no matter how it's delivered.
|
|
903
|
-
|
|
904
|
-
### Snapshots
|
|
905
|
-
|
|
906
|
-
#### `box.snapshot(options?)`
|
|
907
|
-
|
|
908
|
-
Create a snapshot of the sandbox state.
|
|
244
|
+
Dispatch returns after the session starts.
|
|
245
|
+
A later process can retrieve the sandbox and await the stored result.
|
|
909
246
|
|
|
910
247
|
```typescript
|
|
911
|
-
const
|
|
912
|
-
|
|
913
|
-
paths: ["/workspace"], // specific paths (default: all)
|
|
248
|
+
const dispatched = await box.dispatchPrompt("Run the full test suite.", {
|
|
249
|
+
sessionId: "ci-run-42",
|
|
914
250
|
});
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
```
|
|
919
|
-
|
|
920
|
-
#### `box.listSnapshots()`
|
|
921
|
-
|
|
922
|
-
List all snapshots for this sandbox.
|
|
923
|
-
|
|
924
|
-
```typescript
|
|
925
|
-
const snapshots = await box.listSnapshots();
|
|
926
|
-
for (const snap of snapshots) {
|
|
927
|
-
console.log(`${snap.snapshotId}: ${snap.createdAt}`);
|
|
251
|
+
const reloaded = await client.get(box.id);
|
|
252
|
+
if (!reloaded) {
|
|
253
|
+
throw new Error(`Sandbox ${box.id} no longer exists`);
|
|
928
254
|
}
|
|
255
|
+
const result = await reloaded.session(dispatched.sessionId).result();
|
|
256
|
+
console.log(result.status, result.response);
|
|
929
257
|
```
|
|
930
258
|
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
#### Creating a sandbox with BYOS3
|
|
936
|
-
|
|
937
|
-
```typescript
|
|
938
|
-
const box = await client.create({
|
|
939
|
-
name: "my-sandbox",
|
|
940
|
-
storage: {
|
|
941
|
-
type: "s3", // "s3" | "gcs" | "r2"
|
|
942
|
-
bucket: "my-snapshots",
|
|
943
|
-
region: "us-east-1",
|
|
944
|
-
endpoint: "https://s3.us-east-1.amazonaws.com", // optional
|
|
945
|
-
credentials: {
|
|
946
|
-
accessKeyId: "AKIA...",
|
|
947
|
-
secretAccessKey: "...",
|
|
948
|
-
},
|
|
949
|
-
prefix: "sandbox-snapshots/", // optional path prefix
|
|
950
|
-
},
|
|
951
|
-
fromSnapshot: "snap_abc123", // restore from your storage
|
|
952
|
-
});
|
|
953
|
-
```
|
|
954
|
-
|
|
955
|
-
#### Snapshots with BYOS3
|
|
956
|
-
|
|
957
|
-
When storage is configured, snapshots are written directly to your bucket:
|
|
958
|
-
|
|
959
|
-
```typescript
|
|
960
|
-
// Create snapshot to your S3
|
|
961
|
-
const snap = await box.snapshot({
|
|
962
|
-
tags: ["production"],
|
|
963
|
-
storage: {
|
|
964
|
-
type: "s3",
|
|
965
|
-
bucket: "my-snapshots",
|
|
966
|
-
credentials: { accessKeyId: "...", secretAccessKey: "..." },
|
|
967
|
-
},
|
|
968
|
-
});
|
|
969
|
-
|
|
970
|
-
// List snapshots from your S3
|
|
971
|
-
const snapshots = await box.listSnapshots({
|
|
972
|
-
type: "s3",
|
|
973
|
-
bucket: "my-snapshots",
|
|
974
|
-
credentials: { ... },
|
|
975
|
-
});
|
|
976
|
-
|
|
977
|
-
// Restore from your S3
|
|
978
|
-
await box.restoreFromStorage({
|
|
979
|
-
type: "s3",
|
|
980
|
-
bucket: "my-snapshots",
|
|
981
|
-
credentials: { ... },
|
|
982
|
-
});
|
|
983
|
-
```
|
|
984
|
-
|
|
985
|
-
### Runtime Routing
|
|
986
|
-
|
|
987
|
-
By default, SDK runtime calls like `exec()`, `prompt()`, `task()`, file ops, git, and process management go through the Sandbox API, which dispatches them to the correct running sandbox for the authenticated user.
|
|
988
|
-
|
|
989
|
-
Runtime agent calls can pass a named backend profile or an inline provider-neutral profile object:
|
|
990
|
-
|
|
991
|
-
```typescript
|
|
992
|
-
const result = await box.prompt("Audit the authentication flow", {
|
|
993
|
-
backend: {
|
|
994
|
-
profile: {
|
|
995
|
-
name: "security-auditor",
|
|
996
|
-
prompt: {
|
|
997
|
-
systemPrompt: "You are a senior application security auditor.",
|
|
998
|
-
instructions: ["Prioritize authz, tenancy, and secret handling."],
|
|
999
|
-
},
|
|
1000
|
-
tools: { bash: true },
|
|
1001
|
-
permissions: { bash: "allow" },
|
|
1002
|
-
},
|
|
1003
|
-
},
|
|
1004
|
-
});
|
|
1005
|
-
```
|
|
1006
|
-
|
|
1007
|
-
### Direct Runtime Access
|
|
1008
|
-
|
|
1009
|
-
For advanced use cases, use `box.direct()` to make runtime calls directly against the sandbox runtime while keeping normal lifecycle methods on the API client:
|
|
1010
|
-
|
|
1011
|
-
```typescript
|
|
1012
|
-
const directBox = box.direct();
|
|
1013
|
-
const result = await directBox.exec("npm test");
|
|
1014
|
-
```
|
|
1015
|
-
|
|
1016
|
-
This is the recommended advanced path for power users who want runtime-level access without re-implementing auth/header plumbing themselves.
|
|
1017
|
-
|
|
1018
|
-
### Lifecycle Methods
|
|
1019
|
-
|
|
1020
|
-
```typescript
|
|
1021
|
-
// Stop (preserves state)
|
|
1022
|
-
await box.stop();
|
|
1023
|
-
|
|
1024
|
-
// Resume
|
|
1025
|
-
await box.resume();
|
|
1026
|
-
|
|
1027
|
-
// Delete (destroys everything)
|
|
1028
|
-
await box.delete();
|
|
1029
|
-
|
|
1030
|
-
// Refresh status from API
|
|
1031
|
-
await box.refresh();
|
|
1032
|
-
|
|
1033
|
-
// Wait for specific status
|
|
1034
|
-
await box.waitFor("running", { timeoutMs: 60000 });
|
|
1035
|
-
```
|
|
1036
|
-
|
|
1037
|
-
### Properties
|
|
1038
|
-
|
|
1039
|
-
```typescript
|
|
1040
|
-
box.id // Unique identifier
|
|
1041
|
-
box.name // Human-readable name
|
|
1042
|
-
box.status // "pending" | "provisioning" | "running" | "stopped" | "failed"
|
|
1043
|
-
box.connection // raw direct connection info for advanced use
|
|
1044
|
-
box.metadata // Custom metadata
|
|
1045
|
-
box.createdAt // Date
|
|
1046
|
-
box.startedAt // Date | undefined
|
|
1047
|
-
box.lastActivityAt // Date | undefined
|
|
1048
|
-
box.expiresAt // Date | undefined
|
|
1049
|
-
box.error // Error message if failed
|
|
1050
|
-
```
|
|
259
|
+
Reusing the same caller-owned session ID makes a repeated dispatch find the existing session instead of starting another run.
|
|
260
|
+
Use session events with an event ID when the consumer must replay a dropped stream.
|
|
261
|
+
Use the `/session-gateway` entrypoint for browser WebSocket reconnect and replay.
|
|
1051
262
|
|
|
1052
263
|
## Fleets
|
|
1053
264
|
|
|
1054
|
-
A
|
|
1055
|
-
|
|
1056
|
-
Fleets give you:
|
|
1057
|
-
|
|
1058
|
-
- A single id (`fleetId`) plus a stable machine id (`machineId`) per member that you choose
|
|
1059
|
-
- Policy enforcement (CPU / memory / storage / accelerator caps, allowed drivers / images / templates, max spend, max concurrent creates) — checked client-side **before** sandboxes are provisioned
|
|
1060
|
-
- Per-dispatch parallelism, retries, timeouts, idempotency, cancellation, and result buffering
|
|
1061
|
-
- Shared workspace modes (`isolated`, `shared`) with cross-machine snapshot, restore, and reconcile
|
|
1062
|
-
- Fleet-scoped telemetry: usage, cost estimate, trace bundle, embedded intelligence envelope, and full intelligence reports
|
|
1063
|
-
- Scoped tokens for handing a fleet to a downstream service without leaking the parent API key
|
|
1064
|
-
|
|
1065
|
-
### Create a fleet
|
|
1066
|
-
|
|
1067
|
-
There are two creation shapes. Use `create` when every machine is symmetric, and `createWithCoordinator` when one machine acts as orchestrator over a pool of workers.
|
|
265
|
+
A fleet groups several sandboxes under one lifecycle and policy.
|
|
266
|
+
Use it for parallel jobs, coordinated workers, or workloads that need stable machine IDs.
|
|
1068
267
|
|
|
1069
268
|
```typescript
|
|
1070
|
-
|
|
1071
|
-
|
|
269
|
+
const fleet = await client.fleets.createWithCoordinator({
|
|
270
|
+
fleetId: "dependency-audit",
|
|
1072
271
|
defaults: {
|
|
1073
|
-
environment: "
|
|
1074
|
-
maxLifetimeSeconds:
|
|
272
|
+
environment: "universal",
|
|
273
|
+
maxLifetimeSeconds: 1800,
|
|
1075
274
|
},
|
|
1076
275
|
policy: {
|
|
1077
|
-
maxMachines:
|
|
276
|
+
maxMachines: 3,
|
|
1078
277
|
maxConcurrentCreates: 2,
|
|
1079
|
-
maxTotalCpu:
|
|
1080
|
-
maxTotalMemoryMb:
|
|
1081
|
-
maxSpendUsd:
|
|
278
|
+
maxTotalCpu: 6,
|
|
279
|
+
maxTotalMemoryMb: 12_288,
|
|
280
|
+
maxSpendUsd: 2,
|
|
1082
281
|
allowAccelerators: false,
|
|
1083
282
|
},
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
],
|
|
1088
|
-
workspace: { mode: "isolated" },
|
|
1089
|
-
metadata: { experiment: "react-19-bump" },
|
|
1090
|
-
idempotencyKey: "exp-react-19-2025-05-18",
|
|
1091
|
-
});
|
|
1092
|
-
|
|
1093
|
-
// Coordinator + workers
|
|
1094
|
-
const cluster = await client.fleets.createWithCoordinator({
|
|
1095
|
-
defaults: { environment: "python:3.12" },
|
|
1096
|
-
coordinator: { resources: { cpuCores: 1, memoryMB: 1024 } },
|
|
283
|
+
coordinator: {
|
|
284
|
+
resources: { cpuCores: 1, memoryMB: 1024 },
|
|
285
|
+
},
|
|
1097
286
|
workers: [
|
|
1098
|
-
{
|
|
1099
|
-
|
|
287
|
+
{
|
|
288
|
+
machineId: "worker-1",
|
|
289
|
+
resources: { cpuCores: 2, memoryMB: 4096 },
|
|
290
|
+
},
|
|
291
|
+
{
|
|
292
|
+
machineId: "worker-2",
|
|
293
|
+
resources: { cpuCores: 2, memoryMB: 4096 },
|
|
294
|
+
},
|
|
1100
295
|
],
|
|
1101
296
|
});
|
|
1102
|
-
```
|
|
1103
|
-
|
|
1104
|
-
`createWithCoordinator` is sugar over `create`: it injects a `coordinator` machine with `role: "coordinator"` and tags the workers `role: "worker"` in metadata. After creation both shapes return a `SandboxFleet` instance.
|
|
1105
297
|
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
timeoutMs: 60_000,
|
|
1114
|
-
retry: { attempts: 2, backoffMs: 1_000 },
|
|
1115
|
-
dispatchId: "pytest-run-1", // idempotent — same id replays the same dispatch
|
|
1116
|
-
});
|
|
298
|
+
try {
|
|
299
|
+
const results = await fleet.dispatchExec("pnpm test", {
|
|
300
|
+
machines: fleet.ids,
|
|
301
|
+
maxConcurrent: 2,
|
|
302
|
+
retry: { attempts: 2 },
|
|
303
|
+
timeoutMs: 10 * 60 * 1000,
|
|
304
|
+
});
|
|
1117
305
|
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
// Prompt variant — runs an agent prompt on each selected machine
|
|
1124
|
-
const promptResults = await fleet.dispatchPrompt(
|
|
1125
|
-
"Summarize what changed in this branch and why.",
|
|
1126
|
-
{ machines: ["worker-1"], model: "anthropic/claude-sonnet-4-20250514" },
|
|
1127
|
-
);
|
|
1128
|
-
|
|
1129
|
-
// Stream events as they happen
|
|
1130
|
-
for await (const event of fleet.dispatchExecStream("npm test", {
|
|
1131
|
-
machines: fleet.ids,
|
|
1132
|
-
})) {
|
|
1133
|
-
if (event.type === "result") console.log(event.data);
|
|
306
|
+
for (const result of results) {
|
|
307
|
+
console.log(result.machineId, result.ok, result.error?.message);
|
|
308
|
+
}
|
|
309
|
+
} finally {
|
|
310
|
+
await fleet.delete({ continueOnError: true });
|
|
1134
311
|
}
|
|
1135
|
-
|
|
1136
|
-
// Read previously-buffered results by dispatchId
|
|
1137
|
-
const buffered = await fleet.dispatchResults("pytest-run-1", {
|
|
1138
|
-
limit: 100,
|
|
1139
|
-
machines: ["worker-1", "worker-2"],
|
|
1140
|
-
});
|
|
1141
|
-
|
|
1142
|
-
// Cancel an in-flight dispatch
|
|
1143
|
-
await fleet.cancelDispatch("pytest-run-1", "abandoning experiment");
|
|
1144
|
-
```
|
|
1145
|
-
|
|
1146
|
-
### Single-machine helpers
|
|
1147
|
-
|
|
1148
|
-
When you want to talk to one machine in the fleet directly:
|
|
1149
|
-
|
|
1150
|
-
```typescript
|
|
1151
|
-
const result = await fleet.exec("worker-1", "echo hello");
|
|
1152
|
-
const reply = await fleet.prompt("worker-1", "What is the structure?");
|
|
1153
|
-
const box = await fleet.sandbox("worker-1"); // full SandboxInstance
|
|
1154
|
-
```
|
|
1155
|
-
|
|
1156
|
-
### Workspace snapshots (shared workspace mode)
|
|
1157
|
-
|
|
1158
|
-
```typescript
|
|
1159
|
-
const snap = await fleet.createWorkspaceSnapshot();
|
|
1160
|
-
await fleet.restoreWorkspaceSnapshot(snap.snapshotId);
|
|
1161
|
-
await fleet.reconcileWorkspace();
|
|
1162
|
-
```
|
|
1163
|
-
|
|
1164
|
-
### Dynamic topology
|
|
1165
|
-
|
|
1166
|
-
```typescript
|
|
1167
|
-
await fleet.attachMachine({
|
|
1168
|
-
machineId: "worker-3",
|
|
1169
|
-
sandboxId: "sbx_abc", // existing sandbox to bind into the fleet
|
|
1170
|
-
role: "worker",
|
|
1171
|
-
});
|
|
1172
|
-
await fleet.detachMachine("worker-3");
|
|
1173
312
|
```
|
|
1174
313
|
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
```typescript
|
|
1178
|
-
const artifacts = await fleet.collectArtifacts([
|
|
1179
|
-
{ machineId: "worker-1", path: "/workspace/report.json", maxBytes: 1_000_000 },
|
|
1180
|
-
]);
|
|
1181
|
-
|
|
1182
|
-
const usage = await fleet.usage(); // current usage rollup
|
|
1183
|
-
const estimate = await fleet.cost(); // cost estimate
|
|
1184
|
-
const manifest = await fleet.manifest(); // machine manifest as persisted
|
|
314
|
+
Fleet policies are checked before provisioning and do not replace account quotas.
|
|
315
|
+
Use `client.runBatch()` for unrelated one-shot jobs that do not need stable fleet membership.
|
|
1185
316
|
|
|
1186
|
-
|
|
1187
|
-
const token = await fleet.createToken({ expiresInSeconds: 3600 });
|
|
1188
|
-
```
|
|
317
|
+
## Temporary GPU leases
|
|
1189
318
|
|
|
1190
|
-
|
|
319
|
+
Attach a GPU only for the work that needs it.
|
|
320
|
+
Omit `provider` to request the cheapest eligible configured option.
|
|
321
|
+
Every lease requires a spend limit and lifetime.
|
|
1191
322
|
|
|
1192
323
|
```typescript
|
|
1193
|
-
|
|
1194
|
-
defaults: { environment: "python:3.12" },
|
|
1195
|
-
policy: { maxMachines: 4, maxSpendUsd: 5 },
|
|
1196
|
-
machines: [
|
|
1197
|
-
{ machineId: "worker-1", resources: { cpuCores: 2, memoryMB: 4096 } },
|
|
1198
|
-
{ machineId: "worker-2", resources: { cpuCores: 2, memoryMB: 4096 } },
|
|
1199
|
-
],
|
|
1200
|
-
});
|
|
1201
|
-
```
|
|
1202
|
-
|
|
1203
|
-
### Operations
|
|
1204
|
-
|
|
1205
|
-
```typescript
|
|
1206
|
-
const caps = await client.fleets.capabilities(); // which drivers / templates / images
|
|
1207
|
-
const ops = await client.fleets.operations(); // operations summary
|
|
1208
|
-
const recon = await client.fleets.reconcile(); // reconcile drift
|
|
1209
|
-
const reaped = await client.fleets.reapExpired(); // sweep expired fleets
|
|
1210
|
-
```
|
|
1211
|
-
|
|
1212
|
-
### Lookup and delete
|
|
1213
|
-
|
|
1214
|
-
```typescript
|
|
1215
|
-
const found = await client.fleets.list({ fleetId: "fleet_abc" });
|
|
1216
|
-
await client.fleets.delete("fleet_abc", { continueOnError: true });
|
|
1217
|
-
```
|
|
1218
|
-
|
|
1219
|
-
### Single-shot batches without fleets
|
|
1220
|
-
|
|
1221
|
-
For one-shot, ad-hoc parallel work that does not need fleet-level policy / workspaces / dispatch buffering / intelligence reports, `client.runBatch(tasks, options)` is the simpler primitive. New code that needs more than one sandbox under one logical lifecycle should reach for fleets.
|
|
1222
|
-
|
|
1223
|
-
## Intelligence Reports
|
|
1224
|
-
|
|
1225
|
-
The **Intelligence Reports** API generates structured post-hoc analyses over two subject types: a single **sandbox** or a single **fleet**. A fleet subject can optionally be narrowed to one dispatch within the fleet via `subject.dispatchId`. Two modes:
|
|
1226
|
-
|
|
1227
|
-
- **`deterministic`** (default) — platform-side rule-based analysis. Free. Returns immediately or near-immediately. Surfaces lifecycle, runtime, plan-headroom, and resource-density signals derived directly from your trace evidence.
|
|
1228
|
-
- **`agentic`** — runs the **Tangle Trace Analyst**, an LLM-driven reasoning loop, over your OTLP trace evidence. Returns findings with evidence references, recommended actions, and a validation plan. **Billed** against `budget.maxUsd`; the platform never spends past the budget you set. Async (returns a job; poll for terminal state).
|
|
1229
|
-
|
|
1230
|
-
The dedicated client lives on `client.intelligence`:
|
|
1231
|
-
|
|
1232
|
-
```typescript
|
|
1233
|
-
import { Sandbox } from "@tangle-network/sandbox";
|
|
1234
|
-
import type { IntelligenceClient } from "@tangle-network/sandbox";
|
|
1235
|
-
|
|
1236
|
-
const client = new Sandbox({ apiKey, baseUrl });
|
|
1237
|
-
const intelligence: IntelligenceClient = client.intelligence;
|
|
1238
|
-
```
|
|
324
|
+
let lease: Awaited<ReturnType<(typeof box)["gpu"]["attach"]>> | undefined;
|
|
1239
325
|
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
}
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
});
|
|
1252
|
-
|
|
1253
|
-
// Deterministic — narrowed to one dispatch within a fleet
|
|
1254
|
-
await client.intelligence.createReport({
|
|
1255
|
-
subject: {
|
|
1256
|
-
type: "fleet",
|
|
1257
|
-
id: fleet.fleetId,
|
|
1258
|
-
dispatchId: "pytest-run-1",
|
|
1259
|
-
},
|
|
1260
|
-
});
|
|
1261
|
-
|
|
1262
|
-
// Agentic — billed against the budget
|
|
1263
|
-
const agentic = await client.intelligence.createReport({
|
|
1264
|
-
subject: { type: "fleet", id: fleet.fleetId },
|
|
1265
|
-
mode: "agentic",
|
|
1266
|
-
budget: { billTo: "customer", maxUsd: 5 },
|
|
1267
|
-
acknowledgeCost: true,
|
|
1268
|
-
metadata: { experiment: "react-19-bump" },
|
|
1269
|
-
});
|
|
1270
|
-
|
|
1271
|
-
// Shorthand for the agentic + budget pattern
|
|
1272
|
-
const shortcut = await client.intelligence.createAgenticReport({
|
|
1273
|
-
subject: { type: "sandbox", id: box.id },
|
|
1274
|
-
maxUsd: 2,
|
|
1275
|
-
});
|
|
1276
|
-
```
|
|
1277
|
-
|
|
1278
|
-
### Poll a report to completion
|
|
1279
|
-
|
|
1280
|
-
Agentic reports return `status: "pending"` immediately. Either poll yourself with `getReport`, or use the built-in `waitForReport`:
|
|
1281
|
-
|
|
1282
|
-
```typescript
|
|
1283
|
-
const job = await client.intelligence.createAgenticReport({
|
|
1284
|
-
subject: { type: "fleet", id: fleet.fleetId },
|
|
1285
|
-
maxUsd: 5,
|
|
1286
|
-
});
|
|
326
|
+
try {
|
|
327
|
+
lease = await box.gpu.attach({
|
|
328
|
+
accelerator: {
|
|
329
|
+
kind: "nvidia-3090",
|
|
330
|
+
count: 1,
|
|
331
|
+
memoryMB: 24_000,
|
|
332
|
+
},
|
|
333
|
+
maxSpendUsd: 1,
|
|
334
|
+
maxLifetimeSeconds: 900,
|
|
335
|
+
idleTimeoutSeconds: 120,
|
|
336
|
+
});
|
|
1287
337
|
|
|
1288
|
-
const
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
});
|
|
338
|
+
const run = await box.gpu.exec(lease.id, {
|
|
339
|
+
command: "python eval.py",
|
|
340
|
+
timeoutMs: 15 * 60 * 1000,
|
|
341
|
+
});
|
|
1292
342
|
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
343
|
+
process.stdout.write(run.result.stdout);
|
|
344
|
+
process.stderr.write(run.result.stderr);
|
|
345
|
+
} finally {
|
|
346
|
+
if (lease) {
|
|
347
|
+
await box.gpu.detach(lease.id);
|
|
348
|
+
}
|
|
1296
349
|
}
|
|
1297
350
|
```
|
|
1298
351
|
|
|
1299
|
-
|
|
352
|
+
Always detach the lease in `finally`.
|
|
353
|
+
Deleting the base sandbox remains a separate cleanup step.
|
|
1300
354
|
|
|
1301
|
-
|
|
1302
|
-
const recent = await client.intelligence.listReports({
|
|
1303
|
-
subjectType: "fleet",
|
|
1304
|
-
subjectId: fleet.fleetId,
|
|
1305
|
-
limit: 20,
|
|
1306
|
-
});
|
|
1307
|
-
```
|
|
1308
|
-
|
|
1309
|
-
### Per-subject shortcuts
|
|
1310
|
-
|
|
1311
|
-
`SandboxInstance` and `SandboxFleet` expose convenience wrappers so you don't have to thread `subject` manually:
|
|
1312
|
-
|
|
1313
|
-
```typescript
|
|
1314
|
-
await box.createIntelligenceReport({ mode: "deterministic" });
|
|
1315
|
-
await box.createAgenticIntelligenceReport({ maxUsd: 2 });
|
|
1316
|
-
|
|
1317
|
-
await fleet.createIntelligenceReport({ mode: "deterministic" });
|
|
1318
|
-
await fleet.createAgenticIntelligenceReport({ maxUsd: 5 });
|
|
1319
|
-
|
|
1320
|
-
// Fleet helpers accept the v2 refinement fields directly:
|
|
1321
|
-
await fleet.createIntelligenceReport({
|
|
1322
|
-
mode: "deterministic",
|
|
1323
|
-
dispatchId: "pytest-run-1",
|
|
1324
|
-
});
|
|
1325
|
-
```
|
|
1326
|
-
|
|
1327
|
-
Both wrappers post to `POST /v1/intelligence/reports` with the right `subject` filled in.
|
|
1328
|
-
|
|
1329
|
-
### Time windows and baselines
|
|
1330
|
-
|
|
1331
|
-
Every report can be narrowed by a time window and compared against a same-type baseline. The analyzer rejects mixed-type comparisons because the delta would be meaningless.
|
|
1332
|
-
|
|
1333
|
-
```typescript
|
|
1334
|
-
// Bound the analysis to a one-hour window.
|
|
1335
|
-
await fleet.createIntelligenceReport({
|
|
1336
|
-
window: { since: Date.now() - 60 * 60 * 1000 },
|
|
1337
|
-
});
|
|
355
|
+
## Public API map
|
|
1338
356
|
|
|
1339
|
-
|
|
1340
|
-
await fleet.createIntelligenceReport({
|
|
1341
|
-
dispatchId: "run-after",
|
|
1342
|
-
compareTo: { type: "fleet", id: fleet.fleetId, dispatchId: "run-before" },
|
|
1343
|
-
});
|
|
357
|
+
The root entrypoint exports the primary client, instance, session, fleet, image, error, trace, and resource types.
|
|
1344
358
|
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
Estimate cost without creating a report. Subject ownership is verified the same way as `createReport`, so the endpoint never becomes an existence oracle for foreign subjects.
|
|
359
|
+
| Surface | Start with |
|
|
360
|
+
|---|---|
|
|
361
|
+
| Account client | `Sandbox` |
|
|
362
|
+
| One environment | `SandboxInstance` |
|
|
363
|
+
| Continued conversation | `SandboxSession` |
|
|
364
|
+
| Coordinated environments | `SandboxFleetClient`, `SandboxFleet` |
|
|
365
|
+
| Reusable images | `Image`, `ImageBuilder` |
|
|
366
|
+
| Failures | `SandboxError` and its specific subclasses |
|
|
1354
367
|
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
mode: "agentic",
|
|
1359
|
-
});
|
|
1360
|
-
console.log(`Would cost ${estimate.costUsd} USD (${estimate.reason})`);
|
|
1361
|
-
```
|
|
368
|
+
The main client provides `create`, `list`, `get`, `usage`, `subscription`, and `health`.
|
|
369
|
+
Its managers cover environments, public templates, teams, secrets, SSH keys, fleets, and intelligence reports.
|
|
370
|
+
The published TypeScript declarations are the complete method and option reference.
|
|
1362
371
|
|
|
1363
|
-
|
|
372
|
+
Handle SDK failures through the exported error hierarchy.
|
|
1364
373
|
|
|
1365
374
|
```typescript
|
|
1366
|
-
import {
|
|
1367
|
-
AuthError,
|
|
1368
|
-
NetworkError,
|
|
1369
|
-
NotFoundError,
|
|
1370
|
-
QuotaError,
|
|
1371
|
-
StateError,
|
|
1372
|
-
TimeoutError,
|
|
1373
|
-
ValidationError,
|
|
1374
|
-
} from "@tangle-network/sandbox";
|
|
375
|
+
import { SandboxError } from "@tangle-network/sandbox";
|
|
1375
376
|
|
|
1376
377
|
try {
|
|
1377
|
-
await box.exec("
|
|
1378
|
-
} catch (
|
|
1379
|
-
if (
|
|
1380
|
-
console.
|
|
1381
|
-
|
|
1382
|
-
console.log(`Invalid state: ${err.currentState}`);
|
|
1383
|
-
} else if (err instanceof NetworkError) {
|
|
1384
|
-
console.log("Connection failed");
|
|
378
|
+
await box.exec("pnpm test");
|
|
379
|
+
} catch (error) {
|
|
380
|
+
if (error instanceof SandboxError) {
|
|
381
|
+
console.error(error.code, error.status, error.endpoint, error.message);
|
|
382
|
+
throw error;
|
|
1385
383
|
}
|
|
384
|
+
|
|
385
|
+
throw error;
|
|
1386
386
|
}
|
|
1387
387
|
```
|
|
1388
388
|
|
|
1389
|
-
##
|
|
389
|
+
## More documentation
|
|
1390
390
|
|
|
1391
|
-
|
|
391
|
+
- [TypeScript SDK guide](https://sandbox.tangle.tools/docs/sdk/typescript)
|
|
392
|
+
- [Platform quickstart](https://sandbox.tangle.tools/docs/quickstart)
|
|
393
|
+
- [GPU lease guide](https://sandbox.tangle.tools/docs/gpu-leases)
|
|
394
|
+
- [Runnable SDK examples](./examples/README.md)
|
|
395
|
+
- [Session and adapter integration notes](./INTEGRATION.md)
|
|
396
|
+
- [CLI](../cli/README.md)
|
|
397
|
+
- [Python SDK](../sdk-python/README.md)
|
|
1392
398
|
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
ExecResult,
|
|
1401
|
-
ExecOptions,
|
|
1402
|
-
PromptResult,
|
|
1403
|
-
PromptOptions,
|
|
1404
|
-
TaskResult,
|
|
1405
|
-
TaskOptions,
|
|
1406
|
-
SnapshotResult,
|
|
1407
|
-
SnapshotOptions,
|
|
1408
|
-
SnapshotInfo,
|
|
1409
|
-
StorageConfig,
|
|
1410
|
-
BatchTask,
|
|
1411
|
-
BatchResult,
|
|
1412
|
-
BatchOptions,
|
|
1413
|
-
UsageInfo,
|
|
1414
|
-
// Fleets
|
|
1415
|
-
CreateSandboxFleetOptions,
|
|
1416
|
-
CreateSandboxFleetWithCoordinatorOptions,
|
|
1417
|
-
SandboxFleetMachineSpec,
|
|
1418
|
-
SandboxFleetInfo,
|
|
1419
|
-
SandboxFleetManifest,
|
|
1420
|
-
SandboxFleetUsage,
|
|
1421
|
-
SandboxFleetCostEstimate,
|
|
1422
|
-
SandboxFleetToken,
|
|
1423
|
-
SandboxFleetTraceBundle,
|
|
1424
|
-
SandboxFleetTraceOptions,
|
|
1425
|
-
SandboxFleetDispatchResponse,
|
|
1426
|
-
FleetExecDispatchOptions,
|
|
1427
|
-
FleetExecDispatchResult,
|
|
1428
|
-
FleetPromptDispatchOptions,
|
|
1429
|
-
FleetPromptDispatchResult,
|
|
1430
|
-
FleetDispatchResultBuffer,
|
|
1431
|
-
FleetDispatchResultBufferOptions,
|
|
1432
|
-
FleetDispatchStreamOptions,
|
|
1433
|
-
FleetDispatchCancelResult,
|
|
1434
|
-
FleetMachineId,
|
|
1435
|
-
// Intelligence Reports
|
|
1436
|
-
IntelligenceReport,
|
|
1437
|
-
IntelligenceReportBudget,
|
|
1438
|
-
CreateIntelligenceReportOptions,
|
|
1439
|
-
} from "@tangle-network/sandbox";
|
|
1440
|
-
|
|
1441
|
-
// Concrete classes — useful when you need to reference the type itself
|
|
1442
|
-
import {
|
|
1443
|
-
IntelligenceClient,
|
|
1444
|
-
SandboxFleet,
|
|
1445
|
-
SandboxFleetClient,
|
|
1446
|
-
} from "@tangle-network/sandbox";
|
|
399
|
+
## Package development
|
|
400
|
+
|
|
401
|
+
```bash
|
|
402
|
+
pnpm --filter @tangle-network/sandbox check-types
|
|
403
|
+
pnpm --filter @tangle-network/sandbox test
|
|
404
|
+
pnpm --filter @tangle-network/sandbox build
|
|
405
|
+
pnpm --filter @tangle-network/sandbox verify-dist
|
|
1447
406
|
```
|
|
1448
407
|
|
|
1449
408
|
## License
|