hangar-sdk
v0.1.0
Published
TypeScript SDK for hangar: create sandboxes on Firecracker dev machines, run commands, move files, pause, resume, fork and SSH in.
Maintainers
Readme
hangar-sdk
TypeScript SDK for hangar: create sandboxes on Firecracker dev machines, run commands in them, read and write files, pause and resume them, fork them and SSH in.
- Zero runtime dependencies. Uses the global
fetch(Node 18+, Bun, Deno). - ESM and CommonJS builds with type declarations.
Install
npm install hangar-sdkAuthentication
Create an API key on the API Keys page of the hangar dashboard (or hangar keys create in the CLI), then either set it in the environment:
export HANGAR_API_KEY=...
export HANGAR_API_URL=https://152.236.1.51 # optional, this is the defaultor pass it in code (options win over env vars):
const sandbox = await Sandbox.create('herdr', { apiKey: '...', apiUrl: 'https://...' })The key is sent as the X-API-Key header.
Scopes
| Scope | Allows |
| --- | --- |
| machines:read | Sandbox.list, getInfo, isRunning |
| machines:write | create, connect (resume), pause, resume, stop, fork, setTimeout, setMetadata, commands, files, sshCredentials |
| machines:delete | kill |
| images:read | create (it looks up image names), except from an im_ image ID |
:write and :delete imply :read. A full SDK key needs machines:read machines:write machines:delete images:read, which is what the dashboard's Full access and hangar keys create give by default. A call outside the key's scopes throws HangarAuthError (403 insufficient_scope).
Quickstart
import { Sandbox } from 'hangar-sdk'
const sandbox = await Sandbox.create('claude-code')
const r = await sandbox.commands.run('node -v')
console.log(r.stdout)
await sandbox.kill()Sandbox.create(template?, opts?) takes a template ID (herdr), an image name (claude-code) or an image ID (im_...). Image names resolve against your own images first, then official ones; a name that matches no image is used as a template ID. With no argument it uses the herdr template.
const sandbox = await Sandbox.create('herdr', {
name: 'my-box', // default sbx-<random>
vcpus: 4, // defaults: the template's
memMiB: 8192,
diskGiB: 20, // persistent /data disk
envs: { NODE_ENV: 'development' }, // applied to every commands.run of this object
metadata: { userId: 'u_42' }, // labels stored with the sandbox (plaintext: not for secrets)
timeoutMs: 30 * 60_000, // server pauses it 30 min from now (60 s to 24 h)
onTimeout: 'pause', // or 'kill' to delete it instead
})
console.log(sandbox.sandboxId) // m_...create waits until the machine is running.
Commands
const r = await sandbox.commands.run('npm test', {
cwd: '/data/home/app',
envs: { CI: '1' },
timeoutMs: 120_000,
onStdout: (out) => process.stdout.write(out),
onStderr: (err) => process.stderr.write(err),
})
// r: { stdout, stderr, exitCode }A non-zero exit throws CommandExitError, which carries stdout, stderr and exitCode:
import { CommandExitError } from 'hangar-sdk'
try {
await sandbox.commands.run('exit 3')
} catch (e) {
if (e instanceof CommandExitError) console.log(e.exitCode, e.stderr)
}Output is not streamed yet: onStdout and onStderr are called once with the full output after the command finishes.
background: true starts the command detached and returns { pid, kill() } right away:
const server = await sandbox.commands.run('node server.js', { background: true })
await server.kill()Files
await sandbox.files.write('/data/home/app.js', 'console.log(1)') // string or Uint8Array -> { path }
const text = await sandbox.files.read('/data/home/app.js') // string
const bytes = await sandbox.files.read('/data/home/logo.png', { format: 'bytes' })
const entries = await sandbox.files.list('/data/home') // [{ name, path, type: 'file' | 'dir' }]
await sandbox.files.exists('/data/home/app.js') // boolean
await sandbox.files.remove('/data/home/tmp') // files or directoriesFiles go over the command channel as base64, so each read or write is capped at 10 MiB. write creates parent directories and replaces the file atomically. HOME is /data/home, on the persistent disk.
Lifecycle
await sandbox.pause() // snapshot memory and suspend
await sandbox.resume() // restore the snapshot (or start a stopped machine)
const again = await Sandbox.connect(id) // attach; resumes a paused or stopped sandbox
const noWake = await Sandbox.connect(id, { resume: false })
const info = await sandbox.getInfo() // { sandboxId, templateId, imageId?, name, metadata, startedAt, endAt?, onTimeout, state, machine }
await sandbox.isRunning() // boolean
const all = await Sandbox.list() // your sandboxes, as SandboxInfo[]
const mine = await Sandbox.list({ metadata: { userId: 'u_42' } }) // all pairs must match
await sandbox.setTimeout(10 * 60_000) // pause 10 min from now; setTimeout(0) clears it
await sandbox.setTimeout(60_000, { onTimeout: 'kill' })
await sandbox.setMetadata({ userId: 'u_42', stage: 'review' }) // replaces it; {} clears
await sandbox.kill() // delete the machine and its disks; false if already gone
await Sandbox.kill(id)Every lifecycle call waits for its operation to finish (default limit 10 minutes, operationTimeoutMs to change it).
A timeout is enforced by the server: at endAt it suspends the sandbox (onTimeout: 'pause', resume it with Sandbox.connect) or deletes it ('kill'). It fires once and is then cleared, so a resumed sandbox runs without a timeout until you set one again. Without timeoutMs a sandbox runs until you pause or kill it.
Fork
const copy = await sandbox.fork({ name: 'copy' })A fork copies the root disk and /data, including credentials kept under HOME. hangar forks only stopped machines, so fork() first stops a running or paused source (its processes end, /data is kept) and leaves it stopped; call sandbox.resume() to start it again. Pass stopSource: false to fail instead.
SSH
import { readFileSync, writeFileSync, appendFileSync } from 'node:fs'
import { homedir } from 'node:os'
const pub = readFileSync(`${homedir()}/.ssh/id_ed25519.pub`, 'utf8')
const ssh = await sandbox.sshCredentials(pub, { ttlSeconds: 3600 })
// { host, port, username, certificate, knownHostsLine, expiresAt, connectionId }
writeFileSync(`${homedir()}/.ssh/id_ed25519-cert.pub`, ssh.certificate + '\n')
appendFileSync(`${homedir()}/.ssh/known_hosts`, ssh.knownHostsLine + '\n')
// ssh -p <port> <username>@<host>
console.log(`ssh -p ${ssh.port} ${ssh.username}@${ssh.host}`)The sandbox must be running. Certificates last 1 hour by default (24 hours at most) and are revoked when the sandbox stops, pauses or is deleted.
Errors
| Class | When |
| --- | --- |
| HangarError | Base class. status, code, message, requestId, retryable, operationId from the API error envelope. |
| HangarAuthError | 401 / 403: missing, invalid or revoked API key, or no access. |
| HangarQuotaError | 429 quota_exceeded, for example the machine limit. |
| HangarTimeoutError | A request or an operation took too long. |
| HangarNotSupportedError | The server does not have the feature yet (exec). |
| CommandExitError | A command exited non-zero. Carries stdout, stderr, exitCode. |
A failed operation (for example no_capacity while creating) throws HangarError with the operation's code and operationId.
Reads, and mutations (which always carry an Idempotency-Key), are retried up to 3 times with backoff on 502, 503, 504 and network errors. Commands are not retried.
Limits and what is not there yet
- 10 machines per account (forks count). Creating more throws
HangarQuotaError. - The timeout is a deadline from when it was set, not an inactivity timer.
- Command output is not streamed.
Agent skill
skills/hangar/SKILL.md teaches a coding agent to use hangar with an API key: the CLI, REST, SSH certificates and this SDK. It ships in the package: copy its skills/hangar folder into your agent's skills directory (for Claude Code, ~/.claude/skills/ or .claude/skills/ in a repo). With npm it is node_modules/hangar-sdk/skills/hangar; with any package manager, dirname $(node -p "require.resolve('hangar-sdk/package.json')")/skills/hangar.
Development
npm install
npm run build
npm test
HANGAR_LIVE=1 HANGAR_API_KEY=... npm run test:live # creates and deletes one real machine