@insforge/instabox-sdk 0.1.1 → 0.2.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.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/util.ts","../src/commands.ts","../src/files.ts","../src/http.ts","../src/sandbox.ts"],"sourcesContent":["/** Fields of the instabox API error envelope `{ error: { code, message, requestId, retryable, operationId } }`. */\nexport interface InstaboxErrorInit {\n status?: number\n code?: string\n requestId?: string\n retryable?: boolean\n operationId?: string | null\n cause?: unknown\n}\n\n/** Base class for every error this SDK throws. */\nexport class InstaboxError extends Error {\n /** HTTP status, or 0 when the error did not come from an HTTP response (for example a failed operation). */\n readonly status: number\n /** Machine-readable code from the API, e.g. `not_found`, `operation_conflict`. */\n readonly code: string\n readonly requestId?: string\n readonly retryable: boolean\n /** For `operation_conflict` the active operation, for a failed operation its ID. */\n readonly operationId?: string | null\n\n constructor(message: string, init: InstaboxErrorInit = {}) {\n super(message, init.cause === undefined ? undefined : { cause: init.cause })\n this.name = new.target.name\n this.status = init.status ?? 0\n this.code = init.code ?? 'unknown'\n this.requestId = init.requestId\n this.retryable = init.retryable ?? false\n this.operationId = init.operationId\n }\n}\n\n/** 401 / 403: missing, invalid or revoked API key, or not allowed. */\nexport class InstaboxAuthError extends InstaboxError {}\n\n/** 429 `quota_exceeded`: an account limit was reached (for example the machine limit). */\nexport class InstaboxQuotaError extends InstaboxError {}\n\n/** A request or an operation did not finish in time. */\nexport class InstaboxTimeoutError extends InstaboxError {}\n\n/** Result of a finished command. */\nexport interface CommandResult {\n stdout: string\n stderr: string\n exitCode: number\n timedOut: boolean\n truncated: boolean\n /** Error text reported by the server, if any. */\n error?: string\n}\n\n/** A command exited with a non-zero code. Carries the full result. */\nexport class CommandExitError extends InstaboxError implements CommandResult {\n readonly stdout: string\n readonly stderr: string\n readonly exitCode: number\n readonly timedOut: boolean\n readonly truncated: boolean\n readonly error?: string\n\n constructor(result: CommandResult) {\n const tail = result.stderr.trim().split('\\n').slice(-1)[0] ?? ''\n super(`command exited with code ${result.exitCode}${tail ? `: ${tail}` : ''}`, { code: 'command_exit' })\n this.stdout = result.stdout\n this.stderr = result.stderr\n this.exitCode = result.exitCode\n this.timedOut = result.timedOut\n this.truncated = result.truncated\n this.error = result.error\n }\n}\n\n/** Builds the right error class from an HTTP status and the parsed envelope. */\nexport function errorFromResponse(status: number, body: unknown, fallbackMessage: string): InstaboxError {\n const env = (body as { error?: Record<string, unknown> } | null)?.error\n const init: InstaboxErrorInit = {\n status,\n code: typeof env?.code === 'string' ? env.code : `http_${status}`,\n requestId: typeof env?.requestId === 'string' ? env.requestId : undefined,\n retryable: typeof env?.retryable === 'boolean' ? env.retryable : status >= 502 && status <= 504,\n operationId: typeof env?.operationId === 'string' ? env.operationId : null,\n }\n const message = typeof env?.message === 'string' && env.message ? env.message : fallbackMessage\n if (status === 401 || status === 403) return new InstaboxAuthError(message, init)\n if (status === 429) return new InstaboxQuotaError(message, init)\n return new InstaboxError(message, init)\n}\n","export const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))\n\n/** Random UUID v4. Uses Web Crypto when present (Node 19+, Bun, Deno, browsers). */\nexport function uuid(): string {\n const c = (globalThis as { crypto?: Crypto }).crypto\n if (c && typeof c.randomUUID === 'function') return c.randomUUID()\n const b = new Uint8Array(16)\n if (c && typeof c.getRandomValues === 'function') c.getRandomValues(b)\n else for (let i = 0; i < 16; i++) b[i] = Math.floor(Math.random() * 256)\n b[6] = (b[6]! & 0x0f) | 0x40\n b[8] = (b[8]! & 0x3f) | 0x80\n const h = Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('')\n return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`\n}\n\nexport function randomSuffix(len = 8): string {\n const alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789'\n return Array.from({ length: len }, () => alphabet[Math.floor(Math.random() * alphabet.length)]).join('')\n}\n\n/** Quotes a string for POSIX sh. */\nexport function shellQuote(s: string): string {\n return `'${s.replace(/'/g, `'\\\\''`)}'`\n}\n\nexport function bytesToBase64(bytes: Uint8Array): string {\n let bin = ''\n for (let i = 0; i < bytes.length; i += 0x8000) {\n bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000))\n }\n return btoa(bin)\n}\n\nexport function base64ToBytes(b64: string): Uint8Array {\n const bin = atob(b64.replace(/\\s+/g, ''))\n const out = new Uint8Array(bin.length)\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)\n return out\n}\n\nexport function readEnv(name: string): string | undefined {\n const g = globalThis as {\n process?: { env?: Record<string, string | undefined> }\n Deno?: { env?: { get(k: string): string | undefined } }\n }\n try {\n const v = g.process?.env?.[name] ?? g.Deno?.env?.get(name)\n return v === '' ? undefined : v\n } catch {\n return undefined // Deno without --allow-env\n }\n}\n","import { CommandExitError, InstaboxError, type CommandResult } from './errors'\nimport type { HttpClient } from './http'\nimport type { ExecResponse } from './types'\nimport { shellQuote } from './util'\n\nexport interface CommandOptions {\n /** Working directory. Default: the server's default (HOME, `/data/home`). */\n cwd?: string\n /** Extra environment variables, merged over the sandbox-level `envs` from `Sandbox.create`. */\n envs?: Record<string, string>\n /** Command timeout in ms (sent as whole seconds). Default: the server's default. */\n timeoutMs?: number\n /** Text sent to the command's standard input. */\n stdin?: string\n /**\n * Called with stdout once the command finished. Output is not streamed yet:\n * the callback receives the whole stdout in one call.\n */\n onStdout?: (data: string) => void | Promise<void>\n /** Like `onStdout`, for stderr. */\n onStderr?: (data: string) => void | Promise<void>\n /** Start the command detached (nohup) and return right away with its PID. */\n background?: boolean\n}\n\n/** A command started with `background: true`. */\nexport interface CommandHandle {\n pid: number\n /** Sends SIGTERM to the process. Returns false if it had already exited. */\n kill(): Promise<boolean>\n}\n\nexport class Commands {\n /** @internal */\n constructor(\n private readonly http: HttpClient,\n private readonly sandboxId: string,\n private readonly defaultEnvs: Record<string, string>,\n ) {}\n\n /**\n * Runs a shell command in the sandbox and waits for it to finish.\n * Throws `CommandExitError` (carrying stdout, stderr and exitCode) when it exits non-zero.\n */\n run(cmd: string, opts: CommandOptions & { background: true }): Promise<CommandHandle>\n run(cmd: string, opts?: CommandOptions & { background?: false }): Promise<CommandResult>\n run(cmd: string, opts?: CommandOptions): Promise<CommandResult | CommandHandle>\n async run(cmd: string, opts: CommandOptions = {}): Promise<CommandResult | CommandHandle> {\n if (opts.background) {\n const wrapped = `nohup sh -c ${shellQuote(cmd)} >/dev/null 2>&1 & echo $!`\n if (opts.stdin !== undefined)\n throw new InstaboxError('stdin is not supported for background commands', { code: 'bad_request' })\n const r = await this.exec(wrapped, { cwd: opts.cwd, envs: opts.envs, timeoutMs: opts.timeoutMs })\n if (r.exitCode !== 0) throw new CommandExitError(r)\n const pid = Number.parseInt(r.stdout.trim(), 10)\n if (!Number.isSafeInteger(pid) || pid <= 0)\n throw new InstaboxError('exec returned an invalid background PID', { code: 'invalid_response' })\n return {\n pid,\n kill: async () => (await this.exec(`kill ${pid}`)).exitCode === 0,\n }\n }\n const r = await this.exec(cmd, opts)\n if (opts.onStdout && r.stdout) await opts.onStdout(r.stdout)\n if (opts.onStderr && r.stderr) await opts.onStderr(r.stderr)\n if (r.exitCode !== 0) throw new CommandExitError(r)\n return r\n }\n\n /** @internal Raw exec: never throws on a non-zero exit code. */\n async exec(\n cmd: string,\n opts: Pick<CommandOptions, 'cwd' | 'envs' | 'timeoutMs' | 'stdin'> = {},\n ): Promise<CommandResult> {\n const envs = { ...this.defaultEnvs, ...opts.envs }\n const body: Record<string, unknown> = { cmd }\n if (opts.cwd !== undefined) body.cwd = opts.cwd\n if (Object.keys(envs).length) body.envs = envs\n if (opts.stdin !== undefined) body.stdin = opts.stdin\n if (opts.timeoutMs !== undefined) {\n if (!Number.isFinite(opts.timeoutMs) || opts.timeoutMs <= 0 || opts.timeoutMs > 600_000) {\n throw new InstaboxError('command timeoutMs must be greater than 0 and at most 600 000', { code: 'bad_request' })\n }\n body.timeoutSeconds = Math.ceil(opts.timeoutMs / 1000)\n }\n // Exec has no idempotency contract; a retry can run the command twice.\n const res = await this.http.request<ExecResponse>(\n 'POST',\n `/v1/machines/${encodeURIComponent(this.sandboxId)}/exec`,\n {\n body,\n retry: false,\n idempotent: false,\n timeoutMs: (Number(body.timeoutSeconds) || 60) * 1000 + 30_000,\n },\n )\n const out: CommandResult = {\n stdout: res.stdout,\n stderr: res.stderr,\n exitCode: res.exitCode,\n timedOut: res.timedOut,\n truncated: res.truncated,\n }\n if (res.error) out.error = res.error\n return out\n }\n}\n","import type { Commands } from './commands'\nimport { CommandExitError, InstaboxError, type CommandResult } from './errors'\nimport { base64ToBytes, bytesToBase64, shellQuote } from './util'\n\n/** Largest file `files.read` / `files.write` move (files go through exec as base64). */\nexport const MAX_FILE_BYTES = 10 * 1024 * 1024\n// Base64 payload plus shell quoting must fit the API's 64 KiB command limit.\nconst WRITE_CHUNK_B64 = 48 * 1024\n// Encoded chunks must fit the API's 1 MiB stdout limit.\nconst READ_CHUNK_BYTES = 512 * 1024\n\nexport interface EntryInfo {\n name: string\n path: string\n type: 'file' | 'dir'\n}\n\nexport interface WriteInfo {\n path: string\n}\n\n/**\n * File access inside the sandbox. Implemented on top of exec (base64 over the command\n * channel), capped at 10 MiB per file.\n */\nexport class Files {\n /** @internal */\n constructor(private readonly commands: Commands) {}\n\n /** Reads a file. Returns text (UTF-8) by default, or bytes with `{ format: 'bytes' }`. */\n read(path: string, opts?: { format?: 'text' }): Promise<string>\n read(path: string, opts: { format: 'bytes' }): Promise<Uint8Array>\n async read(path: string, opts: { format?: 'text' | 'bytes' } = {}): Promise<string | Uint8Array> {\n const p = shellQuote(path)\n const r = await this.commands.exec(\n `[ -f ${p} ] || { echo \"no such file: \"${p} >&2; exit 3; }; ` +\n `s=$(wc -c < ${p}) || exit 1; [ \"$s\" -le ${MAX_FILE_BYTES} ] || { echo \"file too large: $s bytes\" >&2; exit 4; }; ` +\n `printf '%s' \"$s\"`,\n )\n if (r.exitCode === 3) throw new InstaboxError(`file not found: ${path}`, { status: 404, code: 'not_found' })\n if (r.exitCode === 4) {\n throw new InstaboxError(`${path} is larger than the ${MAX_FILE_BYTES}-byte limit of files.read`, {\n code: 'file_too_large',\n })\n }\n ensureComplete(r)\n const size = Number(r.stdout.trim())\n if (!Number.isSafeInteger(size) || size < 0 || size > MAX_FILE_BYTES) {\n throw new InstaboxError('invalid file size returned by exec', { code: 'invalid_response' })\n }\n const bytes = new Uint8Array(size)\n for (let offset = 0; offset < size; offset += READ_CHUNK_BYTES) {\n const chunk = await this.commands.exec(\n `dd if=${p} bs=${READ_CHUNK_BYTES} skip=${offset / READ_CHUNK_BYTES} count=1 2>/dev/null | base64 | tr -d '\\\\n'`,\n )\n ensureComplete(chunk)\n const data = base64ToBytes(chunk.stdout)\n if (data.length !== Math.min(READ_CHUNK_BYTES, size - offset)) {\n throw new InstaboxError(`file size changed while reading: ${path}`, { code: 'file_changed' })\n }\n bytes.set(data, offset)\n }\n return opts.format === 'bytes' ? bytes : new TextDecoder().decode(bytes)\n }\n\n /** Writes a file, creating parent directories. Replaces the file atomically (temp file + rename). */\n async write(path: string, data: string | Uint8Array): Promise<WriteInfo> {\n const bytes = typeof data === 'string' ? new TextEncoder().encode(data) : data\n if (bytes.length > MAX_FILE_BYTES) {\n throw new InstaboxError(`data is larger than the ${MAX_FILE_BYTES}-byte limit of files.write`, {\n code: 'file_too_large',\n })\n }\n const p = shellQuote(path)\n const tmp = shellQuote(`${path}.instabox-${Math.random().toString(36).slice(2, 10)}.tmp`)\n const b64 = bytesToBase64(bytes)\n const chunks: string[] = []\n for (let i = 0; i < b64.length; i += WRITE_CHUNK_B64) chunks.push(b64.slice(i, i + WRITE_CHUNK_B64))\n if (chunks.length === 0) chunks.push('')\n try {\n for (let i = 0; i < chunks.length; i++) {\n const redirect = i === 0 ? '>' : '>>'\n const prefix = i === 0 ? `mkdir -p \"$(dirname ${p})\" && ` : ''\n const r = await this.commands.exec(`${prefix}printf '%s' '${chunks[i]}' | base64 -d ${redirect} ${tmp}`)\n if (r.exitCode !== 0) throw new CommandExitError(r)\n }\n const r = await this.commands.exec(`mv -f ${tmp} ${p}`)\n if (r.exitCode !== 0) throw new CommandExitError(r)\n } catch (err) {\n await this.commands.exec(`rm -f ${tmp}`).catch(() => {})\n throw err\n }\n return { path }\n }\n\n /** Lists the entries of a directory (not recursive). */\n async list(path: string): Promise<EntryInfo[]> {\n const p = shellQuote(path)\n const r = await this.commands.exec(\n `[ -d ${p} ] || { echo \"no such directory: \"${p} >&2; exit 3; }; ` +\n `cd ${p} && for f in .* *; do case \"$f\" in .|..) continue ;; esac; [ -e \"$f\" ] || [ -L \"$f\" ] || continue; ` +\n `if [ -d \"$f\" ]; then printf 'd\\\\t%s\\\\0' \"$f\"; else printf 'f\\\\t%s\\\\0' \"$f\"; fi; done`,\n )\n if (r.exitCode === 3) throw new InstaboxError(`directory not found: ${path}`, { status: 404, code: 'not_found' })\n ensureComplete(r)\n const base = path.endsWith('/') ? path.slice(0, -1) : path\n return r.stdout\n .split('\\0')\n .filter(Boolean)\n .map((line) => {\n const tab = line.indexOf('\\t')\n const name = line.slice(tab + 1)\n return { name, path: `${base}/${name}`, type: line.slice(0, tab) === 'd' ? 'dir' : 'file' } as EntryInfo\n })\n }\n\n /** Removes a file or a directory (recursively). Missing paths are fine. */\n async remove(path: string): Promise<void> {\n const r = await this.commands.exec(`rm -rf -- ${shellQuote(path)}`)\n if (r.exitCode !== 0) throw new CommandExitError(r)\n }\n\n /** True if a file or directory exists at `path`. */\n async exists(path: string): Promise<boolean> {\n const r = await this.commands.exec(`test -e ${shellQuote(path)}`)\n return r.exitCode === 0\n }\n}\n\nfunction ensureComplete(result: CommandResult): void {\n if (result.exitCode !== 0) throw new CommandExitError(result)\n if (result.truncated) throw new InstaboxError('file command output was truncated', { code: 'output_truncated' })\n}\n","import { InstaboxError, InstaboxTimeoutError, errorFromResponse } from './errors'\nimport type { Operation } from './types'\nimport { readEnv, sleep, uuid } from './util'\n\nexport const DEFAULT_API_URL = 'https://api.box.instacloud.com'\n\n/** Options shared by every call that talks to the API. */\nexport interface ConnectionOptions {\n /** API key from the instabox dashboard's API Keys page. Default: env `INSTABOX_API_KEY`. */\n apiKey?: string\n /** API base URL. Default: env `INSTABOX_API_URL`, else `https://api.box.instacloud.com`. */\n apiUrl?: string\n /** Timeout of a single HTTP request in ms. Default 60 000; exec defaults to its command timeout plus 30 000. */\n requestTimeoutMs?: number\n /** Max time to wait for a lifecycle operation (create, pause, resume, fork, kill) in ms. Default 600 000. */\n operationTimeoutMs?: number\n /** Custom fetch implementation (tests, proxies). Default: global `fetch`. */\n fetch?: typeof fetch\n /** Advanced: first delay of operation polling in ms (grows 1.5x to 1 s). Default 250. */\n pollIntervalMs?: number\n /** Advanced: first delay between retries in ms. Default 250. */\n retryDelayMs?: number\n}\n\ninterface RequestOptions {\n timeoutMs?: number\n body?: unknown\n query?: Record<string, string | number | string[] | undefined>\n /** Retry on 502/503/504 and network errors. Default: true for GET and for requests carrying an Idempotency-Key. */\n retry?: boolean\n /** Send an Idempotency-Key. Default: true for every method other than GET/HEAD. */\n idempotent?: boolean\n}\n\nconst MAX_RETRIES = 3\n\nexport class HttpClient {\n readonly apiUrl: string\n readonly operationTimeoutMs: number\n private readonly apiKey: string\n private readonly requestTimeoutMs?: number\n private readonly fetchImpl: typeof fetch\n private readonly pollIntervalMs: number\n private readonly retryDelayMs: number\n\n constructor(opts: ConnectionOptions = {}) {\n const apiKey = opts.apiKey ?? readEnv('INSTABOX_API_KEY')\n if (!apiKey) {\n throw new InstaboxError(\n 'No instabox API key. Set the INSTABOX_API_KEY environment variable or pass { apiKey } (create one on the API Keys page of the instabox dashboard).',\n { code: 'missing_api_key' },\n )\n }\n this.apiKey = apiKey\n this.apiUrl = (opts.apiUrl ?? readEnv('INSTABOX_API_URL') ?? DEFAULT_API_URL).replace(/\\/+$/, '')\n this.requestTimeoutMs = opts.requestTimeoutMs\n this.operationTimeoutMs = opts.operationTimeoutMs ?? 600_000\n const f = opts.fetch ?? (globalThis as { fetch?: typeof fetch }).fetch\n if (!f) throw new InstaboxError('No global fetch found; use Node 18+ or pass { fetch }.', { code: 'no_fetch' })\n this.fetchImpl = f\n this.pollIntervalMs = opts.pollIntervalMs ?? 250\n this.retryDelayMs = opts.retryDelayMs ?? 250\n }\n\n async request<T>(method: string, path: string, opts: RequestOptions = {}): Promise<T> {\n const res = await this.send(method, path, opts)\n if (res.status === 204) return undefined as T\n return (await res.json()) as T\n }\n\n /** Performs the request with retries; returns a 2xx response or throws an InstaboxError. */\n async send(method: string, path: string, opts: RequestOptions = {}): Promise<Response> {\n const isRead = method === 'GET' || method === 'HEAD'\n const idempotent = opts.idempotent ?? !isRead\n const retry = opts.retry ?? (isRead || idempotent)\n const headers: Record<string, string> = {\n 'X-API-Key': this.apiKey,\n Accept: 'application/json',\n }\n // One key per intended action, reused by every retry so the server dedupes them.\n if (idempotent) headers['Idempotency-Key'] = uuid()\n let body: string | undefined\n if (opts.body !== undefined) {\n headers['Content-Type'] = 'application/json'\n body = JSON.stringify(opts.body)\n }\n let url = this.apiUrl + path\n if (opts.query) {\n const q = new URLSearchParams()\n for (const [k, v] of Object.entries(opts.query)) {\n if (Array.isArray(v)) for (const item of v) q.append(k, item)\n else if (v !== undefined) q.set(k, String(v))\n }\n const s = q.toString()\n if (s) url += `?${s}`\n }\n\n for (let attempt = 0; ; attempt++) {\n const canRetry = retry && attempt < MAX_RETRIES\n const ctrl = new AbortController()\n let timedOut = false\n const timeoutMs = this.requestTimeoutMs ?? opts.timeoutMs ?? 60_000\n const timer = setTimeout(() => {\n timedOut = true\n ctrl.abort()\n }, timeoutMs)\n let res: Response\n try {\n res = await this.fetchImpl(url, { method, headers, body, signal: ctrl.signal })\n } catch (err) {\n clearTimeout(timer)\n if (canRetry) {\n await sleep(this.backoff(attempt))\n continue\n }\n if (timedOut) {\n throw new InstaboxTimeoutError(`${method} ${path} timed out after ${timeoutMs} ms`, {\n code: 'request_timeout',\n cause: err,\n })\n }\n throw new InstaboxError(`${method} ${path} failed: ${(err as Error)?.message ?? String(err)}`, {\n code: 'network_error',\n retryable: true,\n cause: err,\n })\n }\n clearTimeout(timer)\n if (res.ok) return res\n if (canRetry && res.status >= 502 && res.status <= 504) {\n void res.body?.cancel().catch(() => {})\n await sleep(this.backoff(attempt))\n continue\n }\n const text = await res.text().catch(() => '')\n let parsed: unknown = null\n try {\n parsed = text ? JSON.parse(text) : null\n } catch {\n parsed = null\n }\n throw errorFromResponse(res.status, parsed, `${method} ${path} returned ${res.status}`)\n }\n }\n\n private backoff(attempt: number): number {\n return this.retryDelayMs * 2 ** attempt\n }\n\n /** Polls an operation until it is `succeeded` (returns it) or `failed` (throws). */\n async waitForOperation(op: Operation, timeoutMs = this.operationTimeoutMs): Promise<Operation> {\n const deadline = Date.now() + timeoutMs\n let delay = this.pollIntervalMs\n let cur = op\n while (cur.state !== 'succeeded') {\n if (cur.state === 'failed') {\n const e = cur.error\n throw new InstaboxError(e?.message || `operation ${cur.id} (${cur.type}) failed`, {\n code: e?.code ?? 'operation_failed',\n requestId: e?.requestId,\n retryable: e?.retryable ?? false,\n operationId: cur.id,\n })\n }\n if (Date.now() + delay > deadline) {\n throw new InstaboxTimeoutError(\n `operation ${cur.id} (${cur.type}) did not finish within ${timeoutMs} ms (state ${cur.state}${cur.phase ? `, phase ${cur.phase}` : ''})`,\n { code: 'operation_timeout', operationId: cur.id },\n )\n }\n await sleep(delay)\n delay = Math.min(Math.round(delay * 1.5), Math.max(1_000, this.pollIntervalMs))\n cur = await this.request<Operation>('GET', `/v1/operations/${encodeURIComponent(cur.id)}`)\n }\n return cur\n }\n}\n","import { Commands } from './commands'\nimport { InstaboxError } from './errors'\nimport { Files } from './files'\nimport { type ConnectionOptions, HttpClient } from './http'\nimport type {\n Connection,\n Machine,\n MachineList,\n MachineState,\n OnTimeout,\n Operation,\n Snapshot,\n SnapshotList,\n Template,\n} from './types'\nimport { randomSuffix } from './util'\n\nexport const DEFAULT_TEMPLATE = 'universal'\n\nexport interface SandboxOpts extends ConnectionOptions {\n /** Machine name. Default `sbx-<random>`. */\n name?: string\n /** String labels stored with the sandbox; filter on them with `Sandbox.list({ metadata })`. */\n metadata?: Record<string, string>\n /** Environment variables applied to every `commands.run` of this Sandbox object (client-side). */\n envs?: Record<string, string>\n /**\n * The server pauses (or with `onTimeout: 'kill'` deletes) the sandbox this long after creation.\n * Sent as whole seconds, 60 s to 24 h. Default: no timeout. Change it with `setTimeout()`.\n */\n timeoutMs?: number\n /** What happens at the timeout: `pause` (default) or `kill`. */\n onTimeout?: OnTimeout\n /** Stop and archive after this many milliseconds, independent of the pause/kill timeout. */\n archiveMs?: number\n /** vCPUs. Default: the template's. */\n vcpus?: number\n /** Memory in MiB. Default: the template's. */\n memMiB?: number\n /** Size of the persistent `/data` disk in GiB. Default: the template's. */\n diskGiB?: number\n /** Root disk size in GiB; may only grow. */\n rootDiskGiB?: number\n}\n\nexport interface SandboxConnectOpts extends ConnectionOptions {\n /** Resume the sandbox if it is paused (suspended) or stopped. Default true. */\n resume?: boolean\n envs?: Record<string, string>\n}\n\nexport interface SandboxListOpts extends ConnectionOptions {\n /** Only sandboxes whose metadata has every one of these key/value pairs. */\n metadata?: Record<string, string>\n}\n\nexport interface SandboxInfo {\n sandboxId: string\n /** Template the sandbox runs (`template.id`). */\n templateId: string\n /** Snapshot the sandbox was created from, if any. */\n snapshotId?: string\n name: string\n /** String labels stored with the sandbox. */\n metadata: Record<string, string>\n /** Creation time of the machine. */\n startedAt: Date\n /** When the server pauses or kills the sandbox (see `onTimeout`); undefined for no timeout. */\n endAt?: Date\n archiveAt?: Date\n onTimeout: OnTimeout\n state: MachineState\n /** The raw machine object from the API. */\n machine: Machine\n}\n\nexport interface ForkOpts {\n /** Name of the new sandbox. Default `<name>-fork-<random>`. */\n name?: string\n vcpus?: number\n memMiB?: number\n /** May only grow. */\n diskGiB?: number\n /** Root disk size in GiB; may only grow. */\n rootDiskGiB?: number\n /** Timeout of the copy, as in `SandboxOpts.timeoutMs`. Default: none (the source's is not copied). */\n timeoutMs?: number\n onTimeout?: OnTimeout\n /** Metadata of the copy. Default: the source's; `{}` for none. */\n metadata?: Record<string, string>\n /**\n * A fork needs a stopped source. When true (default), `fork()` stops the source first if needed\n * (running processes end, `/data` is kept) and leaves it stopped; call `resume()` to start it again.\n * When false, a source that is not stopped makes the call fail.\n */\n stopSource?: boolean\n}\n\nexport interface CreateSnapshotOpts {\n name: string\n description?: string\n /** Save only the root disk; omit the persistent /data disk. */\n rootOnly?: boolean\n}\n\nexport interface SshCredentials {\n host: string\n port: number\n /** The machine ID. */\n username: string\n /** OpenSSH user certificate for `publicKey`, in authorized_keys format. Save it as `<key>-cert.pub`. */\n certificate: string\n /** Line for known_hosts that trusts the instabox gateway: `@cert-authority [host]:port <ca key>`. */\n knownHostsLine: string\n expiresAt: Date\n connectionId: string\n}\n\nfunction toInfo(m: Machine): SandboxInfo {\n const info: SandboxInfo = {\n sandboxId: m.id,\n templateId: m.template?.id,\n name: m.name,\n metadata: { ...m.metadata },\n startedAt: new Date(m.createdAt),\n onTimeout: m.onTimeout ?? 'pause',\n state: m.state,\n machine: m,\n }\n if (m.snapshot?.id) info.snapshotId = m.snapshot.id\n if (m.timeoutAt) info.endAt = new Date(m.timeoutAt)\n if (m.archiveAt) info.archiveAt = new Date(m.archiveAt)\n return info\n}\n\n/** Milliseconds to the API's whole seconds (rounded up), checked against the server's 60 s to 24 h range. */\nfunction toSeconds(ms: number, field = 'timeoutMs'): number {\n const s = Math.ceil(ms / 1000)\n if (!Number.isFinite(ms) || s < 60 || s > 86_400) {\n throw new InstaboxError(`${field} must be between 60 000 (60 s) and 86 400 000 (24 h); got ${ms}`, {\n code: 'bad_request',\n })\n }\n return s\n}\n\n/** Metadata keys the server accepts; checked before a list filter, where a bad key would silently match nothing. */\nconst METADATA_KEY = /^[A-Za-z0-9_.-]{1,64}$/\n\nconst enc = encodeURIComponent\n\n/** A instabox dev machine. Create one with `Sandbox.create()` or attach with `Sandbox.connect(id)`. */\nexport class Sandbox {\n /** The machine ID (`m_...`). */\n readonly sandboxId: string\n /** Run shell commands. Needs a instabox server with the exec endpoint. */\n readonly commands: Commands\n /** Read and write files. Needs a instabox server with the exec endpoint. */\n readonly files: Files\n private machine: Machine\n\n private constructor(\n private readonly http: HttpClient,\n machine: Machine,\n opts: { envs?: Record<string, string> } = {},\n ) {\n this.sandboxId = machine.id\n this.machine = machine\n this.commands = new Commands(http, machine.id, { ...opts.envs })\n this.files = new Files(this.commands)\n }\n\n /**\n * Creates a sandbox and waits until it is running.\n * `template` is a template ID, a private snapshot name or a snapshot ID (`sn_...`).\n * Template IDs take precedence over snapshot names. Default template: `universal`.\n */\n static async create(opts?: SandboxOpts): Promise<Sandbox>\n static async create(template: string, opts?: SandboxOpts): Promise<Sandbox>\n static async create(a?: string | SandboxOpts, b?: SandboxOpts): Promise<Sandbox> {\n const template = typeof a === 'string' ? a : DEFAULT_TEMPLATE\n const opts = (typeof a === 'string' ? b : a) ?? {}\n const http = new HttpClient(opts)\n const body: Record<string, unknown> = { name: opts.name ?? `sbx-${randomSuffix()}` }\n if (opts.timeoutMs !== undefined) body.timeoutSeconds = toSeconds(opts.timeoutMs)\n if (opts.archiveMs !== undefined) body.archiveSeconds = toSeconds(opts.archiveMs, 'archiveMs')\n Object.assign(body, await resolveSource(http, template))\n if (opts.vcpus !== undefined) body.vcpus = opts.vcpus\n if (opts.memMiB !== undefined) body.memMiB = opts.memMiB\n if (opts.diskGiB !== undefined) body.persistentDiskGiB = opts.diskGiB\n if (opts.rootDiskGiB !== undefined) body.rootDiskGiB = opts.rootDiskGiB\n if (opts.onTimeout) body.onTimeout = opts.onTimeout\n if (opts.metadata) body.metadata = opts.metadata\n const op = await http.request<Operation>('POST', '/v1/machines', { body })\n const done = await http.waitForOperation(op)\n const machine = await getMachine(http, done.machineId)\n return new Sandbox(http, machine, opts)\n }\n\n /** Attaches to an existing sandbox. Resumes it if it is paused or stopped, unless `resume: false`. */\n static async connect(sandboxId: string, opts: SandboxConnectOpts = {}): Promise<Sandbox> {\n const http = new HttpClient(opts)\n const sbx = new Sandbox(http, await getMachine(http, sandboxId), opts)\n await sbx.settle(false)\n if (opts.resume !== false) await sbx.wake()\n return sbx\n }\n\n /** Lists your sandboxes (all pages), optionally only those matching `metadata`. */\n static async list(opts: SandboxListOpts = {}): Promise<SandboxInfo[]> {\n const http = new HttpClient(opts)\n const metadata = Object.entries(opts.metadata ?? {}).map(([k, v]) => {\n if (!METADATA_KEY.test(k))\n throw new InstaboxError(`invalid metadata key ${JSON.stringify(k)}: use 1-64 of [A-Za-z0-9_.-]`, {\n code: 'bad_request',\n })\n return `${k}:${v}`\n })\n const out: SandboxInfo[] = []\n let cursor: string | undefined\n do {\n const page = await http.request<MachineList>('GET', '/v1/machines', { query: { cursor, limit: 100, metadata } })\n out.push(...page.machines.map((m) => toInfo(m)))\n cursor = page.nextCursor ?? undefined\n } while (cursor)\n return out\n }\n\n /** Deletes a sandbox and its disks. Returns false if it did not exist. */\n static async kill(sandboxId: string, opts: ConnectionOptions = {}): Promise<boolean> {\n return killMachine(new HttpClient(opts), sandboxId)\n }\n\n /** Lists the caller's private snapshots. Requires images:read. */\n static async listSnapshots(opts: ConnectionOptions = {}): Promise<Snapshot[]> {\n const result = await new HttpClient(opts).request<SnapshotList>('GET', '/v1/snapshots')\n return result.snapshots\n }\n\n /** Fetches a snapshot by ID. Requires images:read. */\n static async getSnapshot(snapshotId: string, opts: ConnectionOptions = {}): Promise<Snapshot> {\n return new HttpClient(opts).request<Snapshot>('GET', `/v1/snapshots/${enc(snapshotId)}`)\n }\n\n /** Deletes a snapshot. Returns false if absent. Requires images:delete. */\n static async deleteSnapshot(snapshotId: string, opts: ConnectionOptions = {}): Promise<boolean> {\n try {\n await new HttpClient(opts).request<void>('DELETE', `/v1/snapshots/${enc(snapshotId)}`)\n return true\n } catch (err) {\n if (err instanceof InstaboxError && err.status === 404 && err.code === 'not_found') return false\n throw err\n }\n }\n\n /** Saves a stopped sandbox's disks as a private snapshot. Requires images:write. */\n async createSnapshot(opts: CreateSnapshotOpts): Promise<Snapshot> {\n return this.http.request<Snapshot>('POST', `/v1/machines/${enc(this.sandboxId)}/snapshots`, { body: opts })\n }\n\n /** Fetches the current state of the sandbox. */\n async getInfo(): Promise<SandboxInfo> {\n this.machine = await getMachine(this.http, this.sandboxId)\n return toInfo(this.machine)\n }\n\n /**\n * Sets the timeout to `timeoutMs` from now (whole seconds, 60 s to 24 h); 0 clears it.\n * `onTimeout` changes what happens then (`pause` or `kill`).\n */\n async setTimeout(timeoutMs: number, opts: { onTimeout?: OnTimeout } = {}): Promise<void> {\n const body: Record<string, unknown> = { timeoutSeconds: timeoutMs === 0 ? 0 : toSeconds(timeoutMs) }\n if (opts.onTimeout) body.onTimeout = opts.onTimeout\n this.machine = await this.http.request<Machine>('PATCH', `/v1/machines/${enc(this.sandboxId)}`, { body })\n }\n\n /** Replaces the sandbox's metadata (`{}` clears it). */\n async setMetadata(metadata: Record<string, string>): Promise<void> {\n this.machine = await this.http.request<Machine>('PATCH', `/v1/machines/${enc(this.sandboxId)}`, {\n body: { metadata },\n })\n }\n\n /** True if the sandbox is running (fetches fresh state). */\n async isRunning(): Promise<boolean> {\n return (await this.getInfo()).state === 'running'\n }\n\n /** Snapshots memory and stops the sandbox (suspend). `resume()` or `Sandbox.connect()` brings it back. */\n async pause(): Promise<void> {\n await this.mutate('POST', 'suspend')\n }\n\n /** Resumes a paused sandbox from its snapshot, or starts a stopped one. */\n async resume(): Promise<void> {\n await this.settle()\n await this.wake()\n }\n\n /** Resumes or starts based on the cached state; callers make sure the cache is fresh. */\n private async wake(): Promise<void> {\n if (this.machine.state === 'suspended') await this.mutate('POST', 'resume')\n else if (this.machine.state === 'stopped') await this.mutate('POST', 'start')\n }\n\n /** Stops the sandbox (guest shutdown; processes end, `/data` is kept). */\n async stop(): Promise<void> {\n await this.settle()\n if (this.machine.state === 'suspended') await this.mutate('POST', 'start')\n await this.mutate('POST', 'stop')\n }\n\n /** Copies this sandbox (root disk and `/data`) into a new sandbox and waits until it runs. */\n async fork(opts: ForkOpts = {}): Promise<Sandbox> {\n if (opts.timeoutMs !== undefined) toSeconds(opts.timeoutMs)\n await this.settle()\n if (this.machine.state !== 'stopped') {\n if (opts.stopSource === false) {\n throw new InstaboxError(`fork needs a stopped sandbox; ${this.sandboxId} is ${this.machine.state}`, {\n code: 'operation_conflict',\n })\n }\n await this.stop()\n }\n const body: Record<string, unknown> = { name: opts.name ?? `${this.machine.name}-fork-${randomSuffix(4)}` }\n if (opts.vcpus !== undefined) body.vcpus = opts.vcpus\n if (opts.memMiB !== undefined) body.memMiB = opts.memMiB\n if (opts.diskGiB !== undefined) body.persistentDiskGiB = opts.diskGiB\n if (opts.rootDiskGiB !== undefined) body.rootDiskGiB = opts.rootDiskGiB\n if (opts.timeoutMs !== undefined) body.timeoutSeconds = toSeconds(opts.timeoutMs)\n if (opts.onTimeout) body.onTimeout = opts.onTimeout\n if (opts.metadata) body.metadata = opts.metadata\n const op = await this.http.request<Operation>('POST', `/v1/machines/${enc(this.sandboxId)}/fork`, { body })\n const done = await this.http.waitForOperation(op)\n return new Sandbox(this.http, await getMachine(this.http, done.machineId))\n }\n\n /** Deletes the sandbox and its disks. Returns false if it was already gone. */\n async kill(): Promise<boolean> {\n return killMachine(this.http, this.sandboxId)\n }\n\n /**\n * Issues a short-lived SSH certificate for `publicKey` (authorized_keys format).\n * Connect with `ssh -p <port> -o CertificateFile=<cert> -i <key> <username>@<host>` after adding\n * `knownHostsLine` to known_hosts. The sandbox must be running.\n */\n async sshCredentials(publicKey: string, opts: { ttlSeconds?: number } = {}): Promise<SshCredentials> {\n const body: Record<string, unknown> = { publicKey: publicKey.trim() }\n if (opts.ttlSeconds) body.ttlSeconds = opts.ttlSeconds\n const c = await this.http.request<Connection>('POST', `/v1/machines/${enc(this.sandboxId)}/connections`, { body })\n return {\n host: c.host,\n port: c.port,\n username: c.username,\n certificate: c.certificate,\n knownHostsLine: `@cert-authority [${c.host}]:${c.port} ${c.hostTrust.publicKey}`,\n expiresAt: new Date(c.expiresAt),\n connectionId: c.id,\n }\n }\n\n /**\n * Re-reads the machine from the server (other handles or the dashboard may have changed it),\n * waits for its active operation if one is running, and leaves the fresh state cached.\n * Every state-dependent method calls this first, so it never decides from a stale cache.\n */\n private async settle(refresh = true): Promise<void> {\n if (refresh) this.machine = await getMachine(this.http, this.sandboxId)\n if (this.machine.operationId) {\n const op = await this.http.request<Operation>('GET', `/v1/operations/${enc(this.machine.operationId)}`)\n await this.http.waitForOperation(op).catch(() => {})\n this.machine = await getMachine(this.http, this.sandboxId)\n }\n }\n\n private async mutate(method: string, action: string): Promise<void> {\n const op = await this.http.request<Operation>(method, `/v1/machines/${enc(this.sandboxId)}/${action}`)\n await this.http.waitForOperation(op)\n this.machine = await getMachine(this.http, this.sandboxId)\n }\n}\n\nasync function getMachine(http: HttpClient, id: string): Promise<Machine> {\n return http.request<Machine>('GET', `/v1/machines/${enc(id)}`)\n}\n\nasync function killMachine(http: HttpClient, id: string): Promise<boolean> {\n try {\n const op = await http.request<Operation>('DELETE', `/v1/machines/${enc(id)}`)\n await http.waitForOperation(op)\n return true\n } catch (err) {\n if (err instanceof InstaboxError && err.status === 404 && err.code === 'not_found') return false\n throw err\n }\n}\n\nasync function resolveSource(http: HttpClient, ref: string): Promise<{ templateId: string } | { snapshotId: string }> {\n if (/^sn_[a-z2-7]{26}$/.test(ref)) return { snapshotId: ref }\n const { templates } = await http.request<{ templates: Template[] }>('GET', '/v1/templates')\n if (templates.some((template) => template.id === ref)) return { templateId: ref }\n const { snapshots } = await http.request<SnapshotList>('GET', '/v1/snapshots')\n const matches = snapshots.filter((snapshot) => snapshot.name === ref)\n if (matches.length > 1) {\n throw new InstaboxError(`multiple snapshots named ${ref}; use a snapshot ID`, { code: 'ambiguous_snapshot' })\n }\n if (matches[0]) return { snapshotId: matches[0].id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EAAE;AAC9B,WAAO;AAAA,EACT,SAAS,KAAK;AACZ,QAAI,eAAe,iBAAiB,IAAI,WAAW,OAAO,IAAI,SAAS,YAAa,QAAO;AAC3F,UAAM;AAAA,EACR;AACF;AAEA,eAAe,cAAc,MAAkB,KAAuE;AACpH,MAAI,oBAAoB,KAAK,GAAG,EAAG,QAAO,EAAE,YAAY,IAAI;AAC5D,QAAM,EAAE,UAAU,IAAI,MAAM,KAAK,QAAmC,OAAO,eAAe;AAC1F,MAAI,UAAU,KAAK,CAAC,aAAa,SAAS,OAAO,GAAG,EAAG,QAAO,EAAE,YAAY,IAAI;AAChF,QAAM,EAAE,UAAU,IAAI,MAAM,KAAK,QAAsB,OAAO,eAAe;AAC7E,QAAM,UAAU,UAAU,OAAO,CAAC,aAAa,SAAS,SAAS,GAAG;AACpE,MAAI,QAAQ,SAAS,GAAG;AACtB,UAAM,IAAI,cAAc,4BAA4B,GAAG,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAAA,EAC9G;AACA,MAAI,QAAQ,CAAC,EAAG,QAAO,EAAE,YAAY,QAAQ,CAAC,EAAE,GAAG;AACnD,QAAM,IAAI,cAAc,mCAAmC,GAAG,IAAI,EAAE,QAAQ,KAAK,MAAM,YAAY,CAAC;AACtG;","names":["r","r"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/util.ts","../src/commands.ts","../src/files.ts","../src/http.ts","../src/sandbox.ts"],"sourcesContent":["/** Fields of the instabox API error envelope `{ error: { code, message, requestId, retryable, operationId } }`. */\nexport interface InstaboxErrorInit {\n status?: number\n code?: string\n requestId?: string\n retryable?: boolean\n operationId?: string | null\n cause?: unknown\n}\n\n/** Base class for every error this SDK throws. */\nexport class InstaboxError extends Error {\n /** HTTP status, or 0 when the error did not come from an HTTP response (for example a failed operation). */\n readonly status: number\n /** Machine-readable code from the API, e.g. `not_found`, `operation_conflict`. */\n readonly code: string\n readonly requestId?: string\n readonly retryable: boolean\n /** For `operation_conflict` the active operation, for a failed operation its ID. */\n readonly operationId?: string | null\n\n constructor(message: string, init: InstaboxErrorInit = {}) {\n super(message, init.cause === undefined ? undefined : { cause: init.cause })\n this.name = new.target.name\n this.status = init.status ?? 0\n this.code = init.code ?? 'unknown'\n this.requestId = init.requestId\n this.retryable = init.retryable ?? false\n this.operationId = init.operationId\n }\n}\n\n/** 401 / 403: missing, invalid or revoked API key, or not allowed. */\nexport class InstaboxAuthError extends InstaboxError {}\n\n/** 429 `quota_exceeded`: an account limit was reached (for example the machine limit). */\nexport class InstaboxQuotaError extends InstaboxError {}\n\n/** A request or an operation did not finish in time. */\nexport class InstaboxTimeoutError extends InstaboxError {}\n\n/** Result of a finished command. */\nexport interface CommandResult {\n stdout: string\n stderr: string\n exitCode: number\n timedOut: boolean\n truncated: boolean\n /** Error text reported by the server, if any. */\n error?: string\n}\n\n/** A command exited with a non-zero code. Carries the full result. */\nexport class CommandExitError extends InstaboxError implements CommandResult {\n readonly stdout: string\n readonly stderr: string\n readonly exitCode: number\n readonly timedOut: boolean\n readonly truncated: boolean\n readonly error?: string\n\n constructor(result: CommandResult) {\n const tail = result.stderr.trim().split('\\n').slice(-1)[0] ?? ''\n super(`command exited with code ${result.exitCode}${tail ? `: ${tail}` : ''}`, { code: 'command_exit' })\n this.stdout = result.stdout\n this.stderr = result.stderr\n this.exitCode = result.exitCode\n this.timedOut = result.timedOut\n this.truncated = result.truncated\n this.error = result.error\n }\n}\n\n/** Builds the right error class from an HTTP status and the parsed envelope. */\nexport function errorFromResponse(status: number, body: unknown, fallbackMessage: string): InstaboxError {\n const env = (body as { error?: Record<string, unknown> } | null)?.error\n const init: InstaboxErrorInit = {\n status,\n code: typeof env?.code === 'string' ? env.code : `http_${status}`,\n requestId: typeof env?.requestId === 'string' ? env.requestId : undefined,\n retryable: typeof env?.retryable === 'boolean' ? env.retryable : status >= 502 && status <= 504,\n operationId: typeof env?.operationId === 'string' ? env.operationId : null,\n }\n const message = typeof env?.message === 'string' && env.message ? env.message : fallbackMessage\n if (status === 401 || status === 403) return new InstaboxAuthError(message, init)\n if (status === 429) return new InstaboxQuotaError(message, init)\n return new InstaboxError(message, init)\n}\n","export const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))\n\n/** Random UUID v4. Uses Web Crypto when present (Node 19+, Bun, Deno, browsers). */\nexport function uuid(): string {\n const c = (globalThis as { crypto?: Crypto }).crypto\n if (c && typeof c.randomUUID === 'function') return c.randomUUID()\n const b = new Uint8Array(16)\n if (c && typeof c.getRandomValues === 'function') c.getRandomValues(b)\n else for (let i = 0; i < 16; i++) b[i] = Math.floor(Math.random() * 256)\n b[6] = (b[6]! & 0x0f) | 0x40\n b[8] = (b[8]! & 0x3f) | 0x80\n const h = Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('')\n return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`\n}\n\nexport function randomSuffix(len = 8): string {\n const alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789'\n return Array.from({ length: len }, () => alphabet[Math.floor(Math.random() * alphabet.length)]).join('')\n}\n\n/** Quotes a string for POSIX sh. */\nexport function shellQuote(s: string): string {\n return `'${s.replace(/'/g, `'\\\\''`)}'`\n}\n\nexport function bytesToBase64(bytes: Uint8Array): string {\n let bin = ''\n for (let i = 0; i < bytes.length; i += 0x8000) {\n bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000))\n }\n return btoa(bin)\n}\n\nexport function base64ToBytes(b64: string): Uint8Array {\n const bin = atob(b64.replace(/\\s+/g, ''))\n const out = new Uint8Array(bin.length)\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)\n return out\n}\n\nexport function readEnv(name: string): string | undefined {\n const g = globalThis as {\n process?: { env?: Record<string, string | undefined> }\n Deno?: { env?: { get(k: string): string | undefined } }\n }\n try {\n const v = g.process?.env?.[name] ?? g.Deno?.env?.get(name)\n return v === '' ? undefined : v\n } catch {\n return undefined // Deno without --allow-env\n }\n}\n","import { CommandExitError, InstaboxError, type CommandResult } from './errors'\nimport type { HttpClient } from './http'\nimport type { ExecResponse } from './types'\nimport { shellQuote } from './util'\n\nexport interface CommandOptions {\n /** Working directory. Default: the server's default (HOME, `/data/home`). */\n cwd?: string\n /** Extra environment variables, merged over the sandbox-level `envs` from `Sandbox.create`. */\n envs?: Record<string, string>\n /** Command timeout in ms (sent as whole seconds). Default: the server's default. */\n timeoutMs?: number\n /** Text sent to the command's standard input. */\n stdin?: string\n /**\n * Called with stdout once the command finished. Output is not streamed yet:\n * the callback receives the whole stdout in one call.\n */\n onStdout?: (data: string) => void | Promise<void>\n /** Like `onStdout`, for stderr. */\n onStderr?: (data: string) => void | Promise<void>\n /** Start the command detached (nohup) and return right away with its PID. */\n background?: boolean\n}\n\n/** A command started with `background: true`. */\nexport interface CommandHandle {\n pid: number\n /** Sends SIGTERM to the process. Returns false if it had already exited. */\n kill(): Promise<boolean>\n}\n\nexport class Commands {\n /** @internal */\n constructor(\n private readonly http: HttpClient,\n private readonly sandboxId: string,\n private readonly defaultEnvs: Record<string, string>,\n ) {}\n\n /**\n * Runs a shell command in the sandbox and waits for it to finish.\n * Throws `CommandExitError` (carrying stdout, stderr and exitCode) when it exits non-zero.\n */\n run(cmd: string, opts: CommandOptions & { background: true }): Promise<CommandHandle>\n run(cmd: string, opts?: CommandOptions & { background?: false }): Promise<CommandResult>\n run(cmd: string, opts?: CommandOptions): Promise<CommandResult | CommandHandle>\n async run(cmd: string, opts: CommandOptions = {}): Promise<CommandResult | CommandHandle> {\n if (opts.background) {\n const wrapped = `nohup sh -c ${shellQuote(cmd)} >/dev/null 2>&1 & echo $!`\n if (opts.stdin !== undefined)\n throw new InstaboxError('stdin is not supported for background commands', { code: 'bad_request' })\n const r = await this.exec(wrapped, { cwd: opts.cwd, envs: opts.envs, timeoutMs: opts.timeoutMs })\n if (r.exitCode !== 0) throw new CommandExitError(r)\n const pid = Number.parseInt(r.stdout.trim(), 10)\n if (!Number.isSafeInteger(pid) || pid <= 0)\n throw new InstaboxError('exec returned an invalid background PID', { code: 'invalid_response' })\n return {\n pid,\n kill: async () => (await this.exec(`kill ${pid}`)).exitCode === 0,\n }\n }\n const r = await this.exec(cmd, opts)\n if (opts.onStdout && r.stdout) await opts.onStdout(r.stdout)\n if (opts.onStderr && r.stderr) await opts.onStderr(r.stderr)\n if (r.exitCode !== 0) throw new CommandExitError(r)\n return r\n }\n\n /** @internal Raw exec: never throws on a non-zero exit code. */\n async exec(\n cmd: string,\n opts: Pick<CommandOptions, 'cwd' | 'envs' | 'timeoutMs' | 'stdin'> = {},\n ): Promise<CommandResult> {\n const envs = { ...this.defaultEnvs, ...opts.envs }\n const body: Record<string, unknown> = { cmd }\n if (opts.cwd !== undefined) body.cwd = opts.cwd\n if (Object.keys(envs).length) body.envs = envs\n if (opts.stdin !== undefined) body.stdin = opts.stdin\n if (opts.timeoutMs !== undefined) {\n if (!Number.isFinite(opts.timeoutMs) || opts.timeoutMs <= 0 || opts.timeoutMs > 600_000) {\n throw new InstaboxError('command timeoutMs must be greater than 0 and at most 600 000', { code: 'bad_request' })\n }\n body.timeoutSeconds = Math.ceil(opts.timeoutMs / 1000)\n }\n // Exec has no idempotency contract; a retry can run the command twice.\n const res = await this.http.request<ExecResponse>(\n 'POST',\n `/v1/machines/${encodeURIComponent(this.sandboxId)}/exec`,\n {\n body,\n retry: false,\n idempotent: false,\n timeoutMs: (Number(body.timeoutSeconds) || 60) * 1000 + 30_000,\n },\n )\n const out: CommandResult = {\n stdout: res.stdout,\n stderr: res.stderr,\n exitCode: res.exitCode,\n timedOut: res.timedOut,\n truncated: res.truncated,\n }\n if (res.error) out.error = res.error\n return out\n }\n}\n","import type { Commands } from './commands'\nimport { CommandExitError, InstaboxError, type CommandResult } from './errors'\nimport { base64ToBytes, bytesToBase64, shellQuote } from './util'\n\n/** Largest file `files.read` / `files.write` move (files go through exec as base64). */\nexport const MAX_FILE_BYTES = 10 * 1024 * 1024\n// Base64 payload plus shell quoting must fit the API's 64 KiB command limit.\nconst WRITE_CHUNK_B64 = 48 * 1024\n// Encoded chunks must fit the API's 1 MiB stdout limit.\nconst READ_CHUNK_BYTES = 512 * 1024\n\nexport interface EntryInfo {\n name: string\n path: string\n type: 'file' | 'dir'\n}\n\nexport interface WriteInfo {\n path: string\n}\n\n/**\n * File access inside the sandbox. Implemented on top of exec (base64 over the command\n * channel), capped at 10 MiB per file.\n */\nexport class Files {\n /** @internal */\n constructor(private readonly commands: Commands) {}\n\n /** Reads a file. Returns text (UTF-8) by default, or bytes with `{ format: 'bytes' }`. */\n read(path: string, opts?: { format?: 'text' }): Promise<string>\n read(path: string, opts: { format: 'bytes' }): Promise<Uint8Array>\n async read(path: string, opts: { format?: 'text' | 'bytes' } = {}): Promise<string | Uint8Array> {\n const p = shellQuote(path)\n const r = await this.commands.exec(\n `[ -f ${p} ] || { echo \"no such file: \"${p} >&2; exit 3; }; ` +\n `s=$(wc -c < ${p}) || exit 1; [ \"$s\" -le ${MAX_FILE_BYTES} ] || { echo \"file too large: $s bytes\" >&2; exit 4; }; ` +\n `printf '%s' \"$s\"`,\n )\n if (r.exitCode === 3) throw new InstaboxError(`file not found: ${path}`, { status: 404, code: 'not_found' })\n if (r.exitCode === 4) {\n throw new InstaboxError(`${path} is larger than the ${MAX_FILE_BYTES}-byte limit of files.read`, {\n code: 'file_too_large',\n })\n }\n ensureComplete(r)\n const size = Number(r.stdout.trim())\n if (!Number.isSafeInteger(size) || size < 0 || size > MAX_FILE_BYTES) {\n throw new InstaboxError('invalid file size returned by exec', { code: 'invalid_response' })\n }\n const bytes = new Uint8Array(size)\n for (let offset = 0; offset < size; offset += READ_CHUNK_BYTES) {\n const chunk = await this.commands.exec(\n `dd if=${p} bs=${READ_CHUNK_BYTES} skip=${offset / READ_CHUNK_BYTES} count=1 2>/dev/null | base64 | tr -d '\\\\n'`,\n )\n ensureComplete(chunk)\n const data = base64ToBytes(chunk.stdout)\n if (data.length !== Math.min(READ_CHUNK_BYTES, size - offset)) {\n throw new InstaboxError(`file size changed while reading: ${path}`, { code: 'file_changed' })\n }\n bytes.set(data, offset)\n }\n return opts.format === 'bytes' ? bytes : new TextDecoder().decode(bytes)\n }\n\n /** Writes a file, creating parent directories. Replaces the file atomically (temp file + rename). */\n async write(path: string, data: string | Uint8Array): Promise<WriteInfo> {\n const bytes = typeof data === 'string' ? new TextEncoder().encode(data) : data\n if (bytes.length > MAX_FILE_BYTES) {\n throw new InstaboxError(`data is larger than the ${MAX_FILE_BYTES}-byte limit of files.write`, {\n code: 'file_too_large',\n })\n }\n const p = shellQuote(path)\n const tmp = shellQuote(`${path}.instabox-${Math.random().toString(36).slice(2, 10)}.tmp`)\n const b64 = bytesToBase64(bytes)\n const chunks: string[] = []\n for (let i = 0; i < b64.length; i += WRITE_CHUNK_B64) chunks.push(b64.slice(i, i + WRITE_CHUNK_B64))\n if (chunks.length === 0) chunks.push('')\n try {\n for (let i = 0; i < chunks.length; i++) {\n const redirect = i === 0 ? '>' : '>>'\n const prefix = i === 0 ? `mkdir -p \"$(dirname ${p})\" && ` : ''\n const r = await this.commands.exec(`${prefix}printf '%s' '${chunks[i]}' | base64 -d ${redirect} ${tmp}`)\n if (r.exitCode !== 0) throw new CommandExitError(r)\n }\n const r = await this.commands.exec(`mv -f ${tmp} ${p}`)\n if (r.exitCode !== 0) throw new CommandExitError(r)\n } catch (err) {\n await this.commands.exec(`rm -f ${tmp}`).catch(() => {})\n throw err\n }\n return { path }\n }\n\n /** Lists the entries of a directory (not recursive). */\n async list(path: string): Promise<EntryInfo[]> {\n const p = shellQuote(path)\n const r = await this.commands.exec(\n `[ -d ${p} ] || { echo \"no such directory: \"${p} >&2; exit 3; }; ` +\n `cd ${p} && for f in .* *; do case \"$f\" in .|..) continue ;; esac; [ -e \"$f\" ] || [ -L \"$f\" ] || continue; ` +\n `if [ -d \"$f\" ]; then printf 'd\\\\t%s\\\\0' \"$f\"; else printf 'f\\\\t%s\\\\0' \"$f\"; fi; done`,\n )\n if (r.exitCode === 3) throw new InstaboxError(`directory not found: ${path}`, { status: 404, code: 'not_found' })\n ensureComplete(r)\n const base = path.endsWith('/') ? path.slice(0, -1) : path\n return r.stdout\n .split('\\0')\n .filter(Boolean)\n .map((line) => {\n const tab = line.indexOf('\\t')\n const name = line.slice(tab + 1)\n return { name, path: `${base}/${name}`, type: line.slice(0, tab) === 'd' ? 'dir' : 'file' } as EntryInfo\n })\n }\n\n /** Removes a file or a directory (recursively). Missing paths are fine. */\n async remove(path: string): Promise<void> {\n const r = await this.commands.exec(`rm -rf -- ${shellQuote(path)}`)\n if (r.exitCode !== 0) throw new CommandExitError(r)\n }\n\n /** True if a file or directory exists at `path`. */\n async exists(path: string): Promise<boolean> {\n const r = await this.commands.exec(`test -e ${shellQuote(path)}`)\n return r.exitCode === 0\n }\n}\n\nfunction ensureComplete(result: CommandResult): void {\n if (result.exitCode !== 0) throw new CommandExitError(result)\n if (result.truncated) throw new InstaboxError('file command output was truncated', { code: 'output_truncated' })\n}\n","import { InstaboxError, InstaboxTimeoutError, errorFromResponse } from './errors'\nimport type { Operation } from './types'\nimport { readEnv, sleep, uuid } from './util'\n\nexport const DEFAULT_API_URL = 'https://api.instabox.sh'\n\n/** Options shared by every call that talks to the API. */\nexport interface ConnectionOptions {\n /** API key from the instabox dashboard's API Keys page. Default: env `INSTABOX_API_KEY`. */\n apiKey?: string\n /** API base URL. Default: env `INSTABOX_API_URL`, else `https://api.instabox.sh`. */\n apiUrl?: string\n /** Timeout of a single HTTP request in ms. Default 60 000; exec defaults to its command timeout plus 30 000. */\n requestTimeoutMs?: number\n /** Max time to wait for a lifecycle operation (create, pause, resume, fork, kill) in ms. Default 600 000. */\n operationTimeoutMs?: number\n /** Custom fetch implementation (tests, proxies). Default: global `fetch`. */\n fetch?: typeof fetch\n /** Advanced: first delay of operation polling in ms (grows 1.5x to 1 s). Default 250. */\n pollIntervalMs?: number\n /** Advanced: first delay between retries in ms. Default 250. */\n retryDelayMs?: number\n}\n\ninterface RequestOptions {\n timeoutMs?: number\n body?: unknown\n query?: Record<string, string | number | string[] | undefined>\n /** Retry on 502/503/504 and network errors. Default: true for GET and for requests carrying an Idempotency-Key. */\n retry?: boolean\n /** Send an Idempotency-Key. Default: true for every method other than GET/HEAD. */\n idempotent?: boolean\n}\n\nconst MAX_RETRIES = 3\n\nexport class HttpClient {\n readonly apiUrl: string\n readonly operationTimeoutMs: number\n private readonly apiKey: string\n private readonly requestTimeoutMs?: number\n private readonly fetchImpl: typeof fetch\n readonly pollIntervalMs: number\n private readonly retryDelayMs: number\n\n constructor(opts: ConnectionOptions = {}) {\n const apiKey = opts.apiKey ?? readEnv('INSTABOX_API_KEY')\n if (!apiKey) {\n throw new InstaboxError(\n 'No instabox API key. Set the INSTABOX_API_KEY environment variable or pass { apiKey } (create one on the API Keys page of the instabox dashboard).',\n { code: 'missing_api_key' },\n )\n }\n this.apiKey = apiKey\n this.apiUrl = (opts.apiUrl ?? readEnv('INSTABOX_API_URL') ?? DEFAULT_API_URL).replace(/\\/+$/, '')\n this.requestTimeoutMs = opts.requestTimeoutMs\n this.operationTimeoutMs = opts.operationTimeoutMs ?? 600_000\n const f = opts.fetch ?? (globalThis as { fetch?: typeof fetch }).fetch\n if (!f) throw new InstaboxError('No global fetch found; use Node 18+ or pass { fetch }.', { code: 'no_fetch' })\n this.fetchImpl = f\n this.pollIntervalMs = opts.pollIntervalMs ?? 250\n this.retryDelayMs = opts.retryDelayMs ?? 250\n }\n\n async request<T>(method: string, path: string, opts: RequestOptions = {}): Promise<T> {\n const res = await this.send(method, path, opts)\n if (res.status === 204) return undefined as T\n return (await res.json()) as T\n }\n\n /** Performs the request with retries; returns a 2xx response or throws an InstaboxError. */\n async send(method: string, path: string, opts: RequestOptions = {}): Promise<Response> {\n const isRead = method === 'GET' || method === 'HEAD'\n const idempotent = opts.idempotent ?? !isRead\n const retry = opts.retry ?? (isRead || idempotent)\n const headers: Record<string, string> = {\n 'X-API-Key': this.apiKey,\n Accept: 'application/json',\n }\n // One key per intended action, reused by every retry so the server dedupes them.\n if (idempotent) headers['Idempotency-Key'] = uuid()\n let body: string | undefined\n if (opts.body !== undefined) {\n headers['Content-Type'] = 'application/json'\n body = JSON.stringify(opts.body)\n }\n let url = this.apiUrl + path\n if (opts.query) {\n const q = new URLSearchParams()\n for (const [k, v] of Object.entries(opts.query)) {\n if (Array.isArray(v)) for (const item of v) q.append(k, item)\n else if (v !== undefined) q.set(k, String(v))\n }\n const s = q.toString()\n if (s) url += `?${s}`\n }\n\n for (let attempt = 0; ; attempt++) {\n const canRetry = retry && attempt < MAX_RETRIES\n const ctrl = new AbortController()\n let timedOut = false\n const timeoutMs = this.requestTimeoutMs ?? opts.timeoutMs ?? 60_000\n const timer = setTimeout(() => {\n timedOut = true\n ctrl.abort()\n }, timeoutMs)\n let res: Response\n try {\n res = await this.fetchImpl(url, { method, headers, body, signal: ctrl.signal })\n } catch (err) {\n clearTimeout(timer)\n if (canRetry) {\n await sleep(this.backoff(attempt))\n continue\n }\n if (timedOut) {\n throw new InstaboxTimeoutError(`${method} ${path} timed out after ${timeoutMs} ms`, {\n code: 'request_timeout',\n cause: err,\n })\n }\n throw new InstaboxError(`${method} ${path} failed: ${(err as Error)?.message ?? String(err)}`, {\n code: 'network_error',\n retryable: true,\n cause: err,\n })\n }\n clearTimeout(timer)\n if (res.ok) return res\n if (canRetry && res.status >= 502 && res.status <= 504) {\n void res.body?.cancel().catch(() => {})\n await sleep(this.backoff(attempt))\n continue\n }\n const text = await res.text().catch(() => '')\n let parsed: unknown = null\n try {\n parsed = text ? JSON.parse(text) : null\n } catch {\n parsed = null\n }\n throw errorFromResponse(res.status, parsed, `${method} ${path} returned ${res.status}`)\n }\n }\n\n private backoff(attempt: number): number {\n return this.retryDelayMs * 2 ** attempt\n }\n\n /** Polls an operation until it is `succeeded` (returns it) or `failed` (throws). */\n async waitForOperation(op: Operation, timeoutMs = this.operationTimeoutMs): Promise<Operation> {\n const deadline = Date.now() + timeoutMs\n let delay = this.pollIntervalMs\n let cur = op\n while (cur.state !== 'succeeded') {\n if (cur.state === 'failed') {\n const e = cur.error\n throw new InstaboxError(e?.message || `operation ${cur.id} (${cur.type}) failed`, {\n code: e?.code ?? 'operation_failed',\n requestId: e?.requestId,\n retryable: e?.retryable ?? false,\n operationId: cur.id,\n })\n }\n if (Date.now() + delay > deadline) {\n throw new InstaboxTimeoutError(\n `operation ${cur.id} (${cur.type}) did not finish within ${timeoutMs} ms (state ${cur.state}${cur.phase ? `, phase ${cur.phase}` : ''})`,\n { code: 'operation_timeout', operationId: cur.id },\n )\n }\n await sleep(delay)\n delay = Math.min(Math.round(delay * 1.5), Math.max(1_000, this.pollIntervalMs))\n cur = await this.request<Operation>('GET', `/v1/operations/${encodeURIComponent(cur.id)}`)\n }\n return cur\n }\n}\n","import { Commands } from './commands'\nimport { InstaboxError, InstaboxTimeoutError } from './errors'\nimport { Files } from './files'\nimport { type ConnectionOptions, HttpClient } from './http'\nimport type {\n Connection,\n Machine,\n MachineList,\n MachineState,\n MachineVault,\n OnTimeout,\n Operation,\n Snapshot,\n SnapshotList,\n Template,\n VaultApplied,\n} from './types'\nimport { randomSuffix } from './util'\n\nexport const DEFAULT_TEMPLATE = 'agent-browser'\n/** The default when a server does not offer `DEFAULT_TEMPLATE` (an older or self-hosted one). */\nexport const FALLBACK_TEMPLATE = 'universal'\n\nexport interface SandboxOpts extends ConnectionOptions {\n /** Machine name. Default `sbx-<random>`. */\n name?: string\n /** String labels stored with the sandbox; filter on them with `Sandbox.list({ metadata })`. */\n metadata?: Record<string, string>\n /** Environment variables applied to every `commands.run` of this Sandbox object (client-side). */\n envs?: Record<string, string>\n /**\n * The server pauses (or with `onTimeout: 'kill'` deletes) the sandbox this long after creation.\n * Sent as whole seconds, 60 s to 24 h. Default: no timeout. Change it with `setTimeout()`.\n */\n timeoutMs?: number\n /** What happens at the timeout: `pause` (default) or `kill`. */\n onTimeout?: OnTimeout\n /** Stop and archive after this many milliseconds, independent of the pause/kill timeout. */\n archiveMs?: number\n /**\n * The server pauses the sandbox once it has been idle this long (no agent working, no terminal use,\n * little CPU); the next command, file read or SSH sign-in resumes it. Sent as whole seconds, 2 min to\n * 24 h. Default: 30 minutes. `0`: never, the sandbox stays on until paused or killed. Change it later\n * with `setAutoSuspend()`.\n */\n autoSuspendMs?: number\n /** vCPUs. Default: the template's. */\n vcpus?: number\n /** Memory in MiB. Default: the template's. */\n memMiB?: number\n /** Size of the persistent `/data` disk in GiB. Default: the template's. */\n diskGiB?: number\n /** Root disk size in GiB; may only grow. */\n rootDiskGiB?: number\n /**\n * `false`: the sandbox never gets the account's Vault items (the secrets the dashboard's Vault page or\n * `instabox vault set` keeps, written into every sandbox of the account at boot and resume). Pass it for\n * sandboxes made for other people: anything running in a sandbox can read what the Vault writes into it.\n * Default: the sandbox gets them. Cannot be turned on again later.\n */\n vault?: boolean\n}\n\nexport interface SandboxConnectOpts extends ConnectionOptions {\n /** Resume the sandbox if it is paused (suspended) or stopped. Default true. */\n resume?: boolean\n envs?: Record<string, string>\n}\n\nexport interface SandboxListOpts extends ConnectionOptions {\n /** Only sandboxes whose metadata has every one of these key/value pairs. */\n metadata?: Record<string, string>\n}\n\nexport interface SandboxInfo {\n sandboxId: string\n /** Template the sandbox runs (`template.id`). */\n templateId: string\n /** Snapshot the sandbox was created from, if any. */\n snapshotId?: string\n name: string\n /** String labels stored with the sandbox. */\n metadata: Record<string, string>\n /** The sandbox gets the account's Vault items at boot and resume (`vault: false` at creation, or `disableVault()`, turns this off for good). */\n vault: boolean\n /** Creation time of the machine. */\n startedAt: Date\n /** When the server pauses or kills the sandbox (see `onTimeout`); undefined for no timeout. */\n endAt?: Date\n archiveAt?: Date\n onTimeout: OnTimeout\n /** Idle time after which the server pauses the sandbox; undefined when it never does. */\n autoSuspendMs?: number\n state: MachineState\n /** The raw machine object from the API. */\n machine: Machine\n}\n\nexport interface ForkOpts {\n /** Name of the new sandbox. Default `<name>-fork-<random>`. */\n name?: string\n vcpus?: number\n memMiB?: number\n /** May only grow. */\n diskGiB?: number\n /** Root disk size in GiB; may only grow. */\n rootDiskGiB?: number\n /** Timeout of the copy, as in `SandboxOpts.timeoutMs`. Default: none (the source's is not copied). */\n timeoutMs?: number\n onTimeout?: OnTimeout\n /** Idle pause of the copy, as in `SandboxOpts.autoSuspendMs`. Default: 30 minutes (the source's is not copied); `0`: never. */\n autoSuspendMs?: number\n /** Metadata of the copy. Default: the source's; `{}` for none. */\n metadata?: Record<string, string>\n /** `false`: the copy never gets the account's Vault items (a copy of a sandbox without the Vault never does). */\n vault?: boolean\n /**\n * A fork needs a stopped source. When true (default), `fork()` stops the source first if needed\n * (running processes end, `/data` is kept) and leaves it stopped; call `resume()` to start it again.\n * When false, a source that is not stopped makes the call fail.\n */\n stopSource?: boolean\n}\n\nexport interface CreateSnapshotOpts {\n name: string\n description?: string\n /** Save only the root disk; omit the persistent /data disk. */\n rootOnly?: boolean\n}\n\nexport interface SshCredentials {\n host: string\n port: number\n /** The machine ID. */\n username: string\n /** OpenSSH user certificate for `publicKey`, in authorized_keys format. Save it as `<key>-cert.pub`. */\n certificate: string\n /** Line for known_hosts that trusts the instabox gateway: `@cert-authority [host]:port <ca key>`. */\n knownHostsLine: string\n expiresAt: Date\n connectionId: string\n}\n\nfunction toInfo(m: Machine): SandboxInfo {\n const info: SandboxInfo = {\n sandboxId: m.id,\n templateId: m.template?.id,\n name: m.name,\n metadata: { ...m.metadata },\n vault: m.vault ?? true,\n startedAt: new Date(m.createdAt),\n onTimeout: m.onTimeout ?? 'pause',\n state: m.state,\n machine: m,\n }\n if (m.snapshot?.id) info.snapshotId = m.snapshot.id\n if (m.timeoutAt) info.endAt = new Date(m.timeoutAt)\n if (m.archiveAt) info.archiveAt = new Date(m.archiveAt)\n if (m.autoSuspendAfterSeconds) info.autoSuspendMs = m.autoSuspendAfterSeconds * 1000\n return info\n}\n\n/** `autoSuspendMs` to the API's whole seconds: 0 (never), or 2 min to 24 h rounded up. */\nfunction toIdleSeconds(ms: number): number {\n if (ms === 0) return 0\n const s = Math.ceil(ms / 1000)\n if (!Number.isFinite(ms) || s < 120 || s > 86_400) {\n throw new InstaboxError(`autoSuspendMs must be 0 or between 120 000 (2 min) and 86 400 000 (24 h); got ${ms}`, {\n code: 'bad_request',\n })\n }\n return s\n}\n\n/** Milliseconds to the API's whole seconds (rounded up), checked against the server's 60 s to 24 h range. */\nfunction toSeconds(ms: number, field = 'timeoutMs'): number {\n const s = Math.ceil(ms / 1000)\n if (!Number.isFinite(ms) || s < 60 || s > 86_400) {\n throw new InstaboxError(`${field} must be between 60 000 (60 s) and 86 400 000 (24 h); got ${ms}`, {\n code: 'bad_request',\n })\n }\n return s\n}\n\n/** Metadata keys the server accepts; checked before a list filter, where a bad key would silently match nothing. */\nconst METADATA_KEY = /^[A-Za-z0-9_.-]{1,64}$/\n\nconst enc = encodeURIComponent\n\n/** A instabox dev machine. Create one with `Sandbox.create()` or attach with `Sandbox.connect(id)`. */\nexport class Sandbox {\n /** The machine ID (`m_...`). */\n readonly sandboxId: string\n /** Run shell commands. Needs a instabox server with the exec endpoint. */\n readonly commands: Commands\n /** Read and write files. Needs a instabox server with the exec endpoint. */\n readonly files: Files\n private machine: Machine\n\n private constructor(\n private readonly http: HttpClient,\n machine: Machine,\n opts: { envs?: Record<string, string> } = {},\n ) {\n this.sandboxId = machine.id\n this.machine = machine\n this.commands = new Commands(http, machine.id, { ...opts.envs })\n this.files = new Files(this.commands)\n }\n\n /**\n * Creates a sandbox and waits until it is running.\n * `template` is a template ID, a private snapshot name or a snapshot ID (`sn_...`).\n * Template IDs take precedence over snapshot names. Default template: `agent-browser` (universal\n * with a desktop and browser preinstalled, which the dashboard's Computer tab shows), or\n * `universal` on a server that does not offer it.\n */\n static async create(opts?: SandboxOpts): Promise<Sandbox>\n static async create(template: string, opts?: SandboxOpts): Promise<Sandbox>\n static async create(a?: string | SandboxOpts, b?: SandboxOpts): Promise<Sandbox> {\n const opts = (typeof a === 'string' ? b : a) ?? {}\n const http = new HttpClient(opts)\n const body: Record<string, unknown> = { name: opts.name ?? `sbx-${randomSuffix()}` }\n if (opts.timeoutMs !== undefined) body.timeoutSeconds = toSeconds(opts.timeoutMs)\n if (opts.archiveMs !== undefined) body.archiveSeconds = toSeconds(opts.archiveMs, 'archiveMs')\n if (opts.autoSuspendMs !== undefined) body.autoSuspendAfterSeconds = toIdleSeconds(opts.autoSuspendMs)\n // After the checks above: a bad option is refused before any request.\n const template = typeof a === 'string' ? a : await defaultTemplate(http)\n Object.assign(body, await resolveSource(http, template))\n if (opts.vcpus !== undefined) body.vcpus = opts.vcpus\n if (opts.memMiB !== undefined) body.memMiB = opts.memMiB\n if (opts.diskGiB !== undefined) body.persistentDiskGiB = opts.diskGiB\n if (opts.rootDiskGiB !== undefined) body.rootDiskGiB = opts.rootDiskGiB\n if (opts.onTimeout) body.onTimeout = opts.onTimeout\n if (opts.metadata) body.metadata = opts.metadata\n if (opts.vault === false) body.vault = false\n const op = await http.request<Operation>('POST', '/v1/machines', { body })\n const done = await http.waitForOperation(op)\n const machine = await getMachine(http, done.machineId)\n return new Sandbox(http, machine, opts)\n }\n\n /** Attaches to an existing sandbox. Resumes it if it is paused or stopped, unless `resume: false`. */\n static async connect(sandboxId: string, opts: SandboxConnectOpts = {}): Promise<Sandbox> {\n const http = new HttpClient(opts)\n const sbx = new Sandbox(http, await getMachine(http, sandboxId), opts)\n await sbx.settle(false)\n if (opts.resume !== false) await sbx.wake()\n return sbx\n }\n\n /** Lists your sandboxes (all pages), optionally only those matching `metadata`. */\n static async list(opts: SandboxListOpts = {}): Promise<SandboxInfo[]> {\n const http = new HttpClient(opts)\n const metadata = Object.entries(opts.metadata ?? {}).map(([k, v]) => {\n if (!METADATA_KEY.test(k))\n throw new InstaboxError(`invalid metadata key ${JSON.stringify(k)}: use 1-64 of [A-Za-z0-9_.-]`, {\n code: 'bad_request',\n })\n return `${k}:${v}`\n })\n const out: SandboxInfo[] = []\n let cursor: string | undefined\n do {\n const page = await http.request<MachineList>('GET', '/v1/machines', { query: { cursor, limit: 100, metadata } })\n out.push(...page.machines.map((m) => toInfo(m)))\n cursor = page.nextCursor ?? undefined\n } while (cursor)\n return out\n }\n\n /** Deletes a sandbox and its disks. Returns false if it did not exist. */\n static async kill(sandboxId: string, opts: ConnectionOptions = {}): Promise<boolean> {\n return killMachine(new HttpClient(opts), sandboxId)\n }\n\n /** Lists the caller's private snapshots. Requires images:read. */\n static async listSnapshots(opts: ConnectionOptions = {}): Promise<Snapshot[]> {\n const result = await new HttpClient(opts).request<SnapshotList>('GET', '/v1/snapshots')\n return result.snapshots\n }\n\n /** Fetches a snapshot by ID. Requires images:read. */\n static async getSnapshot(snapshotId: string, opts: ConnectionOptions = {}): Promise<Snapshot> {\n return new HttpClient(opts).request<Snapshot>('GET', `/v1/snapshots/${enc(snapshotId)}`)\n }\n\n /** Deletes a snapshot. Returns false if absent. Requires images:delete. */\n static async deleteSnapshot(snapshotId: string, opts: ConnectionOptions = {}): Promise<boolean> {\n try {\n await new HttpClient(opts).request<void>('DELETE', `/v1/snapshots/${enc(snapshotId)}`)\n return true\n } catch (err) {\n if (err instanceof InstaboxError && err.status === 404 && err.code === 'not_found') return false\n throw err\n }\n }\n\n /**\n * Saves a stopped sandbox's disks as a private snapshot. Requires images:write. Waits first for a\n * recent stop's upload to object storage (see `untilSynced`).\n */\n async createSnapshot(opts: CreateSnapshotOpts): Promise<Snapshot> {\n await this.settle()\n await this.untilSynced()\n return this.http.request<Snapshot>('POST', `/v1/machines/${enc(this.sandboxId)}/snapshots`, { body: opts })\n }\n\n /** Fetches the current state of the sandbox. */\n async getInfo(): Promise<SandboxInfo> {\n this.machine = await getMachine(this.http, this.sandboxId)\n return toInfo(this.machine)\n }\n\n /**\n * Sets the timeout to `timeoutMs` from now (whole seconds, 60 s to 24 h); 0 clears it.\n * `onTimeout` changes what happens then (`pause` or `kill`).\n */\n async setTimeout(timeoutMs: number, opts: { onTimeout?: OnTimeout } = {}): Promise<void> {\n const body: Record<string, unknown> = { timeoutSeconds: timeoutMs === 0 ? 0 : toSeconds(timeoutMs) }\n if (opts.onTimeout) body.onTimeout = opts.onTimeout\n this.machine = await this.http.request<Machine>('PATCH', `/v1/machines/${enc(this.sandboxId)}`, { body })\n }\n\n /**\n * Pauses the sandbox once it has been idle `idleMs` (whole seconds, 2 min to 24 h); 0 turns the idle\n * pause off. Unlike a timeout the setting stays across pause and resume.\n */\n async setAutoSuspend(idleMs: number): Promise<void> {\n this.machine = await this.http.request<Machine>('PATCH', `/v1/machines/${enc(this.sandboxId)}`, {\n body: { autoSuspendAfterSeconds: toIdleSeconds(idleMs) },\n })\n }\n\n /** Replaces the sandbox's metadata (`{}` clears it). */\n async setMetadata(metadata: Record<string, string>): Promise<void> {\n this.machine = await this.http.request<Machine>('PATCH', `/v1/machines/${enc(this.sandboxId)}`, {\n body: { metadata },\n })\n }\n\n /**\n * What the Vault writes into this sandbox: whether it takes the Vault, the items that apply with its\n * current metadata (names and paths, never values) and the last write. Requires machines:read.\n * Throws `not_found` on a server without the Vault.\n */\n async vault(): Promise<MachineVault> {\n return this.http.request<MachineVault>('GET', `/v1/machines/${enc(this.sandboxId)}/vault`)\n }\n\n /**\n * Writes the account's current Vault items into the running sandbox now, the same write as after a boot,\n * and returns its record (`error` set when the guest refused it). Requires machines:write.\n */\n async pushVault(): Promise<VaultApplied> {\n return this.http.request<VaultApplied>('POST', `/v1/machines/${enc(this.sandboxId)}/vault`)\n }\n\n /**\n * Turns the Vault off for this sandbox, for good, in any state: its next boot, resume or push removes\n * what the Vault wrote and nothing is written again. Requires machines:write.\n */\n async disableVault(): Promise<void> {\n this.machine = await this.http.request<Machine>('PATCH', `/v1/machines/${enc(this.sandboxId)}`, {\n body: { vault: false },\n })\n }\n\n /** True if the sandbox is running (fetches fresh state). */\n async isRunning(): Promise<boolean> {\n return (await this.getInfo()).state === 'running'\n }\n\n /** Snapshots memory and stops the sandbox (suspend). `resume()` or `Sandbox.connect()` brings it back. */\n async pause(): Promise<void> {\n await this.mutate('POST', 'suspend')\n }\n\n /** Resumes a paused sandbox from its snapshot, or starts a stopped one. */\n async resume(): Promise<void> {\n await this.settle()\n await this.wake()\n }\n\n /** Resumes or starts based on the cached state; callers make sure the cache is fresh. */\n private async wake(): Promise<void> {\n if (this.machine.state === 'suspended') await this.mutate('POST', 'resume')\n else if (this.machine.state === 'stopped') await this.mutate('POST', 'start')\n }\n\n /** Stops the sandbox (guest shutdown; processes end, `/data` is kept). */\n async stop(): Promise<void> {\n await this.settle()\n if (this.machine.state === 'suspended') await this.mutate('POST', 'start')\n await this.mutate('POST', 'stop')\n }\n\n /** Copies this sandbox (root disk and `/data`) into a new sandbox and waits until it runs. */\n async fork(opts: ForkOpts = {}): Promise<Sandbox> {\n if (opts.timeoutMs !== undefined) toSeconds(opts.timeoutMs)\n if (opts.autoSuspendMs !== undefined) toIdleSeconds(opts.autoSuspendMs)\n await this.settle()\n if (this.machine.state !== 'stopped') {\n if (opts.stopSource === false) {\n throw new InstaboxError(`fork needs a stopped sandbox; ${this.sandboxId} is ${this.machine.state}`, {\n code: 'operation_conflict',\n })\n }\n await this.stop()\n }\n await this.untilSynced()\n const body: Record<string, unknown> = { name: opts.name ?? `${this.machine.name}-fork-${randomSuffix(4)}` }\n if (opts.vcpus !== undefined) body.vcpus = opts.vcpus\n if (opts.memMiB !== undefined) body.memMiB = opts.memMiB\n if (opts.diskGiB !== undefined) body.persistentDiskGiB = opts.diskGiB\n if (opts.rootDiskGiB !== undefined) body.rootDiskGiB = opts.rootDiskGiB\n if (opts.timeoutMs !== undefined) body.timeoutSeconds = toSeconds(opts.timeoutMs)\n if (opts.onTimeout) body.onTimeout = opts.onTimeout\n if (opts.autoSuspendMs !== undefined) body.autoSuspendAfterSeconds = toIdleSeconds(opts.autoSuspendMs)\n if (opts.metadata) body.metadata = opts.metadata\n if (opts.vault === false) body.vault = false\n const op = await this.http.request<Operation>('POST', `/v1/machines/${enc(this.sandboxId)}/fork`, { body })\n const done = await this.http.waitForOperation(op)\n return new Sandbox(this.http, await getMachine(this.http, done.machineId))\n }\n\n /** Deletes the sandbox and its disks. Returns false if it was already gone. */\n async kill(): Promise<boolean> {\n return killMachine(this.http, this.sandboxId)\n }\n\n /**\n * Issues a short-lived SSH certificate for `publicKey` (authorized_keys format).\n * Connect with `ssh -p <port> -o CertificateFile=<cert> -i <key> <username>@<host>` after adding\n * `knownHostsLine` to known_hosts. The sandbox must be running.\n */\n async sshCredentials(publicKey: string, opts: { ttlSeconds?: number } = {}): Promise<SshCredentials> {\n const body: Record<string, unknown> = { publicKey: publicKey.trim() }\n if (opts.ttlSeconds) body.ttlSeconds = opts.ttlSeconds\n const c = await this.http.request<Connection>('POST', `/v1/machines/${enc(this.sandboxId)}/connections`, { body })\n return {\n host: c.host,\n port: c.port,\n username: c.username,\n certificate: c.certificate,\n knownHostsLine: `@cert-authority [${c.host}]:${c.port} ${c.hostTrust.publicKey}`,\n expiresAt: new Date(c.expiresAt),\n connectionId: c.id,\n }\n }\n\n /**\n * Re-reads the machine from the server (other handles or the dashboard may have changed it),\n * waits for its active operation if one is running, and leaves the fresh state cached.\n * Every state-dependent method calls this first, so it never decides from a stale cache.\n */\n private async settle(refresh = true): Promise<void> {\n if (refresh) this.machine = await getMachine(this.http, this.sandboxId)\n if (this.machine.operationId) {\n const op = await this.http.request<Operation>('GET', `/v1/operations/${enc(this.machine.operationId)}`)\n await this.http.waitForOperation(op).catch(() => {})\n this.machine = await getMachine(this.http, this.sandboxId)\n }\n }\n\n /**\n * Waits until a stopped sandbox's disks are in object storage (`storage.synced`). A stop returns\n * once the host has the snapshot and uploads it after, so a fork or snapshot right after a stop\n * was refused (\"not uploaded to object storage\"), which took long enough after a pause and resume\n * to fail every time. Only a stopped sandbox is waited for; the server says what else is wrong.\n */\n private async untilSynced(): Promise<void> {\n const deadline = Date.now() + this.http.operationTimeoutMs\n let delay = this.http.pollIntervalMs\n while (this.machine.state === 'stopped' && !this.machine.storage.synced) {\n if (Date.now() + delay > deadline) {\n throw new InstaboxTimeoutError(\n `${this.sandboxId}'s disks were not uploaded to object storage within ${this.http.operationTimeoutMs} ms`,\n { code: 'operation_timeout' },\n )\n }\n await new Promise((r) => setTimeout(r, delay))\n delay = Math.min(delay * 2, 2000)\n this.machine = await getMachine(this.http, this.sandboxId)\n }\n }\n\n private async mutate(method: string, action: string): Promise<void> {\n const op = await this.http.request<Operation>(method, `/v1/machines/${enc(this.sandboxId)}/${action}`)\n await this.http.waitForOperation(op)\n this.machine = await getMachine(this.http, this.sandboxId)\n }\n}\n\nasync function getMachine(http: HttpClient, id: string): Promise<Machine> {\n return http.request<Machine>('GET', `/v1/machines/${enc(id)}`)\n}\n\nasync function killMachine(http: HttpClient, id: string): Promise<boolean> {\n try {\n const op = await http.request<Operation>('DELETE', `/v1/machines/${enc(id)}`)\n await http.waitForOperation(op)\n return true\n } catch (err) {\n if (err instanceof InstaboxError && err.status === 404 && err.code === 'not_found') return false\n throw err\n }\n}\n\n/** DEFAULT_TEMPLATE when the server offers it (listed, not hidden), else FALLBACK_TEMPLATE. */\nasync function defaultTemplate(http: HttpClient): Promise<string> {\n const { templates } = await http.request<{ templates: Template[] }>('GET', '/v1/templates')\n return templates.some((t) => t.id === DEFAULT_TEMPLATE && !t.hidden) ? DEFAULT_TEMPLATE : FALLBACK_TEMPLATE\n}\n\nasync function resolveSource(http: HttpClient, ref: string): Promise<{ templateId: string } | { snapshotId: string }> {\n if (/^sn_[a-z2-7]{26}$/.test(ref)) return { snapshotId: ref }\n const { templates } = await http.request<{ templates: Template[] }>('GET', '/v1/templates')\n if (templates.some((template) => template.id === ref)) return { templateId: ref }\n const { snapshots } = await http.request<SnapshotList>('GET', '/v1/snapshots')\n const matches = snapshots.filter((snapshot) => snapshot.name === ref)\n if (matches.length > 1) {\n throw new InstaboxError(`multiple snapshots named ${ref}; use a snapshot ID`, { code: 'ambiguous_snapshot' })\n }\n if (matches[0]) return { snapshotId: matches[0].id }\n throw new InstaboxError(`template or snapshot not found: ${ref}`, { status: 404, code: 'not_found' })\n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eAAe;AAC1F,MAAI,UAAU,KAAK,CAAC,aAAa,SAAS,OAAO,GAAG,EAAG,QAAO,EAAE,YAAY,IAAI;AAChF,QAAM,EAAE,UAAU,IAAI,MAAM,KAAK,QAAsB,OAAO,eAAe;AAC7E,QAAM,UAAU,UAAU,OAAO,CAAC,aAAa,SAAS,SAAS,GAAG;AACpE,MAAI,QAAQ,SAAS,GAAG;AACtB,UAAM,IAAI,cAAc,4BAA4B,GAAG,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAAA,EAC9G;AACA,MAAI,QAAQ,CAAC,EAAG,QAAO,EAAE,YAAY,QAAQ,CAAC,EAAE,GAAG;AACnD,QAAM,IAAI,cAAc,mCAAmC,GAAG,IAAI,EAAE,QAAQ,KAAK,MAAM,YAAY,CAAC;AACtG;","names":["r","r"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@insforge/instabox-sdk",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "TypeScript SDK for instabox: create sandboxes on Firecracker dev machines, run commands, move files, pause, resume, fork and SSH in.",
5
5
  "private": false,
6
6
  "type": "module",
@@ -11,19 +11,19 @@ InstaBox sandboxes have a root disk and a persistent `/data` disk; HOME is `/dat
11
11
 
12
12
  ```sh
13
13
  export INSTABOX_API_KEY=ibk_...
14
- export INSTABOX_API_URL=https://api.box.instacloud.com
14
+ export INSTABOX_API_URL=https://api.instabox.sh
15
15
  ```
16
16
 
17
17
  Obtain keys from the dashboard's API Keys page or `instabox keys create`. If no key is configured, ask the user to configure one. Never print keys, commit them, or put them into metadata.
18
18
 
19
- | Scope | Operations |
20
- | ----------------- | ---------------------------------------------------------------------- |
21
- | `machines:read` | List/get machines, templates and operations |
22
- | `machines:write` | Create, start, stop, pause, resume, fork, timeout, metadata, exec, SSH |
23
- | `machines:delete` | Delete machines |
24
- | `images:read` | List/get snapshots and resolve snapshot names |
25
- | `images:write` | Save a stopped machine as a snapshot |
26
- | `images:delete` | Delete snapshots |
19
+ | Scope | Operations |
20
+ | ----------------- | ---------------------------------------------------------------------------------- |
21
+ | `machines:read` | List/get machines, templates and operations, a machine's Vault view |
22
+ | `machines:write` | Create, start, stop, pause, resume, fork, timeout, metadata, exec, SSH, Vault push |
23
+ | `machines:delete` | Delete machines |
24
+ | `images:read` | List/get snapshots and resolve snapshot names |
25
+ | `images:write` | Save a stopped machine as a snapshot |
26
+ | `images:delete` | Delete snapshots |
27
27
 
28
28
  The current API calls snapshot scopes `images:*`. Write and delete imply read. Keys cannot manage keys or use admin routes. A `403 insufficient_scope` requires the relevant scope; do not retry it.
29
29
 
@@ -52,7 +52,9 @@ try {
52
52
  }
53
53
  ```
54
54
 
55
- Connection options `{ apiKey, apiUrl }` override environment variables. `universal` is the default template. Create accepts a template ID, a private snapshot name, or a `sn_...` snapshot ID. Template IDs take precedence; duplicate snapshot names require an ID. There are no official snapshots. Template creation and snapshot-ID creation need only machine scopes; snapshot-name lookup also needs `images:read`.
55
+ A new sandbox pauses itself after 30 idle minutes and resumes on the next command, file read or SSH sign-in; pass `autoSuspendMs: 0` for one that must stay on, or another idle time, and `setAutoSuspend(ms)` to change it later. `timeoutMs` is a hard deadline (`onTimeout: 'kill'` deletes the sandbox then), which the examples use so a forgotten sandbox is removed.
56
+
57
+ Connection options `{ apiKey, apiUrl }` override environment variables. `agent-browser` (universal plus a desktop and browser) is the default template; `universal` on a server without it. Create accepts a template ID, a private snapshot name, or a `sn_...` snapshot ID. Template IDs take precedence; duplicate snapshot names require an ID. There are no official snapshots. Template creation and snapshot-ID creation need only machine scopes; snapshot-name lookup also needs `images:read`.
56
58
 
57
59
  Save and restore a private snapshot with the required snapshot scopes:
58
60
 
@@ -79,6 +81,15 @@ try {
79
81
  }
80
82
  ```
81
83
 
84
+ ## Vault
85
+
86
+ The account's Vault (secrets a person set on the dashboard's Vault page or with `instabox vault set NAME`, `set-file PATH`, `import .env`) is written into every sandbox of the account at boot and resume: `env` items as environment variables of every login shell (so of `commands.run` and `instabox exec`), `file` items as files under HOME. An API key cannot read, create or change items; do not try, and never ask for a secret's value to put it somewhere else.
87
+
88
+ - A sandbox made for another person or tenant must be created with `vault: false` (`Sandbox.create('universal', { vault: false })`, `fork({ vault: false })`, `instabox create --no-vault`, REST `"vault": false`): anything running in it can read what the Vault writes. This is for good; `disableVault()` / `PATCH {"vault": false}` does the same to an existing sandbox.
89
+ - A sandbox for the account's own work takes the Vault by default. Before asking the person for a credential, check what is already there: `box.vault()` (`GET /v1/machines/{id}/vault`) lists the item names and the last write; in the sandbox, `env | grep NAME` or the file path.
90
+ - `box.pushVault()` (`POST /v1/machines/{id}/vault`, `instabox vault push <box>`) writes the current items into a running sandbox now; otherwise a changed item arrives at the next boot or resume (a changed `env` item reaches new shells only).
91
+ - An item's selector limits it to sandboxes whose metadata has those labels: create the sandbox with the metadata the person's items expect.
92
+
82
93
  `listSnapshots()` and `getSnapshot(id)` inspect snapshots. `createSnapshot` requires a stopped source; it does not stop it automatically. `rootOnly: true` omits `/data`. `fork()` stops its source by default; `stopSource: false` requires an already stopped source. Pause/resume preserves processes; snapshot restore and fork boot fresh processes.
83
94
 
84
95
  ## CLI and REST
@@ -92,6 +103,8 @@ instabox ssh dev
92
103
  instabox suspend dev
93
104
  instabox resume dev
94
105
  instabox rm dev
106
+ instabox create --name tenant --template universal --no-vault # for someone else
107
+ instabox vault show dev; instabox vault push dev # what the Vault wrote; write it now
95
108
  ```
96
109
 
97
110
  Use `instabox help` for the full command surface. With `INSTABOX_API_KEY` set, no interactive login is needed.