@insforge/instabox-sdk 0.2.0 → 0.2.2
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/README.md +22 -12
- package/dist/index.cjs +67 -21
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +25 -14
- package/dist/index.d.ts +25 -14
- package/dist/index.js +67 -21
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/skills/instabox/SKILL.md +4 -4
package/README.md
CHANGED
|
@@ -56,11 +56,7 @@ await sandbox.kill()
|
|
|
56
56
|
|
|
57
57
|
```ts
|
|
58
58
|
const sandbox = await Sandbox.create('universal', {
|
|
59
|
-
name: 'my-box', // default sbx-<random
|
|
60
|
-
vcpus: 4, // defaults: the template's
|
|
61
|
-
memMiB: 8192,
|
|
62
|
-
rootDiskGiB: 32,
|
|
63
|
-
diskGiB: 20, // persistent /data disk
|
|
59
|
+
name: 'my-box', // default sbx-<random>; lowercase letters, digits and '-'
|
|
64
60
|
envs: { NODE_ENV: 'development' }, // applied to every commands.run of this object
|
|
65
61
|
metadata: { userId: 'u_42' }, // labels stored with the sandbox (plaintext: not for secrets)
|
|
66
62
|
vault: false, // for a sandbox made for someone else: none of the account's Vault items
|
|
@@ -72,6 +68,8 @@ const sandbox = await Sandbox.create('universal', {
|
|
|
72
68
|
console.log(sandbox.sandboxId) // m_...
|
|
73
69
|
```
|
|
74
70
|
|
|
71
|
+
Sizes are fixed by the service: 4 vCPU, 8 GiB memory, a 16 GiB root disk and a 20 GiB `/data` disk. The `vcpus`, `memMiB`, `diskGiB` and `rootDiskGiB` options are for other deployments; `api.instabox.sh` refuses them (`400 spec_not_allowed`).
|
|
72
|
+
|
|
75
73
|
`create` waits for the create operation to succeed. `getInfo().machine.runtime.ready` reports guest readiness. `archiveMs` is optional (60 seconds to 24 hours) and becomes `getInfo().archiveAt`; its deadline is independent of the pause/kill timeout.
|
|
76
74
|
|
|
77
75
|
## Commands
|
|
@@ -100,9 +98,9 @@ try {
|
|
|
100
98
|
}
|
|
101
99
|
```
|
|
102
100
|
|
|
103
|
-
The API returns `timedOut` and `truncated` flags. Each output stream is limited to 1 MiB. Command timeouts are 1–600 seconds; the default HTTP request deadline allows an additional 30 seconds for the result. An explicit `requestTimeoutMs` overrides that default. Output is not streamed: `onStdout` and `onStderr` are called once with the full output after the command finishes.
|
|
101
|
+
The API returns `timedOut` and `truncated` flags. A command that runs past `timeoutMs` throws `CommandExitError` with `timedOut: true` and `exitCode` 124. Each output stream is limited to 1 MiB, and `stdin` to 1 MiB (UTF-8; a longer one throws before the request). Command timeouts are 1–600 seconds; the default HTTP request deadline allows an additional 30 seconds for the result. An explicit `requestTimeoutMs` overrides that default. Output is not streamed: `onStdout` and `onStderr` are called once with the full output after the command finishes.
|
|
104
102
|
|
|
105
|
-
`background: true` starts the command detached and returns `{ pid, kill() }` right away
|
|
103
|
+
`background: true` starts the command detached, in its own process group, and returns `{ pid, kill() }` right away. `kill()` sends SIGTERM to the command and everything it started; it returns false if they had all exited. Background commands need `setsid` in the sandbox.
|
|
106
104
|
|
|
107
105
|
```ts
|
|
108
106
|
const server = await sandbox.commands.run('node server.js', { background: true })
|
|
@@ -120,7 +118,7 @@ await sandbox.files.exists('/data/home/app.js') // boolean
|
|
|
120
118
|
await sandbox.files.remove('/data/home/tmp') // files or directories
|
|
121
119
|
```
|
|
122
120
|
|
|
123
|
-
Files go over the command channel as base64 in bounded chunks. Each read or write is capped at 10 MiB. Truncated file output raises an error. `write` creates parent directories and replaces the file atomically. HOME is `/data/home`, on the persistent disk.
|
|
121
|
+
Files go over the command channel as base64 in bounded chunks. Each read or write is capped at 10 MiB. Truncated file output raises an error. `write` creates parent directories and replaces the file atomically; writing to a path that is a directory throws `InstaboxError` with code `is_a_directory`. Relative paths are relative to HOME. HOME is `/data/home`, on the persistent disk.
|
|
124
122
|
|
|
125
123
|
## Lifecycle
|
|
126
124
|
|
|
@@ -183,10 +181,9 @@ An item's selector limits it to sandboxes whose metadata has those labels, so `m
|
|
|
183
181
|
|
|
184
182
|
## Snapshots
|
|
185
183
|
|
|
186
|
-
Save a
|
|
184
|
+
Save a sandbox's root and `/data` disks as a private snapshot. The sandbox may be running or stopped. From a running sandbox the snapshot comes back with `status: 'pending'` and turns `ready` once saved; `Sandbox.create(snapshot.id)` waits for that (it retries the server's `409 operation_conflict` "still being saved", up to `operationTimeoutMs`). `rootOnly: true` saves only the root disk. Snapshot methods use `/v1/snapshots` and `/v1/machines/{id}/snapshots`.
|
|
187
185
|
|
|
188
186
|
```ts
|
|
189
|
-
await sandbox.stop()
|
|
190
187
|
const snapshot = await sandbox.createSnapshot({ name: 'my-setup', description: 'Prepared workspace' })
|
|
191
188
|
const restored = await Sandbox.create(snapshot.id)
|
|
192
189
|
try {
|
|
@@ -217,14 +214,14 @@ appendFileSync(`${homedir()}/.ssh/known_hosts`, ssh.knownHostsLine + '\n')
|
|
|
217
214
|
console.log(`ssh -p ${ssh.port} ${ssh.username}@${ssh.host}`)
|
|
218
215
|
```
|
|
219
216
|
|
|
220
|
-
The sandbox must be running. Certificates last 1 hour by default (24 hours
|
|
217
|
+
The sandbox must be running. Certificates last 1 hour by default; `ttlSeconds` takes 1 to 86 400 (24 hours), other values throw before the request. Pausing or stopping prevents connections while the sandbox is not running; an unexpired certificate can be used again after resume or start. Deleting the sandbox or revoking the API key that issued the certificate revokes access.
|
|
221
218
|
|
|
222
219
|
## Errors
|
|
223
220
|
|
|
224
221
|
| Class | When |
|
|
225
222
|
| ---------------------- | ------------------------------------------------------------------------------------------------------------- |
|
|
226
223
|
| `InstaboxError` | Base class. `status`, `code`, `message`, `requestId`, `retryable`, `operationId` from the API error envelope. |
|
|
227
|
-
| `InstaboxAuthError` | 401 / 403:
|
|
224
|
+
| `InstaboxAuthError` | 401 / 403: invalid or revoked API key, or no access. No API key at all: code `missing_api_key`, status 0. |
|
|
228
225
|
| `InstaboxQuotaError` | 429 `quota_exceeded`, for example the machine limit. |
|
|
229
226
|
| `InstaboxTimeoutError` | A request or an operation took too long. |
|
|
230
227
|
| `CommandExitError` | A command exited non-zero. Carries `stdout`, `stderr`, `exitCode`. |
|
|
@@ -253,3 +250,16 @@ npm run build
|
|
|
253
250
|
npm test
|
|
254
251
|
INSTABOX_LIVE=1 INSTABOX_API_KEY=... npm run test:live # creates and deletes one real machine
|
|
255
252
|
```
|
|
253
|
+
|
|
254
|
+
## Releasing
|
|
255
|
+
|
|
256
|
+
Bump `version` in `package.json` in a PR. After it merges, tag that commit and push the tag:
|
|
257
|
+
|
|
258
|
+
```bash
|
|
259
|
+
git tag v0.2.1 && git push origin v0.2.1
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
The Release workflow checks that the tag is the package's version and that it is not on npm yet, runs the
|
|
263
|
+
checks and publishes through npm trusted publishing (OIDC): no token is stored anywhere. Once, a maintainer
|
|
264
|
+
adds the trusted publisher on npmjs.com (the package's Settings, Trusted Publisher, GitHub Actions: organization
|
|
265
|
+
`InsForge`, repository `instabox-sdk`, workflow `release.yml`, no environment).
|
package/dist/index.cjs
CHANGED
|
@@ -31,6 +31,7 @@ __export(index_exports, {
|
|
|
31
31
|
InstaboxQuotaError: () => InstaboxQuotaError,
|
|
32
32
|
InstaboxTimeoutError: () => InstaboxTimeoutError,
|
|
33
33
|
MAX_FILE_BYTES: () => MAX_FILE_BYTES,
|
|
34
|
+
MAX_STDIN_BYTES: () => MAX_STDIN_BYTES,
|
|
34
35
|
Sandbox: () => Sandbox
|
|
35
36
|
});
|
|
36
37
|
module.exports = __toCommonJS(index_exports);
|
|
@@ -138,6 +139,7 @@ function readEnv(name) {
|
|
|
138
139
|
}
|
|
139
140
|
|
|
140
141
|
// src/commands.ts
|
|
142
|
+
var MAX_STDIN_BYTES = 1024 * 1024;
|
|
141
143
|
var Commands = class {
|
|
142
144
|
/** @internal */
|
|
143
145
|
constructor(http, sandboxId, defaultEnvs) {
|
|
@@ -150,7 +152,7 @@ var Commands = class {
|
|
|
150
152
|
defaultEnvs;
|
|
151
153
|
async run(cmd, opts = {}) {
|
|
152
154
|
if (opts.background) {
|
|
153
|
-
const wrapped = `nohup sh -c ${shellQuote(cmd)} >/dev/null 2>&1 & echo $!`;
|
|
155
|
+
const wrapped = `command -v setsid >/dev/null || { echo 'setsid not found' >&2; exit 127; }; setsid nohup sh -c ${shellQuote(cmd)} >/dev/null 2>&1 & echo $!`;
|
|
154
156
|
if (opts.stdin !== void 0)
|
|
155
157
|
throw new InstaboxError("stdin is not supported for background commands", { code: "bad_request" });
|
|
156
158
|
const r2 = await this.exec(wrapped, { cwd: opts.cwd, envs: opts.envs, timeoutMs: opts.timeoutMs });
|
|
@@ -160,7 +162,7 @@ var Commands = class {
|
|
|
160
162
|
throw new InstaboxError("exec returned an invalid background PID", { code: "invalid_response" });
|
|
161
163
|
return {
|
|
162
164
|
pid,
|
|
163
|
-
kill: async () => (await this.exec(`kill
|
|
165
|
+
kill: async () => (await this.exec(`kill -s TERM -- -${pid}`)).exitCode === 0
|
|
164
166
|
};
|
|
165
167
|
}
|
|
166
168
|
const r = await this.exec(cmd, opts);
|
|
@@ -175,7 +177,12 @@ var Commands = class {
|
|
|
175
177
|
const body = { cmd };
|
|
176
178
|
if (opts.cwd !== void 0) body.cwd = opts.cwd;
|
|
177
179
|
if (Object.keys(envs).length) body.envs = envs;
|
|
178
|
-
if (opts.stdin !== void 0)
|
|
180
|
+
if (opts.stdin !== void 0) {
|
|
181
|
+
if (new TextEncoder().encode(opts.stdin).length > MAX_STDIN_BYTES) {
|
|
182
|
+
throw new InstaboxError(`stdin is longer than ${MAX_STDIN_BYTES} bytes`, { code: "bad_request" });
|
|
183
|
+
}
|
|
184
|
+
body.stdin = opts.stdin;
|
|
185
|
+
}
|
|
179
186
|
if (opts.timeoutMs !== void 0) {
|
|
180
187
|
if (!Number.isFinite(opts.timeoutMs) || opts.timeoutMs <= 0 || opts.timeoutMs > 6e5) {
|
|
181
188
|
throw new InstaboxError("command timeoutMs must be greater than 0 and at most 600 000", { code: "bad_request" });
|
|
@@ -215,7 +222,7 @@ var Files = class {
|
|
|
215
222
|
}
|
|
216
223
|
commands;
|
|
217
224
|
async read(path, opts = {}) {
|
|
218
|
-
const p =
|
|
225
|
+
const p = arg(path);
|
|
219
226
|
const r = await this.commands.exec(
|
|
220
227
|
`[ -f ${p} ] || { echo "no such file: "${p} >&2; exit 3; }; s=$(wc -c < ${p}) || exit 1; [ "$s" -le ${MAX_FILE_BYTES} ] || { echo "file too large: $s bytes" >&2; exit 4; }; printf '%s' "$s"`
|
|
221
228
|
);
|
|
@@ -244,7 +251,10 @@ var Files = class {
|
|
|
244
251
|
}
|
|
245
252
|
return opts.format === "bytes" ? bytes : new TextDecoder().decode(bytes);
|
|
246
253
|
}
|
|
247
|
-
/**
|
|
254
|
+
/**
|
|
255
|
+
* Writes a file, creating parent directories. Replaces the file atomically (temp file + rename).
|
|
256
|
+
* Throws `is_a_directory` when `path` is a directory.
|
|
257
|
+
*/
|
|
248
258
|
async write(path, data) {
|
|
249
259
|
const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
|
|
250
260
|
if (bytes.length > MAX_FILE_BYTES) {
|
|
@@ -252,23 +262,24 @@ var Files = class {
|
|
|
252
262
|
code: "file_too_large"
|
|
253
263
|
});
|
|
254
264
|
}
|
|
255
|
-
const p =
|
|
256
|
-
const tmp =
|
|
265
|
+
const p = arg(path);
|
|
266
|
+
const tmp = arg(`${path}.instabox-${Math.random().toString(36).slice(2, 10)}.tmp`);
|
|
257
267
|
const b64 = bytesToBase64(bytes);
|
|
258
268
|
const chunks = [];
|
|
259
269
|
for (let i = 0; i < b64.length; i += WRITE_CHUNK_B64) chunks.push(b64.slice(i, i + WRITE_CHUNK_B64));
|
|
260
270
|
if (chunks.length === 0) chunks.push("");
|
|
271
|
+
const notDir = `if [ -d ${p} ]; then echo "is a directory: "${p} >&2; exit 21; fi; `;
|
|
261
272
|
try {
|
|
262
273
|
for (let i = 0; i < chunks.length; i++) {
|
|
263
274
|
const redirect = i === 0 ? ">" : ">>";
|
|
264
|
-
const prefix = i === 0 ?
|
|
275
|
+
const prefix = i === 0 ? `${notDir}mkdir -p -- "$(dirname -- ${p})" && ` : "";
|
|
265
276
|
const r2 = await this.commands.exec(`${prefix}printf '%s' '${chunks[i]}' | base64 -d ${redirect} ${tmp}`);
|
|
266
|
-
if (r2.exitCode !== 0) throw
|
|
277
|
+
if (r2.exitCode !== 0) throw writeError(r2, path);
|
|
267
278
|
}
|
|
268
|
-
const r = await this.commands.exec(
|
|
269
|
-
if (r.exitCode !== 0) throw
|
|
279
|
+
const r = await this.commands.exec(`${notDir}mv -f -- ${tmp} ${p}`);
|
|
280
|
+
if (r.exitCode !== 0) throw writeError(r, path);
|
|
270
281
|
} catch (err) {
|
|
271
|
-
await this.commands.exec(`rm -f ${tmp}`).catch(() => {
|
|
282
|
+
await this.commands.exec(`rm -f -- ${tmp}`).catch(() => {
|
|
272
283
|
});
|
|
273
284
|
throw err;
|
|
274
285
|
}
|
|
@@ -276,7 +287,7 @@ var Files = class {
|
|
|
276
287
|
}
|
|
277
288
|
/** Lists the entries of a directory (not recursive). */
|
|
278
289
|
async list(path) {
|
|
279
|
-
const p =
|
|
290
|
+
const p = arg(path);
|
|
280
291
|
const r = await this.commands.exec(
|
|
281
292
|
`[ -d ${p} ] || { echo "no such directory: "${p} >&2; exit 3; }; cd ${p} && for f in .* *; do case "$f" in .|..) continue ;; esac; [ -e "$f" ] || [ -L "$f" ] || continue; if [ -d "$f" ]; then printf 'd\\t%s\\0' "$f"; else printf 'f\\t%s\\0' "$f"; fi; done`
|
|
282
293
|
);
|
|
@@ -291,15 +302,22 @@ var Files = class {
|
|
|
291
302
|
}
|
|
292
303
|
/** Removes a file or a directory (recursively). Missing paths are fine. */
|
|
293
304
|
async remove(path) {
|
|
294
|
-
const r = await this.commands.exec(`rm -rf -- ${
|
|
305
|
+
const r = await this.commands.exec(`rm -rf -- ${arg(path)}`);
|
|
295
306
|
if (r.exitCode !== 0) throw new CommandExitError(r);
|
|
296
307
|
}
|
|
297
308
|
/** True if a file or directory exists at `path`. */
|
|
298
309
|
async exists(path) {
|
|
299
|
-
const r = await this.commands.exec(`test -e ${
|
|
310
|
+
const r = await this.commands.exec(`test -e ${arg(path)}`);
|
|
300
311
|
return r.exitCode === 0;
|
|
301
312
|
}
|
|
302
313
|
};
|
|
314
|
+
function arg(path) {
|
|
315
|
+
return shellQuote(path.startsWith("-") ? `./${path}` : path);
|
|
316
|
+
}
|
|
317
|
+
function writeError(result, path) {
|
|
318
|
+
if (result.exitCode === 21) return new InstaboxError(`is a directory: ${path}`, { code: "is_a_directory" });
|
|
319
|
+
return new CommandExitError(result);
|
|
320
|
+
}
|
|
303
321
|
function ensureComplete(result) {
|
|
304
322
|
if (result.exitCode !== 0) throw new CommandExitError(result);
|
|
305
323
|
if (result.truncated) throw new InstaboxError("file command output was truncated", { code: "output_truncated" });
|
|
@@ -319,7 +337,7 @@ var HttpClient = class {
|
|
|
319
337
|
constructor(opts = {}) {
|
|
320
338
|
const apiKey = opts.apiKey ?? readEnv("INSTABOX_API_KEY");
|
|
321
339
|
if (!apiKey) {
|
|
322
|
-
throw new
|
|
340
|
+
throw new InstaboxAuthError(
|
|
323
341
|
"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).",
|
|
324
342
|
{ code: "missing_api_key" }
|
|
325
343
|
);
|
|
@@ -518,7 +536,7 @@ var Sandbox = class _Sandbox {
|
|
|
518
536
|
if (opts.onTimeout) body.onTimeout = opts.onTimeout;
|
|
519
537
|
if (opts.metadata) body.metadata = opts.metadata;
|
|
520
538
|
if (opts.vault === false) body.vault = false;
|
|
521
|
-
const op = await http
|
|
539
|
+
const op = await createMachine(http, body);
|
|
522
540
|
const done = await http.waitForOperation(op);
|
|
523
541
|
const machine = await getMachine(http, done.machineId);
|
|
524
542
|
return new _Sandbox(http, machine, opts);
|
|
@@ -574,8 +592,9 @@ var Sandbox = class _Sandbox {
|
|
|
574
592
|
}
|
|
575
593
|
}
|
|
576
594
|
/**
|
|
577
|
-
* Saves
|
|
578
|
-
*
|
|
595
|
+
* Saves the sandbox's disks as a private snapshot. Requires images:write. The sandbox may be running;
|
|
596
|
+
* the snapshot is then returned with `status: 'pending'` and becomes `ready` once saved. For a stopped
|
|
597
|
+
* sandbox it waits first for a recent stop's upload to object storage (see `untilSynced`).
|
|
579
598
|
*/
|
|
580
599
|
async createSnapshot(opts) {
|
|
581
600
|
await this.settle();
|
|
@@ -694,11 +713,18 @@ var Sandbox = class _Sandbox {
|
|
|
694
713
|
/**
|
|
695
714
|
* Issues a short-lived SSH certificate for `publicKey` (authorized_keys format).
|
|
696
715
|
* Connect with `ssh -p <port> -o CertificateFile=<cert> -i <key> <username>@<host>` after adding
|
|
697
|
-
* `knownHostsLine` to known_hosts. The sandbox must be running.
|
|
716
|
+
* `knownHostsLine` to known_hosts. The sandbox must be running. `ttlSeconds`: 1 to 86 400 (24 h);
|
|
717
|
+
* default: the server's (1 h).
|
|
698
718
|
*/
|
|
699
719
|
async sshCredentials(publicKey, opts = {}) {
|
|
700
720
|
const body = { publicKey: publicKey.trim() };
|
|
701
|
-
if (opts.ttlSeconds
|
|
721
|
+
if (opts.ttlSeconds !== void 0) {
|
|
722
|
+
if (!Number.isInteger(opts.ttlSeconds) || opts.ttlSeconds < 1 || opts.ttlSeconds > 86400) {
|
|
723
|
+
const msg = `ttlSeconds must be a whole number between 1 and 86 400 (24 h); got ${opts.ttlSeconds}`;
|
|
724
|
+
throw new InstaboxError(msg, { code: "bad_request" });
|
|
725
|
+
}
|
|
726
|
+
body.ttlSeconds = opts.ttlSeconds;
|
|
727
|
+
}
|
|
702
728
|
const c = await this.http.request("POST", `/v1/machines/${enc(this.sandboxId)}/connections`, { body });
|
|
703
729
|
return {
|
|
704
730
|
host: c.host,
|
|
@@ -764,6 +790,26 @@ async function killMachine(http, id) {
|
|
|
764
790
|
throw err;
|
|
765
791
|
}
|
|
766
792
|
}
|
|
793
|
+
async function createMachine(http, body) {
|
|
794
|
+
const deadline = Date.now() + http.operationTimeoutMs;
|
|
795
|
+
let delay = http.pollIntervalMs;
|
|
796
|
+
for (; ; ) {
|
|
797
|
+
try {
|
|
798
|
+
return await http.request("POST", "/v1/machines", { body });
|
|
799
|
+
} catch (err) {
|
|
800
|
+
const saving = body.snapshotId !== void 0 && err instanceof InstaboxError && err.status === 409 && err.code === "operation_conflict" && /still being saved/i.test(err.message);
|
|
801
|
+
if (!saving) throw err;
|
|
802
|
+
if (Date.now() + delay > deadline) {
|
|
803
|
+
throw new InstaboxTimeoutError(
|
|
804
|
+
`snapshot ${String(body.snapshotId)} was still being saved after ${http.operationTimeoutMs} ms`,
|
|
805
|
+
{ code: "operation_timeout", cause: err }
|
|
806
|
+
);
|
|
807
|
+
}
|
|
808
|
+
await sleep(delay);
|
|
809
|
+
delay = Math.min(delay * 2, 2e3);
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
}
|
|
767
813
|
async function defaultTemplate(http) {
|
|
768
814
|
const { templates } = await http.request("GET", "/v1/templates");
|
|
769
815
|
return templates.some((t) => t.id === DEFAULT_TEMPLATE && !t.hidden) ? DEFAULT_TEMPLATE : FALLBACK_TEMPLATE;
|