@insforge/instabox-sdk 0.0.0-stage → 0.1.1
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/LICENSE +201 -0
- package/README.md +227 -2
- package/dist/index.cjs +700 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +466 -0
- package/dist/index.d.ts +466 -0
- package/dist/index.js +677 -0
- package/dist/index.js.map +1 -0
- package/package.json +65 -4
- package/skills/instabox/SKILL.md +116 -0
|
@@ -0,0 +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 }\n throw new InstaboxError(`template or snapshot not found: ${ref}`, { status: 404, code: 'not_found' })\n}\n"],"mappings":";AAWO,IAAM,gBAAN,cAA4B,MAAM;AAAA;AAAA,EAE9B;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EAET,YAAY,SAAiB,OAA0B,CAAC,GAAG;AACzD,UAAM,SAAS,KAAK,UAAU,SAAY,SAAY,EAAE,OAAO,KAAK,MAAM,CAAC;AAC3E,SAAK,OAAO,WAAW;AACvB,SAAK,SAAS,KAAK,UAAU;AAC7B,SAAK,OAAO,KAAK,QAAQ;AACzB,SAAK,YAAY,KAAK;AACtB,SAAK,YAAY,KAAK,aAAa;AACnC,SAAK,cAAc,KAAK;AAAA,EAC1B;AACF;AAGO,IAAM,oBAAN,cAAgC,cAAc;AAAC;AAG/C,IAAM,qBAAN,cAAiC,cAAc;AAAC;AAGhD,IAAM,uBAAN,cAAmC,cAAc;AAAC;AAclD,IAAM,mBAAN,cAA+B,cAAuC;AAAA,EAClE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,QAAuB;AACjC,UAAM,OAAO,OAAO,OAAO,KAAK,EAAE,MAAM,IAAI,EAAE,MAAM,EAAE,EAAE,CAAC,KAAK;AAC9D,UAAM,4BAA4B,OAAO,QAAQ,GAAG,OAAO,KAAK,IAAI,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AACvG,SAAK,SAAS,OAAO;AACrB,SAAK,SAAS,OAAO;AACrB,SAAK,WAAW,OAAO;AACvB,SAAK,WAAW,OAAO;AACvB,SAAK,YAAY,OAAO;AACx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iB,OAAO,gBAAgB,IAAI,EAAE,CAAC,EAAE;AAC/D;AAEA,eAAe,YAAY,MAAkB,IAA8B;AACzE,MAAI;AACF,UAAM,KAAK,MAAM,KAAK,QAAmB,UAAU,gBAAgB,IAAI,EAAE,CAAC,EAAE;AAC5E,UAAM,KAAK,iBAAiB,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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,67 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@insforge/instabox-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "TypeScript SDK for instabox: create sandboxes on Firecracker dev machines, run commands, move files, pause, resume, fork and SSH in.",
|
|
5
|
+
"private": false,
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.cjs",
|
|
8
|
+
"module": "./dist/index.js",
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"import": {
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"default": "./dist/index.js"
|
|
15
|
+
},
|
|
16
|
+
"require": {
|
|
17
|
+
"types": "./dist/index.d.cts",
|
|
18
|
+
"default": "./dist/index.cjs"
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
"./package.json": "./package.json"
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"dist",
|
|
25
|
+
"README.md",
|
|
26
|
+
"skills",
|
|
27
|
+
"LICENSE"
|
|
28
|
+
],
|
|
29
|
+
"sideEffects": false,
|
|
30
|
+
"engines": {
|
|
31
|
+
"node": ">=18"
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "tsup",
|
|
35
|
+
"prepare": "tsup",
|
|
36
|
+
"typecheck": "tsc --noEmit",
|
|
37
|
+
"test": "vitest run",
|
|
38
|
+
"test:live": "INSTABOX_LIVE=1 vitest run test/live.test.ts",
|
|
39
|
+
"prepublishOnly": "npm run format:check && npm run lint && npm run typecheck && npm run build && npm test",
|
|
40
|
+
"format:check": "prettier --check src test *.ts package.json .prettierrc.json README.md skills .github",
|
|
41
|
+
"lint": "oxlint --deny-warnings src test"
|
|
42
|
+
},
|
|
43
|
+
"keywords": [
|
|
44
|
+
"instabox",
|
|
45
|
+
"sandbox",
|
|
46
|
+
"microvm",
|
|
47
|
+
"firecracker",
|
|
48
|
+
"dev-machine",
|
|
49
|
+
"insforge"
|
|
50
|
+
],
|
|
51
|
+
"publishConfig": {
|
|
52
|
+
"access": "public"
|
|
53
|
+
},
|
|
54
|
+
"devDependencies": {
|
|
55
|
+
"@types/node": "^20.14.0",
|
|
56
|
+
"oxlint": "^1.87.0",
|
|
57
|
+
"prettier": "^3.9.9",
|
|
58
|
+
"tsup": "^8.5.1",
|
|
59
|
+
"typescript": "^5.6.0",
|
|
60
|
+
"vitest": "^4.1.11"
|
|
61
|
+
},
|
|
62
|
+
"license": "Apache-2.0",
|
|
63
|
+
"repository": {
|
|
64
|
+
"type": "git",
|
|
65
|
+
"url": "git+https://github.com/InsForge/instabox-sdk.git"
|
|
66
|
+
}
|
|
67
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: instabox
|
|
3
|
+
description: Use when creating or managing InstaBox sandboxes, running commands, moving files, saving private snapshots, or connecting over SSH from an application, CLI, CI job, or coding agent.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# InstaBox
|
|
7
|
+
|
|
8
|
+
InstaBox sandboxes have a root disk and a persistent `/data` disk; HOME is `/data/home`. Pause preserves memory; stop ends processes and keeps disks. Use templates for a base system and private snapshots for saved workspaces.
|
|
9
|
+
|
|
10
|
+
## Authentication
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
export INSTABOX_API_KEY=ibk_...
|
|
14
|
+
export INSTABOX_API_URL=https://api.box.instacloud.com
|
|
15
|
+
```
|
|
16
|
+
|
|
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
|
+
|
|
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 |
|
|
27
|
+
|
|
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
|
+
|
|
30
|
+
## TypeScript SDK
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
npm install @insforge/instabox-sdk
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { Sandbox } from '@insforge/instabox-sdk'
|
|
38
|
+
|
|
39
|
+
const box = await Sandbox.create('universal', {
|
|
40
|
+
timeoutMs: 30 * 60_000,
|
|
41
|
+
onTimeout: 'kill',
|
|
42
|
+
metadata: { task: 'example' },
|
|
43
|
+
})
|
|
44
|
+
try {
|
|
45
|
+
console.log((await box.commands.run('uname -a')).stdout)
|
|
46
|
+
await box.files.write('/data/home/proof.txt', 'hello')
|
|
47
|
+
await box.pause()
|
|
48
|
+
await box.resume()
|
|
49
|
+
console.log(await box.files.read('/data/home/proof.txt'))
|
|
50
|
+
} finally {
|
|
51
|
+
await box.kill()
|
|
52
|
+
}
|
|
53
|
+
```
|
|
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`.
|
|
56
|
+
|
|
57
|
+
Save and restore a private snapshot with the required snapshot scopes:
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
const source = await Sandbox.create('universal', { timeoutMs: 15 * 60_000, onTimeout: 'kill' })
|
|
61
|
+
let saved: string | undefined
|
|
62
|
+
let restored: Sandbox | undefined
|
|
63
|
+
try {
|
|
64
|
+
await source.files.write('/data/home/proof.txt', 'persisted')
|
|
65
|
+
await source.stop()
|
|
66
|
+
saved = (await source.createSnapshot({ name: 'prepared-workspace' })).id
|
|
67
|
+
restored = await Sandbox.create(saved, { timeoutMs: 15 * 60_000, onTimeout: 'kill' })
|
|
68
|
+
console.log(await restored.files.read('/data/home/proof.txt'))
|
|
69
|
+
} finally {
|
|
70
|
+
try {
|
|
71
|
+
if (restored) await restored.kill()
|
|
72
|
+
} finally {
|
|
73
|
+
try {
|
|
74
|
+
if (saved) await Sandbox.deleteSnapshot(saved)
|
|
75
|
+
} finally {
|
|
76
|
+
await source.kill()
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
`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
|
+
|
|
84
|
+
## CLI and REST
|
|
85
|
+
|
|
86
|
+
```sh
|
|
87
|
+
curl -fsSL "$INSTABOX_API_URL/install.sh" | sh
|
|
88
|
+
instabox templates
|
|
89
|
+
instabox create --name dev --template universal --timeout 30m
|
|
90
|
+
instabox exec dev -- uname -a
|
|
91
|
+
instabox ssh dev
|
|
92
|
+
instabox suspend dev
|
|
93
|
+
instabox resume dev
|
|
94
|
+
instabox rm dev
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Use `instabox help` for the full command surface. With `INSTABOX_API_KEY` set, no interactive login is needed.
|
|
98
|
+
|
|
99
|
+
REST uses `X-API-Key` and the API origin above. Discover templates with `GET /v1/templates`; create with `POST /v1/machines` and `{ "name": "dev", "templateId": "universal" }`. To restore, send `snapshotId` in place of `templateId`.
|
|
100
|
+
|
|
101
|
+
Lifecycle calls and PATCH need a fresh `Idempotency-Key`, reused only when retrying that same request. Lifecycle calls return an operation. Poll `GET /v1/operations/{id}?wait=25s` until `succeeded` or `failed`; report the operation error on failure. Exec returns its result directly and must not be retried automatically.
|
|
102
|
+
|
|
103
|
+
Snapshots: `POST /v1/machines/{id}/snapshots` saves a stopped machine with `{ "name": "my-setup" }`; `GET /v1/snapshots` returns `{ "snapshots": [...] }`; `GET /v1/snapshots/{id}` reads one; `DELETE /v1/snapshots/{id}` deletes one. Snapshot POST and DELETE require an `Idempotency-Key`. Save returns `201` with the snapshot directly; delete returns `204`. Neither returns an operation. Delete the machines and snapshots created for a task.
|
|
104
|
+
|
|
105
|
+
For SSH certificates, use `box.sshCredentials(publicKey)`. Use its returned host, port, username, certificate and `knownHostsLine`; do not hardcode SSH endpoints or disable host verification.
|
|
106
|
+
|
|
107
|
+
## Limits and errors
|
|
108
|
+
|
|
109
|
+
- `CommandExitError` carries stdout, stderr, exitCode, timedOut and truncated. Exec output is buffered and capped at 1 MiB per stream; commands may run for at most 600 seconds. Background commands return a PID and `kill()` handle.
|
|
110
|
+
- Files are limited to 10 MiB per read/write and transferred in chunks. A file whose size changes during a read fails; avoid concurrent writes to files being read.
|
|
111
|
+
- `InstaboxAuthError` covers 401/403; `InstaboxQuotaError` covers 429; `InstaboxTimeoutError` covers request/operation deadlines. `InstaboxError` carries status, code, requestId and operationId.
|
|
112
|
+
- Inspect `GET /v1/usage` for account quotas. Do not assume fixed machine or resource limits.
|
|
113
|
+
- Metadata and saved disks may contain plaintext. Do not save credentials into snapshots or machines that will be forked.
|
|
114
|
+
- Timeout is a one-shot deadline, not inactivity detection; resume does not reset it. Set a new timeout after resuming when needed.
|
|
115
|
+
|
|
116
|
+
See [the package README](../../README.md) for the full SDK reference.
|