wbxsandbox 0.0.0-stage → 0.1.0

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.
Files changed (64) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/LICENSE +21 -0
  3. package/README.md +458 -2
  4. package/dist/account.d.ts +69 -0
  5. package/dist/account.d.ts.map +1 -0
  6. package/dist/account.js +119 -0
  7. package/dist/account.js.map +1 -0
  8. package/dist/client.d.ts +96 -0
  9. package/dist/client.d.ts.map +1 -0
  10. package/dist/client.js +113 -0
  11. package/dist/client.js.map +1 -0
  12. package/dist/errors.d.ts +176 -0
  13. package/dist/errors.d.ts.map +1 -0
  14. package/dist/errors.js +248 -0
  15. package/dist/errors.js.map +1 -0
  16. package/dist/http.d.ts +64 -0
  17. package/dist/http.d.ts.map +1 -0
  18. package/dist/http.js +361 -0
  19. package/dist/http.js.map +1 -0
  20. package/dist/index.d.ts +27 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +26 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/jobs.d.ts +300 -0
  25. package/dist/jobs.d.ts.map +1 -0
  26. package/dist/jobs.js +461 -0
  27. package/dist/jobs.js.map +1 -0
  28. package/dist/pagination.d.ts +32 -0
  29. package/dist/pagination.d.ts.map +1 -0
  30. package/dist/pagination.js +47 -0
  31. package/dist/pagination.js.map +1 -0
  32. package/dist/sandbox.d.ts +486 -0
  33. package/dist/sandbox.d.ts.map +1 -0
  34. package/dist/sandbox.js +894 -0
  35. package/dist/sandbox.js.map +1 -0
  36. package/dist/streams.d.ts +71 -0
  37. package/dist/streams.d.ts.map +1 -0
  38. package/dist/streams.js +235 -0
  39. package/dist/streams.js.map +1 -0
  40. package/dist/types.d.ts +662 -0
  41. package/dist/types.d.ts.map +1 -0
  42. package/dist/types.js +10 -0
  43. package/dist/types.js.map +1 -0
  44. package/dist/util.d.ts +27 -0
  45. package/dist/util.d.ts.map +1 -0
  46. package/dist/util.js +140 -0
  47. package/dist/util.js.map +1 -0
  48. package/dist/version.d.ts +3 -0
  49. package/dist/version.d.ts.map +1 -0
  50. package/dist/version.js +3 -0
  51. package/dist/version.js.map +1 -0
  52. package/package.json +54 -4
  53. package/src/account.ts +121 -0
  54. package/src/client.ts +152 -0
  55. package/src/errors.ts +299 -0
  56. package/src/http.ts +421 -0
  57. package/src/index.ts +75 -0
  58. package/src/jobs.ts +609 -0
  59. package/src/pagination.ts +51 -0
  60. package/src/sandbox.ts +1125 -0
  61. package/src/streams.ts +250 -0
  62. package/src/types.ts +649 -0
  63. package/src/util.ts +140 -0
  64. package/src/version.ts +2 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,51 @@
1
+ # Changelog
2
+
3
+ All notable changes to this package are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the package uses
5
+ [semantic versioning](https://semver.org) (while 0.x, minor releases may break compatibility).
6
+
7
+ ## [0.1.0] – unreleased
8
+
9
+ First release.
10
+
11
+ ### Added
12
+
13
+ - `WBX` client: API key from `WBXSANDBOX_API_KEY`, address from `WBXSANDBOX_URL`
14
+ (default `https://sandbox.wbx.cz`), per-attempt timeouts, `AbortSignal` on every call,
15
+ safe automatic retries with backoff and `Retry-After`, custom `fetch`.
16
+ - Sandboxes: create (template, lifetime, name, sleep on timeout, idle timeout, keep days,
17
+ env, metadata, compute class, network policy and IP version), get, list, kill, refresh,
18
+ set timeout, sleep, pause, resume, keep, public port URL, `runCode`.
19
+ - Commands: `run` (with live output callbacks), `stream` (async iterator of events).
20
+ - Files: read (bytes, text, stream), write (text, bytes, Blob, stream), list, stat, exists,
21
+ mkdir, move, remove, watch.
22
+ - Background processes: start, list, get, stream output, stdin, signals, resize, kill.
23
+ - Jobs: create (idempotency key added automatically), get, list (pages), server-side wait,
24
+ summary, logs, digest, follow, receipt, signed receipt, artifacts, verified download
25
+ (`IntegrityError` also when the server's checksum is missing or malformed, unless
26
+ `verify: false`), cancel, retry; WebAssembly jobs.
27
+ - Batches: create with dependencies and inputs from other jobs, get, list, summary, report
28
+ (JSON and CSV), wait, cancel, jobs of a batch.
29
+ - Metrics: current values; history and live stream (feature `metrics_history`) with
30
+ optional resumption – reconnects back off with jitter, a connection that ends right after
31
+ opening counts as a failure (`maxReconnects`), and at most `maxConnectsPerMinute`
32
+ (default 6) connections are opened a minute.
33
+ - Desktop control for the `desktop` template (feature `desktop`): status (`controller_until`
34
+ as Unix ms), screenshot (image and screen size), actions (`mouse_down` / `mouse_up` with
35
+ optional coordinates, screenshot format, quality and width; a failed action throws
36
+ `ComputerActionError` with `failedIndex` and `results`, or is returned with
37
+ `throwOnFailure: false`; `screenshotError`), taking control back, convenience methods.
38
+ - Templates, features, budget, compute classes, runtimes, receipt keys, webhook secret,
39
+ `verifyWebhook`, `wbx.request()` for endpoints without a wrapper.
40
+ - Typed errors (`WBXError` and subclasses for every HTTP status the API uses;
41
+ `HumanInControlError.controllerUntil`, `ComputerActionError`, `StreamLimitError`).
42
+ - SSE and NDJSON stream parsers with a size limit per event / line (`maxStreamEventSize`,
43
+ default 16 MiB characters; `StreamLimitError` stops reading and closes the connection).
44
+
45
+ ### Security
46
+
47
+ - The API key is kept in a private field of the transport: it is not part of
48
+ `transport.config`, and `util.inspect()` / `console.log()` / `JSON.stringify()` of the
49
+ client, its resources, sandboxes, jobs, batches and errors never contain it.
50
+ - Streamed responses cannot make the client buffer without bound (see `maxStreamEventSize`).
51
+ - A downloaded artifact without a checksum is never returned as verified.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 WBX Sandbox
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,459 @@
1
- # Temporary Holding Version
1
+ # wbxsandbox – TypeScript SDK for WBX Sandbox
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Official TypeScript / JavaScript SDK for [WBX Sandbox](https://sandbox.wbx.cz): isolated cloud
4
+ sandboxes for AI agents and code execution. Every sandbox is a Firecracker microVM with its own
5
+ Linux kernel, disk and network rules.
6
+
7
+ - Sandboxes: commands (also streamed), code, files, background processes, public URLs, sleep and wake
8
+ - Background jobs and batches: no open connection, logs, result files, signed execution receipts
9
+ - Live metrics and desktop control (computer use) for agents
10
+ - Typed errors, timeouts, `AbortSignal` everywhere, safe automatic retries
11
+ - Zero runtime dependencies – only `fetch`, `ReadableStream` and Web Crypto; runs on Node.js 20+,
12
+ Deno, Bun and edge runtimes
13
+
14
+ > **Status:** 0.x – see [Versioning and compatibility](#versioning-and-compatibility).
15
+
16
+ ## Contents
17
+
18
+ - [Install](#install)
19
+ - [Quick start](#quick-start)
20
+ - [Authentication and configuration](#authentication-and-configuration)
21
+ - [Sandboxes](#sandboxes)
22
+ - [Commands and code](#commands-and-code)
23
+ - [Files](#files)
24
+ - [Background processes](#background-processes)
25
+ - [Background jobs](#background-jobs)
26
+ - [Batches](#batches)
27
+ - [Metrics](#metrics) (feature `metrics_history`)
28
+ - [Desktop control](#desktop-control) (feature `desktop`)
29
+ - [Account: templates, budget, compute classes, webhooks](#account)
30
+ - [Errors](#errors)
31
+ - [Timeouts and cancellation](#timeouts-and-cancellation)
32
+ - [Retries](#retries)
33
+ - [Pagination](#pagination)
34
+ - [Runtimes](#runtimes)
35
+ - [Versioning and compatibility](#versioning-and-compatibility)
36
+ - [Links](#links)
37
+
38
+ ## Install
39
+
40
+ ```sh
41
+ npm install wbxsandbox
42
+ ```
43
+
44
+ Requires Node.js 20 or newer (or Deno, Bun, a browser-like edge runtime). The package is ESM
45
+ only and ships its own type declarations.
46
+
47
+ ## Quick start
48
+
49
+ ```ts
50
+ import { WBX } from "wbxsandbox";
51
+
52
+ const wbx = new WBX({ apiKey: process.env.WBXSANDBOX_API_KEY! });
53
+
54
+ const sandbox = await wbx.sandboxes.create({ template: "base", name: "my-project" });
55
+ const r = await sandbox.commands.run("python3 --version");
56
+ console.log(r.stdout);
57
+
58
+ await sandbox.sleep(); // files kept, no compute billed; the next request wakes it up
59
+ ```
60
+
61
+ More in [`examples/`](examples): a sandbox, a job with waiting and logs, a batch with
62
+ dependencies, a metrics stream, desktop control and a framework-agnostic tool for an AI model.
63
+
64
+ ## Authentication and configuration
65
+
66
+ Create an API key in the portal (**Settings → API keys**). The SDK sends it in the `X-API-Key`
67
+ header – never in a URL.
68
+
69
+ ```ts
70
+ const wbx = new WBX({
71
+ apiKey: "…", // default: WBXSANDBOX_API_KEY
72
+ baseURL: "https://sandbox.wbx.cz", // default: WBXSANDBOX_URL, else https://sandbox.wbx.cz
73
+ timeoutMs: 60_000, // per HTTP attempt (methods that wait longer set their own)
74
+ maxRetries: 2, // for safe requests only, see Retries
75
+ maxRetryDelayMs: 60_000, // longest Retry-After the client is willing to wait
76
+ fetch: customFetch, // optional – e.g. a proxy-aware fetch
77
+ headers: { "X-Trace": "…" }, // added to every request
78
+ maxStreamEventSize: 16_777_216, // longest streamed event / NDJSON line (characters, 16 MiB)
79
+ });
80
+ ```
81
+
82
+ The key is kept in a private field: it is not readable from `wbx.transport.config`, and
83
+ `console.log(wbx)`, `util.inspect()` and `JSON.stringify()` of the client, sandboxes, jobs,
84
+ batches and errors never contain it – safe for logs and error trackers.
85
+
86
+ The environment variables are the same as for the Python SDK (`WBXSANDBOX_API_KEY`,
87
+ `WBXSANDBOX_URL`). A missing key raises `AuthenticationError` before any request is sent.
88
+
89
+ ## Sandboxes
90
+
91
+ ```ts
92
+ const sandbox = await wbx.sandboxes.create({
93
+ template: "base", // see wbx.templates.list()
94
+ timeoutSeconds: 600, // lifetime; extend with sandbox.setTimeout()
95
+ name: "my-project", // reuse: an existing sandbox with this name is returned (woken up)
96
+ onTimeout: "pause", // fall asleep instead of being destroyed – files are kept
97
+ idleTimeoutSeconds: 600, // …or after this long without requests
98
+ keepDays: 30, // keep it this long while asleep (plan maximum applies)
99
+ env: { OPENAI_API_KEY: "…" },
100
+ metadata: { user: "42" },
101
+ computeClass: "balanced", // never downgraded
102
+ network: { mode: "allowlist", allow: ["pypi.org", "files.pythonhosted.org"], ip: "dual" },
103
+ });
104
+
105
+ sandbox.id; // "sb_…"
106
+ sandbox.state; // "running"
107
+ sandbox.existing; // true when create({ name }) returned an existing sandbox
108
+ sandbox.ipv6; // public IPv6 address with network.ip "dual" / "ipv6"
109
+ sandbox.info; // the API record (snake_case fields)
110
+
111
+ await sandbox.setTimeout(3600);
112
+ const { url_with_token } = await sandbox.getUrl(8080); // public HTTPS address of a port
113
+ await sandbox.keep(14); // days to keep it after it falls asleep
114
+ await sandbox.sleep(); // files kept, programs stop, no compute billed
115
+ await sandbox.resume(); // or any other request wakes it up
116
+ await sandbox.pause(); // freeze with memory; resume() continues where it stopped
117
+ await sandbox.refresh(); // reload the record
118
+ await sandbox.kill(); // destroy with its data (no error if already gone)
119
+
120
+ const again = await wbx.sandboxes.get(sandbox.id); // attach later, e.g. in the next turn
121
+ const all = await wbx.sandboxes.list();
122
+ ```
123
+
124
+ Records returned by the API keep the API's own field names (`created_at`, `exit_code`, …), so
125
+ the [REST documentation](https://sandbox.wbx.cz/docs/api) applies to them unchanged. Options
126
+ you pass to the SDK are camelCase.
127
+
128
+ ## Commands and code
129
+
130
+ ```ts
131
+ const r = await sandbox.commands.run("pip install -q requests && python3 app.py", {
132
+ cwd: "/home/user",
133
+ env: { DEBUG: "1" },
134
+ timeoutMs: 120_000, // the command is killed after this (r.timedOut); default 60 s, 0 = no limit
135
+ stdin: "input data",
136
+ });
137
+ r.exitCode; r.stdout; r.stderr; r.durationMs; r.timedOut; r.truncated; r.ok;
138
+ r.check(); // throws CommandFailedError unless exit code 0
139
+
140
+ // live output
141
+ await sandbox.commands.run("make test", { onStdout: (d) => process.stdout.write(d) });
142
+
143
+ // events as an async iterator: start → stdout/stderr … → exit
144
+ for await (const ev of sandbox.commands.stream("pytest -q")) {
145
+ if (ev.type === "stdout") process.stdout.write(ev.data);
146
+ if (ev.type === "exit") console.log("exit code", ev.exit_code);
147
+ }
148
+
149
+ // a piece of code: python (default), node or bash
150
+ const out = await sandbox.runCode("print(sum(range(100)))");
151
+ ```
152
+
153
+ A non-zero exit code is a normal result, not an exception. Breaking out of a stream (or
154
+ aborting its signal) disconnects, which kills the command.
155
+
156
+ ## Files
157
+
158
+ ```ts
159
+ await sandbox.files.write("/home/user/data.csv", "a,b\n1,2\n"); // string, Uint8Array, Blob or ReadableStream
160
+ const bytes = await sandbox.files.read("/home/user/data.csv"); // Uint8Array
161
+ const text = await sandbox.files.readText("/home/user/data.csv");
162
+ const stream = await sandbox.files.readStream("/home/user/big.bin"); // ReadableStream<Uint8Array>
163
+
164
+ await sandbox.files.list("/home/user", { depth: 2 }); // [{ name, path, type, size, mode, mtime_ms }]
165
+ await sandbox.files.stat("/home/user/data.csv");
166
+ await sandbox.files.exists("/home/user/data.csv");
167
+ await sandbox.files.mkdir("/home/user/out");
168
+ await sandbox.files.move("/home/user/a.txt", "/home/user/b.txt", { overwrite: true });
169
+ await sandbox.files.remove("/home/user/out", { recursive: true });
170
+
171
+ for await (const ev of sandbox.files.watch("/home/user", { recursive: true })) {
172
+ console.log(ev.type, ev.path); // create, write, remove, rename, chmod
173
+ }
174
+ ```
175
+
176
+ ## Background processes
177
+
178
+ ```ts
179
+ const { pid } = await sandbox.processes.start("python3 -m http.server 8080", { tag: "web" });
180
+ for await (const ev of sandbox.processes.stream(pid)) { /* replays recent output, then live */ }
181
+ await sandbox.processes.sendStdin(pid, "quit\n", { eof: true });
182
+ await sandbox.processes.signal(pid, "SIGTERM");
183
+ await sandbox.processes.kill(pid);
184
+ await sandbox.processes.list();
185
+ ```
186
+
187
+ ## Background jobs
188
+
189
+ A job runs a command in a fresh sandbox without an open connection. Its log, result files and
190
+ execution receipt are kept after the sandbox is gone.
191
+
192
+ ```ts
193
+ const job = await wbx.jobs.create({
194
+ command: "python3 analyze.py",
195
+ template: "base",
196
+ timeoutSeconds: 3600,
197
+ saveArtifacts: true, // keep everything under output/
198
+ maxCost: "0.10", // price limit in your billing currency
199
+ retry: { maxAttempts: 2 }, // after platform errors
200
+ inputs: [{ jobId: earlier.id, name: "output/data.csv" }], // files of earlier jobs → input/
201
+ });
202
+
203
+ await job.wait({ timeoutMs: 30 * 60_000 }); // server-side waiting, no polling
204
+ const s = await job.summary(); // status, exit code, duration, cost, log tail
205
+ for await (const text of job.follow()) process.stdout.write(text); // log while it runs
206
+ const chunk = await job.logs({ offset: 0, limit: 65536 }); // { data, next_offset, complete }
207
+ const digest = await job.digest({ mode: "errors" }); // compact log for a model
208
+ const file = await job.download("output/result.json"); // SHA-256 verified (see below)
209
+ const receipt = await job.receipt();
210
+ const signed = await job.signedReceipt(); // Ed25519, after the job ended
211
+ await job.cancel();
212
+ const again = await job.retry({ env: { API_KEY: "…" } }); // env values are never stored
213
+
214
+ const later = await wbx.jobs.get(job.id);
215
+ await wbx.jobs.wait({ jobIds: [a.id, b.id], until: "any", timeoutSeconds: 30 });
216
+ ```
217
+
218
+ `download()` checks the file against the `X-WBX-SHA256` header the server sends with every
219
+ artifact and throws `IntegrityError` on a mismatch – and also when the header is missing or
220
+ malformed (e.g. stripped by a proxy), since such a file cannot be verified. `{ verify: false }`
221
+ skips the check; `downloadStream()` does not verify.
222
+
223
+ WebAssembly jobs (`runtime: "wasi"`, no network, fast start):
224
+ `wbx.jobs.create({ wasm: { module: bytes, args: ["--fast"] } })`.
225
+
226
+ ## Batches
227
+
228
+ Many jobs with a concurrency limit and a total price limit. Jobs may depend on each other and
229
+ receive each other's result files. A failed job does not stop independent ones.
230
+
231
+ ```ts
232
+ const batch = await wbx.batches.create({
233
+ defaults: { template: "base", saveArtifacts: true },
234
+ maxConcurrency: 10,
235
+ maxTotalCost: "2.00",
236
+ jobs: [
237
+ { command: "python3 prepare.py" }, // index 0
238
+ { command: "python3 train.py --part 1", dependsOn: [0], inputs: [{ fromIndex: 0, name: "output/data.csv" }] },
239
+ { command: "python3 train.py --part 2", dependsOn: [0], inputs: [{ fromIndex: 0, name: "output/data.csv" }] },
240
+ ],
241
+ });
242
+ await batch.wait();
243
+ const report = await batch.report(); // summary + one row per job
244
+ report.summary.status; // completed | partial | failed | cancelled
245
+ report.summary.usage; // CPU time, peak memory, run time, attempts (null = not measured)
246
+ report.jobs[0].cpu_ms; // per job: cpu_ms, peak_memory_mb (nullable)
247
+ await batch.reportCsv();
248
+ await batch.cancel();
249
+ ```
250
+
251
+ ## Metrics
252
+
253
+ > Needs the `metrics_history` feature on your account (`await wbx.features()`); otherwise
254
+ > `history()` and `stream()` throw `FeatureDisabledError`. `get()` always works.
255
+
256
+ ```ts
257
+ await sandbox.metrics.get(); // { cpu_count, cpu_used_pct, mem_total_mb, mem_used_mb, disk_total_mb, disk_used_mb }
258
+
259
+ const h = await sandbox.metrics.history({ since: Date.now() - 10 * 60_000 }); // samples every 10 s, last hour
260
+
261
+ const ac = new AbortController();
262
+ for await (const s of sandbox.metrics.stream({
263
+ signal: ac.signal,
264
+ reconnect: true,
265
+ onState: (st) => console.log("sandbox is", st.state), // first on connect, then on changes
266
+ })) {
267
+ console.log(s.t, s.cpu_pct, s.mem_mb, s.net_rx_bps, s.disk_write_bps);
268
+ }
269
+ ```
270
+
271
+ - `cpu_pct` is 0–100 % of all vCPUs of the sandbox together; rates ending in `_bps` are
272
+ **bytes** per second; `cpu_ms`, `*_bytes` and `*_packets` are cumulative since the sandbox
273
+ started or last woke up.
274
+ - `history()` never wakes a sleeping sandbox – it then returns `state: "sleeping"` and no samples.
275
+ - The server ends a stream after 15 minutes (`end` reason `timeout`), or when the sandbox stops
276
+ (`not_running`, `ended`). With `reconnect: true` the iterator resumes only after `timeout` or a
277
+ dropped connection, asks for the missed samples (`since`) and skips samples it already
278
+ yielded. Pass `since` to start with older samples; `onEnd` receives the reason.
279
+ - Reconnects wait with backoff and jitter. A connection that ends or breaks within 30 s of
280
+ opening counts as a failure: after `maxReconnects` (default 5) such failures in a row the
281
+ iterator throws. At most `maxConnectsPerMinute` (default 6) connections are opened in any
282
+ 60 seconds; further reconnects wait.
283
+ - Limits: `history()` 30 calls a minute per sandbox; opening a stream 10 a minute per sandbox
284
+ and 10 open streams per account – beyond that `RateLimitError` with code `rate_limited` and
285
+ `Retry-After` (history calls are retried automatically within `maxRetryDelayMs`).
286
+
287
+ ## Desktop control
288
+
289
+ > For sandboxes from the `desktop` template; needs the `desktop` feature on your account.
290
+
291
+ ```ts
292
+ const sandbox = await wbx.sandboxes.create({ template: "desktop" });
293
+ const st = await sandbox.computer.status(); // { available, width, height, controller, controller_until, viewers, … }
294
+ const shot = await sandbox.computer.screenshot({ format: "png", maxWidth: 1280 });
295
+ // { data: Uint8Array, width, height (the image), screenWidth, screenHeight (the screen = action coordinates) }
296
+
297
+ await sandbox.computer.click(640, 400);
298
+ await sandbox.computer.type("hello");
299
+ await sandbox.computer.key("ctrl+c");
300
+ await sandbox.computer.scroll(640, 400, 0, 5);
301
+ const r = await sandbox.computer.actions(
302
+ [
303
+ { type: "move", x: 10, y: 10 },
304
+ { type: "click", x: 10, y: 10, button: "right" },
305
+ { type: "mouse_down", x: 20, y: 20 }, // x and y together, or neither (press where the mouse is)
306
+ { type: "mouse_up", x: 200, y: 20 },
307
+ { type: "wait", ms: 200 },
308
+ ],
309
+ { screenshot: true, screenshotFormat: "jpeg", screenshotQuality: 70, screenshotMaxWidth: 1024 },
310
+ ); // r.screenshot.data – the screen after the actions; r.screenshotError if it could not be taken
311
+
312
+ await sandbox.computer.control("agent"); // take control back after a person released it
313
+ ```
314
+
315
+ - The server performs the actions in order and stops at the first one that fails (the ones
316
+ before it were done). It answers HTTP 200 with `ok: false`; the SDK then throws
317
+ `ComputerActionError` with `failedIndex` and `results` (one `{ type, ok, error? }` per
318
+ performed action). Pass `throwOnFailure: false` to get `{ ok: false, error, failedIndex,
319
+ results }` instead.
320
+ - The screenshot of `actions()` is taken only when every action succeeded; its options need
321
+ `screenshot: true`.
322
+ - While a person controls the desktop, actions fail with `HumanInControlError` (HTTP 409);
323
+ `controllerUntil` (and `controller_until` of the status) is Unix time in milliseconds.
324
+ `control("human")` is reserved for a person in the portal (403 `human_only` with an API key).
325
+ - Desktop actions are never retried automatically.
326
+
327
+ ## Account
328
+
329
+ ```ts
330
+ await wbx.templates.list();
331
+ await wbx.features(); // { metrics_history: boolean, desktop: boolean }
332
+ await wbx.budget.get({ days: true }); // limits, spend this month / today, per day
333
+ await wbx.budget.update({ monthly: "50", alertPct: 80 });
334
+ await wbx.compute.preferences(); // compute classes available to you, your default
335
+ await wbx.compute.setDefaultClass("balanced");
336
+ await wbx.runtimes();
337
+ await wbx.receiptKeys(); // public keys that sign receipts (no API key needed)
338
+ const secret = await wbx.webhooks.secret();
339
+
340
+ import { verifyWebhook } from "wbxsandbox";
341
+ await verifyWebhook(secret, rawBody, request.headers.get("x-wbx-signature"));
342
+ ```
343
+
344
+ Endpoints the SDK does not wrap yet: `await wbx.request("GET", "/v1/…", { query, body })` –
345
+ with the same authentication, timeouts, retries and errors.
346
+
347
+ ## Errors
348
+
349
+ Every error extends `WBXError`. HTTP errors extend `APIError` with `status`, `code` (the
350
+ machine-readable `code` of the `{"error": …, "code": …}` body, when sent), `body`, `headers` and
351
+ `retryAfter` (seconds, from `Retry-After`).
352
+
353
+ | Class | When |
354
+ | --- | --- |
355
+ | `BadRequestError` | 400 – invalid request |
356
+ | `AuthenticationError` | 401 – missing or invalid API key |
357
+ | `PaymentRequiredError` | 402 – account may not start new work (`account_suspended`) |
358
+ | `PermissionDeniedError` | 403 – the key may not do this |
359
+ | `FeatureDisabledError` | 403 `feature_disabled` – `.feature` names it |
360
+ | `NotFoundError` | 404 – sandbox, job, batch, file or process not found |
361
+ | `ConflictError` | 409 – wrong state (e.g. sandbox not running, file exists) |
362
+ | `HumanInControlError` | 409 `human_in_control` – a person controls the desktop |
363
+ | `RateLimitError` | 429 – `quota`, `queue_full`, `too_many_waiters`, `rate_limited` |
364
+ | `InternalServerError` | 5xx – including 503 when no capacity is free right now |
365
+ | `TimeoutError` | a request or a wait ran out of time |
366
+ | `ConnectionError` | the API could not be reached |
367
+ | `CommandFailedError` | `result.check()` on a failed command |
368
+ | `ComputerActionError` | a desktop action failed – `.failedIndex`, `.results` |
369
+ | `StreamLimitError` | a streamed event or NDJSON line exceeded `maxStreamEventSize` |
370
+ | `IntegrityError` | a downloaded artifact did not match its SHA-256, or had no checksum |
371
+
372
+ ```ts
373
+ import { FeatureDisabledError, RateLimitError } from "wbxsandbox";
374
+
375
+ try {
376
+ await wbx.sandboxes.create({ template: "base" });
377
+ } catch (e) {
378
+ if (e instanceof RateLimitError && e.code === "quota") console.log("stop another sandbox first");
379
+ else throw e;
380
+ }
381
+ ```
382
+
383
+ ## Timeouts and cancellation
384
+
385
+ Every method takes an options object with `signal` (an `AbortSignal`) and `timeoutMs` (one HTTP
386
+ attempt; `0` = no limit). Aborting rejects with the signal's reason (an `AbortError` by default)
387
+ and stops retries and waits at once. Defaults: 60 s per request; sandbox creation 150 s; files
388
+ 5 min; artifacts 10 min. A command's HTTP limit follows its own `timeoutMs` (+ 30 s).
389
+ For streams the limit applies until the response starts; afterwards use the signal.
390
+
391
+ ```ts
392
+ const ac = new AbortController();
393
+ setTimeout(() => ac.abort(), 5_000);
394
+ await sandbox.commands.run("sleep 60", { signal: ac.signal });
395
+ ```
396
+
397
+ `job.wait()` / `batch.wait()` take `timeoutMs` for the whole wait and throw `TimeoutError`.
398
+
399
+ ## Retries
400
+
401
+ The SDK retries only requests that cannot take effect twice:
402
+
403
+ - `GET`, `HEAD`, `DELETE`, and `PUT` with a body that can be sent again;
404
+ - `POST` that carries an idempotency key – `jobs.create`, `batches.create` and `job.retry` (the
405
+ SDK generates a key when you give none; the server returns the same job/batch for the same
406
+ key) – and requests that are idempotent by design: `sandboxes.create` **with `name`**,
407
+ `jobs.wait`, `job.cancel`, `batch.cancel`.
408
+
409
+ They are retried after connection errors, timeouts, 502, 503 and 504, and after 429 only when
410
+ the server sent `Retry-After` (a 429 without it is a hard limit such as your account quota).
411
+ The delay is exponential with jitter (0.25–0.5 s, doubling up to 8 s) or exactly `Retry-After`
412
+ – if that is longer than `maxRetryDelayMs`, the error is thrown at once. Default: 2 retries;
413
+ change with `maxRetries` on the client or per call.
414
+
415
+ Never retried: commands, unnamed sandbox creation, sleep / pause / resume / timeout, file moves
416
+ and removals, process start and input, desktop actions, uploads from a `ReadableStream`.
417
+
418
+ ## Pagination
419
+
420
+ `wbx.jobs.list()`, `wbx.batches.list()` and `batch.listJobs()` return a `Page`:
421
+
422
+ ```ts
423
+ const page = await wbx.jobs.list({ status: ["failed", "expired"], since: new Date("2026-11-01") });
424
+ page.items; // this page
425
+ page.nextCursor; // undefined on the last page
426
+ await page.getNextPage();
427
+ for await (const job of page) { /* every job of every page, fetched lazily */ }
428
+ ```
429
+
430
+ `wbx.sandboxes.list()` and `wbx.templates.list()` return everything at once (the API does not page them).
431
+
432
+ ## Runtimes
433
+
434
+ The SDK uses only Web standard APIs – `fetch`, `Request`/`Response`, `ReadableStream`,
435
+ `TextEncoder`/`TextDecoder`, `AbortController` and Web Crypto – with no `node:` imports and no
436
+ `Buffer`. It runs on Node.js ≥ 20, Deno, Bun and edge runtimes (Cloudflare Workers, Vercel
437
+ Edge). It is ESM only: all supported Node.js versions can `import` it, and Node.js ≥ 20.19 /
438
+ 22.12 can also `require()` it.
439
+
440
+ Do not ship an API key to a browser: requests from a web page should go through your own
441
+ backend.
442
+
443
+ ## Versioning and compatibility
444
+
445
+ The SDK follows [semantic versioning](https://semver.org). While it is 0.x, a **minor**
446
+ release (0.1 → 0.2) may contain breaking changes, which are listed in the
447
+ [changelog](CHANGELOG.md); patch releases (0.1.0 → 0.1.1) are always compatible. Pin
448
+ `~0.1.0` if you want only fixes. The REST API itself is versioned by its `/v1/` prefix and
449
+ changes there are additive, so an older SDK keeps working against a newer server; new record
450
+ fields appear in the `info` / `data` objects before the SDK types them. Node.js versions are
451
+ supported while they are maintained upstream.
452
+
453
+ ## Links
454
+
455
+ - Documentation: https://sandbox.wbx.cz/docs (TypeScript SDK: https://sandbox.wbx.cz/docs/sdk/typescript)
456
+ - REST API reference: https://sandbox.wbx.cz/docs/api
457
+ - Python SDK: https://pypi.org/project/wbxsandbox/
458
+ - Changelog: [CHANGELOG.md](CHANGELOG.md)
459
+ - License: [MIT](LICENSE)
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Account-level resources: templates, budget, compute classes, webhooks.
3
+ * @module
4
+ */
5
+ import type { RequestOptions, Transport } from "./http.js";
6
+ import type { Budget, ComputePreferences, Template } from "./types.js";
7
+ /** `wbx.templates` */
8
+ export declare class Templates {
9
+ private readonly t;
10
+ /** Not meant to be called directly – use the {@link WBX} client. */
11
+ constructor(t: Transport);
12
+ /** Templates you can create sandboxes from (name, default size, …). */
13
+ list(options?: RequestOptions): Promise<Template[]>;
14
+ }
15
+ /** `wbx.budget` – spending limits for jobs and batches, in your account's billing currency. */
16
+ export declare class BudgetResource {
17
+ private readonly t;
18
+ /** Not meant to be called directly – use the {@link WBX} client. */
19
+ constructor(t: Transport);
20
+ /** Limits, spend this month and today, amounts reserved by running jobs; `days: true` adds spend per day. */
21
+ get(options?: RequestOptions & {
22
+ days?: boolean;
23
+ }): Promise<Budget>;
24
+ /**
25
+ * Sets your own monthly / daily limit (`""` or `0` removes it) and the alert threshold in
26
+ * percent. Limits set by the operator still apply. Keys of connected apps may not do this.
27
+ */
28
+ update(params: {
29
+ monthly?: string | number;
30
+ daily?: string | number;
31
+ alertPct?: number;
32
+ }, options?: RequestOptions): Promise<Budget>;
33
+ }
34
+ /** `wbx.compute` – compute classes. */
35
+ export declare class Compute {
36
+ private readonly t;
37
+ /** Not meant to be called directly – use the {@link WBX} client. */
38
+ constructor(t: Transport);
39
+ /** Classes available to your account (relative price, availability) and your default class. */
40
+ preferences(options?: RequestOptions): Promise<ComputePreferences>;
41
+ /**
42
+ * Sets the default class for new sandboxes and jobs (`""` = the global default). Running
43
+ * sandboxes and accepted jobs keep their class and price.
44
+ */
45
+ setDefaultClass(name: string, options?: RequestOptions): Promise<ComputePreferences>;
46
+ }
47
+ /** `wbx.webhooks` */
48
+ export declare class Webhooks {
49
+ private readonly t;
50
+ /** Not meant to be called directly – use the {@link WBX} client. */
51
+ constructor(t: Transport);
52
+ /** The secret that signs your webhooks (`X-WBX-Signature`). */
53
+ secret(options?: RequestOptions): Promise<string>;
54
+ /** Issues a new webhook secret (the old one stops working). */
55
+ rotateSecret(options?: RequestOptions): Promise<string>;
56
+ }
57
+ /**
58
+ * Checks the `X-WBX-Signature` header (`t=<unix seconds>,v1=<hex HMAC-SHA256>`) of a webhook
59
+ * you received. `body` must be the raw request body exactly as received.
60
+ *
61
+ * ```ts
62
+ * const ok = await verifyWebhook(secret, rawBody, req.headers["x-wbx-signature"]);
63
+ * ```
64
+ */
65
+ export declare function verifyWebhook(secret: string, body: string | Uint8Array, signature: string | null | undefined, options?: {
66
+ toleranceSeconds?: number;
67
+ now?: number;
68
+ }): Promise<boolean>;
69
+ //# sourceMappingURL=account.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"account.d.ts","sourceRoot":"","sources":["../src/account.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAC3D,OAAO,KAAK,EAAE,MAAM,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAGvE,sBAAsB;AACtB,qBAAa,SAAS;IAER,OAAO,CAAC,QAAQ,CAAC,CAAC;IAD9B,oEAAoE;gBACvC,CAAC,EAAE,SAAS;IAEzC,uEAAuE;IACjE,IAAI,CAAC,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,QAAQ,EAAE,CAAC;CAG1D;AAED,+FAA+F;AAC/F,qBAAa,cAAc;IAEb,OAAO,CAAC,QAAQ,CAAC,CAAC;IAD9B,oEAAoE;gBACvC,CAAC,EAAE,SAAS;IAEzC,6GAA6G;IACvG,GAAG,CAAC,OAAO,GAAE,cAAc,GAAG;QAAE,IAAI,CAAC,EAAE,OAAO,CAAA;KAAO,GAAG,OAAO,CAAC,MAAM,CAAC;IAK7E;;;OAGG;IACG,MAAM,CAAC,MAAM,EAAE;QAAE,OAAO,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC;CAQ3I;AAED,uCAAuC;AACvC,qBAAa,OAAO;IAEN,OAAO,CAAC,QAAQ,CAAC,CAAC;IAD9B,oEAAoE;gBACvC,CAAC,EAAE,SAAS;IAEzC,+FAA+F;IACzF,WAAW,CAAC,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAIxE;;;OAGG;IACG,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,kBAAkB,CAAC;CAG3F;AAED,qBAAqB;AACrB,qBAAa,QAAQ;IAEP,OAAO,CAAC,QAAQ,CAAC,CAAC;IAD9B,oEAAoE;gBACvC,CAAC,EAAE,SAAS;IAEzC,+DAA+D;IACzD,MAAM,CAAC,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC;IAIvD,+DAA+D;IACzD,YAAY,CAAC,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC;CAG9D;AAED;;;;;;;GAOG;AACH,wBAAsB,aAAa,CACjC,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,GAAG,UAAU,EACzB,SAAS,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EACpC,OAAO,GAAE;IAAE,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,CAAA;CAAO,GACxD,OAAO,CAAC,OAAO,CAAC,CAoBlB"}