@insforge/instabox-sdk 0.0.0-stage → 0.1.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/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
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,700 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
CommandExitError: () => CommandExitError,
|
|
24
|
+
Commands: () => Commands,
|
|
25
|
+
DEFAULT_API_URL: () => DEFAULT_API_URL,
|
|
26
|
+
DEFAULT_TEMPLATE: () => DEFAULT_TEMPLATE,
|
|
27
|
+
Files: () => Files,
|
|
28
|
+
InstaboxAuthError: () => InstaboxAuthError,
|
|
29
|
+
InstaboxError: () => InstaboxError,
|
|
30
|
+
InstaboxQuotaError: () => InstaboxQuotaError,
|
|
31
|
+
InstaboxTimeoutError: () => InstaboxTimeoutError,
|
|
32
|
+
MAX_FILE_BYTES: () => MAX_FILE_BYTES,
|
|
33
|
+
Sandbox: () => Sandbox
|
|
34
|
+
});
|
|
35
|
+
module.exports = __toCommonJS(index_exports);
|
|
36
|
+
|
|
37
|
+
// src/errors.ts
|
|
38
|
+
var InstaboxError = class extends Error {
|
|
39
|
+
/** HTTP status, or 0 when the error did not come from an HTTP response (for example a failed operation). */
|
|
40
|
+
status;
|
|
41
|
+
/** Machine-readable code from the API, e.g. `not_found`, `operation_conflict`. */
|
|
42
|
+
code;
|
|
43
|
+
requestId;
|
|
44
|
+
retryable;
|
|
45
|
+
/** For `operation_conflict` the active operation, for a failed operation its ID. */
|
|
46
|
+
operationId;
|
|
47
|
+
constructor(message, init = {}) {
|
|
48
|
+
super(message, init.cause === void 0 ? void 0 : { cause: init.cause });
|
|
49
|
+
this.name = new.target.name;
|
|
50
|
+
this.status = init.status ?? 0;
|
|
51
|
+
this.code = init.code ?? "unknown";
|
|
52
|
+
this.requestId = init.requestId;
|
|
53
|
+
this.retryable = init.retryable ?? false;
|
|
54
|
+
this.operationId = init.operationId;
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
var InstaboxAuthError = class extends InstaboxError {
|
|
58
|
+
};
|
|
59
|
+
var InstaboxQuotaError = class extends InstaboxError {
|
|
60
|
+
};
|
|
61
|
+
var InstaboxTimeoutError = class extends InstaboxError {
|
|
62
|
+
};
|
|
63
|
+
var CommandExitError = class extends InstaboxError {
|
|
64
|
+
stdout;
|
|
65
|
+
stderr;
|
|
66
|
+
exitCode;
|
|
67
|
+
timedOut;
|
|
68
|
+
truncated;
|
|
69
|
+
error;
|
|
70
|
+
constructor(result) {
|
|
71
|
+
const tail = result.stderr.trim().split("\n").slice(-1)[0] ?? "";
|
|
72
|
+
super(`command exited with code ${result.exitCode}${tail ? `: ${tail}` : ""}`, { code: "command_exit" });
|
|
73
|
+
this.stdout = result.stdout;
|
|
74
|
+
this.stderr = result.stderr;
|
|
75
|
+
this.exitCode = result.exitCode;
|
|
76
|
+
this.timedOut = result.timedOut;
|
|
77
|
+
this.truncated = result.truncated;
|
|
78
|
+
this.error = result.error;
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
function errorFromResponse(status, body, fallbackMessage) {
|
|
82
|
+
const env = body?.error;
|
|
83
|
+
const init = {
|
|
84
|
+
status,
|
|
85
|
+
code: typeof env?.code === "string" ? env.code : `http_${status}`,
|
|
86
|
+
requestId: typeof env?.requestId === "string" ? env.requestId : void 0,
|
|
87
|
+
retryable: typeof env?.retryable === "boolean" ? env.retryable : status >= 502 && status <= 504,
|
|
88
|
+
operationId: typeof env?.operationId === "string" ? env.operationId : null
|
|
89
|
+
};
|
|
90
|
+
const message = typeof env?.message === "string" && env.message ? env.message : fallbackMessage;
|
|
91
|
+
if (status === 401 || status === 403) return new InstaboxAuthError(message, init);
|
|
92
|
+
if (status === 429) return new InstaboxQuotaError(message, init);
|
|
93
|
+
return new InstaboxError(message, init);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// src/util.ts
|
|
97
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
98
|
+
function uuid() {
|
|
99
|
+
const c = globalThis.crypto;
|
|
100
|
+
if (c && typeof c.randomUUID === "function") return c.randomUUID();
|
|
101
|
+
const b = new Uint8Array(16);
|
|
102
|
+
if (c && typeof c.getRandomValues === "function") c.getRandomValues(b);
|
|
103
|
+
else for (let i = 0; i < 16; i++) b[i] = Math.floor(Math.random() * 256);
|
|
104
|
+
b[6] = b[6] & 15 | 64;
|
|
105
|
+
b[8] = b[8] & 63 | 128;
|
|
106
|
+
const h = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
107
|
+
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
|
|
108
|
+
}
|
|
109
|
+
function randomSuffix(len = 8) {
|
|
110
|
+
const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
|
|
111
|
+
return Array.from({ length: len }, () => alphabet[Math.floor(Math.random() * alphabet.length)]).join("");
|
|
112
|
+
}
|
|
113
|
+
function shellQuote(s) {
|
|
114
|
+
return `'${s.replace(/'/g, `'\\''`)}'`;
|
|
115
|
+
}
|
|
116
|
+
function bytesToBase64(bytes) {
|
|
117
|
+
let bin = "";
|
|
118
|
+
for (let i = 0; i < bytes.length; i += 32768) {
|
|
119
|
+
bin += String.fromCharCode(...bytes.subarray(i, i + 32768));
|
|
120
|
+
}
|
|
121
|
+
return btoa(bin);
|
|
122
|
+
}
|
|
123
|
+
function base64ToBytes(b64) {
|
|
124
|
+
const bin = atob(b64.replace(/\s+/g, ""));
|
|
125
|
+
const out = new Uint8Array(bin.length);
|
|
126
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
127
|
+
return out;
|
|
128
|
+
}
|
|
129
|
+
function readEnv(name) {
|
|
130
|
+
const g = globalThis;
|
|
131
|
+
try {
|
|
132
|
+
const v = g.process?.env?.[name] ?? g.Deno?.env?.get(name);
|
|
133
|
+
return v === "" ? void 0 : v;
|
|
134
|
+
} catch {
|
|
135
|
+
return void 0;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// src/commands.ts
|
|
140
|
+
var Commands = class {
|
|
141
|
+
/** @internal */
|
|
142
|
+
constructor(http, sandboxId, defaultEnvs) {
|
|
143
|
+
this.http = http;
|
|
144
|
+
this.sandboxId = sandboxId;
|
|
145
|
+
this.defaultEnvs = defaultEnvs;
|
|
146
|
+
}
|
|
147
|
+
http;
|
|
148
|
+
sandboxId;
|
|
149
|
+
defaultEnvs;
|
|
150
|
+
async run(cmd, opts = {}) {
|
|
151
|
+
if (opts.background) {
|
|
152
|
+
const wrapped = `nohup sh -c ${shellQuote(cmd)} >/dev/null 2>&1 & echo $!`;
|
|
153
|
+
if (opts.stdin !== void 0)
|
|
154
|
+
throw new InstaboxError("stdin is not supported for background commands", { code: "bad_request" });
|
|
155
|
+
const r2 = await this.exec(wrapped, { cwd: opts.cwd, envs: opts.envs, timeoutMs: opts.timeoutMs });
|
|
156
|
+
if (r2.exitCode !== 0) throw new CommandExitError(r2);
|
|
157
|
+
const pid = Number.parseInt(r2.stdout.trim(), 10);
|
|
158
|
+
if (!Number.isSafeInteger(pid) || pid <= 0)
|
|
159
|
+
throw new InstaboxError("exec returned an invalid background PID", { code: "invalid_response" });
|
|
160
|
+
return {
|
|
161
|
+
pid,
|
|
162
|
+
kill: async () => (await this.exec(`kill ${pid}`)).exitCode === 0
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
const r = await this.exec(cmd, opts);
|
|
166
|
+
if (opts.onStdout && r.stdout) await opts.onStdout(r.stdout);
|
|
167
|
+
if (opts.onStderr && r.stderr) await opts.onStderr(r.stderr);
|
|
168
|
+
if (r.exitCode !== 0) throw new CommandExitError(r);
|
|
169
|
+
return r;
|
|
170
|
+
}
|
|
171
|
+
/** @internal Raw exec: never throws on a non-zero exit code. */
|
|
172
|
+
async exec(cmd, opts = {}) {
|
|
173
|
+
const envs = { ...this.defaultEnvs, ...opts.envs };
|
|
174
|
+
const body = { cmd };
|
|
175
|
+
if (opts.cwd !== void 0) body.cwd = opts.cwd;
|
|
176
|
+
if (Object.keys(envs).length) body.envs = envs;
|
|
177
|
+
if (opts.stdin !== void 0) body.stdin = opts.stdin;
|
|
178
|
+
if (opts.timeoutMs !== void 0) {
|
|
179
|
+
if (!Number.isFinite(opts.timeoutMs) || opts.timeoutMs <= 0 || opts.timeoutMs > 6e5) {
|
|
180
|
+
throw new InstaboxError("command timeoutMs must be greater than 0 and at most 600 000", { code: "bad_request" });
|
|
181
|
+
}
|
|
182
|
+
body.timeoutSeconds = Math.ceil(opts.timeoutMs / 1e3);
|
|
183
|
+
}
|
|
184
|
+
const res = await this.http.request(
|
|
185
|
+
"POST",
|
|
186
|
+
`/v1/machines/${encodeURIComponent(this.sandboxId)}/exec`,
|
|
187
|
+
{
|
|
188
|
+
body,
|
|
189
|
+
retry: false,
|
|
190
|
+
idempotent: false,
|
|
191
|
+
timeoutMs: (Number(body.timeoutSeconds) || 60) * 1e3 + 3e4
|
|
192
|
+
}
|
|
193
|
+
);
|
|
194
|
+
const out = {
|
|
195
|
+
stdout: res.stdout,
|
|
196
|
+
stderr: res.stderr,
|
|
197
|
+
exitCode: res.exitCode,
|
|
198
|
+
timedOut: res.timedOut,
|
|
199
|
+
truncated: res.truncated
|
|
200
|
+
};
|
|
201
|
+
if (res.error) out.error = res.error;
|
|
202
|
+
return out;
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
// src/files.ts
|
|
207
|
+
var MAX_FILE_BYTES = 10 * 1024 * 1024;
|
|
208
|
+
var WRITE_CHUNK_B64 = 48 * 1024;
|
|
209
|
+
var READ_CHUNK_BYTES = 512 * 1024;
|
|
210
|
+
var Files = class {
|
|
211
|
+
/** @internal */
|
|
212
|
+
constructor(commands) {
|
|
213
|
+
this.commands = commands;
|
|
214
|
+
}
|
|
215
|
+
commands;
|
|
216
|
+
async read(path, opts = {}) {
|
|
217
|
+
const p = shellQuote(path);
|
|
218
|
+
const r = await this.commands.exec(
|
|
219
|
+
`[ -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"`
|
|
220
|
+
);
|
|
221
|
+
if (r.exitCode === 3) throw new InstaboxError(`file not found: ${path}`, { status: 404, code: "not_found" });
|
|
222
|
+
if (r.exitCode === 4) {
|
|
223
|
+
throw new InstaboxError(`${path} is larger than the ${MAX_FILE_BYTES}-byte limit of files.read`, {
|
|
224
|
+
code: "file_too_large"
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
ensureComplete(r);
|
|
228
|
+
const size = Number(r.stdout.trim());
|
|
229
|
+
if (!Number.isSafeInteger(size) || size < 0 || size > MAX_FILE_BYTES) {
|
|
230
|
+
throw new InstaboxError("invalid file size returned by exec", { code: "invalid_response" });
|
|
231
|
+
}
|
|
232
|
+
const bytes = new Uint8Array(size);
|
|
233
|
+
for (let offset = 0; offset < size; offset += READ_CHUNK_BYTES) {
|
|
234
|
+
const chunk = await this.commands.exec(
|
|
235
|
+
`dd if=${p} bs=${READ_CHUNK_BYTES} skip=${offset / READ_CHUNK_BYTES} count=1 2>/dev/null | base64 | tr -d '\\n'`
|
|
236
|
+
);
|
|
237
|
+
ensureComplete(chunk);
|
|
238
|
+
const data = base64ToBytes(chunk.stdout);
|
|
239
|
+
if (data.length !== Math.min(READ_CHUNK_BYTES, size - offset)) {
|
|
240
|
+
throw new InstaboxError(`file size changed while reading: ${path}`, { code: "file_changed" });
|
|
241
|
+
}
|
|
242
|
+
bytes.set(data, offset);
|
|
243
|
+
}
|
|
244
|
+
return opts.format === "bytes" ? bytes : new TextDecoder().decode(bytes);
|
|
245
|
+
}
|
|
246
|
+
/** Writes a file, creating parent directories. Replaces the file atomically (temp file + rename). */
|
|
247
|
+
async write(path, data) {
|
|
248
|
+
const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
|
|
249
|
+
if (bytes.length > MAX_FILE_BYTES) {
|
|
250
|
+
throw new InstaboxError(`data is larger than the ${MAX_FILE_BYTES}-byte limit of files.write`, {
|
|
251
|
+
code: "file_too_large"
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
const p = shellQuote(path);
|
|
255
|
+
const tmp = shellQuote(`${path}.instabox-${Math.random().toString(36).slice(2, 10)}.tmp`);
|
|
256
|
+
const b64 = bytesToBase64(bytes);
|
|
257
|
+
const chunks = [];
|
|
258
|
+
for (let i = 0; i < b64.length; i += WRITE_CHUNK_B64) chunks.push(b64.slice(i, i + WRITE_CHUNK_B64));
|
|
259
|
+
if (chunks.length === 0) chunks.push("");
|
|
260
|
+
try {
|
|
261
|
+
for (let i = 0; i < chunks.length; i++) {
|
|
262
|
+
const redirect = i === 0 ? ">" : ">>";
|
|
263
|
+
const prefix = i === 0 ? `mkdir -p "$(dirname ${p})" && ` : "";
|
|
264
|
+
const r2 = await this.commands.exec(`${prefix}printf '%s' '${chunks[i]}' | base64 -d ${redirect} ${tmp}`);
|
|
265
|
+
if (r2.exitCode !== 0) throw new CommandExitError(r2);
|
|
266
|
+
}
|
|
267
|
+
const r = await this.commands.exec(`mv -f ${tmp} ${p}`);
|
|
268
|
+
if (r.exitCode !== 0) throw new CommandExitError(r);
|
|
269
|
+
} catch (err) {
|
|
270
|
+
await this.commands.exec(`rm -f ${tmp}`).catch(() => {
|
|
271
|
+
});
|
|
272
|
+
throw err;
|
|
273
|
+
}
|
|
274
|
+
return { path };
|
|
275
|
+
}
|
|
276
|
+
/** Lists the entries of a directory (not recursive). */
|
|
277
|
+
async list(path) {
|
|
278
|
+
const p = shellQuote(path);
|
|
279
|
+
const r = await this.commands.exec(
|
|
280
|
+
`[ -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\\n' "$f"; else printf 'f\\t%s\\n' "$f"; fi; done`
|
|
281
|
+
);
|
|
282
|
+
if (r.exitCode === 3) throw new InstaboxError(`directory not found: ${path}`, { status: 404, code: "not_found" });
|
|
283
|
+
ensureComplete(r);
|
|
284
|
+
const base = path.endsWith("/") ? path.slice(0, -1) : path;
|
|
285
|
+
return r.stdout.split("\n").filter(Boolean).map((line) => {
|
|
286
|
+
const tab = line.indexOf(" ");
|
|
287
|
+
const name = line.slice(tab + 1);
|
|
288
|
+
return { name, path: `${base}/${name}`, type: line.slice(0, tab) === "d" ? "dir" : "file" };
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
/** Removes a file or a directory (recursively). Missing paths are fine. */
|
|
292
|
+
async remove(path) {
|
|
293
|
+
const r = await this.commands.exec(`rm -rf -- ${shellQuote(path)}`);
|
|
294
|
+
if (r.exitCode !== 0) throw new CommandExitError(r);
|
|
295
|
+
}
|
|
296
|
+
/** True if a file or directory exists at `path`. */
|
|
297
|
+
async exists(path) {
|
|
298
|
+
const r = await this.commands.exec(`test -e ${shellQuote(path)}`);
|
|
299
|
+
return r.exitCode === 0;
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
function ensureComplete(result) {
|
|
303
|
+
if (result.exitCode !== 0) throw new CommandExitError(result);
|
|
304
|
+
if (result.truncated) throw new InstaboxError("file command output was truncated", { code: "output_truncated" });
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// src/http.ts
|
|
308
|
+
var DEFAULT_API_URL = "https://api.box.instacloud.com";
|
|
309
|
+
var MAX_RETRIES = 3;
|
|
310
|
+
var HttpClient = class {
|
|
311
|
+
apiUrl;
|
|
312
|
+
operationTimeoutMs;
|
|
313
|
+
apiKey;
|
|
314
|
+
requestTimeoutMs;
|
|
315
|
+
fetchImpl;
|
|
316
|
+
pollIntervalMs;
|
|
317
|
+
retryDelayMs;
|
|
318
|
+
constructor(opts = {}) {
|
|
319
|
+
const apiKey = opts.apiKey ?? readEnv("INSTABOX_API_KEY");
|
|
320
|
+
if (!apiKey) {
|
|
321
|
+
throw new InstaboxError(
|
|
322
|
+
"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).",
|
|
323
|
+
{ code: "missing_api_key" }
|
|
324
|
+
);
|
|
325
|
+
}
|
|
326
|
+
this.apiKey = apiKey;
|
|
327
|
+
this.apiUrl = (opts.apiUrl ?? readEnv("INSTABOX_API_URL") ?? DEFAULT_API_URL).replace(/\/+$/, "");
|
|
328
|
+
this.requestTimeoutMs = opts.requestTimeoutMs;
|
|
329
|
+
this.operationTimeoutMs = opts.operationTimeoutMs ?? 6e5;
|
|
330
|
+
const f = opts.fetch ?? globalThis.fetch;
|
|
331
|
+
if (!f) throw new InstaboxError("No global fetch found; use Node 18+ or pass { fetch }.", { code: "no_fetch" });
|
|
332
|
+
this.fetchImpl = f;
|
|
333
|
+
this.pollIntervalMs = opts.pollIntervalMs ?? 250;
|
|
334
|
+
this.retryDelayMs = opts.retryDelayMs ?? 250;
|
|
335
|
+
}
|
|
336
|
+
async request(method, path, opts = {}) {
|
|
337
|
+
const res = await this.send(method, path, opts);
|
|
338
|
+
if (res.status === 204) return void 0;
|
|
339
|
+
return await res.json();
|
|
340
|
+
}
|
|
341
|
+
/** Performs the request with retries; returns a 2xx response or throws an InstaboxError. */
|
|
342
|
+
async send(method, path, opts = {}) {
|
|
343
|
+
const isRead = method === "GET" || method === "HEAD";
|
|
344
|
+
const idempotent = opts.idempotent ?? !isRead;
|
|
345
|
+
const retry = opts.retry ?? (isRead || idempotent);
|
|
346
|
+
const headers = {
|
|
347
|
+
"X-API-Key": this.apiKey,
|
|
348
|
+
Accept: "application/json"
|
|
349
|
+
};
|
|
350
|
+
if (idempotent) headers["Idempotency-Key"] = uuid();
|
|
351
|
+
let body;
|
|
352
|
+
if (opts.body !== void 0) {
|
|
353
|
+
headers["Content-Type"] = "application/json";
|
|
354
|
+
body = JSON.stringify(opts.body);
|
|
355
|
+
}
|
|
356
|
+
let url = this.apiUrl + path;
|
|
357
|
+
if (opts.query) {
|
|
358
|
+
const q = new URLSearchParams();
|
|
359
|
+
for (const [k, v] of Object.entries(opts.query)) {
|
|
360
|
+
if (Array.isArray(v)) for (const item of v) q.append(k, item);
|
|
361
|
+
else if (v !== void 0) q.set(k, String(v));
|
|
362
|
+
}
|
|
363
|
+
const s = q.toString();
|
|
364
|
+
if (s) url += `?${s}`;
|
|
365
|
+
}
|
|
366
|
+
for (let attempt = 0; ; attempt++) {
|
|
367
|
+
const canRetry = retry && attempt < MAX_RETRIES;
|
|
368
|
+
const ctrl = new AbortController();
|
|
369
|
+
let timedOut = false;
|
|
370
|
+
const timeoutMs = this.requestTimeoutMs ?? opts.timeoutMs ?? 6e4;
|
|
371
|
+
const timer = setTimeout(() => {
|
|
372
|
+
timedOut = true;
|
|
373
|
+
ctrl.abort();
|
|
374
|
+
}, timeoutMs);
|
|
375
|
+
let res;
|
|
376
|
+
try {
|
|
377
|
+
res = await this.fetchImpl(url, { method, headers, body, signal: ctrl.signal });
|
|
378
|
+
} catch (err) {
|
|
379
|
+
clearTimeout(timer);
|
|
380
|
+
if (canRetry) {
|
|
381
|
+
await sleep(this.backoff(attempt));
|
|
382
|
+
continue;
|
|
383
|
+
}
|
|
384
|
+
if (timedOut) {
|
|
385
|
+
throw new InstaboxTimeoutError(`${method} ${path} timed out after ${timeoutMs} ms`, {
|
|
386
|
+
code: "request_timeout",
|
|
387
|
+
cause: err
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
throw new InstaboxError(`${method} ${path} failed: ${err?.message ?? String(err)}`, {
|
|
391
|
+
code: "network_error",
|
|
392
|
+
retryable: true,
|
|
393
|
+
cause: err
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
clearTimeout(timer);
|
|
397
|
+
if (res.ok) return res;
|
|
398
|
+
if (canRetry && res.status >= 502 && res.status <= 504) {
|
|
399
|
+
void res.body?.cancel().catch(() => {
|
|
400
|
+
});
|
|
401
|
+
await sleep(this.backoff(attempt));
|
|
402
|
+
continue;
|
|
403
|
+
}
|
|
404
|
+
const text = await res.text().catch(() => "");
|
|
405
|
+
let parsed = null;
|
|
406
|
+
try {
|
|
407
|
+
parsed = text ? JSON.parse(text) : null;
|
|
408
|
+
} catch {
|
|
409
|
+
parsed = null;
|
|
410
|
+
}
|
|
411
|
+
throw errorFromResponse(res.status, parsed, `${method} ${path} returned ${res.status}`);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
backoff(attempt) {
|
|
415
|
+
return this.retryDelayMs * 2 ** attempt;
|
|
416
|
+
}
|
|
417
|
+
/** Polls an operation until it is `succeeded` (returns it) or `failed` (throws). */
|
|
418
|
+
async waitForOperation(op, timeoutMs = this.operationTimeoutMs) {
|
|
419
|
+
const deadline = Date.now() + timeoutMs;
|
|
420
|
+
let delay = this.pollIntervalMs;
|
|
421
|
+
let cur = op;
|
|
422
|
+
while (cur.state !== "succeeded") {
|
|
423
|
+
if (cur.state === "failed") {
|
|
424
|
+
const e = cur.error;
|
|
425
|
+
throw new InstaboxError(e?.message || `operation ${cur.id} (${cur.type}) failed`, {
|
|
426
|
+
code: e?.code ?? "operation_failed",
|
|
427
|
+
requestId: e?.requestId,
|
|
428
|
+
retryable: e?.retryable ?? false,
|
|
429
|
+
operationId: cur.id
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
if (Date.now() + delay > deadline) {
|
|
433
|
+
throw new InstaboxTimeoutError(
|
|
434
|
+
`operation ${cur.id} (${cur.type}) did not finish within ${timeoutMs} ms (state ${cur.state}${cur.phase ? `, phase ${cur.phase}` : ""})`,
|
|
435
|
+
{ code: "operation_timeout", operationId: cur.id }
|
|
436
|
+
);
|
|
437
|
+
}
|
|
438
|
+
await sleep(delay);
|
|
439
|
+
delay = Math.min(Math.round(delay * 1.5), Math.max(1e3, this.pollIntervalMs));
|
|
440
|
+
cur = await this.request("GET", `/v1/operations/${encodeURIComponent(cur.id)}`);
|
|
441
|
+
}
|
|
442
|
+
return cur;
|
|
443
|
+
}
|
|
444
|
+
};
|
|
445
|
+
|
|
446
|
+
// src/sandbox.ts
|
|
447
|
+
var DEFAULT_TEMPLATE = "universal";
|
|
448
|
+
function toInfo(m) {
|
|
449
|
+
const info = {
|
|
450
|
+
sandboxId: m.id,
|
|
451
|
+
templateId: m.template?.id,
|
|
452
|
+
name: m.name,
|
|
453
|
+
metadata: { ...m.metadata },
|
|
454
|
+
startedAt: new Date(m.createdAt),
|
|
455
|
+
onTimeout: m.onTimeout ?? "pause",
|
|
456
|
+
state: m.state,
|
|
457
|
+
machine: m
|
|
458
|
+
};
|
|
459
|
+
if (m.snapshot?.id) info.snapshotId = m.snapshot.id;
|
|
460
|
+
if (m.timeoutAt) info.endAt = new Date(m.timeoutAt);
|
|
461
|
+
if (m.archiveAt) info.archiveAt = new Date(m.archiveAt);
|
|
462
|
+
return info;
|
|
463
|
+
}
|
|
464
|
+
function toSeconds(ms, field = "timeoutMs") {
|
|
465
|
+
const s = Math.ceil(ms / 1e3);
|
|
466
|
+
if (!Number.isFinite(ms) || s < 60 || s > 86400) {
|
|
467
|
+
throw new InstaboxError(`${field} must be between 60 000 (60 s) and 86 400 000 (24 h); got ${ms}`, {
|
|
468
|
+
code: "bad_request"
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
return s;
|
|
472
|
+
}
|
|
473
|
+
var METADATA_KEY = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
474
|
+
var enc = encodeURIComponent;
|
|
475
|
+
var Sandbox = class _Sandbox {
|
|
476
|
+
constructor(http, machine, opts = {}) {
|
|
477
|
+
this.http = http;
|
|
478
|
+
this.sandboxId = machine.id;
|
|
479
|
+
this.machine = machine;
|
|
480
|
+
this.commands = new Commands(http, machine.id, { ...opts.envs });
|
|
481
|
+
this.files = new Files(this.commands);
|
|
482
|
+
}
|
|
483
|
+
http;
|
|
484
|
+
/** The machine ID (`m_...`). */
|
|
485
|
+
sandboxId;
|
|
486
|
+
/** Run shell commands. Needs a instabox server with the exec endpoint. */
|
|
487
|
+
commands;
|
|
488
|
+
/** Read and write files. Needs a instabox server with the exec endpoint. */
|
|
489
|
+
files;
|
|
490
|
+
machine;
|
|
491
|
+
static async create(a, b) {
|
|
492
|
+
const template = typeof a === "string" ? a : DEFAULT_TEMPLATE;
|
|
493
|
+
const opts = (typeof a === "string" ? b : a) ?? {};
|
|
494
|
+
const http = new HttpClient(opts);
|
|
495
|
+
const body = { name: opts.name ?? `sbx-${randomSuffix()}` };
|
|
496
|
+
if (opts.timeoutMs !== void 0) body.timeoutSeconds = toSeconds(opts.timeoutMs);
|
|
497
|
+
if (opts.archiveMs !== void 0) body.archiveSeconds = toSeconds(opts.archiveMs, "archiveMs");
|
|
498
|
+
Object.assign(body, await resolveSource(http, template));
|
|
499
|
+
if (opts.vcpus !== void 0) body.vcpus = opts.vcpus;
|
|
500
|
+
if (opts.memMiB !== void 0) body.memMiB = opts.memMiB;
|
|
501
|
+
if (opts.diskGiB !== void 0) body.persistentDiskGiB = opts.diskGiB;
|
|
502
|
+
if (opts.rootDiskGiB !== void 0) body.rootDiskGiB = opts.rootDiskGiB;
|
|
503
|
+
if (opts.onTimeout) body.onTimeout = opts.onTimeout;
|
|
504
|
+
if (opts.metadata) body.metadata = opts.metadata;
|
|
505
|
+
const op = await http.request("POST", "/v1/machines", { body });
|
|
506
|
+
const done = await http.waitForOperation(op);
|
|
507
|
+
const machine = await getMachine(http, done.machineId);
|
|
508
|
+
return new _Sandbox(http, machine, opts);
|
|
509
|
+
}
|
|
510
|
+
/** Attaches to an existing sandbox. Resumes it if it is paused or stopped, unless `resume: false`. */
|
|
511
|
+
static async connect(sandboxId, opts = {}) {
|
|
512
|
+
const http = new HttpClient(opts);
|
|
513
|
+
const sbx = new _Sandbox(http, await getMachine(http, sandboxId), opts);
|
|
514
|
+
await sbx.settle(false);
|
|
515
|
+
if (opts.resume !== false) await sbx.wake();
|
|
516
|
+
return sbx;
|
|
517
|
+
}
|
|
518
|
+
/** Lists your sandboxes (all pages), optionally only those matching `metadata`. */
|
|
519
|
+
static async list(opts = {}) {
|
|
520
|
+
const http = new HttpClient(opts);
|
|
521
|
+
const metadata = Object.entries(opts.metadata ?? {}).map(([k, v]) => {
|
|
522
|
+
if (!METADATA_KEY.test(k))
|
|
523
|
+
throw new InstaboxError(`invalid metadata key ${JSON.stringify(k)}: use 1-64 of [A-Za-z0-9_.-]`, {
|
|
524
|
+
code: "bad_request"
|
|
525
|
+
});
|
|
526
|
+
return `${k}:${v}`;
|
|
527
|
+
});
|
|
528
|
+
const out = [];
|
|
529
|
+
let cursor;
|
|
530
|
+
do {
|
|
531
|
+
const page = await http.request("GET", "/v1/machines", { query: { cursor, limit: 100, metadata } });
|
|
532
|
+
out.push(...page.machines.map((m) => toInfo(m)));
|
|
533
|
+
cursor = page.nextCursor ?? void 0;
|
|
534
|
+
} while (cursor);
|
|
535
|
+
return out;
|
|
536
|
+
}
|
|
537
|
+
/** Deletes a sandbox and its disks. Returns false if it did not exist. */
|
|
538
|
+
static async kill(sandboxId, opts = {}) {
|
|
539
|
+
return killMachine(new HttpClient(opts), sandboxId);
|
|
540
|
+
}
|
|
541
|
+
/** Lists the caller's private snapshots. Requires images:read. */
|
|
542
|
+
static async listSnapshots(opts = {}) {
|
|
543
|
+
const result = await new HttpClient(opts).request("GET", "/v1/snapshots");
|
|
544
|
+
return result.snapshots;
|
|
545
|
+
}
|
|
546
|
+
/** Fetches a snapshot by ID. Requires images:read. */
|
|
547
|
+
static async getSnapshot(snapshotId, opts = {}) {
|
|
548
|
+
return new HttpClient(opts).request("GET", `/v1/snapshots/${enc(snapshotId)}`);
|
|
549
|
+
}
|
|
550
|
+
/** Deletes a snapshot. Returns false if absent. Requires images:delete. */
|
|
551
|
+
static async deleteSnapshot(snapshotId, opts = {}) {
|
|
552
|
+
try {
|
|
553
|
+
await new HttpClient(opts).request("DELETE", `/v1/snapshots/${enc(snapshotId)}`);
|
|
554
|
+
return true;
|
|
555
|
+
} catch (err) {
|
|
556
|
+
if (err instanceof InstaboxError && err.status === 404 && err.code === "not_found") return false;
|
|
557
|
+
throw err;
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
/** Saves a stopped sandbox's disks as a private snapshot. Requires images:write. */
|
|
561
|
+
async createSnapshot(opts) {
|
|
562
|
+
return this.http.request("POST", `/v1/machines/${enc(this.sandboxId)}/snapshots`, { body: opts });
|
|
563
|
+
}
|
|
564
|
+
/** Fetches the current state of the sandbox. */
|
|
565
|
+
async getInfo() {
|
|
566
|
+
this.machine = await getMachine(this.http, this.sandboxId);
|
|
567
|
+
return toInfo(this.machine);
|
|
568
|
+
}
|
|
569
|
+
/**
|
|
570
|
+
* Sets the timeout to `timeoutMs` from now (whole seconds, 60 s to 24 h); 0 clears it.
|
|
571
|
+
* `onTimeout` changes what happens then (`pause` or `kill`).
|
|
572
|
+
*/
|
|
573
|
+
async setTimeout(timeoutMs, opts = {}) {
|
|
574
|
+
const body = { timeoutSeconds: timeoutMs === 0 ? 0 : toSeconds(timeoutMs) };
|
|
575
|
+
if (opts.onTimeout) body.onTimeout = opts.onTimeout;
|
|
576
|
+
this.machine = await this.http.request("PATCH", `/v1/machines/${enc(this.sandboxId)}`, { body });
|
|
577
|
+
}
|
|
578
|
+
/** Replaces the sandbox's metadata (`{}` clears it). */
|
|
579
|
+
async setMetadata(metadata) {
|
|
580
|
+
this.machine = await this.http.request("PATCH", `/v1/machines/${enc(this.sandboxId)}`, {
|
|
581
|
+
body: { metadata }
|
|
582
|
+
});
|
|
583
|
+
}
|
|
584
|
+
/** True if the sandbox is running (fetches fresh state). */
|
|
585
|
+
async isRunning() {
|
|
586
|
+
return (await this.getInfo()).state === "running";
|
|
587
|
+
}
|
|
588
|
+
/** Snapshots memory and stops the sandbox (suspend). `resume()` or `Sandbox.connect()` brings it back. */
|
|
589
|
+
async pause() {
|
|
590
|
+
await this.mutate("POST", "suspend");
|
|
591
|
+
}
|
|
592
|
+
/** Resumes a paused sandbox from its snapshot, or starts a stopped one. */
|
|
593
|
+
async resume() {
|
|
594
|
+
await this.settle();
|
|
595
|
+
await this.wake();
|
|
596
|
+
}
|
|
597
|
+
/** Resumes or starts based on the cached state; callers make sure the cache is fresh. */
|
|
598
|
+
async wake() {
|
|
599
|
+
if (this.machine.state === "suspended") await this.mutate("POST", "resume");
|
|
600
|
+
else if (this.machine.state === "stopped") await this.mutate("POST", "start");
|
|
601
|
+
}
|
|
602
|
+
/** Stops the sandbox (guest shutdown; processes end, `/data` is kept). */
|
|
603
|
+
async stop() {
|
|
604
|
+
await this.settle();
|
|
605
|
+
if (this.machine.state === "suspended") await this.mutate("POST", "start");
|
|
606
|
+
await this.mutate("POST", "stop");
|
|
607
|
+
}
|
|
608
|
+
/** Copies this sandbox (root disk and `/data`) into a new sandbox and waits until it runs. */
|
|
609
|
+
async fork(opts = {}) {
|
|
610
|
+
if (opts.timeoutMs !== void 0) toSeconds(opts.timeoutMs);
|
|
611
|
+
await this.settle();
|
|
612
|
+
if (this.machine.state !== "stopped") {
|
|
613
|
+
if (opts.stopSource === false) {
|
|
614
|
+
throw new InstaboxError(`fork needs a stopped sandbox; ${this.sandboxId} is ${this.machine.state}`, {
|
|
615
|
+
code: "operation_conflict"
|
|
616
|
+
});
|
|
617
|
+
}
|
|
618
|
+
await this.stop();
|
|
619
|
+
}
|
|
620
|
+
const body = { name: opts.name ?? `${this.machine.name}-fork-${randomSuffix(4)}` };
|
|
621
|
+
if (opts.vcpus !== void 0) body.vcpus = opts.vcpus;
|
|
622
|
+
if (opts.memMiB !== void 0) body.memMiB = opts.memMiB;
|
|
623
|
+
if (opts.diskGiB !== void 0) body.persistentDiskGiB = opts.diskGiB;
|
|
624
|
+
if (opts.rootDiskGiB !== void 0) body.rootDiskGiB = opts.rootDiskGiB;
|
|
625
|
+
if (opts.timeoutMs !== void 0) body.timeoutSeconds = toSeconds(opts.timeoutMs);
|
|
626
|
+
if (opts.onTimeout) body.onTimeout = opts.onTimeout;
|
|
627
|
+
if (opts.metadata) body.metadata = opts.metadata;
|
|
628
|
+
const op = await this.http.request("POST", `/v1/machines/${enc(this.sandboxId)}/fork`, { body });
|
|
629
|
+
const done = await this.http.waitForOperation(op);
|
|
630
|
+
return new _Sandbox(this.http, await getMachine(this.http, done.machineId));
|
|
631
|
+
}
|
|
632
|
+
/** Deletes the sandbox and its disks. Returns false if it was already gone. */
|
|
633
|
+
async kill() {
|
|
634
|
+
return killMachine(this.http, this.sandboxId);
|
|
635
|
+
}
|
|
636
|
+
/**
|
|
637
|
+
* Issues a short-lived SSH certificate for `publicKey` (authorized_keys format).
|
|
638
|
+
* Connect with `ssh -p <port> -o CertificateFile=<cert> -i <key> <username>@<host>` after adding
|
|
639
|
+
* `knownHostsLine` to known_hosts. The sandbox must be running.
|
|
640
|
+
*/
|
|
641
|
+
async sshCredentials(publicKey, opts = {}) {
|
|
642
|
+
const body = { publicKey: publicKey.trim() };
|
|
643
|
+
if (opts.ttlSeconds) body.ttlSeconds = opts.ttlSeconds;
|
|
644
|
+
const c = await this.http.request("POST", `/v1/machines/${enc(this.sandboxId)}/connections`, { body });
|
|
645
|
+
return {
|
|
646
|
+
host: c.host,
|
|
647
|
+
port: c.port,
|
|
648
|
+
username: c.username,
|
|
649
|
+
certificate: c.certificate,
|
|
650
|
+
knownHostsLine: `@cert-authority [${c.host}]:${c.port} ${c.hostTrust.publicKey}`,
|
|
651
|
+
expiresAt: new Date(c.expiresAt),
|
|
652
|
+
connectionId: c.id
|
|
653
|
+
};
|
|
654
|
+
}
|
|
655
|
+
/**
|
|
656
|
+
* Re-reads the machine from the server (other handles or the dashboard may have changed it),
|
|
657
|
+
* waits for its active operation if one is running, and leaves the fresh state cached.
|
|
658
|
+
* Every state-dependent method calls this first, so it never decides from a stale cache.
|
|
659
|
+
*/
|
|
660
|
+
async settle(refresh = true) {
|
|
661
|
+
if (refresh) this.machine = await getMachine(this.http, this.sandboxId);
|
|
662
|
+
if (this.machine.operationId) {
|
|
663
|
+
const op = await this.http.request("GET", `/v1/operations/${enc(this.machine.operationId)}`);
|
|
664
|
+
await this.http.waitForOperation(op).catch(() => {
|
|
665
|
+
});
|
|
666
|
+
this.machine = await getMachine(this.http, this.sandboxId);
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
async mutate(method, action) {
|
|
670
|
+
const op = await this.http.request(method, `/v1/machines/${enc(this.sandboxId)}/${action}`);
|
|
671
|
+
await this.http.waitForOperation(op);
|
|
672
|
+
this.machine = await getMachine(this.http, this.sandboxId);
|
|
673
|
+
}
|
|
674
|
+
};
|
|
675
|
+
async function getMachine(http, id) {
|
|
676
|
+
return http.request("GET", `/v1/machines/${enc(id)}`);
|
|
677
|
+
}
|
|
678
|
+
async function killMachine(http, id) {
|
|
679
|
+
try {
|
|
680
|
+
const op = await http.request("DELETE", `/v1/machines/${enc(id)}`);
|
|
681
|
+
await http.waitForOperation(op);
|
|
682
|
+
return true;
|
|
683
|
+
} catch (err) {
|
|
684
|
+
if (err instanceof InstaboxError && err.status === 404 && err.code === "not_found") return false;
|
|
685
|
+
throw err;
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
async function resolveSource(http, ref) {
|
|
689
|
+
if (/^sn_[a-z2-7]{26}$/.test(ref)) return { snapshotId: ref };
|
|
690
|
+
const { templates } = await http.request("GET", "/v1/templates");
|
|
691
|
+
if (templates.some((template) => template.id === ref)) return { templateId: ref };
|
|
692
|
+
const { snapshots } = await http.request("GET", "/v1/snapshots");
|
|
693
|
+
const matches = snapshots.filter((snapshot) => snapshot.name === ref);
|
|
694
|
+
if (matches.length > 1) {
|
|
695
|
+
throw new InstaboxError(`multiple snapshots named ${ref}; use a snapshot ID`, { code: "ambiguous_snapshot" });
|
|
696
|
+
}
|
|
697
|
+
if (matches[0]) return { snapshotId: matches[0].id };
|
|
698
|
+
throw new InstaboxError(`template or snapshot not found: ${ref}`, { status: 404, code: "not_found" });
|
|
699
|
+
}
|
|
700
|
+
//# sourceMappingURL=index.cjs.map
|