@insforge/instabox-sdk 0.5.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -30,11 +30,14 @@ __export(index_exports, {
30
30
  Files: () => Files,
31
31
  InstaboxAuthError: () => InstaboxAuthError,
32
32
  InstaboxError: () => InstaboxError,
33
+ InstaboxNotUtf8Error: () => InstaboxNotUtf8Error,
33
34
  InstaboxQuotaError: () => InstaboxQuotaError,
34
35
  InstaboxTimeoutError: () => InstaboxTimeoutError,
36
+ LIMIT_CODES: () => LIMIT_CODES,
35
37
  MAX_FILE_BYTES: () => MAX_FILE_BYTES,
36
38
  MAX_STDIN_BYTES: () => MAX_STDIN_BYTES,
37
- Sandbox: () => Sandbox
39
+ Sandbox: () => Sandbox,
40
+ isLimitCode: () => isLimitCode
38
41
  });
39
42
  module.exports = __toCommonJS(index_exports);
40
43
 
@@ -62,8 +65,26 @@ var InstaboxAuthError = class extends InstaboxError {
62
65
  };
63
66
  var InstaboxQuotaError = class extends InstaboxError {
64
67
  };
68
+ var LIMIT_CODES = [
69
+ "quota_exceeded",
70
+ "credit_exhausted",
71
+ "spend_limit_reached",
72
+ "subscription_required",
73
+ "payment_method_required",
74
+ "payment_failed",
75
+ "template_limit",
76
+ "template_not_allowed",
77
+ "spec_not_allowed",
78
+ "concurrency_limit",
79
+ "rate_limited"
80
+ ];
81
+ function isLimitCode(code) {
82
+ return code !== void 0 && LIMIT_CODES.includes(code);
83
+ }
65
84
  var InstaboxTimeoutError = class extends InstaboxError {
66
85
  };
86
+ var InstaboxNotUtf8Error = class extends InstaboxError {
87
+ };
67
88
  var CommandExitError = class extends InstaboxError {
68
89
  stdout;
69
90
  stderr;
@@ -92,8 +113,9 @@ function errorFromResponse(status, body, fallbackMessage) {
92
113
  operationId: typeof env?.operationId === "string" ? env.operationId : null
93
114
  };
94
115
  const message = typeof env?.message === "string" && env.message ? env.message : fallbackMessage;
116
+ if (isLimitCode(init.code)) return new InstaboxQuotaError(message, init);
95
117
  if (status === 401 || status === 403) return new InstaboxAuthError(message, init);
96
- if (status === 429) return new InstaboxQuotaError(message, init);
118
+ if (status === 402 || status === 429) return new InstaboxQuotaError(message, init);
97
119
  return new InstaboxError(message, init);
98
120
  }
99
121
 
@@ -142,6 +164,135 @@ function readEnv(name) {
142
164
 
143
165
  // src/commands.ts
144
166
  var MAX_STDIN_BYTES = 1024 * 1024;
167
+ var MAX_TIMEOUT_MS = 6e5;
168
+ var JOBS_DIR = "$HOME/.instabox/jobs";
169
+ var JOB_CHUNK = 512 << 10;
170
+ var JOB_POLL_SEC = 25;
171
+ var JOB_RETRY_MS = 12e4;
172
+ var JOB_NO_SUCH = "instabox-no-job";
173
+ var JOB_IDLE_MIN_MS = 250;
174
+ var JOB_IDLE_MAX_MS = 2e3;
175
+ function abortableSleep(ms, signal) {
176
+ if (signal?.aborted) return Promise.reject(aborted());
177
+ if (!signal) return sleep(ms);
178
+ return new Promise((resolve, reject) => {
179
+ const onAbort = () => {
180
+ clearTimeout(t);
181
+ reject(aborted());
182
+ };
183
+ const t = setTimeout(() => {
184
+ signal.removeEventListener("abort", onAbort);
185
+ resolve();
186
+ }, ms);
187
+ signal.addEventListener("abort", onAbort, { once: true });
188
+ });
189
+ }
190
+ var JOB_WRAPPER = `d=$1
191
+ s=
192
+ trap 's=129' HUP; trap 's=130' INT; trap 's=131' QUIT; trap 's=143' TERM
193
+ echo $$ > "$d/pid.tmp" && mv -f -- "$d/pid.tmp" "$d/pid"
194
+ g=
195
+ while IFS= read -r l; do case $l in 0::*) g=\${l#0::} ;; esac; done 2>/dev/null < '/proc/self/cgroup'
196
+ 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"; }
197
+ k0=$(ok)
198
+ x=$(cat -- "$d/cmd")
199
+ c=$?
200
+ if [ -n "$s" ]; then
201
+ c=$s
202
+ elif [ "$c" = 0 ]; then
203
+ INSTABOX_EXEC_CMD=$x bash -c 'export -n INSTABOX_EXEC_CMD; eval "$INSTABOX_EXEC_CMD"'
204
+ c=$?
205
+ fi
206
+ k1=$(ok)
207
+ if [[ $k0 =~ ^[0-9]+$ && $k1 =~ ^[0-9]+$ ]]; then k=$((k1-k0)); else k=-; fi
208
+ [ -n "$g" ] && echo "$k $g" > "$d/oom"
209
+ echo "$c" > "$d/exit.tmp" && mv -f -- "$d/exit.tmp" "$d/exit"
210
+ `;
211
+ var JOB_STATUS = `st() {
212
+ if [ -s "$1/exit" ]; then echo "exited $(cat -- "$1/exit")"; return; fi
213
+ if [ "$(cat -- "$1/boot" 2>/dev/null)" = "$(cat /proc/sys/kernel/random/boot_id)" ] &&
214
+ p=$(cat -- "$1/pid" 2>/dev/null) && [ -n "$p" ] && kill -0 "$p" 2>/dev/null; then echo running; return; fi
215
+ if [ -s "$1/exit" ]; then echo "exited $(cat -- "$1/exit")"; else echo lost; fi
216
+ }
217
+ 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; }
218
+ `;
219
+ var JOB_UNSUPPORTED_EXIT = 97;
220
+ var JOB_UNSUPPORTED = "instabox-job-unsupported:";
221
+ var JOB_PREFLIGHT = `p=
222
+ command -v bash >/dev/null 2>&1 || p="$p, bash"
223
+ setsid -f true < /dev/null > /dev/null 2>&1 || p="$p, setsid -f (util-linux)"
224
+ [ "$(stat -c %s -- /dev/null 2>/dev/null)" = 0 ] || p="$p, stat -c (GNU coreutils)"
225
+ [ "$(printf abc | dd iflag=skip_bytes,count_bytes skip=1 count=1 bs=65536 status=none 2>/dev/null)" = b ] ||
226
+ p="$p, dd iflag=skip_bytes,count_bytes (GNU coreutils)"
227
+ [ "$(printf abc | base64 -w0 2>/dev/null)" = YWJj ] || p="$p, base64 -w0 (GNU coreutils)"
228
+ if [ -n "$p" ]; then echo "${JOB_UNSUPPORTED}\${p#, }" >&2; exit ${JOB_UNSUPPORTED_EXIT}; fi
229
+ `;
230
+ var JOB_START = `${JOB_PREFLIGHT}set -e
231
+ mkdir -p -- "$J"
232
+ mkdir -- "$d"
233
+ cat > "$d/cmd"
234
+ date +%s.%N > "$d/started"
235
+ cat /proc/sys/kernel/random/boot_id > "$d/boot"
236
+ setsid -f bash -c "$W" instabox-job "$d" < /dev/null > "$d/out" 2>&1
237
+ i=0
238
+ while [ ! -s "$d/pid" ]; do
239
+ i=$((i+1))
240
+ if [ "$i" -gt 200 ]; then echo "the job did not start" >&2; exit 1; fi
241
+ sleep 0.05
242
+ done
243
+ cat -- "$d/pid"
244
+ `;
245
+ var JOB_READ = `[ -d "$d" ] || { echo ${JOB_NO_SUCH}; exit 0; }
246
+ i=0
247
+ while :; do
248
+ s=$(st "$d")
249
+ sz=$(stat -c %s -- "$d/out" 2>/dev/null || echo 0)
250
+ if [ "$s" != running ] || [ "$sz" -gt "$off" ] || [ "$i" -ge $((w*4)) ]; then break; fi
251
+ sleep 0.25
252
+ i=$((i+1))
253
+ done
254
+ case $s in "exited "*) s=$s$(oo "$d") ;; esac
255
+ echo "$s"
256
+ if [ "$max" -gt 0 ]; then
257
+ dd if="$d/out" iflag=skip_bytes,count_bytes skip="$off" count="$max" bs=65536 status=none | base64 -w0
258
+ fi
259
+ `;
260
+ function jobScript(job, vars, script) {
261
+ let s = `J=${JOBS_DIR}
262
+ d=$J/${shellQuote(job)}
263
+ `;
264
+ for (const k of Object.keys(vars).sort()) s += `${k}=${shellQuote(vars[k])}
265
+ `;
266
+ return s + JOB_STATUS + script;
267
+ }
268
+ function transient(e) {
269
+ if (!(e instanceof InstaboxError) || e.code === "aborted") return false;
270
+ return e.retryable || e.status === 429 || e.status >= 500 || e.code === "network_error" || e.code === "request_timeout";
271
+ }
272
+ function aborted() {
273
+ return new InstaboxError("the command was aborted", { code: "aborted" });
274
+ }
275
+ function streamEnded() {
276
+ return new InstaboxError("the stream ended before the command finished (it may still have run)", {
277
+ status: 503,
278
+ code: "host_unavailable"
279
+ });
280
+ }
281
+ function invalid(what) {
282
+ return new InstaboxError(`exec returned ${what}`, { code: "invalid_response" });
283
+ }
284
+ function toResult(res, stdout = res.stdout, stderr = res.stderr) {
285
+ if (!res || typeof res.exitCode !== "number") throw invalid("a result without an exit code");
286
+ const out = {
287
+ stdout: typeof stdout === "string" ? stdout : "",
288
+ stderr: typeof stderr === "string" ? stderr : "",
289
+ exitCode: res.exitCode,
290
+ timedOut: res.timedOut === true,
291
+ truncated: res.truncated === true
292
+ };
293
+ if (typeof res.error === "string" && res.error) out.error = res.error;
294
+ return out;
295
+ }
145
296
  var Commands = class {
146
297
  /** @internal */
147
298
  constructor(http, sandboxId, defaultEnvs) {
@@ -153,28 +304,15 @@ var Commands = class {
153
304
  sandboxId;
154
305
  defaultEnvs;
155
306
  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);
307
+ if (opts.background) return this.startJob(cmd, opts);
308
+ const r = opts.onStdout || opts.onStderr ? await this.execStream(cmd, opts) : await this.exec(cmd, opts);
173
309
  if (r.exitCode !== 0) throw new CommandExitError(r);
174
310
  return r;
175
311
  }
176
- /** @internal Raw exec: never throws on a non-zero exit code. */
177
- async exec(cmd, opts = {}) {
312
+ get execPath() {
313
+ return `/v1/machines/${encodeURIComponent(this.sandboxId)}/exec`;
314
+ }
315
+ execBody(cmd, opts) {
178
316
  const envs = { ...this.defaultEnvs, ...opts.envs };
179
317
  const body = { cmd };
180
318
  if (opts.cwd !== void 0) body.cwd = opts.cwd;
@@ -186,30 +324,297 @@ var Commands = class {
186
324
  body.stdin = opts.stdin;
187
325
  }
188
326
  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" });
327
+ if (!Number.isFinite(opts.timeoutMs) || opts.timeoutMs <= 0 || opts.timeoutMs > MAX_TIMEOUT_MS) {
328
+ throw new InstaboxError(
329
+ "command timeoutMs must be greater than 0 and at most 600 000; for a longer command use { background: true } and wait() on the handle",
330
+ { code: "bad_request" }
331
+ );
191
332
  }
192
333
  body.timeoutSeconds = Math.ceil(opts.timeoutMs / 1e3);
193
334
  }
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
335
+ if (opts.noHistory) body.noHistory = true;
336
+ if (opts.historyCommand !== void 0) body.historyCommand = opts.historyCommand;
337
+ return body;
338
+ }
339
+ /** The request deadline of an exec: its command timeout plus 30 s, unless `requestTimeoutMs` is set. */
340
+ execDeadline(body) {
341
+ return this.http.requestTimeout((Number(body.timeoutSeconds) || 60) * 1e3 + 3e4);
342
+ }
343
+ /** @internal Raw exec: never throws on a non-zero exit code. */
344
+ async exec(cmd, opts = {}) {
345
+ const body = this.execBody(cmd, opts);
346
+ if (opts.signal?.aborted) throw aborted();
347
+ const res = await this.http.request("POST", this.execPath, {
348
+ body,
349
+ retry: false,
350
+ idempotent: false,
351
+ timeoutMs: this.execDeadline(body),
352
+ signal: opts.signal
353
+ });
354
+ return toResult(res);
355
+ }
356
+ /**
357
+ * Exec with the output streamed (`Accept: text/event-stream`): each `stdout`/`stderr` event goes to its
358
+ * callback as it arrives, and the result carries all of it. A server that does not stream answers with
359
+ * the whole result, whose output is passed to the callbacks then.
360
+ */
361
+ async execStream(cmd, opts) {
362
+ const body = this.execBody(cmd, opts);
363
+ if (opts.signal?.aborted) throw aborted();
364
+ const deadline = this.execDeadline(body);
365
+ const ctrl = new AbortController();
366
+ let timedOut = false;
367
+ const timer = setTimeout(() => {
368
+ timedOut = true;
369
+ ctrl.abort();
370
+ }, deadline);
371
+ const onAbort = () => ctrl.abort();
372
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
373
+ let reader;
374
+ let res;
375
+ const fail = (e) => {
376
+ if (opts.signal?.aborted) return aborted();
377
+ if (timedOut) {
378
+ return new InstaboxTimeoutError(`POST ${this.execPath} timed out after ${deadline} ms`, {
379
+ code: "request_timeout"
380
+ });
202
381
  }
203
- );
204
- const out = {
205
- stdout: res.stdout,
206
- stderr: res.stderr,
207
- exitCode: res.exitCode,
208
- timedOut: res.timedOut,
209
- truncated: res.truncated
382
+ return e;
210
383
  };
211
- if (res.error) out.error = res.error;
212
- return out;
384
+ try {
385
+ try {
386
+ res = await this.http.send("POST", this.execPath, {
387
+ body,
388
+ retry: false,
389
+ idempotent: false,
390
+ timeoutMs: deadline,
391
+ accept: "text/event-stream, application/json",
392
+ signal: ctrl.signal
393
+ });
394
+ } catch (e) {
395
+ throw fail(e);
396
+ }
397
+ const type = (res.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
398
+ if (type !== "text/event-stream" || !res.body) {
399
+ let r;
400
+ try {
401
+ r = toResult(await res.json());
402
+ } catch (e) {
403
+ throw fail(e instanceof InstaboxError ? e : invalid("a body that is not JSON"));
404
+ }
405
+ if (opts.onStdout && r.stdout) await opts.onStdout(r.stdout);
406
+ if (opts.onStderr && r.stderr) await opts.onStderr(r.stderr);
407
+ return r;
408
+ }
409
+ reader = res.body.getReader();
410
+ return await this.readEvents(reader, opts, fail);
411
+ } finally {
412
+ clearTimeout(timer);
413
+ opts.signal?.removeEventListener("abort", onAbort);
414
+ if (reader) void reader.cancel().catch(() => {
415
+ });
416
+ ctrl.abort();
417
+ if (res) this.http.release(res);
418
+ }
419
+ }
420
+ /** Reads a streamed exec's server-sent events until its `exit` or `error` event. */
421
+ async readEvents(reader, opts, fail) {
422
+ const dec = new TextDecoder();
423
+ const out = { stdout: "", stderr: "" };
424
+ let buf = "";
425
+ let event = "";
426
+ let data = null;
427
+ for (; ; ) {
428
+ let chunk;
429
+ try {
430
+ chunk = await reader.read();
431
+ } catch {
432
+ throw fail(streamEnded());
433
+ }
434
+ if (chunk.done) throw fail(streamEnded());
435
+ buf += dec.decode(chunk.value, { stream: true });
436
+ let start = 0;
437
+ for (let nl = buf.indexOf("\n", start); nl >= 0; nl = buf.indexOf("\n", start)) {
438
+ let line = buf.slice(start, nl);
439
+ start = nl + 1;
440
+ if (line.endsWith("\r")) line = line.slice(0, -1);
441
+ if (line === "") {
442
+ const r = await this.dispatch(event, data, out, opts);
443
+ if (r) return r;
444
+ event = "";
445
+ data = null;
446
+ continue;
447
+ }
448
+ if (line.startsWith(":")) continue;
449
+ const colon = line.indexOf(":");
450
+ const field = colon < 0 ? line : line.slice(0, colon);
451
+ let value = colon < 0 ? "" : line.slice(colon + 1);
452
+ if (value.startsWith(" ")) value = value.slice(1);
453
+ if (field === "event") event = value;
454
+ else if (field === "data") data = data === null ? value : `${data}
455
+ ${value}`;
456
+ }
457
+ buf = buf.slice(start);
458
+ }
459
+ }
460
+ /** Handles one event: output goes to its callback, `exit` is the result, `error` is thrown. */
461
+ async dispatch(event, data, out, opts) {
462
+ if (data === null) return void 0;
463
+ if (event === "stdout" || event === "stderr") {
464
+ let chunk;
465
+ try {
466
+ chunk = JSON.parse(data)?.data;
467
+ } catch {
468
+ chunk = void 0;
469
+ }
470
+ if (typeof chunk !== "string") throw invalid(`a ${event} event without data`);
471
+ out[event] += chunk;
472
+ const cb = event === "stdout" ? opts.onStdout : opts.onStderr;
473
+ if (cb && chunk) await cb(chunk);
474
+ return void 0;
475
+ }
476
+ if (event === "exit") {
477
+ let res;
478
+ try {
479
+ res = JSON.parse(data);
480
+ } catch {
481
+ throw invalid("an exit event that is not JSON");
482
+ }
483
+ return { ...toResult(res, out.stdout, out.stderr), truncated: false };
484
+ }
485
+ if (event === "error") {
486
+ let code;
487
+ try {
488
+ code = JSON.parse(data)?.error?.code;
489
+ } catch {
490
+ code = void 0;
491
+ }
492
+ const status = code === "host_unavailable" ? 503 : 500;
493
+ throw this.http.errorFromBody(status, data, `POST ${this.execPath} failed while streaming`);
494
+ }
495
+ return void 0;
496
+ }
497
+ /** Starts a background job the CLI's way and returns its handle. */
498
+ async startJob(cmd, opts) {
499
+ if (opts.stdin !== void 0)
500
+ throw new InstaboxError("stdin is not supported for background commands", { code: "bad_request" });
501
+ if (opts.onStdout || opts.onStderr) {
502
+ throw new InstaboxError(
503
+ "onStdout and onStderr are not supported with background: true; pass onStdout to wait() on the returned handle to follow the output",
504
+ { code: "bad_request" }
505
+ );
506
+ }
507
+ if (cmd.includes("\0")) throw new InstaboxError("the command contains a NUL byte", { code: "bad_request" });
508
+ const jobId = randomSuffix(8);
509
+ const r = await this.exec(jobScript(jobId, { W: JOB_WRAPPER }, JOB_START), {
510
+ cwd: opts.cwd,
511
+ envs: opts.envs,
512
+ timeoutMs: opts.timeoutMs,
513
+ stdin: cmd,
514
+ signal: opts.signal,
515
+ historyCommand: `background: ${cmd}`
516
+ });
517
+ const missing = r.stderr.split("\n").find((l) => l.startsWith(JOB_UNSUPPORTED));
518
+ if (r.exitCode === JOB_UNSUPPORTED_EXIT && missing) {
519
+ throw new InstaboxError(
520
+ `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`,
521
+ { code: "background_unsupported" }
522
+ );
523
+ }
524
+ if (r.exitCode !== 0) throw new CommandExitError(r);
525
+ const pid = Number.parseInt(r.stdout.trim(), 10);
526
+ if (!/^\d+$/.test(r.stdout.trim()) || !Number.isSafeInteger(pid) || pid <= 0)
527
+ throw new InstaboxError("exec returned an invalid background PID", { code: "invalid_response" });
528
+ return {
529
+ pid,
530
+ jobId,
531
+ kill: async () => (await this.exec(`kill -s TERM -- -${pid}`)).exitCode === 0,
532
+ wait: (w) => this.waitJob(jobId, w)
533
+ };
534
+ }
535
+ /** One read of a job: its status and up to `max` bytes of output from `off`, waiting up to `w` seconds. */
536
+ async readJob(jobId, off, max, w, signal) {
537
+ const r = await this.exec(jobScript(jobId, { off: String(off), max: String(max), w: String(w) }, JOB_READ), {
538
+ timeoutMs: (w + 30) * 1e3,
539
+ noHistory: true,
540
+ signal
541
+ });
542
+ if (r.exitCode !== 0 || r.timedOut) {
543
+ const msg = r.stderr.trim().split("\n").slice(-1)[0] || `exit status ${r.exitCode}`;
544
+ throw new InstaboxError(`reading job ${jobId} failed in the sandbox: ${msg}`, { code: "job_read_failed" });
545
+ }
546
+ if (r.truncated) throw invalid("a truncated job read");
547
+ const nl = r.stdout.indexOf("\n");
548
+ const head = (nl < 0 ? r.stdout : r.stdout.slice(0, nl)).trim();
549
+ if (head === JOB_NO_SUCH) return null;
550
+ const rest = nl < 0 ? "" : r.stdout.slice(nl + 1).trim();
551
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(rest)) throw invalid("job output that is not base64");
552
+ const bytes = base64ToBytes(rest);
553
+ const m = /^exited (-?\d+)(?: \S+ \S+ \S+)?$/.exec(head);
554
+ if (m) return { status: "exited", exitCode: Number(m[1]), bytes };
555
+ return { status: head === "running" ? "running" : "lost", bytes };
556
+ }
557
+ /** `readJob` for the wait loop. Reads change nothing, so a transient error is retried for up to 2 minutes. */
558
+ async pollJob(jobId, off, w, until, signal) {
559
+ let delay = 1e3;
560
+ const start = Date.now();
561
+ for (; ; ) {
562
+ try {
563
+ return await this.readJob(jobId, off, JOB_CHUNK, w, signal);
564
+ } catch (e) {
565
+ if (signal?.aborted) throw aborted();
566
+ if (!transient(e) || Date.now() - start > JOB_RETRY_MS || Date.now() + delay >= until) throw e;
567
+ await sleep(delay);
568
+ delay = Math.min(delay * 2, 15e3);
569
+ }
570
+ }
571
+ }
572
+ /** Follows a job's output until it ends. */
573
+ async waitJob(jobId, opts = {}) {
574
+ const { signal } = opts;
575
+ if (opts.timeoutMs !== void 0 && (!Number.isFinite(opts.timeoutMs) || opts.timeoutMs <= 0))
576
+ throw new InstaboxError("wait timeoutMs must be greater than 0", { code: "bad_request" });
577
+ const until = opts.timeoutMs === void 0 ? Infinity : Date.now() + opts.timeoutMs;
578
+ const maxWait = Math.max(0, Math.min(JOB_POLL_SEC, Math.floor((this.http.requestTimeout(Infinity) - 5e3) / 1e3)));
579
+ const dec = new TextDecoder();
580
+ let stdout = "";
581
+ let off = 0;
582
+ let idle = JOB_IDLE_MIN_MS;
583
+ const emit = async (text) => {
584
+ stdout += text;
585
+ if (text && opts.onStdout) await opts.onStdout(text);
586
+ };
587
+ for (; ; ) {
588
+ if (signal?.aborted) throw aborted();
589
+ const left = until - Date.now();
590
+ const w = Math.max(0, Math.min(maxWait, Math.ceil(left / 1e3)));
591
+ const read = await this.pollJob(jobId, off, w, until, signal);
592
+ if (read === null) throw new InstaboxError(`no job ${jobId} in the sandbox`, { status: 404, code: "not_found" });
593
+ if (w === 0 && read.status === "running" && read.bytes.length === 0) {
594
+ await abortableSleep(Math.min(idle, Math.max(0, until - Date.now())), signal);
595
+ idle = Math.min(idle * 2, JOB_IDLE_MAX_MS);
596
+ } else if (read.bytes.length > 0) idle = JOB_IDLE_MIN_MS;
597
+ off += read.bytes.length;
598
+ await emit(dec.decode(read.bytes, { stream: true }));
599
+ if (read.bytes.length === JOB_CHUNK) continue;
600
+ if (read.status !== "running") {
601
+ await emit(dec.decode());
602
+ if (read.exitCode === void 0) {
603
+ throw new InstaboxError(
604
+ `job ${jobId} ended without an exit code (the sandbox restarted or the job was killed)`,
605
+ { code: "job_lost" }
606
+ );
607
+ }
608
+ const r = { stdout, stderr: "", exitCode: read.exitCode, timedOut: false, truncated: false };
609
+ if (r.exitCode !== 0) throw new CommandExitError(r);
610
+ return r;
611
+ }
612
+ if (Date.now() >= until) {
613
+ throw new InstaboxTimeoutError(`job ${jobId} is still running after ${opts.timeoutMs} ms`, {
614
+ code: "job_wait_timeout"
615
+ });
616
+ }
617
+ }
213
618
  }
214
619
  };
215
620
 
@@ -470,17 +875,69 @@ var Desktop = class {
470
875
 
471
876
  // src/files.ts
472
877
  var MAX_FILE_BYTES = 10 * 1024 * 1024;
878
+ var TRANSFER_TIMEOUT_MS = 3e5;
473
879
  var WRITE_CHUNK_B64 = 48 * 1024;
474
880
  var READ_CHUNK_BYTES = 512 * 1024;
475
881
  var Files = class {
476
882
  /** @internal */
477
- constructor(commands) {
883
+ constructor(commands, http, sandboxId) {
478
884
  this.commands = commands;
885
+ this.http = http;
886
+ this.sandboxId = sandboxId;
479
887
  }
480
888
  commands;
889
+ http;
890
+ sandboxId;
891
+ home;
892
+ /** False once a server answered that it has no file routes. */
893
+ routes = true;
481
894
  async read(path, opts = {}) {
482
- const p = arg(path);
483
895
  const limit = opts.maxBytes ?? MAX_FILE_BYTES;
896
+ const streamed = await this.readStream(path, limit);
897
+ const bytes = streamed ?? await this.readExec(path, limit);
898
+ return opts.format === "bytes" ? bytes : decodeUtf8(bytes);
899
+ }
900
+ /** Reads over `GET .../files/content`; undefined when the server has no such route. */
901
+ async readStream(path, limit) {
902
+ if (!this.http || !this.sandboxId || !this.routes) return void 0;
903
+ const abs = await this.absolute(path);
904
+ let res;
905
+ try {
906
+ res = await this.http.send("GET", `/v1/machines/${encodeURIComponent(this.sandboxId)}/files/content`, {
907
+ query: { path: abs },
908
+ timeoutMs: TRANSFER_TIMEOUT_MS
909
+ });
910
+ } catch (err) {
911
+ if (routeMissing(err)) {
912
+ this.routes = false;
913
+ return void 0;
914
+ }
915
+ if (err instanceof InstaboxError && (err.code === "not_found" || err.code === "not_a_file")) {
916
+ throw new InstaboxError(`file not found: ${path}`, {
917
+ status: 404,
918
+ code: "not_found",
919
+ requestId: err.requestId,
920
+ cause: err
921
+ });
922
+ }
923
+ throw err;
924
+ }
925
+ const declared = Number(res.headers.get("Content-Length") ?? NaN);
926
+ if (Number.isSafeInteger(declared) && declared > limit) {
927
+ void res.body?.cancel().catch(() => {
928
+ });
929
+ throw new InstaboxError(`${path} is larger than the ${limit}-byte limit of files.read`, {
930
+ code: "file_too_large"
931
+ });
932
+ }
933
+ const bytes = await readBody(res, limit, path);
934
+ if (Number.isSafeInteger(declared) && bytes.length !== declared) {
935
+ throw new InstaboxError(`got ${bytes.length} of ${declared} bytes of ${path}`, { code: "file_changed" });
936
+ }
937
+ return bytes;
938
+ }
939
+ async readExec(path, limit) {
940
+ const p = arg(path);
484
941
  const r = await this.commands.exec(
485
942
  `[ -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
943
  );
@@ -507,7 +964,7 @@ var Files = class {
507
964
  }
508
965
  bytes.set(data, offset);
509
966
  }
510
- return opts.format === "bytes" ? bytes : new TextDecoder().decode(bytes);
967
+ return bytes;
511
968
  }
512
969
  /**
513
970
  * Writes a file, creating parent directories. Replaces the file atomically (temp file + rename).
@@ -520,6 +977,49 @@ var Files = class {
520
977
  code: "file_too_large"
521
978
  });
522
979
  }
980
+ if (await this.writeStream(path, bytes)) return { path };
981
+ await this.writeExec(path, bytes);
982
+ return { path };
983
+ }
984
+ /**
985
+ * Writes over `PUT .../files?parents=true`, which writes a temp file beside the target and renames
986
+ * it into place once every byte arrived. False when the server has no such route.
987
+ */
988
+ async writeStream(path, bytes) {
989
+ if (!this.http || !this.sandboxId || !this.routes) return false;
990
+ const abs = await this.absolute(path);
991
+ let res;
992
+ try {
993
+ res = await this.http.request("PUT", `/v1/machines/${encodeURIComponent(this.sandboxId)}/files`, {
994
+ query: { path: abs, parents: "true" },
995
+ rawBody: bytes,
996
+ idempotent: false,
997
+ retry: true,
998
+ timeoutMs: TRANSFER_TIMEOUT_MS
999
+ });
1000
+ } catch (err) {
1001
+ if (routeMissing(err)) {
1002
+ this.routes = false;
1003
+ return false;
1004
+ }
1005
+ if (err instanceof InstaboxError && err.code === "not_a_file") {
1006
+ const dir = await this.commands.exec(`test -d ${arg(path)}`).catch(() => void 0);
1007
+ if (dir?.exitCode === 0) {
1008
+ throw new InstaboxError(`is a directory: ${path}`, { status: 409, code: "is_a_directory", cause: err });
1009
+ }
1010
+ }
1011
+ throw err;
1012
+ }
1013
+ const want = await sha256Hex(bytes);
1014
+ if (res?.size !== bytes.length || want !== void 0 && res.sha256 !== want) {
1015
+ throw new InstaboxError(
1016
+ `the sandbox received ${res?.size} bytes with sha256 ${res?.sha256}; sent ${bytes.length} with ${want}`,
1017
+ { code: "transfer_mismatch" }
1018
+ );
1019
+ }
1020
+ return true;
1021
+ }
1022
+ async writeExec(path, bytes) {
523
1023
  const p = arg(path);
524
1024
  const tmp = arg(`${path}.instabox-${Math.random().toString(36).slice(2, 10)}.tmp`);
525
1025
  const b64 = bytesToBase64(bytes);
@@ -541,7 +1041,22 @@ var Files = class {
541
1041
  });
542
1042
  throw err;
543
1043
  }
544
- return { path };
1044
+ }
1045
+ /** The file routes take absolute paths; a relative one is relative to exec's working directory (HOME). */
1046
+ async absolute(path) {
1047
+ if (path.startsWith("/")) return path;
1048
+ this.home ??= this.commands.exec(`printf '%s' "$PWD"`).then((r) => {
1049
+ ensureComplete(r);
1050
+ if (!r.stdout.startsWith("/")) {
1051
+ throw new InstaboxError("invalid working directory returned by exec", { code: "invalid_response" });
1052
+ }
1053
+ return r.stdout;
1054
+ });
1055
+ const home = await this.home.catch((err) => {
1056
+ this.home = void 0;
1057
+ throw err;
1058
+ });
1059
+ return `${home.replace(/\/+$/, "")}/${path}`;
545
1060
  }
546
1061
  /** Lists the entries of a directory (not recursive). */
547
1062
  async list(path) {
@@ -572,6 +1087,51 @@ var Files = class {
572
1087
  function arg(path) {
573
1088
  return shellQuote(path.startsWith("-") ? `./${path}` : path);
574
1089
  }
1090
+ async function readBody(res, limit, path) {
1091
+ const tooLarge = () => new InstaboxError(`${path} is larger than the ${limit}-byte limit of files.read`, { code: "file_too_large" });
1092
+ const reader = res.body?.getReader();
1093
+ if (!reader) return new Uint8Array(0);
1094
+ const chunks = [];
1095
+ let n = 0;
1096
+ try {
1097
+ for (; ; ) {
1098
+ const { done, value } = await reader.read();
1099
+ if (done) break;
1100
+ n += value.length;
1101
+ if (n > limit) {
1102
+ void reader.cancel().catch(() => {
1103
+ });
1104
+ throw tooLarge();
1105
+ }
1106
+ chunks.push(value);
1107
+ }
1108
+ } catch (err) {
1109
+ if (err instanceof InstaboxError) throw err;
1110
+ throw new InstaboxError(`reading ${path} stopped after ${n} bytes: ${err?.message ?? String(err)}`, {
1111
+ code: "file_changed",
1112
+ retryable: true,
1113
+ cause: err
1114
+ });
1115
+ }
1116
+ const out = new Uint8Array(n);
1117
+ let off = 0;
1118
+ for (const c of chunks) {
1119
+ out.set(c, off);
1120
+ off += c.length;
1121
+ }
1122
+ return out;
1123
+ }
1124
+ function routeMissing(err) {
1125
+ if (!(err instanceof InstaboxError)) return false;
1126
+ if (err.status === 405) return true;
1127
+ return err.status === 404 && (err.code === "http_404" || err.code === "not_found" && err.message === "route not found");
1128
+ }
1129
+ async function sha256Hex(bytes) {
1130
+ const subtle = globalThis.crypto?.subtle;
1131
+ if (!subtle) return void 0;
1132
+ const d = new Uint8Array(await subtle.digest("SHA-256", bytes));
1133
+ return Array.from(d, (x) => x.toString(16).padStart(2, "0")).join("");
1134
+ }
575
1135
  function writeError(result, path) {
576
1136
  if (result.exitCode === 21) return new InstaboxError(`is a directory: ${path}`, { code: "is_a_directory" });
577
1137
  return new CommandExitError(result);
@@ -580,18 +1140,42 @@ function ensureComplete(result) {
580
1140
  if (result.exitCode !== 0) throw new CommandExitError(result);
581
1141
  if (result.truncated) throw new InstaboxError("file command output was truncated", { code: "output_truncated" });
582
1142
  }
1143
+ function decodeUtf8(bytes) {
1144
+ try {
1145
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
1146
+ } catch (err) {
1147
+ throw new InstaboxNotUtf8Error("file is not UTF-8 text; read it with { format: 'bytes' }", {
1148
+ code: "not_utf8",
1149
+ cause: err
1150
+ });
1151
+ }
1152
+ }
583
1153
 
584
1154
  // src/http.ts
585
1155
  var DEFAULT_API_URL = "https://api.instabox.sh";
586
1156
  var MAX_RETRIES = 3;
1157
+ var REDACTED = "[redacted]";
1158
+ var BUILTIN_ERRORS = new Set(
1159
+ [Error, TypeError, RangeError, SyntaxError, ReferenceError, EvalError, URIError].map((c) => c.prototype)
1160
+ );
1161
+ function guarded(f) {
1162
+ try {
1163
+ return f();
1164
+ } catch {
1165
+ return void 0;
1166
+ }
1167
+ }
587
1168
  var HttpClient = class {
588
1169
  apiUrl;
589
1170
  operationTimeoutMs;
590
- apiKey;
1171
+ // An ES private field: invisible to JSON.stringify, util.inspect, structuredClone and property walks.
1172
+ #apiKey;
591
1173
  requestTimeoutMs;
592
1174
  fetchImpl;
593
1175
  pollIntervalMs;
594
1176
  retryDelayMs;
1177
+ /** Removes the caller's abort listener of a response `send` returned; see `release`. */
1178
+ releases = /* @__PURE__ */ new WeakMap();
595
1179
  constructor(opts = {}) {
596
1180
  const apiKey = opts.apiKey ?? readEnv("INSTABOX_API_KEY");
597
1181
  if (!apiKey) {
@@ -600,7 +1184,7 @@ var HttpClient = class {
600
1184
  { code: "missing_api_key" }
601
1185
  );
602
1186
  }
603
- this.apiKey = apiKey;
1187
+ this.#apiKey = apiKey;
604
1188
  this.apiUrl = (opts.apiUrl ?? readEnv("INSTABOX_API_URL") ?? DEFAULT_API_URL).replace(/\/+$/, "");
605
1189
  this.requestTimeoutMs = opts.requestTimeoutMs;
606
1190
  this.operationTimeoutMs = opts.operationTimeoutMs ?? 6e5;
@@ -612,8 +1196,23 @@ var HttpClient = class {
612
1196
  }
613
1197
  async request(method, path, opts = {}) {
614
1198
  const res = await this.send(method, path, opts);
615
- if (res.status === 204) return void 0;
616
- return await res.json();
1199
+ try {
1200
+ if (res.status === 204) return void 0;
1201
+ return await res.json();
1202
+ } finally {
1203
+ this.release(res);
1204
+ }
1205
+ }
1206
+ /**
1207
+ * Unwires the caller's `signal` from a response `send` returned, once its body is read or dropped.
1208
+ * Until then an abort still ends the body; after it the signal holds no listener of this request,
1209
+ * so a signal shared by many requests (a long `wait()`) does not collect one per request.
1210
+ */
1211
+ release(res) {
1212
+ const f = this.releases.get(res);
1213
+ if (!f) return;
1214
+ this.releases.delete(res);
1215
+ f();
617
1216
  }
618
1217
  /** Performs the request with retries; returns a 2xx response or throws an InstaboxError. */
619
1218
  async send(method, path, opts = {}) {
@@ -621,15 +1220,20 @@ var HttpClient = class {
621
1220
  const idempotent = opts.idempotent ?? !isRead;
622
1221
  const retry = opts.retry ?? (isRead || idempotent);
623
1222
  const headers = {
624
- "X-API-Key": this.apiKey,
625
- Accept: "application/json"
1223
+ "X-API-Key": this.#apiKey,
1224
+ Accept: opts.accept ?? "application/json",
1225
+ ...opts.headers
626
1226
  };
627
1227
  if (idempotent) headers["Idempotency-Key"] = uuid();
628
1228
  let body;
629
- if (opts.body !== void 0) {
1229
+ if (opts.rawBody !== void 0) {
1230
+ headers["Content-Type"] = "application/octet-stream";
1231
+ body = opts.rawBody;
1232
+ } else if (opts.body !== void 0) {
630
1233
  headers["Content-Type"] = "application/json";
631
1234
  body = JSON.stringify(opts.body);
632
1235
  }
1236
+ const where = this.#redact(`${method} ${path}`);
633
1237
  let url = this.apiUrl + path;
634
1238
  if (opts.query) {
635
1239
  const q = new URLSearchParams();
@@ -649,44 +1253,124 @@ var HttpClient = class {
649
1253
  timedOut = true;
650
1254
  ctrl.abort();
651
1255
  }, timeoutMs);
1256
+ const onAbort = () => ctrl.abort();
1257
+ if (opts.signal?.aborted) ctrl.abort();
1258
+ else opts.signal?.addEventListener("abort", onAbort, { once: true });
652
1259
  let res;
653
1260
  try {
654
1261
  res = await this.fetchImpl(url, { method, headers, body, signal: ctrl.signal });
655
1262
  } catch (err) {
656
1263
  clearTimeout(timer);
1264
+ opts.signal?.removeEventListener("abort", onAbort);
1265
+ if (opts.signal?.aborted) throw new InstaboxError(`${where} was aborted`, { code: "aborted" });
657
1266
  if (canRetry) {
658
1267
  await sleep(this.backoff(attempt));
659
1268
  continue;
660
1269
  }
1270
+ const cause = this.#copyError(err);
661
1271
  if (timedOut) {
662
- throw new InstaboxTimeoutError(`${method} ${path} timed out after ${timeoutMs} ms`, {
1272
+ throw new InstaboxTimeoutError(`${where} timed out after ${timeoutMs} ms`, {
663
1273
  code: "request_timeout",
664
- cause: err
1274
+ cause
665
1275
  });
666
1276
  }
667
- throw new InstaboxError(`${method} ${path} failed: ${err?.message ?? String(err)}`, {
1277
+ throw new InstaboxError(`${where} failed: ${cause.message}`, {
668
1278
  code: "network_error",
669
1279
  retryable: true,
670
- cause: err
1280
+ cause
671
1281
  });
672
1282
  }
673
1283
  clearTimeout(timer);
674
- if (res.ok) return res;
1284
+ const unwire = () => opts.signal?.removeEventListener("abort", onAbort);
1285
+ if (res.ok) {
1286
+ if (opts.signal) this.releases.set(res, unwire);
1287
+ return res;
1288
+ }
675
1289
  if (canRetry && res.status >= 502 && res.status <= 504) {
1290
+ unwire();
676
1291
  void res.body?.cancel().catch(() => {
677
1292
  });
678
1293
  await sleep(this.backoff(attempt));
679
1294
  continue;
680
1295
  }
681
- const text = await res.text().catch(() => "");
1296
+ const text = this.#redact(await res.text().catch(() => ""));
1297
+ unwire();
682
1298
  let parsed = null;
683
1299
  try {
684
- parsed = text ? JSON.parse(text) : null;
1300
+ parsed = text ? JSON.parse(text, (_k, v) => typeof v === "string" ? this.#redact(v) : v) : null;
685
1301
  } catch {
686
1302
  parsed = null;
687
1303
  }
688
- throw errorFromResponse(res.status, parsed, `${method} ${path} returned ${res.status}`);
1304
+ throw errorFromResponse(res.status, parsed, `${where} returned ${res.status}`);
1305
+ }
1306
+ }
1307
+ /** The deadline of one request: `requestTimeoutMs` when set, else `defaultMs`. */
1308
+ requestTimeout(defaultMs) {
1309
+ return this.requestTimeoutMs ?? defaultMs;
1310
+ }
1311
+ /**
1312
+ * The error for an API error envelope found in a 2xx response body (a streamed exec's `error`
1313
+ * event), with the API key redacted as for an error response.
1314
+ */
1315
+ errorFromBody(status, text, fallbackMessage) {
1316
+ let parsed = null;
1317
+ try {
1318
+ parsed = JSON.parse(this.#redact(text), (_k, v) => typeof v === "string" ? this.#redact(v) : v);
1319
+ } catch {
1320
+ parsed = null;
1321
+ }
1322
+ return errorFromResponse(status, parsed, this.#redact(fallbackMessage));
1323
+ }
1324
+ /** Replaces the API key in `s`. */
1325
+ #redact(s) {
1326
+ return s.split(this.#apiKey).join(REDACTED);
1327
+ }
1328
+ /**
1329
+ * A copy of an error thrown by fetch, safe to hand to the app. Some fetch implementations put the request
1330
+ * (and so the X-API-Key header) in their errors, and a custom fetch may throw anything, so the original is
1331
+ * never passed on. The copy keeps the message, name, stack and the string, number and boolean fields (all
1332
+ * with the key redacted), and a copy of the cause. Object fields such as a request config are dropped.
1333
+ * Built-in error classes are kept (`instanceof TypeError` still holds); other classes keep only their name.
1334
+ * Every read is guarded, so a getter or proxy that throws cannot leak the key or replace this error.
1335
+ */
1336
+ #copyError(err, depth = 3) {
1337
+ const isError = guarded(() => err instanceof Error) === true;
1338
+ const raw = guarded(() => isError ? err.message : err);
1339
+ const message = this.#redact(guarded(() => String(raw)) ?? REDACTED);
1340
+ const copy = new Error(message);
1341
+ if (!isError) return copy;
1342
+ const e = err;
1343
+ const proto = guarded(() => Object.getPrototypeOf(e));
1344
+ if (BUILTIN_ERRORS.has(proto)) Object.setPrototypeOf(copy, proto);
1345
+ const name = guarded(() => String(e.name));
1346
+ if (name !== void 0)
1347
+ Object.defineProperty(copy, "name", { value: this.#redact(name), configurable: true, writable: true });
1348
+ const stack = guarded(() => e.stack);
1349
+ if (typeof stack === "string") copy.stack = this.#redact(stack);
1350
+ for (const k of guarded(() => Object.getOwnPropertyNames(e)) ?? []) {
1351
+ if (k === "message" || k === "stack" || k === "name" || k === "cause") continue;
1352
+ const d = guarded(() => Object.getOwnPropertyDescriptor(e, k));
1353
+ if (!d || !("value" in d) || !d.enumerable) continue;
1354
+ if (typeof d.value === "string") copy[this.#redact(k)] = this.#redact(d.value);
1355
+ else if (typeof d.value === "number" || typeof d.value === "boolean") copy[this.#redact(k)] = d.value;
689
1356
  }
1357
+ const cause = guarded(() => e.cause);
1358
+ if (cause !== void 0 && depth > 0) {
1359
+ Object.defineProperty(copy, "cause", {
1360
+ value: this.#copyError(cause, depth - 1),
1361
+ configurable: true,
1362
+ writable: true
1363
+ });
1364
+ }
1365
+ return copy;
1366
+ }
1367
+ /** JSON form, without the API key. */
1368
+ toJSON() {
1369
+ return { apiUrl: this.apiUrl, apiKey: REDACTED };
1370
+ }
1371
+ /** `util.inspect` and `console.log` form, without the API key. */
1372
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")](_depth, options, inspect) {
1373
+ return `HttpClient ${inspect(this.toJSON(), options)}`;
690
1374
  }
691
1375
  backoff(attempt) {
692
1376
  return this.retryDelayMs * 2 ** attempt;
@@ -699,17 +1383,22 @@ var HttpClient = class {
699
1383
  while (cur.state !== "succeeded") {
700
1384
  if (cur.state === "failed") {
701
1385
  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,
1386
+ const r = (v) => typeof v === "string" ? this.#redact(v) : void 0;
1387
+ const code = r(e?.code) ?? "operation_failed";
1388
+ const Cls = isLimitCode(code) ? InstaboxQuotaError : InstaboxError;
1389
+ throw new Cls(r(e?.message || `operation ${cur.id} (${cur.type}) failed`) ?? REDACTED, {
1390
+ code,
1391
+ requestId: r(e?.requestId),
705
1392
  retryable: e?.retryable ?? false,
706
- operationId: cur.id
1393
+ operationId: r(cur.id)
707
1394
  });
708
1395
  }
709
1396
  if (Date.now() + delay > deadline) {
710
1397
  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 }
1398
+ this.#redact(
1399
+ `operation ${cur.id} (${cur.type}) did not finish within ${timeoutMs} ms (state ${cur.state}${cur.phase ? `, phase ${cur.phase}` : ""})`
1400
+ ),
1401
+ { code: "operation_timeout", operationId: this.#redact(String(cur.id)) }
713
1402
  );
714
1403
  }
715
1404
  await sleep(delay);
@@ -731,16 +1420,20 @@ function toInfo(m) {
731
1420
  metadata: { ...m.metadata },
732
1421
  vault: m.vault ?? true,
733
1422
  startedAt: new Date(m.createdAt),
734
- onTimeout: m.onTimeout ?? "pause",
735
1423
  state: m.state,
736
1424
  machine: m
737
1425
  };
738
1426
  if (m.snapshot?.id) info.snapshotId = m.snapshot.id;
739
- if (m.timeoutAt) info.endAt = new Date(m.timeoutAt);
740
1427
  if (m.archiveAt) info.archiveAt = new Date(m.archiveAt);
741
1428
  if (m.autoSuspendAfterSeconds) info.autoSuspendMs = m.autoSuspendAfterSeconds * 1e3;
742
1429
  return info;
743
1430
  }
1431
+ function timeoutRemoved(what, use) {
1432
+ return new InstaboxError(
1433
+ `${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)`,
1434
+ { code: "retired_option" }
1435
+ );
1436
+ }
744
1437
  function toIdleSeconds(ms) {
745
1438
  if (ms === 0) return 0;
746
1439
  const s = Math.ceil(ms / 1e3);
@@ -751,7 +1444,7 @@ function toIdleSeconds(ms) {
751
1444
  }
752
1445
  return s;
753
1446
  }
754
- function toSeconds(ms, field = "timeoutMs") {
1447
+ function toSeconds(ms, field) {
755
1448
  const s = Math.ceil(ms / 1e3);
756
1449
  if (!Number.isFinite(ms) || s < 60 || s > 86400) {
757
1450
  throw new InstaboxError(`${field} must be between 60 000 (60 s) and 86 400 000 (24 h); got ${ms}`, {
@@ -768,7 +1461,7 @@ var Sandbox = class _Sandbox {
768
1461
  this.sandboxId = machine.id;
769
1462
  this.machine = machine;
770
1463
  this.commands = new Commands(http, machine.id, { ...opts.envs });
771
- this.files = new Files(this.commands);
1464
+ this.files = new Files(this.commands, http, machine.id);
772
1465
  this.desktop = new Desktop(http, machine.id, this.commands, this.files);
773
1466
  }
774
1467
  http;
@@ -783,9 +1476,17 @@ var Sandbox = class _Sandbox {
783
1476
  machine;
784
1477
  static async create(a, b) {
785
1478
  const opts = (typeof a === "string" ? b : a) ?? {};
1479
+ const retired = ["timeoutMs", "onTimeout"].filter(
1480
+ (k) => opts[k] !== void 0
1481
+ );
1482
+ if (retired.length) {
1483
+ throw timeoutRemoved(
1484
+ retired.join(" and "),
1485
+ "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"
1486
+ );
1487
+ }
786
1488
  const http = new HttpClient(opts);
787
1489
  const body = { name: opts.name ?? `sbx-${randomSuffix()}` };
788
- if (opts.timeoutMs !== void 0) body.timeoutSeconds = toSeconds(opts.timeoutMs);
789
1490
  if (opts.archiveMs !== void 0) body.archiveSeconds = toSeconds(opts.archiveMs, "archiveMs");
790
1491
  if (opts.autoSuspendMs !== void 0) body.autoSuspendAfterSeconds = toIdleSeconds(opts.autoSuspendMs);
791
1492
  const template = typeof a === "string" ? a : await defaultTemplate(http);
@@ -794,7 +1495,6 @@ var Sandbox = class _Sandbox {
794
1495
  if (opts.memMiB !== void 0) body.memMiB = opts.memMiB;
795
1496
  if (opts.diskGiB !== void 0) body.persistentDiskGiB = opts.diskGiB;
796
1497
  if (opts.rootDiskGiB !== void 0) body.rootDiskGiB = opts.rootDiskGiB;
797
- if (opts.onTimeout) body.onTimeout = opts.onTimeout;
798
1498
  if (opts.metadata) body.metadata = opts.metadata;
799
1499
  if (opts.vault === false) body.vault = false;
800
1500
  const op = await createMachine(http, body);
@@ -887,24 +1587,23 @@ var Sandbox = class _Sandbox {
887
1587
  this.machine = await getMachine(this.http, this.sandboxId);
888
1588
  return toInfo(this.machine);
889
1589
  }
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
1590
  /**
900
1591
  * 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.
1592
+ * pause off. The setting stays across pause and resume.
902
1593
  */
903
1594
  async setAutoSuspend(idleMs) {
904
1595
  this.machine = await this.http.request("PATCH", `/v1/machines/${enc2(this.sandboxId)}`, {
905
1596
  body: { autoSuspendAfterSeconds: toIdleSeconds(idleMs) }
906
1597
  });
907
1598
  }
1599
+ /**
1600
+ * @deprecated Removed in 0.6.0: sandboxes have no lifetime timeout since 2026-10-20. Always rejects with
1601
+ * `InstaboxError` (`code: 'retired_option'`) naming the replacements (`setAutoSuspend()`, `kill()`), and
1602
+ * sends no request.
1603
+ */
1604
+ async setTimeout(..._args) {
1605
+ throw timeoutRemoved("setTimeout()", "Use setAutoSuspend(ms) to pause the sandbox once it has been idle that long");
1606
+ }
908
1607
  /** Replaces the sandbox's metadata (`{}` clears it). */
909
1608
  async setMetadata(metadata) {
910
1609
  this.machine = await this.http.request("PATCH", `/v1/machines/${enc2(this.sandboxId)}`, {
@@ -1047,7 +1746,9 @@ async function getUsage(http, id, opts) {
1047
1746
  }
1048
1747
  async function killMachine(http, id) {
1049
1748
  try {
1050
- const op = await http.request("DELETE", `/v1/machines/${enc2(id)}`);
1749
+ const op = await http.request("DELETE", `/v1/machines/${enc2(id)}`, {
1750
+ headers: { "X-Confirm-Delete": id }
1751
+ });
1051
1752
  await http.waitForOperation(op);
1052
1753
  return true;
1053
1754
  } catch (err) {