@insforge/instabox-sdk 0.5.3 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js 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,142 @@ 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
+ }
253
+ function utf8Text(bytes) {
254
+ try {
255
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
256
+ } catch {
257
+ return void 0;
258
+ }
259
+ }
105
260
  var Commands = class {
106
261
  /** @internal */
107
262
  constructor(http, sandboxId, defaultEnvs) {
@@ -112,29 +267,50 @@ var Commands = class {
112
267
  http;
113
268
  sandboxId;
114
269
  defaultEnvs;
270
+ /**
271
+ * @internal Uploads stdin the exec request cannot carry to a temporary file and returns its path
272
+ * (set by `Sandbox`, which owns the file routes).
273
+ */
274
+ stageStdin;
115
275
  async run(cmd, opts = {}) {
116
- if (opts.background) {
117
- 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 $!`;
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);
276
+ if (opts.background) return this.startJob(cmd, opts);
277
+ let o = opts;
278
+ let staged;
279
+ if (opts.stdin !== void 0) {
280
+ const bytes = typeof opts.stdin === "string" ? new TextEncoder().encode(opts.stdin) : opts.stdin;
281
+ if (!(bytes instanceof Uint8Array)) {
282
+ throw new InstaboxError("stdin must be a string or a Uint8Array", { code: "bad_request" });
283
+ }
284
+ const text = bytes.length <= MAX_STDIN_BYTES ? utf8Text(bytes) : void 0;
285
+ if (text !== void 0) o = { ...opts, stdin: text };
286
+ else {
287
+ if (!this.stageStdin) {
288
+ throw new InstaboxError(`stdin is longer than ${MAX_STDIN_BYTES} bytes or not UTF-8 text`, {
289
+ code: "bad_request"
290
+ });
291
+ }
292
+ staged = await this.stageStdin(bytes, opts.signal);
293
+ const q2 = shellQuote(staged);
294
+ cmd = `exec <${q2} || exit 1
295
+ rm -f -- ${q2}
296
+ ${cmd}`;
297
+ o = { ...opts, stdin: void 0 };
298
+ }
299
+ }
300
+ let r;
301
+ try {
302
+ r = o.onStdout || o.onStderr ? await this.execStream(cmd, o) : await this.exec(cmd, o);
303
+ } finally {
304
+ if (staged && !r) await this.exec(`rm -f -- ${shellQuote(staged)}`, { noHistory: true }).catch(() => {
305
+ });
306
+ }
133
307
  if (r.exitCode !== 0) throw new CommandExitError(r);
134
308
  return r;
135
309
  }
136
- /** @internal Raw exec: never throws on a non-zero exit code. */
137
- async exec(cmd, opts = {}) {
310
+ get execPath() {
311
+ return `/v1/machines/${encodeURIComponent(this.sandboxId)}/exec`;
312
+ }
313
+ execBody(cmd, opts) {
138
314
  const envs = { ...this.defaultEnvs, ...opts.envs };
139
315
  const body = { cmd };
140
316
  if (opts.cwd !== void 0) body.cwd = opts.cwd;
@@ -146,30 +322,297 @@ var Commands = class {
146
322
  body.stdin = opts.stdin;
147
323
  }
148
324
  if (opts.timeoutMs !== void 0) {
149
- if (!Number.isFinite(opts.timeoutMs) || opts.timeoutMs <= 0 || opts.timeoutMs > 6e5) {
150
- throw new InstaboxError("command timeoutMs must be greater than 0 and at most 600 000", { code: "bad_request" });
325
+ if (!Number.isFinite(opts.timeoutMs) || opts.timeoutMs <= 0 || opts.timeoutMs > MAX_TIMEOUT_MS) {
326
+ throw new InstaboxError(
327
+ "command timeoutMs must be greater than 0 and at most 600 000; for a longer command use { background: true } and wait() on the handle",
328
+ { code: "bad_request" }
329
+ );
151
330
  }
152
331
  body.timeoutSeconds = Math.ceil(opts.timeoutMs / 1e3);
153
332
  }
154
- const res = await this.http.request(
155
- "POST",
156
- `/v1/machines/${encodeURIComponent(this.sandboxId)}/exec`,
157
- {
158
- body,
159
- retry: false,
160
- idempotent: false,
161
- timeoutMs: (Number(body.timeoutSeconds) || 60) * 1e3 + 3e4
333
+ if (opts.noHistory) body.noHistory = true;
334
+ if (opts.historyCommand !== void 0) body.historyCommand = opts.historyCommand;
335
+ return body;
336
+ }
337
+ /** The request deadline of an exec: its command timeout plus 30 s, unless `requestTimeoutMs` is set. */
338
+ execDeadline(body) {
339
+ return this.http.requestTimeout((Number(body.timeoutSeconds) || 60) * 1e3 + 3e4);
340
+ }
341
+ /** @internal Raw exec: never throws on a non-zero exit code. */
342
+ async exec(cmd, opts = {}) {
343
+ const body = this.execBody(cmd, opts);
344
+ if (opts.signal?.aborted) throw aborted();
345
+ const res = await this.http.request("POST", this.execPath, {
346
+ body,
347
+ retry: false,
348
+ idempotent: false,
349
+ timeoutMs: this.execDeadline(body),
350
+ signal: opts.signal
351
+ });
352
+ return toResult(res);
353
+ }
354
+ /**
355
+ * Exec with the output streamed (`Accept: text/event-stream`): each `stdout`/`stderr` event goes to its
356
+ * callback as it arrives, and the result carries all of it. A server that does not stream answers with
357
+ * the whole result, whose output is passed to the callbacks then.
358
+ */
359
+ async execStream(cmd, opts) {
360
+ const body = this.execBody(cmd, opts);
361
+ if (opts.signal?.aborted) throw aborted();
362
+ const deadline = this.execDeadline(body);
363
+ const ctrl = new AbortController();
364
+ let timedOut = false;
365
+ const timer = setTimeout(() => {
366
+ timedOut = true;
367
+ ctrl.abort();
368
+ }, deadline);
369
+ const onAbort = () => ctrl.abort();
370
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
371
+ let reader;
372
+ let res;
373
+ const fail = (e) => {
374
+ if (opts.signal?.aborted) return aborted();
375
+ if (timedOut) {
376
+ return new InstaboxTimeoutError(`POST ${this.execPath} timed out after ${deadline} ms`, {
377
+ code: "request_timeout"
378
+ });
162
379
  }
163
- );
164
- const out = {
165
- stdout: res.stdout,
166
- stderr: res.stderr,
167
- exitCode: res.exitCode,
168
- timedOut: res.timedOut,
169
- truncated: res.truncated
380
+ return e;
170
381
  };
171
- if (res.error) out.error = res.error;
172
- return out;
382
+ try {
383
+ try {
384
+ res = await this.http.send("POST", this.execPath, {
385
+ body,
386
+ retry: false,
387
+ idempotent: false,
388
+ timeoutMs: deadline,
389
+ accept: "text/event-stream, application/json",
390
+ signal: ctrl.signal
391
+ });
392
+ } catch (e) {
393
+ throw fail(e);
394
+ }
395
+ const type = (res.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
396
+ if (type !== "text/event-stream" || !res.body) {
397
+ let r;
398
+ try {
399
+ r = toResult(await res.json());
400
+ } catch (e) {
401
+ throw fail(e instanceof InstaboxError ? e : invalid("a body that is not JSON"));
402
+ }
403
+ if (opts.onStdout && r.stdout) await opts.onStdout(r.stdout);
404
+ if (opts.onStderr && r.stderr) await opts.onStderr(r.stderr);
405
+ return r;
406
+ }
407
+ reader = res.body.getReader();
408
+ return await this.readEvents(reader, opts, fail);
409
+ } finally {
410
+ clearTimeout(timer);
411
+ opts.signal?.removeEventListener("abort", onAbort);
412
+ if (reader) void reader.cancel().catch(() => {
413
+ });
414
+ ctrl.abort();
415
+ if (res) this.http.release(res);
416
+ }
417
+ }
418
+ /** Reads a streamed exec's server-sent events until its `exit` or `error` event. */
419
+ async readEvents(reader, opts, fail) {
420
+ const dec2 = new TextDecoder();
421
+ const out = { stdout: "", stderr: "" };
422
+ let buf = "";
423
+ let event = "";
424
+ let data = null;
425
+ for (; ; ) {
426
+ let chunk;
427
+ try {
428
+ chunk = await reader.read();
429
+ } catch {
430
+ throw fail(streamEnded());
431
+ }
432
+ if (chunk.done) throw fail(streamEnded());
433
+ buf += dec2.decode(chunk.value, { stream: true });
434
+ let start = 0;
435
+ for (let nl = buf.indexOf("\n", start); nl >= 0; nl = buf.indexOf("\n", start)) {
436
+ let line = buf.slice(start, nl);
437
+ start = nl + 1;
438
+ if (line.endsWith("\r")) line = line.slice(0, -1);
439
+ if (line === "") {
440
+ const r = await this.dispatch(event, data, out, opts);
441
+ if (r) return r;
442
+ event = "";
443
+ data = null;
444
+ continue;
445
+ }
446
+ if (line.startsWith(":")) continue;
447
+ const colon = line.indexOf(":");
448
+ const field = colon < 0 ? line : line.slice(0, colon);
449
+ let value = colon < 0 ? "" : line.slice(colon + 1);
450
+ if (value.startsWith(" ")) value = value.slice(1);
451
+ if (field === "event") event = value;
452
+ else if (field === "data") data = data === null ? value : `${data}
453
+ ${value}`;
454
+ }
455
+ buf = buf.slice(start);
456
+ }
457
+ }
458
+ /** Handles one event: output goes to its callback, `exit` is the result, `error` is thrown. */
459
+ async dispatch(event, data, out, opts) {
460
+ if (data === null) return void 0;
461
+ if (event === "stdout" || event === "stderr") {
462
+ let chunk;
463
+ try {
464
+ chunk = JSON.parse(data)?.data;
465
+ } catch {
466
+ chunk = void 0;
467
+ }
468
+ if (typeof chunk !== "string") throw invalid(`a ${event} event without data`);
469
+ out[event] += chunk;
470
+ const cb = event === "stdout" ? opts.onStdout : opts.onStderr;
471
+ if (cb && chunk) await cb(chunk);
472
+ return void 0;
473
+ }
474
+ if (event === "exit") {
475
+ let res;
476
+ try {
477
+ res = JSON.parse(data);
478
+ } catch {
479
+ throw invalid("an exit event that is not JSON");
480
+ }
481
+ return { ...toResult(res, out.stdout, out.stderr), truncated: false };
482
+ }
483
+ if (event === "error") {
484
+ let code;
485
+ try {
486
+ code = JSON.parse(data)?.error?.code;
487
+ } catch {
488
+ code = void 0;
489
+ }
490
+ const status = code === "host_unavailable" ? 503 : 500;
491
+ throw this.http.errorFromBody(status, data, `POST ${this.execPath} failed while streaming`);
492
+ }
493
+ return void 0;
494
+ }
495
+ /** Starts a background job the CLI's way and returns its handle. */
496
+ async startJob(cmd, opts) {
497
+ if (opts.stdin !== void 0)
498
+ throw new InstaboxError("stdin is not supported for background commands", { code: "bad_request" });
499
+ if (opts.onStdout || opts.onStderr) {
500
+ throw new InstaboxError(
501
+ "onStdout and onStderr are not supported with background: true; pass onStdout to wait() on the returned handle to follow the output",
502
+ { code: "bad_request" }
503
+ );
504
+ }
505
+ if (cmd.includes("\0")) throw new InstaboxError("the command contains a NUL byte", { code: "bad_request" });
506
+ const jobId = randomSuffix(8);
507
+ const r = await this.exec(jobScript(jobId, { W: JOB_WRAPPER }, JOB_START), {
508
+ cwd: opts.cwd,
509
+ envs: opts.envs,
510
+ timeoutMs: opts.timeoutMs,
511
+ stdin: cmd,
512
+ signal: opts.signal,
513
+ historyCommand: `background: ${cmd}`
514
+ });
515
+ const missing = r.stderr.split("\n").find((l) => l.startsWith(JOB_UNSUPPORTED));
516
+ if (r.exitCode === JOB_UNSUPPORTED_EXIT && missing) {
517
+ throw new InstaboxError(
518
+ `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`,
519
+ { code: "background_unsupported" }
520
+ );
521
+ }
522
+ if (r.exitCode !== 0) throw new CommandExitError(r);
523
+ const pid = Number.parseInt(r.stdout.trim(), 10);
524
+ if (!/^\d+$/.test(r.stdout.trim()) || !Number.isSafeInteger(pid) || pid <= 0)
525
+ throw new InstaboxError("exec returned an invalid background PID", { code: "invalid_response" });
526
+ return {
527
+ pid,
528
+ jobId,
529
+ kill: async () => (await this.exec(`kill -s TERM -- -${pid}`)).exitCode === 0,
530
+ wait: (w) => this.waitJob(jobId, w)
531
+ };
532
+ }
533
+ /** One read of a job: its status and up to `max` bytes of output from `off`, waiting up to `w` seconds. */
534
+ async readJob(jobId, off, max, w, signal) {
535
+ const r = await this.exec(jobScript(jobId, { off: String(off), max: String(max), w: String(w) }, JOB_READ), {
536
+ timeoutMs: (w + 30) * 1e3,
537
+ noHistory: true,
538
+ signal
539
+ });
540
+ if (r.exitCode !== 0 || r.timedOut) {
541
+ const msg = r.stderr.trim().split("\n").slice(-1)[0] || `exit status ${r.exitCode}`;
542
+ throw new InstaboxError(`reading job ${jobId} failed in the sandbox: ${msg}`, { code: "job_read_failed" });
543
+ }
544
+ if (r.truncated) throw invalid("a truncated job read");
545
+ const nl = r.stdout.indexOf("\n");
546
+ const head = (nl < 0 ? r.stdout : r.stdout.slice(0, nl)).trim();
547
+ if (head === JOB_NO_SUCH) return null;
548
+ const rest = nl < 0 ? "" : r.stdout.slice(nl + 1).trim();
549
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(rest)) throw invalid("job output that is not base64");
550
+ const bytes = base64ToBytes(rest);
551
+ const m = /^exited (-?\d+)(?: \S+ \S+ \S+)?$/.exec(head);
552
+ if (m) return { status: "exited", exitCode: Number(m[1]), bytes };
553
+ return { status: head === "running" ? "running" : "lost", bytes };
554
+ }
555
+ /** `readJob` for the wait loop. Reads change nothing, so a transient error is retried for up to 2 minutes. */
556
+ async pollJob(jobId, off, w, until, signal) {
557
+ let delay = 1e3;
558
+ const start = Date.now();
559
+ for (; ; ) {
560
+ try {
561
+ return await this.readJob(jobId, off, JOB_CHUNK, w, signal);
562
+ } catch (e) {
563
+ if (signal?.aborted) throw aborted();
564
+ if (!transient(e) || Date.now() - start > JOB_RETRY_MS || Date.now() + delay >= until) throw e;
565
+ await sleep(delay);
566
+ delay = Math.min(delay * 2, 15e3);
567
+ }
568
+ }
569
+ }
570
+ /** Follows a job's output until it ends. */
571
+ async waitJob(jobId, opts = {}) {
572
+ const { signal } = opts;
573
+ if (opts.timeoutMs !== void 0 && (!Number.isFinite(opts.timeoutMs) || opts.timeoutMs <= 0))
574
+ throw new InstaboxError("wait timeoutMs must be greater than 0", { code: "bad_request" });
575
+ const until = opts.timeoutMs === void 0 ? Infinity : Date.now() + opts.timeoutMs;
576
+ const maxWait = Math.max(0, Math.min(JOB_POLL_SEC, Math.floor((this.http.requestTimeout(Infinity) - 5e3) / 1e3)));
577
+ const dec2 = new TextDecoder();
578
+ let stdout = "";
579
+ let off = 0;
580
+ let idle = JOB_IDLE_MIN_MS;
581
+ const emit = async (text) => {
582
+ stdout += text;
583
+ if (text && opts.onStdout) await opts.onStdout(text);
584
+ };
585
+ for (; ; ) {
586
+ if (signal?.aborted) throw aborted();
587
+ const left = until - Date.now();
588
+ const w = Math.max(0, Math.min(maxWait, Math.ceil(left / 1e3)));
589
+ const read = await this.pollJob(jobId, off, w, until, signal);
590
+ if (read === null) throw new InstaboxError(`no job ${jobId} in the sandbox`, { status: 404, code: "not_found" });
591
+ if (w === 0 && read.status === "running" && read.bytes.length === 0) {
592
+ await abortableSleep(Math.min(idle, Math.max(0, until - Date.now())), signal);
593
+ idle = Math.min(idle * 2, JOB_IDLE_MAX_MS);
594
+ } else if (read.bytes.length > 0) idle = JOB_IDLE_MIN_MS;
595
+ off += read.bytes.length;
596
+ await emit(dec2.decode(read.bytes, { stream: true }));
597
+ if (read.bytes.length === JOB_CHUNK) continue;
598
+ if (read.status !== "running") {
599
+ await emit(dec2.decode());
600
+ if (read.exitCode === void 0) {
601
+ throw new InstaboxError(
602
+ `job ${jobId} ended without an exit code (the sandbox restarted or the job was killed)`,
603
+ { code: "job_lost" }
604
+ );
605
+ }
606
+ const r = { stdout, stderr: "", exitCode: read.exitCode, timedOut: false, truncated: false };
607
+ if (r.exitCode !== 0) throw new CommandExitError(r);
608
+ return r;
609
+ }
610
+ if (Date.now() >= until) {
611
+ throw new InstaboxTimeoutError(`job ${jobId} is still running after ${opts.timeoutMs} ms`, {
612
+ code: "job_wait_timeout"
613
+ });
614
+ }
615
+ }
173
616
  }
174
617
  };
175
618
 
@@ -428,19 +871,639 @@ var Desktop = class {
428
871
  }
429
872
  };
430
873
 
874
+ // src/guest.ts
875
+ var TRANSFER_TMP_PREFIX = "/tmp/.instabox-transfer-";
876
+ var STDIN_TMP_PREFIX = "/tmp/.instabox-stdin-";
877
+ var PUSH_MARK = "INSTABOX-PUSH\0";
878
+ var PULL_MARK = "INSTABOX-PULL\0";
879
+ var EXEC_CHUNK_BYTES = 768e3;
880
+ var GUEST_FNS = `fsize() { local n; n=$(wc -c < "$1") && echo $((n)); }
881
+ fmode() { stat -c %a -- "$1" 2>/dev/null || stat -f %Lp -- "$1"; }
882
+ b64() { base64 | tr -d '\\n'; }
883
+ rng() { { dd bs=1 skip="$2" count=0 2>/dev/null; head -c "$3"; } < "$1"; }
884
+ rpe() { readlink -e -- "$1" 2>/dev/null || { [ -e "$1" ] && rpm "$1"; }; }
885
+ rpm() {
886
+ realpath -m -- "$1" 2>/dev/null && return
887
+ local r; r=$(readlink -f -- "$1" 2>/dev/null) && [ -n "$r" ] && { printf '%s\\n' "$r"; return; }
888
+ r=$(CDPATH= cd -P -- "$(dirname -- "$1")" 2>/dev/null && pwd -P) && { printf '%s/%s\\n' "\${r%/}" "$(basename -- "$1")"; return; }
889
+ case $1 in /*) printf '%s\\n' "$1" ;; *) printf '%s\\n' "$PWD/$1" ;; esac
890
+ }
891
+ `;
892
+ var PUSH_CHUNK_SCRIPT = `if [ "$IB_FIRST" = 1 ]; then (umask 077; set -C; base64 -d > "$IB_TMP"); else base64 -d >> "$IB_TMP"; fi
893
+ `;
894
+ var PUSH_FINISH_SCRIPT = `set -eo pipefail
895
+ trap 'rm -f -- "$IB_TMP"' EXIT
896
+ ${GUEST_FNS}d=$IB_DEST
897
+ case $d in "~") d=$HOME ;; "~/"*) d=$HOME/\${d#"~/"} ;; esac
898
+ mkdir -p -- "$d"
899
+ tar -xzf "$IB_TMP" -C "$d" --no-same-owner
900
+ printf 'INSTABOX-PUSH\\0ok\\0%s\\0' "$(rpm "$d")"
901
+ `;
902
+ var PULL_START = `${GUEST_FNS}set -eo pipefail
903
+ printf 'INSTABOX-PULL\\0'
904
+ r=$(rpe "$1") || { printf 'missing\\0'; exit 0; }
905
+ [ -d "$r" ] || { printf 'not_a_dir\\0%s\\0' "$r"; exit 0; }
906
+ umask 077
907
+ trap '[ "$ok" = 1 ] || rm -f -- "$2"' EXIT
908
+ COPYFILE_DISABLE=1 tar -czf "$2" -C "$r" .
909
+ printf 'dir\\0%s\\0%s\\0' "$r" "$(fsize "$2")"
910
+ ok=1
911
+ `;
912
+ var PULL_CHUNK = `${GUEST_FNS}set -eo pipefail
913
+ printf 'INSTABOX-PULL\\0'
914
+ rng "$3" "$2" "$4" | b64
915
+ `;
916
+ var PULL_REMOVE = `rm -f -- "$2"`;
917
+ function q(s) {
918
+ return `'${s.replace(/'/g, `'\\''`)}'`;
919
+ }
920
+ function pullCmd(script, ...args) {
921
+ const run2 = `bash -c "$S" _ "$p" ${args.map(q).join(" ")}`;
922
+ return `S=${q(script)}
923
+ p=$IB_PATH; case $p in "~") p=$HOME ;; "~/"*) p=$HOME/\${p#"~/"} ;; esac; case $p in /*) ;; *) p=$PWD/$p ;; esac
924
+ if sudo -n true 2>/dev/null; then exec sudo -n ${run2}; else exec ${run2}; fi`;
925
+ }
926
+ var pullStartCmd = (tmp) => pullCmd(PULL_START, tmp);
927
+ var pullChunkCmd = (tmp, off, n) => pullCmd(PULL_CHUNK, String(off), tmp, String(n));
928
+ var pullRemoveCmd = (tmp) => pullCmd(PULL_REMOVE, tmp);
929
+ function randomHex(bytes = 8) {
930
+ const b = new Uint8Array(bytes);
931
+ const c = globalThis.crypto;
932
+ if (c?.getRandomValues) c.getRandomValues(b);
933
+ else for (let i = 0; i < bytes; i++) b[i] = Math.floor(Math.random() * 256);
934
+ return Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
935
+ }
936
+
937
+ // src/tar.ts
938
+ var BLOCK = 512;
939
+ var enc2 = new TextEncoder();
940
+ var dec = new TextDecoder();
941
+ function octal(buf, off, width, value) {
942
+ const s = Math.floor(value).toString(8).padStart(width - 1, "0");
943
+ buf.set(enc2.encode(s.slice(-(width - 1))), off);
944
+ buf[off + width - 1] = 0;
945
+ }
946
+ function putString(buf, off, width, s) {
947
+ buf.set(enc2.encode(s).subarray(0, width), off);
948
+ }
949
+ function isAscii(s) {
950
+ return /^[\x20-\x7e]*$/.test(s);
951
+ }
952
+ function paxRecord(key, value) {
953
+ const body = ` ${key}=${value}
954
+ `;
955
+ const n = enc2.encode(body).length;
956
+ let len = n + String(n).length;
957
+ if (String(len).length !== String(n).length) len = n + String(len).length;
958
+ return `${len}${body}`;
959
+ }
960
+ function header(name, type, mode, mtime, size, linkname) {
961
+ const h = new Uint8Array(BLOCK);
962
+ putString(h, 0, 100, name);
963
+ octal(h, 100, 8, mode & 4095);
964
+ octal(h, 108, 8, 0);
965
+ octal(h, 116, 8, 0);
966
+ octal(h, 124, 12, size);
967
+ octal(h, 136, 12, Math.max(0, mtime));
968
+ h.fill(32, 148, 156);
969
+ h[156] = type.charCodeAt(0);
970
+ putString(h, 157, 100, linkname);
971
+ putString(h, 257, 6, "ustar\0");
972
+ putString(h, 263, 2, "00");
973
+ let sum = 0;
974
+ for (const b of h) sum += b;
975
+ const s = sum.toString(8).padStart(6, "0");
976
+ putString(h, 148, 6, s);
977
+ h[154] = 0;
978
+ h[155] = 32;
979
+ return h;
980
+ }
981
+ var USTAR_MAX_SIZE = 8589934591;
982
+ function headers(e) {
983
+ const name = e.type === "dir" ? `${e.name}/` : e.name;
984
+ const link = e.linkname ?? "";
985
+ const size = e.type === "file" ? e.size ?? 0 : 0;
986
+ const pax = [];
987
+ if (enc2.encode(name).length > 100 || !isAscii(name)) pax.push(paxRecord("path", name));
988
+ if (enc2.encode(link).length > 100 || !isAscii(link)) pax.push(paxRecord("linkpath", link));
989
+ if (size > USTAR_MAX_SIZE) pax.push(paxRecord("size", String(size)));
990
+ const type = e.type === "dir" ? "5" : e.type === "symlink" ? "2" : "0";
991
+ const out = [];
992
+ if (pax.length) {
993
+ const data = enc2.encode(pax.join(""));
994
+ out.push(header("PaxHeader", "x", 420, e.mtime, data.length, ""));
995
+ out.push(padded(data));
996
+ }
997
+ out.push(
998
+ header(asciiPrefix(name, 100), type, e.mode, e.mtime, size > USTAR_MAX_SIZE ? 0 : size, asciiPrefix(link, 100))
999
+ );
1000
+ return out;
1001
+ }
1002
+ function asciiPrefix(s, max) {
1003
+ return s.replace(/[^\x20-\x7e]/g, "_").slice(0, max);
1004
+ }
1005
+ function padded(data) {
1006
+ const n = Math.ceil(data.length / BLOCK) * BLOCK;
1007
+ if (n === data.length) return data;
1008
+ const out = new Uint8Array(n);
1009
+ out.set(data);
1010
+ return out;
1011
+ }
1012
+ async function* tarStream(entries) {
1013
+ for await (const e of entries) {
1014
+ for (const h of headers(e)) yield h;
1015
+ if (e.type !== "file") continue;
1016
+ const size = e.size ?? 0;
1017
+ let n = 0;
1018
+ if (e.data) {
1019
+ for await (const chunk of e.data()) {
1020
+ if (n + chunk.length > size) {
1021
+ throw new InstaboxError(`${e.name} grew while it was being uploaded`, { code: "file_changed" });
1022
+ }
1023
+ n += chunk.length;
1024
+ if (chunk.length) yield chunk;
1025
+ }
1026
+ }
1027
+ if (n !== size) {
1028
+ throw new InstaboxError(`${e.name} shrank while it was being uploaded (${n} of ${size} bytes)`, {
1029
+ code: "file_changed"
1030
+ });
1031
+ }
1032
+ if (size % BLOCK) yield new Uint8Array(BLOCK - size % BLOCK);
1033
+ }
1034
+ yield new Uint8Array(BLOCK * 2);
1035
+ }
1036
+ var ByteReader = class {
1037
+ buf = new Uint8Array(0);
1038
+ it;
1039
+ done = false;
1040
+ constructor(src) {
1041
+ this.it = src[Symbol.asyncIterator]();
1042
+ }
1043
+ async fill() {
1044
+ if (this.done) return false;
1045
+ const r = await this.it.next();
1046
+ if (r.done) {
1047
+ this.done = true;
1048
+ return false;
1049
+ }
1050
+ const chunk = r.value instanceof Uint8Array ? r.value : new Uint8Array(r.value);
1051
+ if (this.buf.length === 0) this.buf = chunk;
1052
+ else {
1053
+ const b = new Uint8Array(this.buf.length + chunk.length);
1054
+ b.set(this.buf);
1055
+ b.set(chunk, this.buf.length);
1056
+ this.buf = b;
1057
+ }
1058
+ return true;
1059
+ }
1060
+ /** Exactly n bytes, or null at a clean end of input before any of them. */
1061
+ async exact(n) {
1062
+ while (this.buf.length < n) {
1063
+ if (!await this.fill()) {
1064
+ if (this.buf.length === 0) return null;
1065
+ throw truncated();
1066
+ }
1067
+ }
1068
+ const out = this.buf.subarray(0, n);
1069
+ this.buf = this.buf.subarray(n);
1070
+ return out;
1071
+ }
1072
+ /** n bytes as they arrive, in chunks. */
1073
+ async *chunks(n) {
1074
+ let left = n;
1075
+ while (left > 0) {
1076
+ if (this.buf.length === 0 && !await this.fill()) throw truncated();
1077
+ const take = Math.min(left, this.buf.length);
1078
+ const out = this.buf.subarray(0, take);
1079
+ this.buf = this.buf.subarray(take);
1080
+ left -= take;
1081
+ yield out;
1082
+ }
1083
+ }
1084
+ async skip(n) {
1085
+ for await (const _ of this.chunks(n)) void _;
1086
+ }
1087
+ };
1088
+ function truncated() {
1089
+ return new InstaboxError("the archive from the sandbox ended early", { code: "file_changed", retryable: true });
1090
+ }
1091
+ function invalidArchive(why) {
1092
+ return new InstaboxError(`the archive from the sandbox is not valid tar: ${why}`, { code: "invalid_response" });
1093
+ }
1094
+ function cstring(b) {
1095
+ const z = b.indexOf(0);
1096
+ return dec.decode(z < 0 ? b : b.subarray(0, z));
1097
+ }
1098
+ function number(b) {
1099
+ if (b[0] & 128) {
1100
+ let n = b[0] & 127;
1101
+ for (let i = 1; i < b.length; i++) n = n * 256 + b[i];
1102
+ return n;
1103
+ }
1104
+ const s = cstring(b).trim();
1105
+ if (s === "") return 0;
1106
+ if (!/^[0-7]+$/.test(s)) throw invalidArchive(`bad number ${JSON.stringify(s)}`);
1107
+ return parseInt(s, 8);
1108
+ }
1109
+ function parsePax(data) {
1110
+ const out = {};
1111
+ let off = 0;
1112
+ while (off < data.length) {
1113
+ const sp = data.indexOf(32, off);
1114
+ if (sp < 0) break;
1115
+ const len = parseInt(dec.decode(data.subarray(off, sp)), 10);
1116
+ if (!Number.isSafeInteger(len) || len <= 0 || off + len > data.length) throw invalidArchive("bad PAX record");
1117
+ const rec = dec.decode(data.subarray(sp + 1, off + len - 1));
1118
+ const eq = rec.indexOf("=");
1119
+ if (eq > 0) out[rec.slice(0, eq)] = rec.slice(eq + 1);
1120
+ off += len;
1121
+ }
1122
+ return out;
1123
+ }
1124
+ async function* untarStream(src) {
1125
+ const r = new ByteReader(src);
1126
+ let pax = {};
1127
+ let longName;
1128
+ let longLink;
1129
+ for (; ; ) {
1130
+ const h = await r.exact(BLOCK);
1131
+ if (h === null) return;
1132
+ if (h.every((b) => b === 0)) return;
1133
+ let sum = 0;
1134
+ for (let i = 0; i < BLOCK; i++) sum += i >= 148 && i < 156 ? 32 : h[i];
1135
+ if (sum !== number(h.subarray(148, 156))) throw invalidArchive("bad header checksum");
1136
+ const type = String.fromCharCode(h[156]);
1137
+ let size = number(h.subarray(124, 136));
1138
+ const magic = dec.decode(h.subarray(257, 263));
1139
+ let name = cstring(h.subarray(0, 100));
1140
+ if (magic === "ustar\0") {
1141
+ const prefix = cstring(h.subarray(345, 500));
1142
+ if (prefix) name = `${prefix}/${name}`;
1143
+ }
1144
+ let linkname = cstring(h.subarray(157, 257));
1145
+ const mode = number(h.subarray(100, 108)) & 4095;
1146
+ if (type === "x" || type === "g" || type === "L" || type === "K") {
1147
+ const data2 = await r.exact(size) ?? new Uint8Array(0);
1148
+ await r.skip((BLOCK - size % BLOCK) % BLOCK);
1149
+ if (type === "x") pax = { ...pax, ...parsePax(data2) };
1150
+ else if (type === "L") longName = cstring(data2);
1151
+ else if (type === "K") longLink = cstring(data2);
1152
+ continue;
1153
+ }
1154
+ if (pax.size !== void 0) size = Number(pax.size);
1155
+ name = pax.path ?? longName ?? name;
1156
+ linkname = pax.linkpath ?? longLink ?? linkname;
1157
+ pax = {};
1158
+ longName = longLink = void 0;
1159
+ if (!Number.isSafeInteger(size) || size < 0) throw invalidArchive("bad size");
1160
+ const kind = type === "0" || type === "\0" || type === "7" ? "file" : type === "5" ? "dir" : type === "2" ? "symlink" : type === "1" ? "link" : "other";
1161
+ const dataSize = kind === "file" || kind === "other" ? size : 0;
1162
+ let consumed = false;
1163
+ const data = {
1164
+ [Symbol.asyncIterator]: () => {
1165
+ consumed = true;
1166
+ return r.chunks(kind === "file" ? dataSize : 0);
1167
+ }
1168
+ };
1169
+ yield { name, type: kind, mode, size: kind === "file" ? size : 0, linkname, data };
1170
+ if (kind !== "file" || !consumed) await r.skip(dataSize);
1171
+ await r.skip((BLOCK - dataSize % BLOCK) % BLOCK);
1172
+ }
1173
+ }
1174
+
1175
+ // src/local.ts
1176
+ function load() {
1177
+ return Promise.all([
1178
+ import("node:fs"),
1179
+ import("node:fs/promises"),
1180
+ import("node:path"),
1181
+ import("node:zlib"),
1182
+ import("node:stream"),
1183
+ import("node:stream/promises"),
1184
+ import("node:child_process")
1185
+ ]).then(
1186
+ // A namespace import of a CommonJS built-in (node:stream) types differently from `typeof import`.
1187
+ ([fs, fsp, path, zlib, stream, sp, cp]) => ({ fs, fsp, path, zlib, stream, sp, cp })
1188
+ );
1189
+ }
1190
+ var mods;
1191
+ function node() {
1192
+ const m = mods ??= load().catch((err) => {
1193
+ mods = void 0;
1194
+ throw new InstaboxError("files.upload and files.download need Node.js (or Bun or Deno) file system access", {
1195
+ code: "unsupported",
1196
+ cause: err
1197
+ });
1198
+ });
1199
+ return m;
1200
+ }
1201
+ function localError(err, what) {
1202
+ if (err instanceof InstaboxError) return err;
1203
+ const code = err?.code;
1204
+ const msg = err?.message ?? String(err);
1205
+ if (code === "ENOENT")
1206
+ return new InstaboxError(`${what}: no such file or directory`, { code: "local_not_found", cause: err });
1207
+ return new InstaboxError(`${what}: ${msg}`, { code: "local_io_error", cause: err });
1208
+ }
1209
+ function run(n, file, args) {
1210
+ return new Promise((resolve) => {
1211
+ n.cp.execFile(
1212
+ file,
1213
+ args,
1214
+ { encoding: "buffer", maxBuffer: 256 * 1024 * 1024 },
1215
+ (err, stdout) => resolve({ ok: !err, stdout })
1216
+ );
1217
+ });
1218
+ }
1219
+ async function listLocal(n, dir, opts = {}) {
1220
+ if (opts.git !== false) {
1221
+ const inside = await run(n, "git", ["-C", dir, "rev-parse", "--is-inside-work-tree"]);
1222
+ if (inside.ok && inside.stdout.toString().trim() === "true") {
1223
+ const args = opts.all ? ["-C", dir, "ls-files", "-co", "--exclude-standard", "-z"] : ["-C", dir, "ls-files", "-c", "-z"];
1224
+ const ls = await run(n, "git", args);
1225
+ if (!ls.ok) throw new InstaboxError(`git ls-files failed in ${dir}`, { code: "local_io_error" });
1226
+ return { names: ls.stdout.toString("utf8").split("\0").filter(Boolean), git: true };
1227
+ }
1228
+ }
1229
+ const names = [];
1230
+ const walk = async (rel) => {
1231
+ const abs = rel ? n.path.join(dir, rel) : dir;
1232
+ const ents = await n.fsp.readdir(abs, { withFileTypes: true });
1233
+ ents.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
1234
+ for (const e of ents) {
1235
+ const r = rel ? `${rel}/${e.name}` : e.name;
1236
+ names.push(r);
1237
+ if (e.isDirectory()) await walk(r);
1238
+ }
1239
+ };
1240
+ await walk("");
1241
+ return { names, git: false };
1242
+ }
1243
+ function packLocal(n, dir, names, counts) {
1244
+ async function* entries() {
1245
+ for (const rel of names) {
1246
+ const abs = n.path.join(dir, ...rel.split("/"));
1247
+ let st;
1248
+ try {
1249
+ st = await n.fsp.lstat(abs);
1250
+ } catch (err) {
1251
+ if (err.code === "ENOENT") continue;
1252
+ throw localError(err, abs);
1253
+ }
1254
+ const base = { name: rel, mode: st.mode & 4095, mtime: Math.floor(st.mtimeMs / 1e3) };
1255
+ if (st.isFile()) {
1256
+ counts.files++;
1257
+ yield {
1258
+ ...base,
1259
+ type: "file",
1260
+ size: st.size,
1261
+ data: () => n.fs.createReadStream(abs, { highWaterMark: 256 * 1024 })
1262
+ };
1263
+ } else if (st.isDirectory()) yield { ...base, type: "dir" };
1264
+ else if (st.isSymbolicLink()) yield { ...base, type: "symlink", linkname: await n.fsp.readlink(abs) };
1265
+ }
1266
+ }
1267
+ const tar = n.stream.Readable.from(tarStream(entries()), { objectMode: false });
1268
+ const gz = n.zlib.createGzip();
1269
+ n.stream.pipeline(tar, gz, () => {
1270
+ });
1271
+ return gz;
1272
+ }
1273
+ function unsafe(name) {
1274
+ return new InstaboxError(`unsafe path ${JSON.stringify(name)} in the archive from the sandbox`, {
1275
+ code: "invalid_response"
1276
+ });
1277
+ }
1278
+ function components(name) {
1279
+ if (name.startsWith("/")) throw unsafe(name);
1280
+ const parts = [];
1281
+ for (const p of name.split("/")) {
1282
+ if (p === "" || p === ".") continue;
1283
+ if (p === ".." || p.includes("\\") || p.includes("\0")) throw unsafe(name);
1284
+ parts.push(p);
1285
+ }
1286
+ return parts;
1287
+ }
1288
+ async function unpackLocal(n, src, dest) {
1289
+ await n.fsp.mkdir(dest, { recursive: true });
1290
+ const root = await n.fsp.realpath(dest);
1291
+ const gunzip = n.zlib.createGunzip();
1292
+ n.stream.pipeline(n.stream.Readable.from(src, { objectMode: false }), gunzip, () => {
1293
+ });
1294
+ const dirModes = [];
1295
+ let files = 0;
1296
+ const ensureDir = async (parts, name) => {
1297
+ let cur = root;
1298
+ for (const p of parts) {
1299
+ cur = n.path.join(cur, p);
1300
+ let st;
1301
+ try {
1302
+ st = await n.fsp.lstat(cur);
1303
+ } catch (err) {
1304
+ if (err.code !== "ENOENT") throw err;
1305
+ }
1306
+ if (!st) await n.fsp.mkdir(cur, { mode: 493 });
1307
+ else if (!st.isDirectory()) throw unsafe(name);
1308
+ }
1309
+ return cur;
1310
+ };
1311
+ const clear = async (abs, name) => {
1312
+ let st;
1313
+ try {
1314
+ st = await n.fsp.lstat(abs);
1315
+ } catch {
1316
+ return;
1317
+ }
1318
+ if (st.isDirectory()) {
1319
+ throw new InstaboxError(`${name} is a directory locally; the archive has a file there`, {
1320
+ code: "local_io_error"
1321
+ });
1322
+ }
1323
+ await n.fsp.unlink(abs);
1324
+ };
1325
+ for await (const e of untarStream(gunzip)) {
1326
+ const parts = components(e.name);
1327
+ if (parts.length === 0) {
1328
+ for await (const _ of e.data) void _;
1329
+ continue;
1330
+ }
1331
+ const parent = await ensureDir(parts.slice(0, -1), e.name);
1332
+ const abs = n.path.join(parent, parts[parts.length - 1]);
1333
+ if (e.type === "dir") {
1334
+ await ensureDir(parts, e.name);
1335
+ dirModes.push([abs, e.mode]);
1336
+ } else if (e.type === "file") {
1337
+ await clear(abs, e.name);
1338
+ await n.sp.pipeline(
1339
+ n.stream.Readable.from(e.data, { objectMode: false }),
1340
+ n.fs.createWriteStream(abs, { flags: "wx", mode: e.mode | 128 })
1341
+ );
1342
+ await n.fsp.chmod(abs, e.mode);
1343
+ files++;
1344
+ } else if (e.type === "symlink") {
1345
+ await clear(abs, e.name);
1346
+ await n.fsp.symlink(e.linkname, abs);
1347
+ } else if (e.type === "link") {
1348
+ const tparts = components(e.linkname);
1349
+ const target = n.path.join(await ensureDir(tparts.slice(0, -1), e.linkname), tparts[tparts.length - 1] ?? "");
1350
+ const st = await n.fsp.lstat(target).catch(() => void 0);
1351
+ if (!st?.isFile()) throw unsafe(e.linkname);
1352
+ await clear(abs, e.name);
1353
+ await n.fsp.copyFile(target, abs);
1354
+ files++;
1355
+ }
1356
+ }
1357
+ for (const [abs, mode] of dirModes.reverse()) await n.fsp.chmod(abs, mode);
1358
+ return files;
1359
+ }
1360
+
431
1361
  // src/files.ts
432
1362
  var MAX_FILE_BYTES = 10 * 1024 * 1024;
1363
+ var MAX_UPLOAD_BYTES = 5 * 1024 * 1024 * 1024;
1364
+ var TRANSFER_TIMEOUT_MS = 3e5;
1365
+ var TRANSFER_MAX_MS = 72e5 + 12e4;
1366
+ var TRANSFER_IDLE_MS = 12e4;
1367
+ var TRANSFER_EXEC_MS = 6e5;
433
1368
  var WRITE_CHUNK_B64 = 48 * 1024;
434
1369
  var READ_CHUNK_BYTES = 512 * 1024;
1370
+ var PROBE_PATH = "instabox-sdk-route-probe";
435
1371
  var Files = class {
436
1372
  /** @internal */
437
- constructor(commands) {
1373
+ constructor(commands, http, sandboxId) {
438
1374
  this.commands = commands;
1375
+ this.http = http;
1376
+ this.sandboxId = sandboxId;
439
1377
  }
440
1378
  commands;
1379
+ http;
1380
+ sandboxId;
1381
+ home;
1382
+ /** False once a server answered that it has no file routes. */
1383
+ routes = true;
1384
+ /** True once a server answered on a file route, so a stream need not probe for it. */
1385
+ routesSeen = false;
1386
+ get filesPath() {
1387
+ return `/v1/machines/${encodeURIComponent(this.sandboxId ?? "")}/files`;
1388
+ }
441
1389
  async read(path, opts = {}) {
442
- const p = arg(path);
443
1390
  const limit = opts.maxBytes ?? MAX_FILE_BYTES;
1391
+ if (!(limit >= 0)) throw new InstaboxError("maxBytes must be a number, at least 0", { code: "bad_request" });
1392
+ const res = await this.openRoute(path);
1393
+ const bytes = res ? await this.readRoute(res, path, limit) : await this.readExec(path, limit);
1394
+ return opts.format === "bytes" ? bytes : decodeUtf8(bytes);
1395
+ }
1396
+ /**
1397
+ * Opens a file for reading as a stream, with no size cap: the bytes arrive as the server sends them,
1398
+ * so a file of any size reads in bounded memory. Errors before the first byte (`not_found`, a
1399
+ * directory) reject the promise; a stream cut short errors with `file_changed`. Read it with
1400
+ * `for await`, `getReader()`, or in Node `Readable.fromWeb(stream)` and `pipeline`. On a server
1401
+ * without the file routes the file is read over exec first (at most 10 MiB).
1402
+ */
1403
+ async readStream(path, opts = {}) {
1404
+ const res = await this.openRoute(path, opts.signal);
1405
+ if (!res) return iterable(oneChunk(await this.readExec(path, MAX_FILE_BYTES)));
1406
+ return iterable(this.countedBody(res, path, opts.signal));
1407
+ }
1408
+ /**
1409
+ * `GET .../files/content` of `path` (or of `abs`, already absolute); undefined when the server has
1410
+ * no such route. `not_found` and `not_a_file` become `not_found`: a directory is not a file either.
1411
+ */
1412
+ async openRoute(path, signal, abs) {
1413
+ if (!this.http || !this.sandboxId || !this.routes) return void 0;
1414
+ abs ??= await this.absolute(path);
1415
+ try {
1416
+ const res = await this.http.send("GET", `${this.filesPath}/content`, {
1417
+ query: { path: abs },
1418
+ timeoutMs: TRANSFER_TIMEOUT_MS,
1419
+ signal
1420
+ });
1421
+ this.routesSeen = true;
1422
+ return res;
1423
+ } catch (err) {
1424
+ if (routeMissing(err)) {
1425
+ this.routes = false;
1426
+ return void 0;
1427
+ }
1428
+ if (err instanceof InstaboxError && (err.code === "not_found" || err.code === "not_a_file")) {
1429
+ throw new InstaboxError(`file not found: ${path}`, {
1430
+ status: 404,
1431
+ code: "not_found",
1432
+ requestId: err.requestId,
1433
+ cause: err
1434
+ });
1435
+ }
1436
+ throw err;
1437
+ }
1438
+ }
1439
+ /** Reads a whole response body of `path`, at most `limit` bytes. */
1440
+ async readRoute(res, path, limit) {
1441
+ try {
1442
+ const declared = Number(res.headers.get("Content-Length") ?? NaN);
1443
+ if (Number.isSafeInteger(declared) && declared > limit) {
1444
+ void res.body?.cancel().catch(() => {
1445
+ });
1446
+ throw new InstaboxError(`${path} is larger than the ${limit}-byte limit of files.read`, {
1447
+ code: "file_too_large"
1448
+ });
1449
+ }
1450
+ const bytes = await readBody(res, limit, path);
1451
+ if (Number.isSafeInteger(declared) && bytes.length !== declared) {
1452
+ throw new InstaboxError(`got ${bytes.length} of ${declared} bytes of ${path}`, { code: "file_changed" });
1453
+ }
1454
+ return bytes;
1455
+ } finally {
1456
+ this.http?.release(res);
1457
+ }
1458
+ }
1459
+ /** A response body as a stream that errors with `file_changed` when it ends short of Content-Length. */
1460
+ countedBody(res, path, signal) {
1461
+ const http = this.http;
1462
+ const declared = Number(res.headers.get("Content-Length") ?? NaN);
1463
+ const reader = res.body?.getReader();
1464
+ let n = 0;
1465
+ return new ReadableStream(
1466
+ {
1467
+ async pull(c) {
1468
+ if (!reader) {
1469
+ http.release(res);
1470
+ return c.close();
1471
+ }
1472
+ let r;
1473
+ try {
1474
+ r = await reader.read();
1475
+ } catch (err) {
1476
+ http.release(res);
1477
+ if (signal?.aborted) return c.error(new InstaboxError(`reading ${path} was aborted`, { code: "aborted" }));
1478
+ const msg = err?.message ?? String(err);
1479
+ return c.error(
1480
+ new InstaboxError(`reading ${path} stopped after ${n} bytes: ${msg}`, {
1481
+ code: "file_changed",
1482
+ retryable: true,
1483
+ cause: err
1484
+ })
1485
+ );
1486
+ }
1487
+ if (r.done) {
1488
+ http.release(res);
1489
+ if (Number.isSafeInteger(declared) && n !== declared) {
1490
+ return c.error(new InstaboxError(`got ${n} of ${declared} bytes of ${path}`, { code: "file_changed" }));
1491
+ }
1492
+ return c.close();
1493
+ }
1494
+ n += r.value.length;
1495
+ c.enqueue(r.value);
1496
+ },
1497
+ cancel(reason) {
1498
+ http.release(res);
1499
+ return reader?.cancel(reason);
1500
+ }
1501
+ },
1502
+ { highWaterMark: 0 }
1503
+ );
1504
+ }
1505
+ async readExec(path, limit) {
1506
+ const p = arg(path);
444
1507
  const r = await this.commands.exec(
445
1508
  `[ -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
1509
  );
@@ -467,19 +1530,206 @@ var Files = class {
467
1530
  }
468
1531
  bytes.set(data, offset);
469
1532
  }
470
- return opts.format === "bytes" ? bytes : new TextDecoder().decode(bytes);
1533
+ return bytes;
471
1534
  }
472
1535
  /**
473
- * Writes a file, creating parent directories. Replaces the file atomically (temp file + rename).
474
- * Throws `is_a_directory` when `path` is a directory.
1536
+ * Writes a file, creating parent directories. Replaces the file atomically (temp file + rename), so
1537
+ * a failed or aborted write leaves the old file. Throws `is_a_directory` when `path` is a directory.
1538
+ *
1539
+ * `data` is a string, bytes, or a stream (a Node `Readable`, a web `ReadableStream`, an
1540
+ * `AsyncIterable` of chunks): a stream is sent as it is read, in bounded memory, up to the server's
1541
+ * 5 GiB. The size and SHA-256 the server reports are checked against what was sent
1542
+ * (`transfer_mismatch` when they differ). On a server without the file routes, writes go over exec
1543
+ * and are capped at 10 MiB (`file_too_large`).
475
1544
  */
476
- async write(path, data) {
477
- const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
478
- if (bytes.length > MAX_FILE_BYTES) {
479
- throw new InstaboxError(`data is larger than the ${MAX_FILE_BYTES}-byte limit of files.write`, {
480
- code: "file_too_large"
1545
+ async write(path, data, opts = {}) {
1546
+ const bytes = asBytes(data);
1547
+ if (bytes) {
1548
+ if (await this.writeRoute(path, bytes, opts.signal)) return { path };
1549
+ if (bytes.length > MAX_FILE_BYTES) throw tooLargeForExec();
1550
+ await this.writeExec(path, bytes);
1551
+ return { path };
1552
+ }
1553
+ const src = asIterable(data);
1554
+ if (await this.routesAvailable(opts.signal)) {
1555
+ if (await this.writeRoute(path, src, opts.signal)) return { path };
1556
+ throw noRoutes();
1557
+ }
1558
+ await this.writeExec(path, await collect(src, MAX_FILE_BYTES));
1559
+ return { path };
1560
+ }
1561
+ /**
1562
+ * Writes over `PUT .../files?parents=true`, which writes a temp file beside the target and renames
1563
+ * it into place once every byte arrived. False when the server has no such route.
1564
+ */
1565
+ async writeRoute(path, body, signal) {
1566
+ if (!this.http || !this.sandboxId || !this.routes) return false;
1567
+ const abs = await this.absolute(path);
1568
+ try {
1569
+ return await this.put(abs, body, { parents: "true" }, signal) !== void 0;
1570
+ } catch (err) {
1571
+ if (err instanceof InstaboxError && err.code === "not_a_file") {
1572
+ const dir = await this.commands.exec(`test -d ${arg(path)}`).catch(() => void 0);
1573
+ if (dir?.exitCode === 0) {
1574
+ throw new InstaboxError(`is a directory: ${path}`, { status: 409, code: "is_a_directory", cause: err });
1575
+ }
1576
+ }
1577
+ throw err;
1578
+ }
1579
+ }
1580
+ /**
1581
+ * True when the server has the file routes. A stream can be sent only once, so before the first one
1582
+ * the route is probed with a relative path, which the server refuses (400) before touching the
1583
+ * sandbox; a server without the route answers 404 or 405.
1584
+ */
1585
+ async routesAvailable(signal) {
1586
+ if (!this.http || !this.sandboxId || !this.routes) return false;
1587
+ if (this.routesSeen) return true;
1588
+ try {
1589
+ await this.http.request("PUT", this.filesPath, {
1590
+ query: { path: PROBE_PATH },
1591
+ rawBody: new Uint8Array(0),
1592
+ idempotent: false,
1593
+ retry: true,
1594
+ signal
481
1595
  });
1596
+ } catch (err) {
1597
+ if (routeMissing(err)) {
1598
+ this.routes = false;
1599
+ return false;
1600
+ }
1601
+ if (!(err instanceof InstaboxError) || err.status !== 400) throw err;
482
1602
  }
1603
+ this.routesSeen = true;
1604
+ return true;
1605
+ }
1606
+ /**
1607
+ * `PUT .../files` of `body` to the absolute path `abs`, checking the size and SHA-256 the server
1608
+ * reports. Bytes are retried on 502-504 (the server replaces the file atomically, so a repeat writes
1609
+ * the same bytes); a stream is sent once, as it is read, and given up when it moves nothing for
1610
+ * 2 minutes. Undefined when the server has no such route.
1611
+ */
1612
+ async put(abs, body, query, signal) {
1613
+ if (!this.http || !this.sandboxId || !this.routes) return void 0;
1614
+ let res;
1615
+ let sent;
1616
+ let want;
1617
+ if (body instanceof Uint8Array) {
1618
+ try {
1619
+ res = await this.http.request("PUT", this.filesPath, {
1620
+ query: { path: abs, ...query },
1621
+ rawBody: body,
1622
+ idempotent: false,
1623
+ retry: true,
1624
+ timeoutMs: bufferedTimeout(body.length),
1625
+ signal
1626
+ });
1627
+ } catch (err) {
1628
+ if (routeMissing(err)) {
1629
+ this.routes = false;
1630
+ return void 0;
1631
+ }
1632
+ throw err;
1633
+ }
1634
+ sent = body.length;
1635
+ want = await sha256Hex(body);
1636
+ } else {
1637
+ const up = await this.putStream(abs, body, query, signal);
1638
+ if (!up) return void 0;
1639
+ ({ res, sent, want } = up);
1640
+ }
1641
+ this.routesSeen = true;
1642
+ if (res?.size !== sent || want !== void 0 && res.sha256 !== want) {
1643
+ throw new InstaboxError(
1644
+ `the sandbox received ${res?.size} bytes with sha256 ${res?.sha256}; sent ${sent} with ${want}`,
1645
+ { code: "transfer_mismatch" }
1646
+ );
1647
+ }
1648
+ return { size: sent };
1649
+ }
1650
+ async putStream(abs, src, query, signal) {
1651
+ const hash = await sha256Stream();
1652
+ const ctrl = new AbortController();
1653
+ let idle;
1654
+ let idleFired = false;
1655
+ const touch = () => {
1656
+ clearTimeout(idle);
1657
+ idle = setTimeout(() => {
1658
+ idleFired = true;
1659
+ ctrl.abort();
1660
+ }, TRANSFER_IDLE_MS);
1661
+ };
1662
+ const onAbort = () => ctrl.abort();
1663
+ if (signal?.aborted) ctrl.abort();
1664
+ else signal?.addEventListener("abort", onAbort, { once: true });
1665
+ const it = src[Symbol.asyncIterator]();
1666
+ let sent = 0;
1667
+ let srcErr;
1668
+ const stream = new ReadableStream(
1669
+ {
1670
+ async pull(c) {
1671
+ touch();
1672
+ let r;
1673
+ try {
1674
+ r = await it.next();
1675
+ if (!r.done) {
1676
+ const b = chunkBytes(r.value);
1677
+ sent += b.length;
1678
+ if (sent > MAX_UPLOAD_BYTES) {
1679
+ throw new InstaboxError(`data is larger than the ${MAX_UPLOAD_BYTES}-byte limit of files.write`, {
1680
+ status: 413,
1681
+ code: "too_large"
1682
+ });
1683
+ }
1684
+ hash?.update(b);
1685
+ if (b.length) c.enqueue(b);
1686
+ return;
1687
+ }
1688
+ } catch (err) {
1689
+ clearTimeout(idle);
1690
+ srcErr = sourceError(err);
1691
+ throw srcErr;
1692
+ }
1693
+ clearTimeout(idle);
1694
+ c.close();
1695
+ },
1696
+ async cancel() {
1697
+ clearTimeout(idle);
1698
+ await it.return?.();
1699
+ }
1700
+ },
1701
+ { highWaterMark: 0 }
1702
+ );
1703
+ try {
1704
+ const res = await this.http.request("PUT", this.filesPath, {
1705
+ query: { path: abs, ...query },
1706
+ streamBody: stream,
1707
+ idempotent: false,
1708
+ timeoutMs: TRANSFER_MAX_MS,
1709
+ signal: ctrl.signal
1710
+ });
1711
+ return { res, sent, want: hash?.digest("hex") };
1712
+ } catch (err) {
1713
+ if (srcErr) throw srcErr;
1714
+ if (idleFired) {
1715
+ throw new InstaboxTimeoutError(`the upload to ${abs} moved nothing for ${TRANSFER_IDLE_MS / 1e3} s`, {
1716
+ code: "request_timeout",
1717
+ cause: err
1718
+ });
1719
+ }
1720
+ if (routeMissing(err)) {
1721
+ this.routes = false;
1722
+ return void 0;
1723
+ }
1724
+ throw err;
1725
+ } finally {
1726
+ clearTimeout(idle);
1727
+ signal?.removeEventListener("abort", onAbort);
1728
+ void it.return?.()?.catch?.(() => {
1729
+ });
1730
+ }
1731
+ }
1732
+ async writeExec(path, bytes) {
483
1733
  const p = arg(path);
484
1734
  const tmp = arg(`${path}.instabox-${Math.random().toString(36).slice(2, 10)}.tmp`);
485
1735
  const b64 = bytesToBase64(bytes);
@@ -501,7 +1751,188 @@ var Files = class {
501
1751
  });
502
1752
  throw err;
503
1753
  }
504
- return { path };
1754
+ }
1755
+ /**
1756
+ * Puts `src` at the absolute temporary path `abs` (mode 0600): over the file route, or in base64
1757
+ * chunks over exec (`instabox push`'s fallback) on a server without it.
1758
+ */
1759
+ async putTemp(abs, src, signal) {
1760
+ const replayable = src instanceof Uint8Array;
1761
+ if (replayable || await this.routesAvailable(signal)) {
1762
+ if (await this.put(abs, src, { mode: "0600" }, signal)) return;
1763
+ if (!replayable) throw noRoutes();
1764
+ }
1765
+ let first = true;
1766
+ for await (const chunk of rechunk(replayable ? [src] : src, EXEC_CHUNK_BYTES)) {
1767
+ if (signal?.aborted) throw new InstaboxError("the transfer was aborted", { code: "aborted" });
1768
+ await this.transferExec(PUSH_CHUNK_SCRIPT, { IB_TMP: abs, IB_FIRST: first ? "1" : "0" }, "", signal, {
1769
+ stdin: bytesToBase64(chunk)
1770
+ });
1771
+ first = false;
1772
+ }
1773
+ if (first) await this.transferExec(PUSH_CHUNK_SCRIPT, { IB_TMP: abs, IB_FIRST: "1" }, "", signal, { stdin: "" });
1774
+ }
1775
+ /**
1776
+ * Runs a transfer script and returns its stdout after `mark`. A non-zero exit throws `transfer_failed`
1777
+ * (`permission_denied`, status 403, when the sandbox refused access), as the CLI reports it.
1778
+ */
1779
+ async transferExec(cmd, envs, mark, signal, extra = {}) {
1780
+ const r = await this.commands.exec(cmd, { envs, timeoutMs: TRANSFER_EXEC_MS, signal, stdin: extra.stdin });
1781
+ if (r.timedOut) {
1782
+ throw new InstaboxTimeoutError(`the transfer timed out after ${TRANSFER_EXEC_MS / 1e3} s in the sandbox`, {
1783
+ code: "request_timeout"
1784
+ });
1785
+ }
1786
+ if (r.exitCode !== 0) {
1787
+ const msg = r.stderr.trim() || `exit status ${r.exitCode}`;
1788
+ if (/Permission denied|Operation not permitted/.test(msg)) {
1789
+ throw new InstaboxError(`in the sandbox: ${msg}`, { status: 403, code: "permission_denied" });
1790
+ }
1791
+ throw new InstaboxError(`in the sandbox: ${msg}`, { code: "transfer_failed" });
1792
+ }
1793
+ if (!mark) return "";
1794
+ const i = r.stdout.indexOf(mark);
1795
+ if (i < 0 || r.truncated)
1796
+ throw new InstaboxError("unexpected output from the sandbox", { code: "invalid_response" });
1797
+ return r.stdout.slice(i + mark.length);
1798
+ }
1799
+ /**
1800
+ * Uploads a local directory's contents into `remoteDir` in one call, as one gzipped tar, the way
1801
+ * `instabox push` does: streamed over `PUT .../files` to a temporary file, then unpacked in the
1802
+ * sandbox with `tar`. `remoteDir` and its parents are created; existing files there are replaced,
1803
+ * others kept. In a git work tree only what git tracks is uploaded (pass `all: true` to add
1804
+ * untracked files git does not ignore, `git: false` to upload everything). Symlinks are uploaded as
1805
+ * symlinks, never followed; sockets, FIFOs and devices are skipped. Node.js (or Bun, Deno) only.
1806
+ */
1807
+ async upload(localDir, remoteDir, opts = {}) {
1808
+ const n = await node();
1809
+ const st = await n.fsp.stat(localDir).catch((err) => {
1810
+ throw localError(err, localDir);
1811
+ });
1812
+ if (!st.isDirectory()) {
1813
+ throw new InstaboxError(`${localDir} is not a directory; write a single file with files.write`, {
1814
+ code: "not_a_directory"
1815
+ });
1816
+ }
1817
+ const { names } = await listLocal(n, localDir, opts).catch((err) => {
1818
+ throw localError(err, localDir);
1819
+ });
1820
+ const counts = { files: 0 };
1821
+ let bytes = 0;
1822
+ const packed = packLocal(n, localDir, names, counts);
1823
+ async function* counted() {
1824
+ try {
1825
+ for await (const chunk of packed) {
1826
+ bytes += chunk.length;
1827
+ yield chunk;
1828
+ }
1829
+ } catch (err) {
1830
+ throw localError(err, localDir);
1831
+ }
1832
+ }
1833
+ const tmp = TRANSFER_TMP_PREFIX + randomHex();
1834
+ try {
1835
+ await this.putTemp(tmp, counted(), opts.signal);
1836
+ const out = await this.transferExec(
1837
+ PUSH_FINISH_SCRIPT,
1838
+ { IB_TMP: tmp, IB_DEST: remoteDir },
1839
+ PUSH_MARK,
1840
+ opts.signal
1841
+ );
1842
+ const f = out.split("\0");
1843
+ if (f[0] !== "ok" || !f[1])
1844
+ throw new InstaboxError("unexpected output from the sandbox", { code: "invalid_response" });
1845
+ return { path: f[1], files: counts.files, bytes };
1846
+ } catch (err) {
1847
+ await this.commands.exec(`rm -f -- ${shellQuote(tmp)}`).catch(() => {
1848
+ });
1849
+ throw err;
1850
+ }
1851
+ }
1852
+ /**
1853
+ * Downloads a sandbox directory into `localDir` in one call, as one gzipped tar, the way
1854
+ * `instabox pull` packs it: `tar` in the sandbox (as root when sudo allows, as the file routes read),
1855
+ * streamed back over `GET .../files/content` and unpacked as it arrives. `localDir` and its parents
1856
+ * are created; existing files are replaced, others kept. Everything under `remoteDir` comes, dot
1857
+ * files and empty directories included; symlinks arrive as symlinks. No entry can write outside
1858
+ * `localDir`. Node.js (or Bun, Deno) only.
1859
+ */
1860
+ async download(remoteDir, localDir, opts = {}) {
1861
+ const n = await node();
1862
+ const tmp = TRANSFER_TMP_PREFIX + randomHex();
1863
+ const envs = { IB_PATH: remoteDir };
1864
+ const f = (await this.transferExec(pullStartCmd(tmp), envs, PULL_MARK, opts.signal)).split("\0");
1865
+ if (f[0] === "missing") {
1866
+ throw new InstaboxError(`directory not found: ${remoteDir}`, { status: 404, code: "not_found" });
1867
+ }
1868
+ if (f[0] === "not_a_dir") {
1869
+ throw new InstaboxError(`${f[1]} is not a directory; read a single file with files.read or files.readStream`, {
1870
+ code: "not_a_directory"
1871
+ });
1872
+ }
1873
+ const size = Number(f[2]);
1874
+ if (f[0] !== "dir" || !f[1] || !Number.isSafeInteger(size) || size < 0) {
1875
+ throw new InstaboxError("unexpected output from the sandbox", { code: "invalid_response" });
1876
+ }
1877
+ try {
1878
+ let bytes = 0;
1879
+ const src = this.fetchTemp(tmp, size, envs, opts.signal);
1880
+ async function* counted() {
1881
+ for await (const chunk of src) {
1882
+ bytes += chunk.length;
1883
+ yield chunk;
1884
+ }
1885
+ }
1886
+ const files = await unpackLocal(n, counted(), localDir).catch((err) => {
1887
+ throw localError(err, localDir);
1888
+ });
1889
+ if (bytes !== size) {
1890
+ throw new InstaboxError(`got ${bytes} of ${size} bytes of the archive`, { code: "file_changed" });
1891
+ }
1892
+ return { path: localDir, remotePath: f[1], files, bytes };
1893
+ } finally {
1894
+ await this.commands.exec(pullRemoveCmd(tmp), { envs }).catch(() => {
1895
+ });
1896
+ }
1897
+ }
1898
+ /** The temporary archive's bytes: over the file route, or in base64 chunks over exec without it. */
1899
+ async *fetchTemp(tmp, size, envs, signal) {
1900
+ const res = await this.openRoute(tmp, signal, tmp);
1901
+ if (res) {
1902
+ yield* iterable(this.countedBody(res, tmp, signal));
1903
+ return;
1904
+ }
1905
+ for (let off = 0; off < size; off += EXEC_CHUNK_BYTES) {
1906
+ const want = Math.min(EXEC_CHUNK_BYTES, size - off);
1907
+ const b = base64ToBytes(await this.transferExec(pullChunkCmd(tmp, off, want), envs, PULL_MARK, signal));
1908
+ if (b.length !== want) throw new InstaboxError("the archive changed while reading it", { code: "file_changed" });
1909
+ yield b;
1910
+ }
1911
+ }
1912
+ /**
1913
+ * @internal Stages bytes as a temporary file for a command's stdin (`instabox exec --stdin`'s way) and
1914
+ * returns its path. The command removes it as it starts.
1915
+ */
1916
+ async stageStdin(bytes, signal) {
1917
+ const p = STDIN_TMP_PREFIX + randomHex();
1918
+ await this.putTemp(p, bytes, signal);
1919
+ return p;
1920
+ }
1921
+ /** The file routes take absolute paths; a relative one is relative to exec's working directory (HOME). */
1922
+ async absolute(path) {
1923
+ if (path.startsWith("/")) return path;
1924
+ this.home ??= this.commands.exec(`printf '%s' "$PWD"`).then((r) => {
1925
+ ensureComplete(r);
1926
+ if (!r.stdout.startsWith("/")) {
1927
+ throw new InstaboxError("invalid working directory returned by exec", { code: "invalid_response" });
1928
+ }
1929
+ return r.stdout;
1930
+ });
1931
+ const home = await this.home.catch((err) => {
1932
+ this.home = void 0;
1933
+ throw err;
1934
+ });
1935
+ return `${home.replace(/\/+$/, "")}/${path}`;
505
1936
  }
506
1937
  /** Lists the entries of a directory (not recursive). */
507
1938
  async list(path) {
@@ -532,6 +1963,168 @@ var Files = class {
532
1963
  function arg(path) {
533
1964
  return shellQuote(path.startsWith("-") ? `./${path}` : path);
534
1965
  }
1966
+ function tooLargeForExec() {
1967
+ return new InstaboxError(
1968
+ `data is larger than the ${MAX_FILE_BYTES}-byte limit of files.write on a server without the file routes`,
1969
+ { code: "file_too_large" }
1970
+ );
1971
+ }
1972
+ function noRoutes() {
1973
+ return new InstaboxError("this server has no file routes (PUT /v1/machines/{id}/files) to stream to", {
1974
+ status: 404,
1975
+ code: "unsupported"
1976
+ });
1977
+ }
1978
+ function bufferedTimeout(size) {
1979
+ return Math.min(TRANSFER_MAX_MS, Math.max(TRANSFER_TIMEOUT_MS, Math.ceil(size / 65536) * 1e3));
1980
+ }
1981
+ function asBytes(data) {
1982
+ if (typeof data === "string") return new TextEncoder().encode(data);
1983
+ if (data instanceof Uint8Array) return data;
1984
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
1985
+ return void 0;
1986
+ }
1987
+ function asIterable(data) {
1988
+ const d = data;
1989
+ if (d && typeof d[Symbol.asyncIterator] === "function") return data;
1990
+ if (d && typeof d.getReader === "function") return iterable(data);
1991
+ throw new InstaboxError(
1992
+ "files.write takes a string, a Uint8Array, an ArrayBuffer, a ReadableStream or an AsyncIterable of chunks",
1993
+ { code: "bad_request" }
1994
+ );
1995
+ }
1996
+ function chunkBytes(chunk) {
1997
+ if (chunk instanceof Uint8Array) return chunk;
1998
+ if (typeof chunk === "string") return new TextEncoder().encode(chunk);
1999
+ if (chunk instanceof ArrayBuffer) return new Uint8Array(chunk);
2000
+ throw new InstaboxError("a stream given to files.write yielded something other than bytes or a string", {
2001
+ code: "bad_request"
2002
+ });
2003
+ }
2004
+ function sourceError(err) {
2005
+ if (err instanceof InstaboxError) return err;
2006
+ const msg = err?.message ?? String(err);
2007
+ return new InstaboxError(`reading the data to write failed: ${msg}`, { code: "source_error", cause: err });
2008
+ }
2009
+ async function collect(src, limit) {
2010
+ const parts = [];
2011
+ let n = 0;
2012
+ try {
2013
+ for await (const c of src) {
2014
+ const b = chunkBytes(c);
2015
+ n += b.length;
2016
+ if (n > limit) throw tooLargeForExec();
2017
+ parts.push(b);
2018
+ }
2019
+ } catch (err) {
2020
+ throw sourceError(err);
2021
+ }
2022
+ return concat(parts, n);
2023
+ }
2024
+ function concat(parts, n) {
2025
+ const out = new Uint8Array(n);
2026
+ let off = 0;
2027
+ for (const p of parts) {
2028
+ out.set(p, off);
2029
+ off += p.length;
2030
+ }
2031
+ return out;
2032
+ }
2033
+ async function* rechunk(src, size) {
2034
+ let buf = new Uint8Array(size);
2035
+ let n = 0;
2036
+ for await (const c of src) {
2037
+ let b = chunkBytes(c);
2038
+ while (b.length) {
2039
+ const take = Math.min(size - n, b.length);
2040
+ buf.set(b.subarray(0, take), n);
2041
+ n += take;
2042
+ b = b.subarray(take);
2043
+ if (n === size) {
2044
+ yield buf;
2045
+ buf = new Uint8Array(size);
2046
+ n = 0;
2047
+ }
2048
+ }
2049
+ }
2050
+ if (n) yield buf.subarray(0, n);
2051
+ }
2052
+ function oneChunk(bytes) {
2053
+ return new ReadableStream({
2054
+ start(c) {
2055
+ if (bytes.length) c.enqueue(bytes);
2056
+ c.close();
2057
+ }
2058
+ });
2059
+ }
2060
+ function iterable(stream) {
2061
+ const s = stream;
2062
+ if (typeof s[Symbol.asyncIterator] !== "function") {
2063
+ Object.defineProperty(s, Symbol.asyncIterator, {
2064
+ configurable: true,
2065
+ value: async function* () {
2066
+ const reader = stream.getReader();
2067
+ try {
2068
+ for (; ; ) {
2069
+ const { done, value } = await reader.read();
2070
+ if (done) return;
2071
+ yield value;
2072
+ }
2073
+ } finally {
2074
+ reader.releaseLock();
2075
+ }
2076
+ }
2077
+ });
2078
+ }
2079
+ return s;
2080
+ }
2081
+ async function readBody(res, limit, path) {
2082
+ const tooLarge = () => new InstaboxError(`${path} is larger than the ${limit}-byte limit of files.read`, { code: "file_too_large" });
2083
+ const reader = res.body?.getReader();
2084
+ if (!reader) return new Uint8Array(0);
2085
+ const chunks = [];
2086
+ let n = 0;
2087
+ try {
2088
+ for (; ; ) {
2089
+ const { done, value } = await reader.read();
2090
+ if (done) break;
2091
+ n += value.length;
2092
+ if (n > limit) {
2093
+ void reader.cancel().catch(() => {
2094
+ });
2095
+ throw tooLarge();
2096
+ }
2097
+ chunks.push(value);
2098
+ }
2099
+ } catch (err) {
2100
+ if (err instanceof InstaboxError) throw err;
2101
+ throw new InstaboxError(`reading ${path} stopped after ${n} bytes: ${err?.message ?? String(err)}`, {
2102
+ code: "file_changed",
2103
+ retryable: true,
2104
+ cause: err
2105
+ });
2106
+ }
2107
+ return concat(chunks, n);
2108
+ }
2109
+ function routeMissing(err) {
2110
+ if (!(err instanceof InstaboxError)) return false;
2111
+ if (err.status === 405) return true;
2112
+ return err.status === 404 && (err.code === "http_404" || err.code === "not_found" && err.message === "route not found");
2113
+ }
2114
+ async function sha256Hex(bytes) {
2115
+ const subtle = globalThis.crypto?.subtle;
2116
+ if (!subtle) return void 0;
2117
+ const d = new Uint8Array(await subtle.digest("SHA-256", bytes));
2118
+ return Array.from(d, (x) => x.toString(16).padStart(2, "0")).join("");
2119
+ }
2120
+ async function sha256Stream() {
2121
+ try {
2122
+ const c = await import("node:crypto");
2123
+ return c.createHash("sha256");
2124
+ } catch {
2125
+ return void 0;
2126
+ }
2127
+ }
535
2128
  function writeError(result, path) {
536
2129
  if (result.exitCode === 21) return new InstaboxError(`is a directory: ${path}`, { code: "is_a_directory" });
537
2130
  return new CommandExitError(result);
@@ -540,18 +2133,42 @@ function ensureComplete(result) {
540
2133
  if (result.exitCode !== 0) throw new CommandExitError(result);
541
2134
  if (result.truncated) throw new InstaboxError("file command output was truncated", { code: "output_truncated" });
542
2135
  }
2136
+ function decodeUtf8(bytes) {
2137
+ try {
2138
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
2139
+ } catch (err) {
2140
+ throw new InstaboxNotUtf8Error("file is not UTF-8 text; read it with { format: 'bytes' }", {
2141
+ code: "not_utf8",
2142
+ cause: err
2143
+ });
2144
+ }
2145
+ }
543
2146
 
544
2147
  // src/http.ts
545
2148
  var DEFAULT_API_URL = "https://api.instabox.sh";
546
2149
  var MAX_RETRIES = 3;
2150
+ var REDACTED = "[redacted]";
2151
+ var BUILTIN_ERRORS = new Set(
2152
+ [Error, TypeError, RangeError, SyntaxError, ReferenceError, EvalError, URIError].map((c) => c.prototype)
2153
+ );
2154
+ function guarded(f) {
2155
+ try {
2156
+ return f();
2157
+ } catch {
2158
+ return void 0;
2159
+ }
2160
+ }
547
2161
  var HttpClient = class {
548
2162
  apiUrl;
549
2163
  operationTimeoutMs;
550
- apiKey;
2164
+ // An ES private field: invisible to JSON.stringify, util.inspect, structuredClone and property walks.
2165
+ #apiKey;
551
2166
  requestTimeoutMs;
552
2167
  fetchImpl;
553
2168
  pollIntervalMs;
554
2169
  retryDelayMs;
2170
+ /** Removes the caller's abort listener of a response `send` returned; see `release`. */
2171
+ releases = /* @__PURE__ */ new WeakMap();
555
2172
  constructor(opts = {}) {
556
2173
  const apiKey = opts.apiKey ?? readEnv("INSTABOX_API_KEY");
557
2174
  if (!apiKey) {
@@ -560,7 +2177,7 @@ var HttpClient = class {
560
2177
  { code: "missing_api_key" }
561
2178
  );
562
2179
  }
563
- this.apiKey = apiKey;
2180
+ this.#apiKey = apiKey;
564
2181
  this.apiUrl = (opts.apiUrl ?? readEnv("INSTABOX_API_URL") ?? DEFAULT_API_URL).replace(/\/+$/, "");
565
2182
  this.requestTimeoutMs = opts.requestTimeoutMs;
566
2183
  this.operationTimeoutMs = opts.operationTimeoutMs ?? 6e5;
@@ -572,32 +2189,55 @@ var HttpClient = class {
572
2189
  }
573
2190
  async request(method, path, opts = {}) {
574
2191
  const res = await this.send(method, path, opts);
575
- if (res.status === 204) return void 0;
576
- return await res.json();
2192
+ try {
2193
+ if (res.status === 204) return void 0;
2194
+ return await res.json();
2195
+ } finally {
2196
+ this.release(res);
2197
+ }
2198
+ }
2199
+ /**
2200
+ * Unwires the caller's `signal` from a response `send` returned, once its body is read or dropped.
2201
+ * Until then an abort still ends the body; after it the signal holds no listener of this request,
2202
+ * so a signal shared by many requests (a long `wait()`) does not collect one per request.
2203
+ */
2204
+ release(res) {
2205
+ const f = this.releases.get(res);
2206
+ if (!f) return;
2207
+ this.releases.delete(res);
2208
+ f();
577
2209
  }
578
2210
  /** Performs the request with retries; returns a 2xx response or throws an InstaboxError. */
579
2211
  async send(method, path, opts = {}) {
580
2212
  const isRead = method === "GET" || method === "HEAD";
581
2213
  const idempotent = opts.idempotent ?? !isRead;
582
- const retry = opts.retry ?? (isRead || idempotent);
583
- const headers = {
584
- "X-API-Key": this.apiKey,
585
- Accept: "application/json"
2214
+ const retry = opts.streamBody ? false : opts.retry ?? (isRead || idempotent);
2215
+ const headers2 = {
2216
+ "X-API-Key": this.#apiKey,
2217
+ Accept: opts.accept ?? "application/json",
2218
+ ...opts.headers
586
2219
  };
587
- if (idempotent) headers["Idempotency-Key"] = uuid();
2220
+ if (idempotent) headers2["Idempotency-Key"] = uuid();
588
2221
  let body;
589
- if (opts.body !== void 0) {
590
- headers["Content-Type"] = "application/json";
2222
+ if (opts.streamBody !== void 0) {
2223
+ headers2["Content-Type"] = "application/octet-stream";
2224
+ body = opts.streamBody;
2225
+ } else if (opts.rawBody !== void 0) {
2226
+ headers2["Content-Type"] = "application/octet-stream";
2227
+ body = opts.rawBody;
2228
+ } else if (opts.body !== void 0) {
2229
+ headers2["Content-Type"] = "application/json";
591
2230
  body = JSON.stringify(opts.body);
592
2231
  }
2232
+ const where = this.#redact(`${method} ${path}`);
593
2233
  let url = this.apiUrl + path;
594
2234
  if (opts.query) {
595
- const q = new URLSearchParams();
2235
+ const q2 = new URLSearchParams();
596
2236
  for (const [k, v] of Object.entries(opts.query)) {
597
- if (Array.isArray(v)) for (const item of v) q.append(k, item);
598
- else if (v !== void 0) q.set(k, String(v));
2237
+ if (Array.isArray(v)) for (const item of v) q2.append(k, item);
2238
+ else if (v !== void 0) q2.set(k, String(v));
599
2239
  }
600
- const s = q.toString();
2240
+ const s = q2.toString();
601
2241
  if (s) url += `?${s}`;
602
2242
  }
603
2243
  for (let attempt = 0; ; attempt++) {
@@ -609,45 +2249,130 @@ var HttpClient = class {
609
2249
  timedOut = true;
610
2250
  ctrl.abort();
611
2251
  }, timeoutMs);
2252
+ const onAbort = () => ctrl.abort();
2253
+ if (opts.signal?.aborted) ctrl.abort();
2254
+ else opts.signal?.addEventListener("abort", onAbort, { once: true });
612
2255
  let res;
613
2256
  try {
614
- res = await this.fetchImpl(url, { method, headers, body, signal: ctrl.signal });
2257
+ const init = { method, headers: headers2, body, signal: ctrl.signal };
2258
+ if (opts.streamBody !== void 0) {
2259
+ init.duplex = "half";
2260
+ init.redirect = "error";
2261
+ }
2262
+ res = await this.fetchImpl(url, init);
615
2263
  } catch (err) {
616
2264
  clearTimeout(timer);
2265
+ opts.signal?.removeEventListener("abort", onAbort);
2266
+ if (opts.signal?.aborted) throw new InstaboxError(`${where} was aborted`, { code: "aborted" });
617
2267
  if (canRetry) {
618
2268
  await sleep(this.backoff(attempt));
619
2269
  continue;
620
2270
  }
2271
+ const cause = this.#copyError(err);
621
2272
  if (timedOut) {
622
- throw new InstaboxTimeoutError(`${method} ${path} timed out after ${timeoutMs} ms`, {
2273
+ throw new InstaboxTimeoutError(`${where} timed out after ${timeoutMs} ms`, {
623
2274
  code: "request_timeout",
624
- cause: err
2275
+ cause
625
2276
  });
626
2277
  }
627
- throw new InstaboxError(`${method} ${path} failed: ${err?.message ?? String(err)}`, {
2278
+ throw new InstaboxError(`${where} failed: ${cause.message}`, {
628
2279
  code: "network_error",
629
2280
  retryable: true,
630
- cause: err
2281
+ cause
631
2282
  });
632
2283
  }
633
2284
  clearTimeout(timer);
634
- if (res.ok) return res;
2285
+ const unwire = () => opts.signal?.removeEventListener("abort", onAbort);
2286
+ if (res.ok) {
2287
+ if (opts.signal) this.releases.set(res, unwire);
2288
+ return res;
2289
+ }
635
2290
  if (canRetry && res.status >= 502 && res.status <= 504) {
2291
+ unwire();
636
2292
  void res.body?.cancel().catch(() => {
637
2293
  });
638
2294
  await sleep(this.backoff(attempt));
639
2295
  continue;
640
2296
  }
641
- const text = await res.text().catch(() => "");
2297
+ const text = this.#redact(await res.text().catch(() => ""));
2298
+ unwire();
642
2299
  let parsed = null;
643
2300
  try {
644
- parsed = text ? JSON.parse(text) : null;
2301
+ parsed = text ? JSON.parse(text, (_k, v) => typeof v === "string" ? this.#redact(v) : v) : null;
645
2302
  } catch {
646
2303
  parsed = null;
647
2304
  }
648
- throw errorFromResponse(res.status, parsed, `${method} ${path} returned ${res.status}`);
2305
+ throw errorFromResponse(res.status, parsed, `${where} returned ${res.status}`);
649
2306
  }
650
2307
  }
2308
+ /** The deadline of one request: `requestTimeoutMs` when set, else `defaultMs`. */
2309
+ requestTimeout(defaultMs) {
2310
+ return this.requestTimeoutMs ?? defaultMs;
2311
+ }
2312
+ /**
2313
+ * The error for an API error envelope found in a 2xx response body (a streamed exec's `error`
2314
+ * event), with the API key redacted as for an error response.
2315
+ */
2316
+ errorFromBody(status, text, fallbackMessage) {
2317
+ let parsed = null;
2318
+ try {
2319
+ parsed = JSON.parse(this.#redact(text), (_k, v) => typeof v === "string" ? this.#redact(v) : v);
2320
+ } catch {
2321
+ parsed = null;
2322
+ }
2323
+ return errorFromResponse(status, parsed, this.#redact(fallbackMessage));
2324
+ }
2325
+ /** Replaces the API key in `s`. */
2326
+ #redact(s) {
2327
+ return s.split(this.#apiKey).join(REDACTED);
2328
+ }
2329
+ /**
2330
+ * A copy of an error thrown by fetch, safe to hand to the app. Some fetch implementations put the request
2331
+ * (and so the X-API-Key header) in their errors, and a custom fetch may throw anything, so the original is
2332
+ * never passed on. The copy keeps the message, name, stack and the string, number and boolean fields (all
2333
+ * with the key redacted), and a copy of the cause. Object fields such as a request config are dropped.
2334
+ * Built-in error classes are kept (`instanceof TypeError` still holds); other classes keep only their name.
2335
+ * Every read is guarded, so a getter or proxy that throws cannot leak the key or replace this error.
2336
+ */
2337
+ #copyError(err, depth = 3) {
2338
+ const isError = guarded(() => err instanceof Error) === true;
2339
+ const raw = guarded(() => isError ? err.message : err);
2340
+ const message = this.#redact(guarded(() => String(raw)) ?? REDACTED);
2341
+ const copy = new Error(message);
2342
+ if (!isError) return copy;
2343
+ const e = err;
2344
+ const proto = guarded(() => Object.getPrototypeOf(e));
2345
+ if (BUILTIN_ERRORS.has(proto)) Object.setPrototypeOf(copy, proto);
2346
+ const name = guarded(() => String(e.name));
2347
+ if (name !== void 0)
2348
+ Object.defineProperty(copy, "name", { value: this.#redact(name), configurable: true, writable: true });
2349
+ const stack = guarded(() => e.stack);
2350
+ if (typeof stack === "string") copy.stack = this.#redact(stack);
2351
+ for (const k of guarded(() => Object.getOwnPropertyNames(e)) ?? []) {
2352
+ if (k === "message" || k === "stack" || k === "name" || k === "cause") continue;
2353
+ const d = guarded(() => Object.getOwnPropertyDescriptor(e, k));
2354
+ if (!d || !("value" in d) || !d.enumerable) continue;
2355
+ if (typeof d.value === "string") copy[this.#redact(k)] = this.#redact(d.value);
2356
+ else if (typeof d.value === "number" || typeof d.value === "boolean") copy[this.#redact(k)] = d.value;
2357
+ }
2358
+ const cause = guarded(() => e.cause);
2359
+ if (cause !== void 0 && depth > 0) {
2360
+ Object.defineProperty(copy, "cause", {
2361
+ value: this.#copyError(cause, depth - 1),
2362
+ configurable: true,
2363
+ writable: true
2364
+ });
2365
+ }
2366
+ return copy;
2367
+ }
2368
+ /** JSON form, without the API key. */
2369
+ toJSON() {
2370
+ return { apiUrl: this.apiUrl, apiKey: REDACTED };
2371
+ }
2372
+ /** `util.inspect` and `console.log` form, without the API key. */
2373
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")](_depth, options, inspect) {
2374
+ return `HttpClient ${inspect(this.toJSON(), options)}`;
2375
+ }
651
2376
  backoff(attempt) {
652
2377
  return this.retryDelayMs * 2 ** attempt;
653
2378
  }
@@ -659,17 +2384,22 @@ var HttpClient = class {
659
2384
  while (cur.state !== "succeeded") {
660
2385
  if (cur.state === "failed") {
661
2386
  const e = cur.error;
662
- throw new InstaboxError(e?.message || `operation ${cur.id} (${cur.type}) failed`, {
663
- code: e?.code ?? "operation_failed",
664
- requestId: e?.requestId,
2387
+ const r = (v) => typeof v === "string" ? this.#redact(v) : void 0;
2388
+ const code = r(e?.code) ?? "operation_failed";
2389
+ const Cls = isLimitCode(code) ? InstaboxQuotaError : InstaboxError;
2390
+ throw new Cls(r(e?.message || `operation ${cur.id} (${cur.type}) failed`) ?? REDACTED, {
2391
+ code,
2392
+ requestId: r(e?.requestId),
665
2393
  retryable: e?.retryable ?? false,
666
- operationId: cur.id
2394
+ operationId: r(cur.id)
667
2395
  });
668
2396
  }
669
2397
  if (Date.now() + delay > deadline) {
670
2398
  throw new InstaboxTimeoutError(
671
- `operation ${cur.id} (${cur.type}) did not finish within ${timeoutMs} ms (state ${cur.state}${cur.phase ? `, phase ${cur.phase}` : ""})`,
672
- { code: "operation_timeout", operationId: cur.id }
2399
+ this.#redact(
2400
+ `operation ${cur.id} (${cur.type}) did not finish within ${timeoutMs} ms (state ${cur.state}${cur.phase ? `, phase ${cur.phase}` : ""})`
2401
+ ),
2402
+ { code: "operation_timeout", operationId: this.#redact(String(cur.id)) }
673
2403
  );
674
2404
  }
675
2405
  await sleep(delay);
@@ -691,16 +2421,20 @@ function toInfo(m) {
691
2421
  metadata: { ...m.metadata },
692
2422
  vault: m.vault ?? true,
693
2423
  startedAt: new Date(m.createdAt),
694
- onTimeout: m.onTimeout ?? "pause",
695
2424
  state: m.state,
696
2425
  machine: m
697
2426
  };
698
2427
  if (m.snapshot?.id) info.snapshotId = m.snapshot.id;
699
- if (m.timeoutAt) info.endAt = new Date(m.timeoutAt);
700
2428
  if (m.archiveAt) info.archiveAt = new Date(m.archiveAt);
701
2429
  if (m.autoSuspendAfterSeconds) info.autoSuspendMs = m.autoSuspendAfterSeconds * 1e3;
702
2430
  return info;
703
2431
  }
2432
+ function timeoutRemoved(what, use) {
2433
+ return new InstaboxError(
2434
+ `${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)`,
2435
+ { code: "retired_option" }
2436
+ );
2437
+ }
704
2438
  function toIdleSeconds(ms) {
705
2439
  if (ms === 0) return 0;
706
2440
  const s = Math.ceil(ms / 1e3);
@@ -711,7 +2445,7 @@ function toIdleSeconds(ms) {
711
2445
  }
712
2446
  return s;
713
2447
  }
714
- function toSeconds(ms, field = "timeoutMs") {
2448
+ function toSeconds(ms, field) {
715
2449
  const s = Math.ceil(ms / 1e3);
716
2450
  if (!Number.isFinite(ms) || s < 60 || s > 86400) {
717
2451
  throw new InstaboxError(`${field} must be between 60 000 (60 s) and 86 400 000 (24 h); got ${ms}`, {
@@ -721,14 +2455,15 @@ function toSeconds(ms, field = "timeoutMs") {
721
2455
  return s;
722
2456
  }
723
2457
  var METADATA_KEY = /^[A-Za-z0-9_.-]{1,64}$/;
724
- var enc2 = encodeURIComponent;
2458
+ var enc3 = encodeURIComponent;
725
2459
  var Sandbox = class _Sandbox {
726
2460
  constructor(http, machine, opts = {}) {
727
2461
  this.http = http;
728
2462
  this.sandboxId = machine.id;
729
2463
  this.machine = machine;
730
2464
  this.commands = new Commands(http, machine.id, { ...opts.envs });
731
- this.files = new Files(this.commands);
2465
+ this.files = new Files(this.commands, http, machine.id);
2466
+ this.commands.stageStdin = (bytes, signal) => this.files.stageStdin(bytes, signal);
732
2467
  this.desktop = new Desktop(http, machine.id, this.commands, this.files);
733
2468
  }
734
2469
  http;
@@ -743,9 +2478,17 @@ var Sandbox = class _Sandbox {
743
2478
  machine;
744
2479
  static async create(a, b) {
745
2480
  const opts = (typeof a === "string" ? b : a) ?? {};
2481
+ const retired = ["timeoutMs", "onTimeout"].filter(
2482
+ (k) => opts[k] !== void 0
2483
+ );
2484
+ if (retired.length) {
2485
+ throw timeoutRemoved(
2486
+ retired.join(" and "),
2487
+ "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"
2488
+ );
2489
+ }
746
2490
  const http = new HttpClient(opts);
747
2491
  const body = { name: opts.name ?? `sbx-${randomSuffix()}` };
748
- if (opts.timeoutMs !== void 0) body.timeoutSeconds = toSeconds(opts.timeoutMs);
749
2492
  if (opts.archiveMs !== void 0) body.archiveSeconds = toSeconds(opts.archiveMs, "archiveMs");
750
2493
  if (opts.autoSuspendMs !== void 0) body.autoSuspendAfterSeconds = toIdleSeconds(opts.autoSuspendMs);
751
2494
  const template = typeof a === "string" ? a : await defaultTemplate(http);
@@ -754,7 +2497,6 @@ var Sandbox = class _Sandbox {
754
2497
  if (opts.memMiB !== void 0) body.memMiB = opts.memMiB;
755
2498
  if (opts.diskGiB !== void 0) body.persistentDiskGiB = opts.diskGiB;
756
2499
  if (opts.rootDiskGiB !== void 0) body.rootDiskGiB = opts.rootDiskGiB;
757
- if (opts.onTimeout) body.onTimeout = opts.onTimeout;
758
2500
  if (opts.metadata) body.metadata = opts.metadata;
759
2501
  if (opts.vault === false) body.vault = false;
760
2502
  const op = await createMachine(http, body);
@@ -812,12 +2554,12 @@ var Sandbox = class _Sandbox {
812
2554
  }
813
2555
  /** Fetches a snapshot by ID. Requires images:read. */
814
2556
  static async getSnapshot(snapshotId, opts = {}) {
815
- return new HttpClient(opts).request("GET", `/v1/snapshots/${enc2(snapshotId)}`);
2557
+ return new HttpClient(opts).request("GET", `/v1/snapshots/${enc3(snapshotId)}`);
816
2558
  }
817
2559
  /** Deletes a snapshot. Returns false if absent. Requires images:delete. */
818
2560
  static async deleteSnapshot(snapshotId, opts = {}) {
819
2561
  try {
820
- await new HttpClient(opts).request("DELETE", `/v1/snapshots/${enc2(snapshotId)}`);
2562
+ await new HttpClient(opts).request("DELETE", `/v1/snapshots/${enc3(snapshotId)}`);
821
2563
  return true;
822
2564
  } catch (err) {
823
2565
  if (err instanceof InstaboxError && err.status === 404 && err.code === "not_found") return false;
@@ -832,7 +2574,7 @@ var Sandbox = class _Sandbox {
832
2574
  async createSnapshot(opts) {
833
2575
  await this.settle();
834
2576
  await this.untilSynced();
835
- return this.http.request("POST", `/v1/machines/${enc2(this.sandboxId)}/snapshots`, { body: opts });
2577
+ return this.http.request("POST", `/v1/machines/${enc3(this.sandboxId)}/snapshots`, { body: opts });
836
2578
  }
837
2579
  /** This sandbox's recent CPU and memory samples; see `Sandbox.getMetrics`. */
838
2580
  async getMetrics(opts = {}) {
@@ -847,27 +2589,26 @@ var Sandbox = class _Sandbox {
847
2589
  this.machine = await getMachine(this.http, this.sandboxId);
848
2590
  return toInfo(this.machine);
849
2591
  }
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
2592
  /**
860
2593
  * Pauses the sandbox once it has been idle `idleMs` (whole seconds, 2 min to 24 h); 0 turns the idle
861
- * pause off. Unlike a timeout the setting stays across pause and resume.
2594
+ * pause off. The setting stays across pause and resume.
862
2595
  */
863
2596
  async setAutoSuspend(idleMs) {
864
- this.machine = await this.http.request("PATCH", `/v1/machines/${enc2(this.sandboxId)}`, {
2597
+ this.machine = await this.http.request("PATCH", `/v1/machines/${enc3(this.sandboxId)}`, {
865
2598
  body: { autoSuspendAfterSeconds: toIdleSeconds(idleMs) }
866
2599
  });
867
2600
  }
2601
+ /**
2602
+ * @deprecated Removed in 0.6.0: sandboxes have no lifetime timeout since 2026-10-20. Always rejects with
2603
+ * `InstaboxError` (`code: 'retired_option'`) naming the replacements (`setAutoSuspend()`, `kill()`), and
2604
+ * sends no request.
2605
+ */
2606
+ async setTimeout(..._args) {
2607
+ throw timeoutRemoved("setTimeout()", "Use setAutoSuspend(ms) to pause the sandbox once it has been idle that long");
2608
+ }
868
2609
  /** Replaces the sandbox's metadata (`{}` clears it). */
869
2610
  async setMetadata(metadata) {
870
- this.machine = await this.http.request("PATCH", `/v1/machines/${enc2(this.sandboxId)}`, {
2611
+ this.machine = await this.http.request("PATCH", `/v1/machines/${enc3(this.sandboxId)}`, {
871
2612
  body: { metadata }
872
2613
  });
873
2614
  }
@@ -877,21 +2618,21 @@ var Sandbox = class _Sandbox {
877
2618
  * Throws `not_found` on a server without the Vault.
878
2619
  */
879
2620
  async vault() {
880
- return this.http.request("GET", `/v1/machines/${enc2(this.sandboxId)}/vault`);
2621
+ return this.http.request("GET", `/v1/machines/${enc3(this.sandboxId)}/vault`);
881
2622
  }
882
2623
  /**
883
2624
  * Writes the account's current Vault items into the running sandbox now, the same write as after a boot,
884
2625
  * and returns its record (`error` set when the guest refused it). Requires machines:write.
885
2626
  */
886
2627
  async pushVault() {
887
- return this.http.request("POST", `/v1/machines/${enc2(this.sandboxId)}/vault`);
2628
+ return this.http.request("POST", `/v1/machines/${enc3(this.sandboxId)}/vault`);
888
2629
  }
889
2630
  /**
890
2631
  * Turns the Vault off for this sandbox, for good, in any state: its next boot, resume or push removes
891
2632
  * what the Vault wrote and nothing is written again. Requires machines:write.
892
2633
  */
893
2634
  async disableVault() {
894
- this.machine = await this.http.request("PATCH", `/v1/machines/${enc2(this.sandboxId)}`, {
2635
+ this.machine = await this.http.request("PATCH", `/v1/machines/${enc3(this.sandboxId)}`, {
895
2636
  body: { vault: false }
896
2637
  });
897
2638
  }
@@ -938,7 +2679,7 @@ var Sandbox = class _Sandbox {
938
2679
  }
939
2680
  body.ttlSeconds = opts.ttlSeconds;
940
2681
  }
941
- const c = await this.http.request("POST", `/v1/machines/${enc2(this.sandboxId)}/connections`, { body });
2682
+ const c = await this.http.request("POST", `/v1/machines/${enc3(this.sandboxId)}/connections`, { body });
942
2683
  return {
943
2684
  host: c.host,
944
2685
  port: c.port,
@@ -957,7 +2698,7 @@ var Sandbox = class _Sandbox {
957
2698
  async settle(refresh = true) {
958
2699
  if (refresh) this.machine = await getMachine(this.http, this.sandboxId);
959
2700
  if (this.machine.operationId) {
960
- const op = await this.http.request("GET", `/v1/operations/${enc2(this.machine.operationId)}`);
2701
+ const op = await this.http.request("GET", `/v1/operations/${enc3(this.machine.operationId)}`);
961
2702
  await this.http.waitForOperation(op).catch(() => {
962
2703
  });
963
2704
  this.machine = await getMachine(this.http, this.sandboxId);
@@ -985,29 +2726,31 @@ var Sandbox = class _Sandbox {
985
2726
  }
986
2727
  }
987
2728
  async mutate(method, action) {
988
- const op = await this.http.request(method, `/v1/machines/${enc2(this.sandboxId)}/${action}`);
2729
+ const op = await this.http.request(method, `/v1/machines/${enc3(this.sandboxId)}/${action}`);
989
2730
  await this.http.waitForOperation(op);
990
2731
  this.machine = await getMachine(this.http, this.sandboxId);
991
2732
  }
992
2733
  };
993
2734
  async function getMachine(http, id) {
994
- return http.request("GET", `/v1/machines/${enc2(id)}`);
2735
+ return http.request("GET", `/v1/machines/${enc3(id)}`);
995
2736
  }
996
2737
  async function getMetrics(http, id, opts) {
997
- const out = await http.request("GET", `/v1/machines/${enc2(id)}/metrics`, {
2738
+ const out = await http.request("GET", `/v1/machines/${enc3(id)}/metrics`, {
998
2739
  query: { since: opts.since?.toISOString() }
999
2740
  });
1000
2741
  return out.metrics.map((s) => ({ ...s, timestamp: new Date(s.timestamp) }));
1001
2742
  }
1002
2743
  async function getUsage(http, id, opts) {
1003
- const u = await http.request("GET", `/v1/machines/${enc2(id)}/usage`, {
2744
+ const u = await http.request("GET", `/v1/machines/${enc3(id)}/usage`, {
1004
2745
  query: { from: opts.from?.toISOString(), to: opts.to?.toISOString() }
1005
2746
  });
1006
2747
  return { ...u, from: new Date(u.from), to: new Date(u.to) };
1007
2748
  }
1008
2749
  async function killMachine(http, id) {
1009
2750
  try {
1010
- const op = await http.request("DELETE", `/v1/machines/${enc2(id)}`);
2751
+ const op = await http.request("DELETE", `/v1/machines/${enc3(id)}`, {
2752
+ headers: { "X-Confirm-Delete": id }
2753
+ });
1011
2754
  await http.waitForOperation(op);
1012
2755
  return true;
1013
2756
  } catch (err) {
@@ -1062,10 +2805,14 @@ export {
1062
2805
  Files,
1063
2806
  InstaboxAuthError,
1064
2807
  InstaboxError,
2808
+ InstaboxNotUtf8Error,
1065
2809
  InstaboxQuotaError,
1066
2810
  InstaboxTimeoutError,
2811
+ LIMIT_CODES,
1067
2812
  MAX_FILE_BYTES,
1068
2813
  MAX_STDIN_BYTES,
1069
- Sandbox
2814
+ MAX_UPLOAD_BYTES,
2815
+ Sandbox,
2816
+ isLimitCode
1070
2817
  };
1071
2818
  //# sourceMappingURL=index.js.map