Foundational Compute

TypeScript SDK

Classes, methods, options and defaults of the @fdtn/sdk package for Node.js. Times are in milliseconds.

1Install

Needs Node.js 22.19 or newer. fdtn auth saves your key.

$ 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. Never put the key in code that runs in a browser.

2Create 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)
OptionDefaultWhat it does
template'base'base, small, claude or your own. Sets the size.
timeoutMs300_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).
allowInternetAccesstruefalse blocks outbound traffic.
networkprivate portsallowPublicTraffic (default false), allowOut, denyOut (address lists).
lifecyclekill on timeout{ onTimeout: 'pause' } pauses when the lifetime ends.
requestTimeoutMs60_000How long the SDK waits. 0: no limit.
signalnoneCancels the call.
apiKey, domainsee API keysKey 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).

When machines are busy, a create waits in the queue for up to 30 minutes. For batch work, set requestTimeoutMs: 1_800_000.

3Run 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()
OptionDefaultWhat it does
backgroundfalsetrue resolves to a handle at once.
cwduser's home folderFolder to run in.
usertemplate's userUser, such as 'root'.
envs{}Variables for this command.
onStdout, onStderrnoneFunctions that get output as it comes.
stdinfalsetrue keeps stdin open.
timeoutMs60_000Longest 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).

4Read and write files

Every method also takes user and requestTimeoutMs. To copy folders, use fdtn cp -r (Files).

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)
MethodResolves toWhat it does
read(path, { format })string, Uint8Array, Blob or ReadableStreamformat: 'text' (default), 'bytes', 'blob' or 'stream'.
write(path, data)file infoWrites a string, ArrayBuffer, Blob or ReadableStream. Makes missing folders.
write([{ path, data }])array of infoSeveral files at once.
list(path, { depth })array of entriesEntries with name, type, path, size and more. depth defaults to 1.
exists(path), getInfo(path)boolean, entryChecks one path.
makeDir(path), rename(oldPath, newPath), remove(path)boolean, entry, nothingMakes, moves or removes. remove also removes folder contents.

5Pause, resume and stop

Pause keeps memory and files and stops the charge. Sandbox.connect resumes from the same point (paused limits).

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()
MethodWhat 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).
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/<name> -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 objectSandbox.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)WhereDefaultLimit
Sandbox lifetimetimeoutMs on create, setTimeout()300_00086_400_000
Command run timecommands.run(cmd, { timeoutMs })60_0000 means no limit
Wait for an answerrequestTimeoutMs on any call60_0000 means no limit

Errors

Import from @fdtn/sdk and test with instanceof. Status codes: HTTP API errors.

ClassWhen
AuthenticationErrorNo key, a wrong key, or an unsafe key file.
CommandExitErrorNon-zero exit. Has exitCode, stdout, stderr.
TimeoutErrorA timeout passed, or the lifetime ended.
SandboxNotFoundErrorUnknown or ended sandbox.
NotFoundError, FileNotFoundErrorA file, folder or template is missing.
InvalidArgumentErrorA wrong argument.
NotEnoughSpaceErrorThe sandbox disk is full.
RateLimitErrorToo many requests or queued creates. Wait, then retry.
ServiceBusyErrorThe service is busy (503). Retry in a moment.
SandboxErrorBase 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