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