@insforge/instabox-sdk 0.5.3 → 0.6.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/README.md +59 -40
- package/dist/index.cjs +783 -82
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +227 -40
- package/dist/index.d.ts +227 -40
- package/dist/index.js +783 -82
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/skills/instabox/SKILL.md +21 -25
package/dist/index.js
CHANGED
|
@@ -22,8 +22,26 @@ var InstaboxAuthError = class extends InstaboxError {
|
|
|
22
22
|
};
|
|
23
23
|
var InstaboxQuotaError = class extends InstaboxError {
|
|
24
24
|
};
|
|
25
|
+
var LIMIT_CODES = [
|
|
26
|
+
"quota_exceeded",
|
|
27
|
+
"credit_exhausted",
|
|
28
|
+
"spend_limit_reached",
|
|
29
|
+
"subscription_required",
|
|
30
|
+
"payment_method_required",
|
|
31
|
+
"payment_failed",
|
|
32
|
+
"template_limit",
|
|
33
|
+
"template_not_allowed",
|
|
34
|
+
"spec_not_allowed",
|
|
35
|
+
"concurrency_limit",
|
|
36
|
+
"rate_limited"
|
|
37
|
+
];
|
|
38
|
+
function isLimitCode(code) {
|
|
39
|
+
return code !== void 0 && LIMIT_CODES.includes(code);
|
|
40
|
+
}
|
|
25
41
|
var InstaboxTimeoutError = class extends InstaboxError {
|
|
26
42
|
};
|
|
43
|
+
var InstaboxNotUtf8Error = class extends InstaboxError {
|
|
44
|
+
};
|
|
27
45
|
var CommandExitError = class extends InstaboxError {
|
|
28
46
|
stdout;
|
|
29
47
|
stderr;
|
|
@@ -52,8 +70,9 @@ function errorFromResponse(status, body, fallbackMessage) {
|
|
|
52
70
|
operationId: typeof env?.operationId === "string" ? env.operationId : null
|
|
53
71
|
};
|
|
54
72
|
const message = typeof env?.message === "string" && env.message ? env.message : fallbackMessage;
|
|
73
|
+
if (isLimitCode(init.code)) return new InstaboxQuotaError(message, init);
|
|
55
74
|
if (status === 401 || status === 403) return new InstaboxAuthError(message, init);
|
|
56
|
-
if (status === 429) return new InstaboxQuotaError(message, init);
|
|
75
|
+
if (status === 402 || status === 429) return new InstaboxQuotaError(message, init);
|
|
57
76
|
return new InstaboxError(message, init);
|
|
58
77
|
}
|
|
59
78
|
|
|
@@ -102,6 +121,135 @@ function readEnv(name) {
|
|
|
102
121
|
|
|
103
122
|
// src/commands.ts
|
|
104
123
|
var MAX_STDIN_BYTES = 1024 * 1024;
|
|
124
|
+
var MAX_TIMEOUT_MS = 6e5;
|
|
125
|
+
var JOBS_DIR = "$HOME/.instabox/jobs";
|
|
126
|
+
var JOB_CHUNK = 512 << 10;
|
|
127
|
+
var JOB_POLL_SEC = 25;
|
|
128
|
+
var JOB_RETRY_MS = 12e4;
|
|
129
|
+
var JOB_NO_SUCH = "instabox-no-job";
|
|
130
|
+
var JOB_IDLE_MIN_MS = 250;
|
|
131
|
+
var JOB_IDLE_MAX_MS = 2e3;
|
|
132
|
+
function abortableSleep(ms, signal) {
|
|
133
|
+
if (signal?.aborted) return Promise.reject(aborted());
|
|
134
|
+
if (!signal) return sleep(ms);
|
|
135
|
+
return new Promise((resolve, reject) => {
|
|
136
|
+
const onAbort = () => {
|
|
137
|
+
clearTimeout(t);
|
|
138
|
+
reject(aborted());
|
|
139
|
+
};
|
|
140
|
+
const t = setTimeout(() => {
|
|
141
|
+
signal.removeEventListener("abort", onAbort);
|
|
142
|
+
resolve();
|
|
143
|
+
}, ms);
|
|
144
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
var JOB_WRAPPER = `d=$1
|
|
148
|
+
s=
|
|
149
|
+
trap 's=129' HUP; trap 's=130' INT; trap 's=131' QUIT; trap 's=143' TERM
|
|
150
|
+
echo $$ > "$d/pid.tmp" && mv -f -- "$d/pid.tmp" "$d/pid"
|
|
151
|
+
g=
|
|
152
|
+
while IFS= read -r l; do case $l in 0::*) g=\${l#0::} ;; esac; done 2>/dev/null < '/proc/self/cgroup'
|
|
153
|
+
ok() { [ -n "$g" ] || return; while read -r k v; do if [ "$k" = oom_kill ]; then echo "$v"; return; fi; done 2>/dev/null < '/sys/fs/cgroup'"$g/memory.events"; }
|
|
154
|
+
k0=$(ok)
|
|
155
|
+
x=$(cat -- "$d/cmd")
|
|
156
|
+
c=$?
|
|
157
|
+
if [ -n "$s" ]; then
|
|
158
|
+
c=$s
|
|
159
|
+
elif [ "$c" = 0 ]; then
|
|
160
|
+
INSTABOX_EXEC_CMD=$x bash -c 'export -n INSTABOX_EXEC_CMD; eval "$INSTABOX_EXEC_CMD"'
|
|
161
|
+
c=$?
|
|
162
|
+
fi
|
|
163
|
+
k1=$(ok)
|
|
164
|
+
if [[ $k0 =~ ^[0-9]+$ && $k1 =~ ^[0-9]+$ ]]; then k=$((k1-k0)); else k=-; fi
|
|
165
|
+
[ -n "$g" ] && echo "$k $g" > "$d/oom"
|
|
166
|
+
echo "$c" > "$d/exit.tmp" && mv -f -- "$d/exit.tmp" "$d/exit"
|
|
167
|
+
`;
|
|
168
|
+
var JOB_STATUS = `st() {
|
|
169
|
+
if [ -s "$1/exit" ]; then echo "exited $(cat -- "$1/exit")"; return; fi
|
|
170
|
+
if [ "$(cat -- "$1/boot" 2>/dev/null)" = "$(cat /proc/sys/kernel/random/boot_id)" ] &&
|
|
171
|
+
p=$(cat -- "$1/pid" 2>/dev/null) && [ -n "$p" ] && kill -0 "$p" 2>/dev/null; then echo running; return; fi
|
|
172
|
+
if [ -s "$1/exit" ]; then echo "exited $(cat -- "$1/exit")"; else echo lost; fi
|
|
173
|
+
}
|
|
174
|
+
oo() { local k g b; b=$(cat -- "$1/boot" 2>/dev/null); if read -r k g < "$1/oom" 2>/dev/null && [ -n "$g" ] && [ -n "$b" ]; then printf ' %s %s %s' "$k" "$g" "$b"; fi; }
|
|
175
|
+
`;
|
|
176
|
+
var JOB_UNSUPPORTED_EXIT = 97;
|
|
177
|
+
var JOB_UNSUPPORTED = "instabox-job-unsupported:";
|
|
178
|
+
var JOB_PREFLIGHT = `p=
|
|
179
|
+
command -v bash >/dev/null 2>&1 || p="$p, bash"
|
|
180
|
+
setsid -f true < /dev/null > /dev/null 2>&1 || p="$p, setsid -f (util-linux)"
|
|
181
|
+
[ "$(stat -c %s -- /dev/null 2>/dev/null)" = 0 ] || p="$p, stat -c (GNU coreutils)"
|
|
182
|
+
[ "$(printf abc | dd iflag=skip_bytes,count_bytes skip=1 count=1 bs=65536 status=none 2>/dev/null)" = b ] ||
|
|
183
|
+
p="$p, dd iflag=skip_bytes,count_bytes (GNU coreutils)"
|
|
184
|
+
[ "$(printf abc | base64 -w0 2>/dev/null)" = YWJj ] || p="$p, base64 -w0 (GNU coreutils)"
|
|
185
|
+
if [ -n "$p" ]; then echo "${JOB_UNSUPPORTED}\${p#, }" >&2; exit ${JOB_UNSUPPORTED_EXIT}; fi
|
|
186
|
+
`;
|
|
187
|
+
var JOB_START = `${JOB_PREFLIGHT}set -e
|
|
188
|
+
mkdir -p -- "$J"
|
|
189
|
+
mkdir -- "$d"
|
|
190
|
+
cat > "$d/cmd"
|
|
191
|
+
date +%s.%N > "$d/started"
|
|
192
|
+
cat /proc/sys/kernel/random/boot_id > "$d/boot"
|
|
193
|
+
setsid -f bash -c "$W" instabox-job "$d" < /dev/null > "$d/out" 2>&1
|
|
194
|
+
i=0
|
|
195
|
+
while [ ! -s "$d/pid" ]; do
|
|
196
|
+
i=$((i+1))
|
|
197
|
+
if [ "$i" -gt 200 ]; then echo "the job did not start" >&2; exit 1; fi
|
|
198
|
+
sleep 0.05
|
|
199
|
+
done
|
|
200
|
+
cat -- "$d/pid"
|
|
201
|
+
`;
|
|
202
|
+
var JOB_READ = `[ -d "$d" ] || { echo ${JOB_NO_SUCH}; exit 0; }
|
|
203
|
+
i=0
|
|
204
|
+
while :; do
|
|
205
|
+
s=$(st "$d")
|
|
206
|
+
sz=$(stat -c %s -- "$d/out" 2>/dev/null || echo 0)
|
|
207
|
+
if [ "$s" != running ] || [ "$sz" -gt "$off" ] || [ "$i" -ge $((w*4)) ]; then break; fi
|
|
208
|
+
sleep 0.25
|
|
209
|
+
i=$((i+1))
|
|
210
|
+
done
|
|
211
|
+
case $s in "exited "*) s=$s$(oo "$d") ;; esac
|
|
212
|
+
echo "$s"
|
|
213
|
+
if [ "$max" -gt 0 ]; then
|
|
214
|
+
dd if="$d/out" iflag=skip_bytes,count_bytes skip="$off" count="$max" bs=65536 status=none | base64 -w0
|
|
215
|
+
fi
|
|
216
|
+
`;
|
|
217
|
+
function jobScript(job, vars, script) {
|
|
218
|
+
let s = `J=${JOBS_DIR}
|
|
219
|
+
d=$J/${shellQuote(job)}
|
|
220
|
+
`;
|
|
221
|
+
for (const k of Object.keys(vars).sort()) s += `${k}=${shellQuote(vars[k])}
|
|
222
|
+
`;
|
|
223
|
+
return s + JOB_STATUS + script;
|
|
224
|
+
}
|
|
225
|
+
function transient(e) {
|
|
226
|
+
if (!(e instanceof InstaboxError) || e.code === "aborted") return false;
|
|
227
|
+
return e.retryable || e.status === 429 || e.status >= 500 || e.code === "network_error" || e.code === "request_timeout";
|
|
228
|
+
}
|
|
229
|
+
function aborted() {
|
|
230
|
+
return new InstaboxError("the command was aborted", { code: "aborted" });
|
|
231
|
+
}
|
|
232
|
+
function streamEnded() {
|
|
233
|
+
return new InstaboxError("the stream ended before the command finished (it may still have run)", {
|
|
234
|
+
status: 503,
|
|
235
|
+
code: "host_unavailable"
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
function invalid(what) {
|
|
239
|
+
return new InstaboxError(`exec returned ${what}`, { code: "invalid_response" });
|
|
240
|
+
}
|
|
241
|
+
function toResult(res, stdout = res.stdout, stderr = res.stderr) {
|
|
242
|
+
if (!res || typeof res.exitCode !== "number") throw invalid("a result without an exit code");
|
|
243
|
+
const out = {
|
|
244
|
+
stdout: typeof stdout === "string" ? stdout : "",
|
|
245
|
+
stderr: typeof stderr === "string" ? stderr : "",
|
|
246
|
+
exitCode: res.exitCode,
|
|
247
|
+
timedOut: res.timedOut === true,
|
|
248
|
+
truncated: res.truncated === true
|
|
249
|
+
};
|
|
250
|
+
if (typeof res.error === "string" && res.error) out.error = res.error;
|
|
251
|
+
return out;
|
|
252
|
+
}
|
|
105
253
|
var Commands = class {
|
|
106
254
|
/** @internal */
|
|
107
255
|
constructor(http, sandboxId, defaultEnvs) {
|
|
@@ -113,28 +261,15 @@ var Commands = class {
|
|
|
113
261
|
sandboxId;
|
|
114
262
|
defaultEnvs;
|
|
115
263
|
async run(cmd, opts = {}) {
|
|
116
|
-
if (opts.background)
|
|
117
|
-
|
|
118
|
-
if (opts.stdin !== void 0)
|
|
119
|
-
throw new InstaboxError("stdin is not supported for background commands", { code: "bad_request" });
|
|
120
|
-
const r2 = await this.exec(wrapped, { cwd: opts.cwd, envs: opts.envs, timeoutMs: opts.timeoutMs });
|
|
121
|
-
if (r2.exitCode !== 0) throw new CommandExitError(r2);
|
|
122
|
-
const pid = Number.parseInt(r2.stdout.trim(), 10);
|
|
123
|
-
if (!Number.isSafeInteger(pid) || pid <= 0)
|
|
124
|
-
throw new InstaboxError("exec returned an invalid background PID", { code: "invalid_response" });
|
|
125
|
-
return {
|
|
126
|
-
pid,
|
|
127
|
-
kill: async () => (await this.exec(`kill -s TERM -- -${pid}`)).exitCode === 0
|
|
128
|
-
};
|
|
129
|
-
}
|
|
130
|
-
const r = await this.exec(cmd, opts);
|
|
131
|
-
if (opts.onStdout && r.stdout) await opts.onStdout(r.stdout);
|
|
132
|
-
if (opts.onStderr && r.stderr) await opts.onStderr(r.stderr);
|
|
264
|
+
if (opts.background) return this.startJob(cmd, opts);
|
|
265
|
+
const r = opts.onStdout || opts.onStderr ? await this.execStream(cmd, opts) : await this.exec(cmd, opts);
|
|
133
266
|
if (r.exitCode !== 0) throw new CommandExitError(r);
|
|
134
267
|
return r;
|
|
135
268
|
}
|
|
136
|
-
|
|
137
|
-
|
|
269
|
+
get execPath() {
|
|
270
|
+
return `/v1/machines/${encodeURIComponent(this.sandboxId)}/exec`;
|
|
271
|
+
}
|
|
272
|
+
execBody(cmd, opts) {
|
|
138
273
|
const envs = { ...this.defaultEnvs, ...opts.envs };
|
|
139
274
|
const body = { cmd };
|
|
140
275
|
if (opts.cwd !== void 0) body.cwd = opts.cwd;
|
|
@@ -146,30 +281,297 @@ var Commands = class {
|
|
|
146
281
|
body.stdin = opts.stdin;
|
|
147
282
|
}
|
|
148
283
|
if (opts.timeoutMs !== void 0) {
|
|
149
|
-
if (!Number.isFinite(opts.timeoutMs) || opts.timeoutMs <= 0 || opts.timeoutMs >
|
|
150
|
-
throw new InstaboxError(
|
|
284
|
+
if (!Number.isFinite(opts.timeoutMs) || opts.timeoutMs <= 0 || opts.timeoutMs > MAX_TIMEOUT_MS) {
|
|
285
|
+
throw new InstaboxError(
|
|
286
|
+
"command timeoutMs must be greater than 0 and at most 600 000; for a longer command use { background: true } and wait() on the handle",
|
|
287
|
+
{ code: "bad_request" }
|
|
288
|
+
);
|
|
151
289
|
}
|
|
152
290
|
body.timeoutSeconds = Math.ceil(opts.timeoutMs / 1e3);
|
|
153
291
|
}
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
292
|
+
if (opts.noHistory) body.noHistory = true;
|
|
293
|
+
if (opts.historyCommand !== void 0) body.historyCommand = opts.historyCommand;
|
|
294
|
+
return body;
|
|
295
|
+
}
|
|
296
|
+
/** The request deadline of an exec: its command timeout plus 30 s, unless `requestTimeoutMs` is set. */
|
|
297
|
+
execDeadline(body) {
|
|
298
|
+
return this.http.requestTimeout((Number(body.timeoutSeconds) || 60) * 1e3 + 3e4);
|
|
299
|
+
}
|
|
300
|
+
/** @internal Raw exec: never throws on a non-zero exit code. */
|
|
301
|
+
async exec(cmd, opts = {}) {
|
|
302
|
+
const body = this.execBody(cmd, opts);
|
|
303
|
+
if (opts.signal?.aborted) throw aborted();
|
|
304
|
+
const res = await this.http.request("POST", this.execPath, {
|
|
305
|
+
body,
|
|
306
|
+
retry: false,
|
|
307
|
+
idempotent: false,
|
|
308
|
+
timeoutMs: this.execDeadline(body),
|
|
309
|
+
signal: opts.signal
|
|
310
|
+
});
|
|
311
|
+
return toResult(res);
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Exec with the output streamed (`Accept: text/event-stream`): each `stdout`/`stderr` event goes to its
|
|
315
|
+
* callback as it arrives, and the result carries all of it. A server that does not stream answers with
|
|
316
|
+
* the whole result, whose output is passed to the callbacks then.
|
|
317
|
+
*/
|
|
318
|
+
async execStream(cmd, opts) {
|
|
319
|
+
const body = this.execBody(cmd, opts);
|
|
320
|
+
if (opts.signal?.aborted) throw aborted();
|
|
321
|
+
const deadline = this.execDeadline(body);
|
|
322
|
+
const ctrl = new AbortController();
|
|
323
|
+
let timedOut = false;
|
|
324
|
+
const timer = setTimeout(() => {
|
|
325
|
+
timedOut = true;
|
|
326
|
+
ctrl.abort();
|
|
327
|
+
}, deadline);
|
|
328
|
+
const onAbort = () => ctrl.abort();
|
|
329
|
+
opts.signal?.addEventListener("abort", onAbort, { once: true });
|
|
330
|
+
let reader;
|
|
331
|
+
let res;
|
|
332
|
+
const fail = (e) => {
|
|
333
|
+
if (opts.signal?.aborted) return aborted();
|
|
334
|
+
if (timedOut) {
|
|
335
|
+
return new InstaboxTimeoutError(`POST ${this.execPath} timed out after ${deadline} ms`, {
|
|
336
|
+
code: "request_timeout"
|
|
337
|
+
});
|
|
162
338
|
}
|
|
163
|
-
|
|
164
|
-
const out = {
|
|
165
|
-
stdout: res.stdout,
|
|
166
|
-
stderr: res.stderr,
|
|
167
|
-
exitCode: res.exitCode,
|
|
168
|
-
timedOut: res.timedOut,
|
|
169
|
-
truncated: res.truncated
|
|
339
|
+
return e;
|
|
170
340
|
};
|
|
171
|
-
|
|
172
|
-
|
|
341
|
+
try {
|
|
342
|
+
try {
|
|
343
|
+
res = await this.http.send("POST", this.execPath, {
|
|
344
|
+
body,
|
|
345
|
+
retry: false,
|
|
346
|
+
idempotent: false,
|
|
347
|
+
timeoutMs: deadline,
|
|
348
|
+
accept: "text/event-stream, application/json",
|
|
349
|
+
signal: ctrl.signal
|
|
350
|
+
});
|
|
351
|
+
} catch (e) {
|
|
352
|
+
throw fail(e);
|
|
353
|
+
}
|
|
354
|
+
const type = (res.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
|
|
355
|
+
if (type !== "text/event-stream" || !res.body) {
|
|
356
|
+
let r;
|
|
357
|
+
try {
|
|
358
|
+
r = toResult(await res.json());
|
|
359
|
+
} catch (e) {
|
|
360
|
+
throw fail(e instanceof InstaboxError ? e : invalid("a body that is not JSON"));
|
|
361
|
+
}
|
|
362
|
+
if (opts.onStdout && r.stdout) await opts.onStdout(r.stdout);
|
|
363
|
+
if (opts.onStderr && r.stderr) await opts.onStderr(r.stderr);
|
|
364
|
+
return r;
|
|
365
|
+
}
|
|
366
|
+
reader = res.body.getReader();
|
|
367
|
+
return await this.readEvents(reader, opts, fail);
|
|
368
|
+
} finally {
|
|
369
|
+
clearTimeout(timer);
|
|
370
|
+
opts.signal?.removeEventListener("abort", onAbort);
|
|
371
|
+
if (reader) void reader.cancel().catch(() => {
|
|
372
|
+
});
|
|
373
|
+
ctrl.abort();
|
|
374
|
+
if (res) this.http.release(res);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
/** Reads a streamed exec's server-sent events until its `exit` or `error` event. */
|
|
378
|
+
async readEvents(reader, opts, fail) {
|
|
379
|
+
const dec = new TextDecoder();
|
|
380
|
+
const out = { stdout: "", stderr: "" };
|
|
381
|
+
let buf = "";
|
|
382
|
+
let event = "";
|
|
383
|
+
let data = null;
|
|
384
|
+
for (; ; ) {
|
|
385
|
+
let chunk;
|
|
386
|
+
try {
|
|
387
|
+
chunk = await reader.read();
|
|
388
|
+
} catch {
|
|
389
|
+
throw fail(streamEnded());
|
|
390
|
+
}
|
|
391
|
+
if (chunk.done) throw fail(streamEnded());
|
|
392
|
+
buf += dec.decode(chunk.value, { stream: true });
|
|
393
|
+
let start = 0;
|
|
394
|
+
for (let nl = buf.indexOf("\n", start); nl >= 0; nl = buf.indexOf("\n", start)) {
|
|
395
|
+
let line = buf.slice(start, nl);
|
|
396
|
+
start = nl + 1;
|
|
397
|
+
if (line.endsWith("\r")) line = line.slice(0, -1);
|
|
398
|
+
if (line === "") {
|
|
399
|
+
const r = await this.dispatch(event, data, out, opts);
|
|
400
|
+
if (r) return r;
|
|
401
|
+
event = "";
|
|
402
|
+
data = null;
|
|
403
|
+
continue;
|
|
404
|
+
}
|
|
405
|
+
if (line.startsWith(":")) continue;
|
|
406
|
+
const colon = line.indexOf(":");
|
|
407
|
+
const field = colon < 0 ? line : line.slice(0, colon);
|
|
408
|
+
let value = colon < 0 ? "" : line.slice(colon + 1);
|
|
409
|
+
if (value.startsWith(" ")) value = value.slice(1);
|
|
410
|
+
if (field === "event") event = value;
|
|
411
|
+
else if (field === "data") data = data === null ? value : `${data}
|
|
412
|
+
${value}`;
|
|
413
|
+
}
|
|
414
|
+
buf = buf.slice(start);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
/** Handles one event: output goes to its callback, `exit` is the result, `error` is thrown. */
|
|
418
|
+
async dispatch(event, data, out, opts) {
|
|
419
|
+
if (data === null) return void 0;
|
|
420
|
+
if (event === "stdout" || event === "stderr") {
|
|
421
|
+
let chunk;
|
|
422
|
+
try {
|
|
423
|
+
chunk = JSON.parse(data)?.data;
|
|
424
|
+
} catch {
|
|
425
|
+
chunk = void 0;
|
|
426
|
+
}
|
|
427
|
+
if (typeof chunk !== "string") throw invalid(`a ${event} event without data`);
|
|
428
|
+
out[event] += chunk;
|
|
429
|
+
const cb = event === "stdout" ? opts.onStdout : opts.onStderr;
|
|
430
|
+
if (cb && chunk) await cb(chunk);
|
|
431
|
+
return void 0;
|
|
432
|
+
}
|
|
433
|
+
if (event === "exit") {
|
|
434
|
+
let res;
|
|
435
|
+
try {
|
|
436
|
+
res = JSON.parse(data);
|
|
437
|
+
} catch {
|
|
438
|
+
throw invalid("an exit event that is not JSON");
|
|
439
|
+
}
|
|
440
|
+
return { ...toResult(res, out.stdout, out.stderr), truncated: false };
|
|
441
|
+
}
|
|
442
|
+
if (event === "error") {
|
|
443
|
+
let code;
|
|
444
|
+
try {
|
|
445
|
+
code = JSON.parse(data)?.error?.code;
|
|
446
|
+
} catch {
|
|
447
|
+
code = void 0;
|
|
448
|
+
}
|
|
449
|
+
const status = code === "host_unavailable" ? 503 : 500;
|
|
450
|
+
throw this.http.errorFromBody(status, data, `POST ${this.execPath} failed while streaming`);
|
|
451
|
+
}
|
|
452
|
+
return void 0;
|
|
453
|
+
}
|
|
454
|
+
/** Starts a background job the CLI's way and returns its handle. */
|
|
455
|
+
async startJob(cmd, opts) {
|
|
456
|
+
if (opts.stdin !== void 0)
|
|
457
|
+
throw new InstaboxError("stdin is not supported for background commands", { code: "bad_request" });
|
|
458
|
+
if (opts.onStdout || opts.onStderr) {
|
|
459
|
+
throw new InstaboxError(
|
|
460
|
+
"onStdout and onStderr are not supported with background: true; pass onStdout to wait() on the returned handle to follow the output",
|
|
461
|
+
{ code: "bad_request" }
|
|
462
|
+
);
|
|
463
|
+
}
|
|
464
|
+
if (cmd.includes("\0")) throw new InstaboxError("the command contains a NUL byte", { code: "bad_request" });
|
|
465
|
+
const jobId = randomSuffix(8);
|
|
466
|
+
const r = await this.exec(jobScript(jobId, { W: JOB_WRAPPER }, JOB_START), {
|
|
467
|
+
cwd: opts.cwd,
|
|
468
|
+
envs: opts.envs,
|
|
469
|
+
timeoutMs: opts.timeoutMs,
|
|
470
|
+
stdin: cmd,
|
|
471
|
+
signal: opts.signal,
|
|
472
|
+
historyCommand: `background: ${cmd}`
|
|
473
|
+
});
|
|
474
|
+
const missing = r.stderr.split("\n").find((l) => l.startsWith(JOB_UNSUPPORTED));
|
|
475
|
+
if (r.exitCode === JOB_UNSUPPORTED_EXIT && missing) {
|
|
476
|
+
throw new InstaboxError(
|
|
477
|
+
`background commands need tools this sandbox lacks: ${missing.slice(JOB_UNSUPPORTED.length).trim()}. Run the command without background: true, or use an image with bash, util-linux and GNU coreutils`,
|
|
478
|
+
{ code: "background_unsupported" }
|
|
479
|
+
);
|
|
480
|
+
}
|
|
481
|
+
if (r.exitCode !== 0) throw new CommandExitError(r);
|
|
482
|
+
const pid = Number.parseInt(r.stdout.trim(), 10);
|
|
483
|
+
if (!/^\d+$/.test(r.stdout.trim()) || !Number.isSafeInteger(pid) || pid <= 0)
|
|
484
|
+
throw new InstaboxError("exec returned an invalid background PID", { code: "invalid_response" });
|
|
485
|
+
return {
|
|
486
|
+
pid,
|
|
487
|
+
jobId,
|
|
488
|
+
kill: async () => (await this.exec(`kill -s TERM -- -${pid}`)).exitCode === 0,
|
|
489
|
+
wait: (w) => this.waitJob(jobId, w)
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
/** One read of a job: its status and up to `max` bytes of output from `off`, waiting up to `w` seconds. */
|
|
493
|
+
async readJob(jobId, off, max, w, signal) {
|
|
494
|
+
const r = await this.exec(jobScript(jobId, { off: String(off), max: String(max), w: String(w) }, JOB_READ), {
|
|
495
|
+
timeoutMs: (w + 30) * 1e3,
|
|
496
|
+
noHistory: true,
|
|
497
|
+
signal
|
|
498
|
+
});
|
|
499
|
+
if (r.exitCode !== 0 || r.timedOut) {
|
|
500
|
+
const msg = r.stderr.trim().split("\n").slice(-1)[0] || `exit status ${r.exitCode}`;
|
|
501
|
+
throw new InstaboxError(`reading job ${jobId} failed in the sandbox: ${msg}`, { code: "job_read_failed" });
|
|
502
|
+
}
|
|
503
|
+
if (r.truncated) throw invalid("a truncated job read");
|
|
504
|
+
const nl = r.stdout.indexOf("\n");
|
|
505
|
+
const head = (nl < 0 ? r.stdout : r.stdout.slice(0, nl)).trim();
|
|
506
|
+
if (head === JOB_NO_SUCH) return null;
|
|
507
|
+
const rest = nl < 0 ? "" : r.stdout.slice(nl + 1).trim();
|
|
508
|
+
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(rest)) throw invalid("job output that is not base64");
|
|
509
|
+
const bytes = base64ToBytes(rest);
|
|
510
|
+
const m = /^exited (-?\d+)(?: \S+ \S+ \S+)?$/.exec(head);
|
|
511
|
+
if (m) return { status: "exited", exitCode: Number(m[1]), bytes };
|
|
512
|
+
return { status: head === "running" ? "running" : "lost", bytes };
|
|
513
|
+
}
|
|
514
|
+
/** `readJob` for the wait loop. Reads change nothing, so a transient error is retried for up to 2 minutes. */
|
|
515
|
+
async pollJob(jobId, off, w, until, signal) {
|
|
516
|
+
let delay = 1e3;
|
|
517
|
+
const start = Date.now();
|
|
518
|
+
for (; ; ) {
|
|
519
|
+
try {
|
|
520
|
+
return await this.readJob(jobId, off, JOB_CHUNK, w, signal);
|
|
521
|
+
} catch (e) {
|
|
522
|
+
if (signal?.aborted) throw aborted();
|
|
523
|
+
if (!transient(e) || Date.now() - start > JOB_RETRY_MS || Date.now() + delay >= until) throw e;
|
|
524
|
+
await sleep(delay);
|
|
525
|
+
delay = Math.min(delay * 2, 15e3);
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
/** Follows a job's output until it ends. */
|
|
530
|
+
async waitJob(jobId, opts = {}) {
|
|
531
|
+
const { signal } = opts;
|
|
532
|
+
if (opts.timeoutMs !== void 0 && (!Number.isFinite(opts.timeoutMs) || opts.timeoutMs <= 0))
|
|
533
|
+
throw new InstaboxError("wait timeoutMs must be greater than 0", { code: "bad_request" });
|
|
534
|
+
const until = opts.timeoutMs === void 0 ? Infinity : Date.now() + opts.timeoutMs;
|
|
535
|
+
const maxWait = Math.max(0, Math.min(JOB_POLL_SEC, Math.floor((this.http.requestTimeout(Infinity) - 5e3) / 1e3)));
|
|
536
|
+
const dec = new TextDecoder();
|
|
537
|
+
let stdout = "";
|
|
538
|
+
let off = 0;
|
|
539
|
+
let idle = JOB_IDLE_MIN_MS;
|
|
540
|
+
const emit = async (text) => {
|
|
541
|
+
stdout += text;
|
|
542
|
+
if (text && opts.onStdout) await opts.onStdout(text);
|
|
543
|
+
};
|
|
544
|
+
for (; ; ) {
|
|
545
|
+
if (signal?.aborted) throw aborted();
|
|
546
|
+
const left = until - Date.now();
|
|
547
|
+
const w = Math.max(0, Math.min(maxWait, Math.ceil(left / 1e3)));
|
|
548
|
+
const read = await this.pollJob(jobId, off, w, until, signal);
|
|
549
|
+
if (read === null) throw new InstaboxError(`no job ${jobId} in the sandbox`, { status: 404, code: "not_found" });
|
|
550
|
+
if (w === 0 && read.status === "running" && read.bytes.length === 0) {
|
|
551
|
+
await abortableSleep(Math.min(idle, Math.max(0, until - Date.now())), signal);
|
|
552
|
+
idle = Math.min(idle * 2, JOB_IDLE_MAX_MS);
|
|
553
|
+
} else if (read.bytes.length > 0) idle = JOB_IDLE_MIN_MS;
|
|
554
|
+
off += read.bytes.length;
|
|
555
|
+
await emit(dec.decode(read.bytes, { stream: true }));
|
|
556
|
+
if (read.bytes.length === JOB_CHUNK) continue;
|
|
557
|
+
if (read.status !== "running") {
|
|
558
|
+
await emit(dec.decode());
|
|
559
|
+
if (read.exitCode === void 0) {
|
|
560
|
+
throw new InstaboxError(
|
|
561
|
+
`job ${jobId} ended without an exit code (the sandbox restarted or the job was killed)`,
|
|
562
|
+
{ code: "job_lost" }
|
|
563
|
+
);
|
|
564
|
+
}
|
|
565
|
+
const r = { stdout, stderr: "", exitCode: read.exitCode, timedOut: false, truncated: false };
|
|
566
|
+
if (r.exitCode !== 0) throw new CommandExitError(r);
|
|
567
|
+
return r;
|
|
568
|
+
}
|
|
569
|
+
if (Date.now() >= until) {
|
|
570
|
+
throw new InstaboxTimeoutError(`job ${jobId} is still running after ${opts.timeoutMs} ms`, {
|
|
571
|
+
code: "job_wait_timeout"
|
|
572
|
+
});
|
|
573
|
+
}
|
|
574
|
+
}
|
|
173
575
|
}
|
|
174
576
|
};
|
|
175
577
|
|
|
@@ -430,17 +832,69 @@ var Desktop = class {
|
|
|
430
832
|
|
|
431
833
|
// src/files.ts
|
|
432
834
|
var MAX_FILE_BYTES = 10 * 1024 * 1024;
|
|
835
|
+
var TRANSFER_TIMEOUT_MS = 3e5;
|
|
433
836
|
var WRITE_CHUNK_B64 = 48 * 1024;
|
|
434
837
|
var READ_CHUNK_BYTES = 512 * 1024;
|
|
435
838
|
var Files = class {
|
|
436
839
|
/** @internal */
|
|
437
|
-
constructor(commands) {
|
|
840
|
+
constructor(commands, http, sandboxId) {
|
|
438
841
|
this.commands = commands;
|
|
842
|
+
this.http = http;
|
|
843
|
+
this.sandboxId = sandboxId;
|
|
439
844
|
}
|
|
440
845
|
commands;
|
|
846
|
+
http;
|
|
847
|
+
sandboxId;
|
|
848
|
+
home;
|
|
849
|
+
/** False once a server answered that it has no file routes. */
|
|
850
|
+
routes = true;
|
|
441
851
|
async read(path, opts = {}) {
|
|
442
|
-
const p = arg(path);
|
|
443
852
|
const limit = opts.maxBytes ?? MAX_FILE_BYTES;
|
|
853
|
+
const streamed = await this.readStream(path, limit);
|
|
854
|
+
const bytes = streamed ?? await this.readExec(path, limit);
|
|
855
|
+
return opts.format === "bytes" ? bytes : decodeUtf8(bytes);
|
|
856
|
+
}
|
|
857
|
+
/** Reads over `GET .../files/content`; undefined when the server has no such route. */
|
|
858
|
+
async readStream(path, limit) {
|
|
859
|
+
if (!this.http || !this.sandboxId || !this.routes) return void 0;
|
|
860
|
+
const abs = await this.absolute(path);
|
|
861
|
+
let res;
|
|
862
|
+
try {
|
|
863
|
+
res = await this.http.send("GET", `/v1/machines/${encodeURIComponent(this.sandboxId)}/files/content`, {
|
|
864
|
+
query: { path: abs },
|
|
865
|
+
timeoutMs: TRANSFER_TIMEOUT_MS
|
|
866
|
+
});
|
|
867
|
+
} catch (err) {
|
|
868
|
+
if (routeMissing(err)) {
|
|
869
|
+
this.routes = false;
|
|
870
|
+
return void 0;
|
|
871
|
+
}
|
|
872
|
+
if (err instanceof InstaboxError && (err.code === "not_found" || err.code === "not_a_file")) {
|
|
873
|
+
throw new InstaboxError(`file not found: ${path}`, {
|
|
874
|
+
status: 404,
|
|
875
|
+
code: "not_found",
|
|
876
|
+
requestId: err.requestId,
|
|
877
|
+
cause: err
|
|
878
|
+
});
|
|
879
|
+
}
|
|
880
|
+
throw err;
|
|
881
|
+
}
|
|
882
|
+
const declared = Number(res.headers.get("Content-Length") ?? NaN);
|
|
883
|
+
if (Number.isSafeInteger(declared) && declared > limit) {
|
|
884
|
+
void res.body?.cancel().catch(() => {
|
|
885
|
+
});
|
|
886
|
+
throw new InstaboxError(`${path} is larger than the ${limit}-byte limit of files.read`, {
|
|
887
|
+
code: "file_too_large"
|
|
888
|
+
});
|
|
889
|
+
}
|
|
890
|
+
const bytes = await readBody(res, limit, path);
|
|
891
|
+
if (Number.isSafeInteger(declared) && bytes.length !== declared) {
|
|
892
|
+
throw new InstaboxError(`got ${bytes.length} of ${declared} bytes of ${path}`, { code: "file_changed" });
|
|
893
|
+
}
|
|
894
|
+
return bytes;
|
|
895
|
+
}
|
|
896
|
+
async readExec(path, limit) {
|
|
897
|
+
const p = arg(path);
|
|
444
898
|
const r = await this.commands.exec(
|
|
445
899
|
`[ -f ${p} ] || { echo "no such file: "${p} >&2; exit 3; }; s=$(wc -c < ${p}) || exit 1; [ "$s" -le ${limit} ] || { echo "file too large: $s bytes" >&2; exit 4; }; printf '%s' "$s"`
|
|
446
900
|
);
|
|
@@ -467,7 +921,7 @@ var Files = class {
|
|
|
467
921
|
}
|
|
468
922
|
bytes.set(data, offset);
|
|
469
923
|
}
|
|
470
|
-
return
|
|
924
|
+
return bytes;
|
|
471
925
|
}
|
|
472
926
|
/**
|
|
473
927
|
* Writes a file, creating parent directories. Replaces the file atomically (temp file + rename).
|
|
@@ -480,6 +934,49 @@ var Files = class {
|
|
|
480
934
|
code: "file_too_large"
|
|
481
935
|
});
|
|
482
936
|
}
|
|
937
|
+
if (await this.writeStream(path, bytes)) return { path };
|
|
938
|
+
await this.writeExec(path, bytes);
|
|
939
|
+
return { path };
|
|
940
|
+
}
|
|
941
|
+
/**
|
|
942
|
+
* Writes over `PUT .../files?parents=true`, which writes a temp file beside the target and renames
|
|
943
|
+
* it into place once every byte arrived. False when the server has no such route.
|
|
944
|
+
*/
|
|
945
|
+
async writeStream(path, bytes) {
|
|
946
|
+
if (!this.http || !this.sandboxId || !this.routes) return false;
|
|
947
|
+
const abs = await this.absolute(path);
|
|
948
|
+
let res;
|
|
949
|
+
try {
|
|
950
|
+
res = await this.http.request("PUT", `/v1/machines/${encodeURIComponent(this.sandboxId)}/files`, {
|
|
951
|
+
query: { path: abs, parents: "true" },
|
|
952
|
+
rawBody: bytes,
|
|
953
|
+
idempotent: false,
|
|
954
|
+
retry: true,
|
|
955
|
+
timeoutMs: TRANSFER_TIMEOUT_MS
|
|
956
|
+
});
|
|
957
|
+
} catch (err) {
|
|
958
|
+
if (routeMissing(err)) {
|
|
959
|
+
this.routes = false;
|
|
960
|
+
return false;
|
|
961
|
+
}
|
|
962
|
+
if (err instanceof InstaboxError && err.code === "not_a_file") {
|
|
963
|
+
const dir = await this.commands.exec(`test -d ${arg(path)}`).catch(() => void 0);
|
|
964
|
+
if (dir?.exitCode === 0) {
|
|
965
|
+
throw new InstaboxError(`is a directory: ${path}`, { status: 409, code: "is_a_directory", cause: err });
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
throw err;
|
|
969
|
+
}
|
|
970
|
+
const want = await sha256Hex(bytes);
|
|
971
|
+
if (res?.size !== bytes.length || want !== void 0 && res.sha256 !== want) {
|
|
972
|
+
throw new InstaboxError(
|
|
973
|
+
`the sandbox received ${res?.size} bytes with sha256 ${res?.sha256}; sent ${bytes.length} with ${want}`,
|
|
974
|
+
{ code: "transfer_mismatch" }
|
|
975
|
+
);
|
|
976
|
+
}
|
|
977
|
+
return true;
|
|
978
|
+
}
|
|
979
|
+
async writeExec(path, bytes) {
|
|
483
980
|
const p = arg(path);
|
|
484
981
|
const tmp = arg(`${path}.instabox-${Math.random().toString(36).slice(2, 10)}.tmp`);
|
|
485
982
|
const b64 = bytesToBase64(bytes);
|
|
@@ -501,7 +998,22 @@ var Files = class {
|
|
|
501
998
|
});
|
|
502
999
|
throw err;
|
|
503
1000
|
}
|
|
504
|
-
|
|
1001
|
+
}
|
|
1002
|
+
/** The file routes take absolute paths; a relative one is relative to exec's working directory (HOME). */
|
|
1003
|
+
async absolute(path) {
|
|
1004
|
+
if (path.startsWith("/")) return path;
|
|
1005
|
+
this.home ??= this.commands.exec(`printf '%s' "$PWD"`).then((r) => {
|
|
1006
|
+
ensureComplete(r);
|
|
1007
|
+
if (!r.stdout.startsWith("/")) {
|
|
1008
|
+
throw new InstaboxError("invalid working directory returned by exec", { code: "invalid_response" });
|
|
1009
|
+
}
|
|
1010
|
+
return r.stdout;
|
|
1011
|
+
});
|
|
1012
|
+
const home = await this.home.catch((err) => {
|
|
1013
|
+
this.home = void 0;
|
|
1014
|
+
throw err;
|
|
1015
|
+
});
|
|
1016
|
+
return `${home.replace(/\/+$/, "")}/${path}`;
|
|
505
1017
|
}
|
|
506
1018
|
/** Lists the entries of a directory (not recursive). */
|
|
507
1019
|
async list(path) {
|
|
@@ -532,6 +1044,51 @@ var Files = class {
|
|
|
532
1044
|
function arg(path) {
|
|
533
1045
|
return shellQuote(path.startsWith("-") ? `./${path}` : path);
|
|
534
1046
|
}
|
|
1047
|
+
async function readBody(res, limit, path) {
|
|
1048
|
+
const tooLarge = () => new InstaboxError(`${path} is larger than the ${limit}-byte limit of files.read`, { code: "file_too_large" });
|
|
1049
|
+
const reader = res.body?.getReader();
|
|
1050
|
+
if (!reader) return new Uint8Array(0);
|
|
1051
|
+
const chunks = [];
|
|
1052
|
+
let n = 0;
|
|
1053
|
+
try {
|
|
1054
|
+
for (; ; ) {
|
|
1055
|
+
const { done, value } = await reader.read();
|
|
1056
|
+
if (done) break;
|
|
1057
|
+
n += value.length;
|
|
1058
|
+
if (n > limit) {
|
|
1059
|
+
void reader.cancel().catch(() => {
|
|
1060
|
+
});
|
|
1061
|
+
throw tooLarge();
|
|
1062
|
+
}
|
|
1063
|
+
chunks.push(value);
|
|
1064
|
+
}
|
|
1065
|
+
} catch (err) {
|
|
1066
|
+
if (err instanceof InstaboxError) throw err;
|
|
1067
|
+
throw new InstaboxError(`reading ${path} stopped after ${n} bytes: ${err?.message ?? String(err)}`, {
|
|
1068
|
+
code: "file_changed",
|
|
1069
|
+
retryable: true,
|
|
1070
|
+
cause: err
|
|
1071
|
+
});
|
|
1072
|
+
}
|
|
1073
|
+
const out = new Uint8Array(n);
|
|
1074
|
+
let off = 0;
|
|
1075
|
+
for (const c of chunks) {
|
|
1076
|
+
out.set(c, off);
|
|
1077
|
+
off += c.length;
|
|
1078
|
+
}
|
|
1079
|
+
return out;
|
|
1080
|
+
}
|
|
1081
|
+
function routeMissing(err) {
|
|
1082
|
+
if (!(err instanceof InstaboxError)) return false;
|
|
1083
|
+
if (err.status === 405) return true;
|
|
1084
|
+
return err.status === 404 && (err.code === "http_404" || err.code === "not_found" && err.message === "route not found");
|
|
1085
|
+
}
|
|
1086
|
+
async function sha256Hex(bytes) {
|
|
1087
|
+
const subtle = globalThis.crypto?.subtle;
|
|
1088
|
+
if (!subtle) return void 0;
|
|
1089
|
+
const d = new Uint8Array(await subtle.digest("SHA-256", bytes));
|
|
1090
|
+
return Array.from(d, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
1091
|
+
}
|
|
535
1092
|
function writeError(result, path) {
|
|
536
1093
|
if (result.exitCode === 21) return new InstaboxError(`is a directory: ${path}`, { code: "is_a_directory" });
|
|
537
1094
|
return new CommandExitError(result);
|
|
@@ -540,18 +1097,42 @@ function ensureComplete(result) {
|
|
|
540
1097
|
if (result.exitCode !== 0) throw new CommandExitError(result);
|
|
541
1098
|
if (result.truncated) throw new InstaboxError("file command output was truncated", { code: "output_truncated" });
|
|
542
1099
|
}
|
|
1100
|
+
function decodeUtf8(bytes) {
|
|
1101
|
+
try {
|
|
1102
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
1103
|
+
} catch (err) {
|
|
1104
|
+
throw new InstaboxNotUtf8Error("file is not UTF-8 text; read it with { format: 'bytes' }", {
|
|
1105
|
+
code: "not_utf8",
|
|
1106
|
+
cause: err
|
|
1107
|
+
});
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
543
1110
|
|
|
544
1111
|
// src/http.ts
|
|
545
1112
|
var DEFAULT_API_URL = "https://api.instabox.sh";
|
|
546
1113
|
var MAX_RETRIES = 3;
|
|
1114
|
+
var REDACTED = "[redacted]";
|
|
1115
|
+
var BUILTIN_ERRORS = new Set(
|
|
1116
|
+
[Error, TypeError, RangeError, SyntaxError, ReferenceError, EvalError, URIError].map((c) => c.prototype)
|
|
1117
|
+
);
|
|
1118
|
+
function guarded(f) {
|
|
1119
|
+
try {
|
|
1120
|
+
return f();
|
|
1121
|
+
} catch {
|
|
1122
|
+
return void 0;
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
547
1125
|
var HttpClient = class {
|
|
548
1126
|
apiUrl;
|
|
549
1127
|
operationTimeoutMs;
|
|
550
|
-
|
|
1128
|
+
// An ES private field: invisible to JSON.stringify, util.inspect, structuredClone and property walks.
|
|
1129
|
+
#apiKey;
|
|
551
1130
|
requestTimeoutMs;
|
|
552
1131
|
fetchImpl;
|
|
553
1132
|
pollIntervalMs;
|
|
554
1133
|
retryDelayMs;
|
|
1134
|
+
/** Removes the caller's abort listener of a response `send` returned; see `release`. */
|
|
1135
|
+
releases = /* @__PURE__ */ new WeakMap();
|
|
555
1136
|
constructor(opts = {}) {
|
|
556
1137
|
const apiKey = opts.apiKey ?? readEnv("INSTABOX_API_KEY");
|
|
557
1138
|
if (!apiKey) {
|
|
@@ -560,7 +1141,7 @@ var HttpClient = class {
|
|
|
560
1141
|
{ code: "missing_api_key" }
|
|
561
1142
|
);
|
|
562
1143
|
}
|
|
563
|
-
this
|
|
1144
|
+
this.#apiKey = apiKey;
|
|
564
1145
|
this.apiUrl = (opts.apiUrl ?? readEnv("INSTABOX_API_URL") ?? DEFAULT_API_URL).replace(/\/+$/, "");
|
|
565
1146
|
this.requestTimeoutMs = opts.requestTimeoutMs;
|
|
566
1147
|
this.operationTimeoutMs = opts.operationTimeoutMs ?? 6e5;
|
|
@@ -572,8 +1153,23 @@ var HttpClient = class {
|
|
|
572
1153
|
}
|
|
573
1154
|
async request(method, path, opts = {}) {
|
|
574
1155
|
const res = await this.send(method, path, opts);
|
|
575
|
-
|
|
576
|
-
|
|
1156
|
+
try {
|
|
1157
|
+
if (res.status === 204) return void 0;
|
|
1158
|
+
return await res.json();
|
|
1159
|
+
} finally {
|
|
1160
|
+
this.release(res);
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
/**
|
|
1164
|
+
* Unwires the caller's `signal` from a response `send` returned, once its body is read or dropped.
|
|
1165
|
+
* Until then an abort still ends the body; after it the signal holds no listener of this request,
|
|
1166
|
+
* so a signal shared by many requests (a long `wait()`) does not collect one per request.
|
|
1167
|
+
*/
|
|
1168
|
+
release(res) {
|
|
1169
|
+
const f = this.releases.get(res);
|
|
1170
|
+
if (!f) return;
|
|
1171
|
+
this.releases.delete(res);
|
|
1172
|
+
f();
|
|
577
1173
|
}
|
|
578
1174
|
/** Performs the request with retries; returns a 2xx response or throws an InstaboxError. */
|
|
579
1175
|
async send(method, path, opts = {}) {
|
|
@@ -581,15 +1177,20 @@ var HttpClient = class {
|
|
|
581
1177
|
const idempotent = opts.idempotent ?? !isRead;
|
|
582
1178
|
const retry = opts.retry ?? (isRead || idempotent);
|
|
583
1179
|
const headers = {
|
|
584
|
-
"X-API-Key": this
|
|
585
|
-
Accept: "application/json"
|
|
1180
|
+
"X-API-Key": this.#apiKey,
|
|
1181
|
+
Accept: opts.accept ?? "application/json",
|
|
1182
|
+
...opts.headers
|
|
586
1183
|
};
|
|
587
1184
|
if (idempotent) headers["Idempotency-Key"] = uuid();
|
|
588
1185
|
let body;
|
|
589
|
-
if (opts.
|
|
1186
|
+
if (opts.rawBody !== void 0) {
|
|
1187
|
+
headers["Content-Type"] = "application/octet-stream";
|
|
1188
|
+
body = opts.rawBody;
|
|
1189
|
+
} else if (opts.body !== void 0) {
|
|
590
1190
|
headers["Content-Type"] = "application/json";
|
|
591
1191
|
body = JSON.stringify(opts.body);
|
|
592
1192
|
}
|
|
1193
|
+
const where = this.#redact(`${method} ${path}`);
|
|
593
1194
|
let url = this.apiUrl + path;
|
|
594
1195
|
if (opts.query) {
|
|
595
1196
|
const q = new URLSearchParams();
|
|
@@ -609,44 +1210,124 @@ var HttpClient = class {
|
|
|
609
1210
|
timedOut = true;
|
|
610
1211
|
ctrl.abort();
|
|
611
1212
|
}, timeoutMs);
|
|
1213
|
+
const onAbort = () => ctrl.abort();
|
|
1214
|
+
if (opts.signal?.aborted) ctrl.abort();
|
|
1215
|
+
else opts.signal?.addEventListener("abort", onAbort, { once: true });
|
|
612
1216
|
let res;
|
|
613
1217
|
try {
|
|
614
1218
|
res = await this.fetchImpl(url, { method, headers, body, signal: ctrl.signal });
|
|
615
1219
|
} catch (err) {
|
|
616
1220
|
clearTimeout(timer);
|
|
1221
|
+
opts.signal?.removeEventListener("abort", onAbort);
|
|
1222
|
+
if (opts.signal?.aborted) throw new InstaboxError(`${where} was aborted`, { code: "aborted" });
|
|
617
1223
|
if (canRetry) {
|
|
618
1224
|
await sleep(this.backoff(attempt));
|
|
619
1225
|
continue;
|
|
620
1226
|
}
|
|
1227
|
+
const cause = this.#copyError(err);
|
|
621
1228
|
if (timedOut) {
|
|
622
|
-
throw new InstaboxTimeoutError(`${
|
|
1229
|
+
throw new InstaboxTimeoutError(`${where} timed out after ${timeoutMs} ms`, {
|
|
623
1230
|
code: "request_timeout",
|
|
624
|
-
cause
|
|
1231
|
+
cause
|
|
625
1232
|
});
|
|
626
1233
|
}
|
|
627
|
-
throw new InstaboxError(`${
|
|
1234
|
+
throw new InstaboxError(`${where} failed: ${cause.message}`, {
|
|
628
1235
|
code: "network_error",
|
|
629
1236
|
retryable: true,
|
|
630
|
-
cause
|
|
1237
|
+
cause
|
|
631
1238
|
});
|
|
632
1239
|
}
|
|
633
1240
|
clearTimeout(timer);
|
|
634
|
-
|
|
1241
|
+
const unwire = () => opts.signal?.removeEventListener("abort", onAbort);
|
|
1242
|
+
if (res.ok) {
|
|
1243
|
+
if (opts.signal) this.releases.set(res, unwire);
|
|
1244
|
+
return res;
|
|
1245
|
+
}
|
|
635
1246
|
if (canRetry && res.status >= 502 && res.status <= 504) {
|
|
1247
|
+
unwire();
|
|
636
1248
|
void res.body?.cancel().catch(() => {
|
|
637
1249
|
});
|
|
638
1250
|
await sleep(this.backoff(attempt));
|
|
639
1251
|
continue;
|
|
640
1252
|
}
|
|
641
|
-
const text = await res.text().catch(() => "");
|
|
1253
|
+
const text = this.#redact(await res.text().catch(() => ""));
|
|
1254
|
+
unwire();
|
|
642
1255
|
let parsed = null;
|
|
643
1256
|
try {
|
|
644
|
-
parsed = text ? JSON.parse(text) : null;
|
|
1257
|
+
parsed = text ? JSON.parse(text, (_k, v) => typeof v === "string" ? this.#redact(v) : v) : null;
|
|
645
1258
|
} catch {
|
|
646
1259
|
parsed = null;
|
|
647
1260
|
}
|
|
648
|
-
throw errorFromResponse(res.status, parsed, `${
|
|
1261
|
+
throw errorFromResponse(res.status, parsed, `${where} returned ${res.status}`);
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
/** The deadline of one request: `requestTimeoutMs` when set, else `defaultMs`. */
|
|
1265
|
+
requestTimeout(defaultMs) {
|
|
1266
|
+
return this.requestTimeoutMs ?? defaultMs;
|
|
1267
|
+
}
|
|
1268
|
+
/**
|
|
1269
|
+
* The error for an API error envelope found in a 2xx response body (a streamed exec's `error`
|
|
1270
|
+
* event), with the API key redacted as for an error response.
|
|
1271
|
+
*/
|
|
1272
|
+
errorFromBody(status, text, fallbackMessage) {
|
|
1273
|
+
let parsed = null;
|
|
1274
|
+
try {
|
|
1275
|
+
parsed = JSON.parse(this.#redact(text), (_k, v) => typeof v === "string" ? this.#redact(v) : v);
|
|
1276
|
+
} catch {
|
|
1277
|
+
parsed = null;
|
|
1278
|
+
}
|
|
1279
|
+
return errorFromResponse(status, parsed, this.#redact(fallbackMessage));
|
|
1280
|
+
}
|
|
1281
|
+
/** Replaces the API key in `s`. */
|
|
1282
|
+
#redact(s) {
|
|
1283
|
+
return s.split(this.#apiKey).join(REDACTED);
|
|
1284
|
+
}
|
|
1285
|
+
/**
|
|
1286
|
+
* A copy of an error thrown by fetch, safe to hand to the app. Some fetch implementations put the request
|
|
1287
|
+
* (and so the X-API-Key header) in their errors, and a custom fetch may throw anything, so the original is
|
|
1288
|
+
* never passed on. The copy keeps the message, name, stack and the string, number and boolean fields (all
|
|
1289
|
+
* with the key redacted), and a copy of the cause. Object fields such as a request config are dropped.
|
|
1290
|
+
* Built-in error classes are kept (`instanceof TypeError` still holds); other classes keep only their name.
|
|
1291
|
+
* Every read is guarded, so a getter or proxy that throws cannot leak the key or replace this error.
|
|
1292
|
+
*/
|
|
1293
|
+
#copyError(err, depth = 3) {
|
|
1294
|
+
const isError = guarded(() => err instanceof Error) === true;
|
|
1295
|
+
const raw = guarded(() => isError ? err.message : err);
|
|
1296
|
+
const message = this.#redact(guarded(() => String(raw)) ?? REDACTED);
|
|
1297
|
+
const copy = new Error(message);
|
|
1298
|
+
if (!isError) return copy;
|
|
1299
|
+
const e = err;
|
|
1300
|
+
const proto = guarded(() => Object.getPrototypeOf(e));
|
|
1301
|
+
if (BUILTIN_ERRORS.has(proto)) Object.setPrototypeOf(copy, proto);
|
|
1302
|
+
const name = guarded(() => String(e.name));
|
|
1303
|
+
if (name !== void 0)
|
|
1304
|
+
Object.defineProperty(copy, "name", { value: this.#redact(name), configurable: true, writable: true });
|
|
1305
|
+
const stack = guarded(() => e.stack);
|
|
1306
|
+
if (typeof stack === "string") copy.stack = this.#redact(stack);
|
|
1307
|
+
for (const k of guarded(() => Object.getOwnPropertyNames(e)) ?? []) {
|
|
1308
|
+
if (k === "message" || k === "stack" || k === "name" || k === "cause") continue;
|
|
1309
|
+
const d = guarded(() => Object.getOwnPropertyDescriptor(e, k));
|
|
1310
|
+
if (!d || !("value" in d) || !d.enumerable) continue;
|
|
1311
|
+
if (typeof d.value === "string") copy[this.#redact(k)] = this.#redact(d.value);
|
|
1312
|
+
else if (typeof d.value === "number" || typeof d.value === "boolean") copy[this.#redact(k)] = d.value;
|
|
649
1313
|
}
|
|
1314
|
+
const cause = guarded(() => e.cause);
|
|
1315
|
+
if (cause !== void 0 && depth > 0) {
|
|
1316
|
+
Object.defineProperty(copy, "cause", {
|
|
1317
|
+
value: this.#copyError(cause, depth - 1),
|
|
1318
|
+
configurable: true,
|
|
1319
|
+
writable: true
|
|
1320
|
+
});
|
|
1321
|
+
}
|
|
1322
|
+
return copy;
|
|
1323
|
+
}
|
|
1324
|
+
/** JSON form, without the API key. */
|
|
1325
|
+
toJSON() {
|
|
1326
|
+
return { apiUrl: this.apiUrl, apiKey: REDACTED };
|
|
1327
|
+
}
|
|
1328
|
+
/** `util.inspect` and `console.log` form, without the API key. */
|
|
1329
|
+
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")](_depth, options, inspect) {
|
|
1330
|
+
return `HttpClient ${inspect(this.toJSON(), options)}`;
|
|
650
1331
|
}
|
|
651
1332
|
backoff(attempt) {
|
|
652
1333
|
return this.retryDelayMs * 2 ** attempt;
|
|
@@ -659,17 +1340,22 @@ var HttpClient = class {
|
|
|
659
1340
|
while (cur.state !== "succeeded") {
|
|
660
1341
|
if (cur.state === "failed") {
|
|
661
1342
|
const e = cur.error;
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
1343
|
+
const r = (v) => typeof v === "string" ? this.#redact(v) : void 0;
|
|
1344
|
+
const code = r(e?.code) ?? "operation_failed";
|
|
1345
|
+
const Cls = isLimitCode(code) ? InstaboxQuotaError : InstaboxError;
|
|
1346
|
+
throw new Cls(r(e?.message || `operation ${cur.id} (${cur.type}) failed`) ?? REDACTED, {
|
|
1347
|
+
code,
|
|
1348
|
+
requestId: r(e?.requestId),
|
|
665
1349
|
retryable: e?.retryable ?? false,
|
|
666
|
-
operationId: cur.id
|
|
1350
|
+
operationId: r(cur.id)
|
|
667
1351
|
});
|
|
668
1352
|
}
|
|
669
1353
|
if (Date.now() + delay > deadline) {
|
|
670
1354
|
throw new InstaboxTimeoutError(
|
|
671
|
-
|
|
672
|
-
|
|
1355
|
+
this.#redact(
|
|
1356
|
+
`operation ${cur.id} (${cur.type}) did not finish within ${timeoutMs} ms (state ${cur.state}${cur.phase ? `, phase ${cur.phase}` : ""})`
|
|
1357
|
+
),
|
|
1358
|
+
{ code: "operation_timeout", operationId: this.#redact(String(cur.id)) }
|
|
673
1359
|
);
|
|
674
1360
|
}
|
|
675
1361
|
await sleep(delay);
|
|
@@ -691,16 +1377,20 @@ function toInfo(m) {
|
|
|
691
1377
|
metadata: { ...m.metadata },
|
|
692
1378
|
vault: m.vault ?? true,
|
|
693
1379
|
startedAt: new Date(m.createdAt),
|
|
694
|
-
onTimeout: m.onTimeout ?? "pause",
|
|
695
1380
|
state: m.state,
|
|
696
1381
|
machine: m
|
|
697
1382
|
};
|
|
698
1383
|
if (m.snapshot?.id) info.snapshotId = m.snapshot.id;
|
|
699
|
-
if (m.timeoutAt) info.endAt = new Date(m.timeoutAt);
|
|
700
1384
|
if (m.archiveAt) info.archiveAt = new Date(m.archiveAt);
|
|
701
1385
|
if (m.autoSuspendAfterSeconds) info.autoSuspendMs = m.autoSuspendAfterSeconds * 1e3;
|
|
702
1386
|
return info;
|
|
703
1387
|
}
|
|
1388
|
+
function timeoutRemoved(what, use) {
|
|
1389
|
+
return new InstaboxError(
|
|
1390
|
+
`${what}: sandboxes have no lifetime timeout since 2026-10-20 (removed in @insforge/instabox-sdk 0.6.0), so it would do nothing. ${use}, or call kill() when you are done (in a finally block)`,
|
|
1391
|
+
{ code: "retired_option" }
|
|
1392
|
+
);
|
|
1393
|
+
}
|
|
704
1394
|
function toIdleSeconds(ms) {
|
|
705
1395
|
if (ms === 0) return 0;
|
|
706
1396
|
const s = Math.ceil(ms / 1e3);
|
|
@@ -711,7 +1401,7 @@ function toIdleSeconds(ms) {
|
|
|
711
1401
|
}
|
|
712
1402
|
return s;
|
|
713
1403
|
}
|
|
714
|
-
function toSeconds(ms, field
|
|
1404
|
+
function toSeconds(ms, field) {
|
|
715
1405
|
const s = Math.ceil(ms / 1e3);
|
|
716
1406
|
if (!Number.isFinite(ms) || s < 60 || s > 86400) {
|
|
717
1407
|
throw new InstaboxError(`${field} must be between 60 000 (60 s) and 86 400 000 (24 h); got ${ms}`, {
|
|
@@ -728,7 +1418,7 @@ var Sandbox = class _Sandbox {
|
|
|
728
1418
|
this.sandboxId = machine.id;
|
|
729
1419
|
this.machine = machine;
|
|
730
1420
|
this.commands = new Commands(http, machine.id, { ...opts.envs });
|
|
731
|
-
this.files = new Files(this.commands);
|
|
1421
|
+
this.files = new Files(this.commands, http, machine.id);
|
|
732
1422
|
this.desktop = new Desktop(http, machine.id, this.commands, this.files);
|
|
733
1423
|
}
|
|
734
1424
|
http;
|
|
@@ -743,9 +1433,17 @@ var Sandbox = class _Sandbox {
|
|
|
743
1433
|
machine;
|
|
744
1434
|
static async create(a, b) {
|
|
745
1435
|
const opts = (typeof a === "string" ? b : a) ?? {};
|
|
1436
|
+
const retired = ["timeoutMs", "onTimeout"].filter(
|
|
1437
|
+
(k) => opts[k] !== void 0
|
|
1438
|
+
);
|
|
1439
|
+
if (retired.length) {
|
|
1440
|
+
throw timeoutRemoved(
|
|
1441
|
+
retired.join(" and "),
|
|
1442
|
+
"Use autoSuspendMs to pause the sandbox once it has been idle that long (default 30 minutes), archiveMs to stop and archive it that long after creation"
|
|
1443
|
+
);
|
|
1444
|
+
}
|
|
746
1445
|
const http = new HttpClient(opts);
|
|
747
1446
|
const body = { name: opts.name ?? `sbx-${randomSuffix()}` };
|
|
748
|
-
if (opts.timeoutMs !== void 0) body.timeoutSeconds = toSeconds(opts.timeoutMs);
|
|
749
1447
|
if (opts.archiveMs !== void 0) body.archiveSeconds = toSeconds(opts.archiveMs, "archiveMs");
|
|
750
1448
|
if (opts.autoSuspendMs !== void 0) body.autoSuspendAfterSeconds = toIdleSeconds(opts.autoSuspendMs);
|
|
751
1449
|
const template = typeof a === "string" ? a : await defaultTemplate(http);
|
|
@@ -754,7 +1452,6 @@ var Sandbox = class _Sandbox {
|
|
|
754
1452
|
if (opts.memMiB !== void 0) body.memMiB = opts.memMiB;
|
|
755
1453
|
if (opts.diskGiB !== void 0) body.persistentDiskGiB = opts.diskGiB;
|
|
756
1454
|
if (opts.rootDiskGiB !== void 0) body.rootDiskGiB = opts.rootDiskGiB;
|
|
757
|
-
if (opts.onTimeout) body.onTimeout = opts.onTimeout;
|
|
758
1455
|
if (opts.metadata) body.metadata = opts.metadata;
|
|
759
1456
|
if (opts.vault === false) body.vault = false;
|
|
760
1457
|
const op = await createMachine(http, body);
|
|
@@ -847,24 +1544,23 @@ var Sandbox = class _Sandbox {
|
|
|
847
1544
|
this.machine = await getMachine(this.http, this.sandboxId);
|
|
848
1545
|
return toInfo(this.machine);
|
|
849
1546
|
}
|
|
850
|
-
/**
|
|
851
|
-
* Sets the timeout to `timeoutMs` from now (whole seconds, 60 s to 24 h); 0 clears it.
|
|
852
|
-
* `onTimeout` changes what happens then (`pause` or `kill`).
|
|
853
|
-
*/
|
|
854
|
-
async setTimeout(timeoutMs, opts = {}) {
|
|
855
|
-
const body = { timeoutSeconds: timeoutMs === 0 ? 0 : toSeconds(timeoutMs) };
|
|
856
|
-
if (opts.onTimeout) body.onTimeout = opts.onTimeout;
|
|
857
|
-
this.machine = await this.http.request("PATCH", `/v1/machines/${enc2(this.sandboxId)}`, { body });
|
|
858
|
-
}
|
|
859
1547
|
/**
|
|
860
1548
|
* Pauses the sandbox once it has been idle `idleMs` (whole seconds, 2 min to 24 h); 0 turns the idle
|
|
861
|
-
* pause off.
|
|
1549
|
+
* pause off. The setting stays across pause and resume.
|
|
862
1550
|
*/
|
|
863
1551
|
async setAutoSuspend(idleMs) {
|
|
864
1552
|
this.machine = await this.http.request("PATCH", `/v1/machines/${enc2(this.sandboxId)}`, {
|
|
865
1553
|
body: { autoSuspendAfterSeconds: toIdleSeconds(idleMs) }
|
|
866
1554
|
});
|
|
867
1555
|
}
|
|
1556
|
+
/**
|
|
1557
|
+
* @deprecated Removed in 0.6.0: sandboxes have no lifetime timeout since 2026-10-20. Always rejects with
|
|
1558
|
+
* `InstaboxError` (`code: 'retired_option'`) naming the replacements (`setAutoSuspend()`, `kill()`), and
|
|
1559
|
+
* sends no request.
|
|
1560
|
+
*/
|
|
1561
|
+
async setTimeout(..._args) {
|
|
1562
|
+
throw timeoutRemoved("setTimeout()", "Use setAutoSuspend(ms) to pause the sandbox once it has been idle that long");
|
|
1563
|
+
}
|
|
868
1564
|
/** Replaces the sandbox's metadata (`{}` clears it). */
|
|
869
1565
|
async setMetadata(metadata) {
|
|
870
1566
|
this.machine = await this.http.request("PATCH", `/v1/machines/${enc2(this.sandboxId)}`, {
|
|
@@ -1007,7 +1703,9 @@ async function getUsage(http, id, opts) {
|
|
|
1007
1703
|
}
|
|
1008
1704
|
async function killMachine(http, id) {
|
|
1009
1705
|
try {
|
|
1010
|
-
const op = await http.request("DELETE", `/v1/machines/${enc2(id)}
|
|
1706
|
+
const op = await http.request("DELETE", `/v1/machines/${enc2(id)}`, {
|
|
1707
|
+
headers: { "X-Confirm-Delete": id }
|
|
1708
|
+
});
|
|
1011
1709
|
await http.waitForOperation(op);
|
|
1012
1710
|
return true;
|
|
1013
1711
|
} catch (err) {
|
|
@@ -1062,10 +1760,13 @@ export {
|
|
|
1062
1760
|
Files,
|
|
1063
1761
|
InstaboxAuthError,
|
|
1064
1762
|
InstaboxError,
|
|
1763
|
+
InstaboxNotUtf8Error,
|
|
1065
1764
|
InstaboxQuotaError,
|
|
1066
1765
|
InstaboxTimeoutError,
|
|
1766
|
+
LIMIT_CODES,
|
|
1067
1767
|
MAX_FILE_BYTES,
|
|
1068
1768
|
MAX_STDIN_BYTES,
|
|
1069
|
-
Sandbox
|
|
1769
|
+
Sandbox,
|
|
1770
|
+
isLimitCode
|
|
1070
1771
|
};
|
|
1071
1772
|
//# sourceMappingURL=index.js.map
|