# TypeScript SDK Classes, methods, options and defaults of the `@fdtn/sdk` package for Node.js. Times are in milliseconds. ## 1. Install Needs Node.js 22.19 or newer. `fdtn auth` saves your key. ```bash $ npm i https://compute.fdtn.dev/install/fdtn-sdk-0.1.5.tgz $ curl -fsSL https://compute.fdtn.dev/install | sh $ fdtn auth ``` The package is an ES module. Name your file `.mjs`, or set `"type": "module"` in `package.json`. The SDK reads the key from `apiKey`, then `FDTN_API_KEY`, then `~/.fdtn/key`. See [API keys](https://fdtn.dev/docs/keys.md). Never put the key in code that runs in a browser. ## 2. Create a sandbox (create.mjs): ``` import { Sandbox } from '@fdtn/sdk' const sbx = await Sandbox.create('base', { timeoutMs: 600_000, // lifetime: 10 minutes metadata: { run: 'eval-1' }, envs: { MODE: 'test' }, requestTimeoutMs: 1_800_000, // wait up to 30 minutes in the queue }) console.log(sbx.sandboxId) ``` | Option | Default | What it does | |---|---|---| | `template` | `'base'` | `base`, `small`, `claude` or your own. Sets the size. | | `timeoutMs` | `300_000` (5 minutes) | Lifetime. Maximum `86_400_000` (24 hours). | | `metadata` | `{}` | String pairs to find sandboxes. | | `envs` | `{}` | Environment variables for every command. After a resume, pass them per command (`envs` on `commands.run`). | | `allowInternetAccess` | `true` | `false` blocks outbound traffic. | | `network` | private ports | `allowPublicTraffic` (default `false`), `allowOut`, `denyOut` (address lists). | | `lifecycle` | kill on timeout | `{ onTimeout: 'pause' }` pauses when the lifetime ends. | | `requestTimeoutMs` | `60_000` | How long the SDK waits. `0`: no limit. | | `signal` | none | Cancels the call. | | `apiKey`, `domain` | see [API keys](https://fdtn.dev/docs/keys.md) | Key and service domain for this call. | Metadata: up to 64 pairs, keys 1 to 128 bytes, values up to 1024 bytes. `fdtn_` keys are reserved, except `fdtn_own_fleet_only` ([Create options](https://fdtn.dev/docs/api.md#create-options)). When machines are busy, a create waits in the queue for up to 30 minutes. For batch work, set `requestTimeoutMs: 1_800_000`. ## 3. Run commands `sbx.commands.run` waits and resolves to `stdout`, `stderr` and `exitCode`. A non-zero exit throws `CommandExitError`. ``` const result = await sbx.commands.run("python3 -c 'print(1 + 1)'") console.log(result.stdout) // "2\n" // Stream output; no time limit await sbx.commands.run('npm install', { cwd: '/app', onStdout: (d) => process.stdout.write(d), onStderr: (d) => process.stderr.write(d), timeoutMs: 0, }) // Background: resolves to a handle at once const server = await sbx.commands.run('python3 -m http.server 8000', { background: true, timeoutMs: 0 }) await server.kill() ``` | Option | Default | What it does | |---|---|---| | `background` | `false` | `true` resolves to a handle at once. | | `cwd` | user's home folder | Folder to run in. | | `user` | template's user | User, such as `'root'`. | | `envs` | `{}` | Variables for this command. | | `onStdout`, `onStderr` | none | Functions that get output as it comes. | | `stdin` | `false` | `true` keeps stdin open. | | `timeoutMs` | `60_000` | Longest run time. `0`: no limit. | A background handle has `pid`, `wait()`, `kill()`, `sendStdin(data)`, `closeStdin()`, `disconnect()`, and the output so far. By PID: `sbx.commands.list()`, `connect(pid)`, `sendStdin(pid, data)`, `closeStdin(pid)` and `kill(pid)`. ## 4. Read and write files Every method also takes `user` and `requestTimeoutMs`. To copy folders, use `fdtn cp -r` ([Files](https://fdtn.dev/docs/files.md)). ``` await sbx.files.write('/app/input.json', JSON.stringify({ n: 3 })) const bytes = await sbx.files.read('/app/model.bin', { format: 'bytes' }) await sbx.files.write([ { path: '/app/a.txt', data: 'a' }, { path: '/app/b.txt', data: 'b' }, ]) for (const e of await sbx.files.list('/app')) console.log(e.name, e.type, e.size) ``` | Method | Resolves to | What it does | |---|---|---| | `read(path, { format })` | string, `Uint8Array`, `Blob` or `ReadableStream` | `format`: `'text'` (default), `'bytes'`, `'blob'` or `'stream'`. | | `write(path, data)` | file info | Writes a string, `ArrayBuffer`, `Blob` or `ReadableStream`. Makes missing folders. | | `write([{ path, data }])` | array of info | Several files at once. | | `list(path, { depth })` | array of entries | Entries with `name`, `type`, `path`, `size` and more. `depth` defaults to 1. | | `exists(path)`, `getInfo(path)` | boolean, entry | Checks one path. | | `makeDir(path)`, `rename(oldPath, newPath)`, `remove(path)` | boolean, entry, nothing | Makes, moves or removes. `remove` also removes folder contents. | ## 5. Pause, resume and stop Pause keeps memory and files and stops the charge. `Sandbox.connect` resumes from the same point ([paused limits](https://fdtn.dev/docs/limits.md#paused)). ``` const id = sbx.sandboxId await sbx.pause() // Later, from any program with the same key: const again = await Sandbox.connect(id) // resumes it await again.kill() ``` | Method | What it does | |---|---| | `Sandbox.connect(id, { timeoutMs })` | Object for a sandbox; a paused one resumes. `timeoutMs` sets a new lifetime; a running sandbox keeps a later end time. | | `sbx.pause()` | `false` if already paused. | | `sbx.kill()` | Ends the sandbox and deletes its files. | | `sbx.setTimeout(ms)` | Time left, from now. Maximum `86_400_000`. | | `sbx.getInfo()` | `sandboxId`, `templateId`, `metadata`, `startedAt`, `endAt`, `state`, `cpuCount`, `memoryMB` and more. | | `sbx.isRunning()` | Is the sandbox up? | | `sbx.getMetrics({ start, end })` | Samples of CPU, memory and disk use. The first seconds have no samples. | | `sbx.getHost(port)` | Host name for a port ([Ports](https://fdtn.dev/docs/ports.md)). | | `sbx.createSnapshot({ name })` | Saves the sandbox as a template. Give `name`, then start from it with `Sandbox.create(name)`. Delete it with `fdtn api /templates/ -X DELETE`. | | `Sandbox.list({ query, limit, order })` | Pager with `hasNext` and `nextItems()`. Usually one page, newest first. `query` takes `metadata`, `state`, `template`, `startedAfter`. | | By ID, no object | `Sandbox.kill(id)`, `Sandbox.pause(id)`, `Sandbox.getInfo(id)`, `Sandbox.setTimeout(id, ms)`, `Sandbox.getMetrics(id)`. | ``` const pager = Sandbox.list({ query: { metadata: { run: 'eval-1' }, state: ['running', 'paused'] } }) while (pager.hasNext) { for (const s of await pager.nextItems()) console.log(s.sandboxId, s.state) } ``` ## Timeouts | Setting (ms) | Where | Default | Limit | |---|---|---|---| | Sandbox lifetime | `timeoutMs` on create, `setTimeout()` | 300_000 | 86_400_000 | | Command run time | `commands.run(cmd, { timeoutMs })` | 60_000 | `0` means no limit | | Wait for an answer | `requestTimeoutMs` on any call | 60_000 | `0` means no limit | ## Errors Import from `@fdtn/sdk` and test with `instanceof`. Status codes: [HTTP API errors](https://fdtn.dev/docs/api.md#errors). | Class | When | |---|---| | `AuthenticationError` | No key, a wrong key, or an unsafe key file. | | `CommandExitError` | Non-zero exit. Has `exitCode`, `stdout`, `stderr`. | | `TimeoutError` | A timeout passed, or the lifetime ended. | | `SandboxNotFoundError` | Unknown or ended sandbox. | | `NotFoundError`, `FileNotFoundError` | A file, folder or template is missing. | | `InvalidArgumentError` | A wrong argument. | | `NotEnoughSpaceError` | The sandbox disk is full. | | `RateLimitError` | Too many requests or queued creates. Wait, then retry. | | `ServiceBusyError` | The service is busy (503). Retry in a moment. | | `SandboxError` | Base class of most errors. `AuthenticationError` and `ServiceBusyError` are separate: catch them too. | ``` import { Sandbox, CommandExitError } from '@fdtn/sdk' try { await sbx.commands.run('exit 3') } catch (e) { if (e instanceof CommandExitError) console.log(e.exitCode, e.stderr) // 3 else throw e } ``` ## Full example Start ten sandboxes at once: (many.mjs): ``` import { Sandbox } from '@fdtn/sdk' async function one(i) { const sbx = await Sandbox.create('base', { metadata: { run: 'demo' }, requestTimeoutMs: 1_800_000 }) try { return (await sbx.commands.run(`echo ${i}`)).stdout.trim() } finally { await sbx.kill() } } console.log(await Promise.all(Array.from({ length: 10 }, (_, i) => one(i)))) ``` ## Next - [**Python SDK**: The same API for Python.](https://fdtn.dev/docs/python.md) - [**CLI reference**: The main commands and their options.](https://fdtn.dev/docs/cli.md) - [**HTTP API**: The endpoints the SDK calls.](https://fdtn.dev/docs/api.md) Source: https://fdtn.dev/docs/typescript/