@sandboxrouter/sdk 0.20.1 → 0.21.1

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/recommend.js CHANGED
@@ -12,6 +12,18 @@ const LOAD_JOB = {
12
12
  assistant: "start",
13
13
  browser: "start",
14
14
  };
15
+ const sizeLabel = (s) => `${s.vcpu} vCPU / ${s.memoryGb} GB`;
16
+ /** The sandbox size most rows were measured at: the only size a ranking compares. Ties go to the larger size. */
17
+ export function comparisonSize(sizes) {
18
+ const seen = new Map();
19
+ for (const s of sizes) {
20
+ if (!s)
21
+ continue;
22
+ const k = `${s.vcpu}x${s.memoryGb}`;
23
+ seen.set(k, { size: s, n: (seen.get(k)?.n ?? 0) + 1 });
24
+ }
25
+ return [...seen.values()].sort((a, b) => b.n - a.n || b.size.vcpu - a.size.vcpu || b.size.memoryGb - a.size.memoryGb)[0]?.size;
26
+ }
15
27
  const mid = (xs) => {
16
28
  const s = [...xs].sort((a, b) => a - b);
17
29
  const m = Math.floor(s.length / 2);
@@ -21,8 +33,12 @@ const mid = (xs) => {
21
33
  * Rank providers for a job from the published benchmarks. Costs and times are per successful job: each is
22
34
  * divided by the provider's success rate, so one that fails often pays for it. For `count` of 10 or more, the
23
35
  * start time is the one measured with that many asked for at once (the largest measured size not above
24
- * `count`); providers not yet measured at that size are listed after the ones that were, since the limit that
25
- * stopped them was the benchmarking account's, not theirs.
36
+ * `count`); providers not tested at that size are listed after the ones that were. A batch that an account
37
+ * limit stopped short is not in the published data at all, so it is never read as the provider failing.
38
+ *
39
+ * Only providers measured at the same sandbox size are ranked against each other: that size is the one most of
40
+ * them ran at (`comparisonSize`). A provider measured at another size is listed after them with `otherSize` and a
41
+ * note, and its numbers stay out of the medians.
26
42
  */
27
43
  export function recommend(data, opts = {}) {
28
44
  const job = opts.job ?? "short";
@@ -51,8 +67,6 @@ export function recommend(data, opts = {}) {
51
67
  notes.push(`bills at least ${j.minimumSeconds} s per sandbox`);
52
68
  if (!reuse && j.perSandboxUsd)
53
69
  notes.push(`$${j.perSandboxUsd} per sandbox started`);
54
- if (j.limited)
55
- notes.push(`${j.limited} reported limit refusals`);
56
70
  if (j.note)
57
71
  notes.push(j.note);
58
72
  raw.push({
@@ -70,8 +84,13 @@ export function recommend(data, opts = {}) {
70
84
  });
71
85
  }
72
86
  }
87
+ const cohort = comparisonSize(raw.map((r) => r.size));
73
88
  const mostRuns = Math.max(1, ...raw.map((r) => r.runs));
74
89
  for (const r of raw) {
90
+ if (cohort && r.size && (r.size.vcpu !== cohort.vcpu || r.size.memoryGb !== cohort.memoryGb)) {
91
+ r.otherSize = true;
92
+ r.notes.push(`measured at ${sizeLabel(r.size)}, not ${sizeLabel(cohort)}: listed after the others, not ranked against them`);
93
+ }
75
94
  const fee = data.conditionalStartFees?.[r.provider];
76
95
  if (!reuse && fee)
77
96
  r.notes.push(`excludes ${fee.minUsd === fee.maxUsd ? `$${fee.minUsd}` : `$${fee.minUsd}–$${fee.maxUsd}`} per start ${fee.when ?? "above allowance"}`);
@@ -90,25 +109,28 @@ export function recommend(data, opts = {}) {
90
109
  r.secondsEach = (job === "start" ? 0 : startS) + l.p50Ms / 1000;
91
110
  }
92
111
  else if (l) {
93
- r.notes.push(`${l.ok} of ${l.n} completed${l.limited ? ` (${l.limited} reported limit refusals)` : ""}`);
112
+ r.notes.push(`${l.ok} of ${l.n} started when asked for at once`);
94
113
  }
95
114
  else {
96
- r.notes.push(`not measured at ${load.n} at once yet`);
115
+ r.notes.push(`not tested at ${load.n} at once`);
97
116
  }
98
117
  }
99
118
  const ok = (r) => Math.max(r.successRate, 0.01);
100
- const midCost = mid(raw.map((r) => r.usdKey / ok(r)));
101
- const midTime = mid(raw.map((r) => r.secondsEach / ok(r)));
119
+ const sameSize = raw.filter((r) => !r.otherSize);
120
+ const midCost = mid(sameSize.map((r) => r.usdKey / ok(r)));
121
+ const midTime = mid(sameSize.map((r) => r.secondsEach / ok(r)));
102
122
  const scored = raw.map((r) => ({ ...r, valueScore: (r.usdKey / ok(r) / midCost) * (r.secondsEach / ok(r) / midTime) }));
103
123
  const key = (r) => priority === "cost" ? r.usdKey / ok(r) : priority === "speed" ? r.secondsEach / ok(r) : r.valueScore;
104
124
  const atScale = (r) => (load && r.measuredAtOnce === undefined ? 1 : 0);
105
- scored.sort((a, b) => atScale(a) - atScale(b) || key(a) - key(b) || a.provider.localeCompare(b.provider));
125
+ const offSize = (r) => (r.otherSize ? 1 : 0);
126
+ scored.sort((a, b) => offSize(a) - offSize(b) || atScale(a) - atScale(b) || key(a) - key(b) || a.provider.localeCompare(b.provider));
106
127
  const results = scored.slice(0, opts.limit ?? scored.length).map(({ usdKey: _, ...r }, i) => ({ ...r, rank: i + 1, valueScore: Math.round(r.valueScore * 100) / 100 }));
107
128
  const what = job === "start" ? "starting a sandbox" : `the ${job} job${reuse ? " in a running sandbox" : " in a new sandbox"}`;
108
129
  const by = priority === "cost" ? "lowest cost" : priority === "speed" ? "shortest time" : "best value (cost times time, each against the median)";
109
130
  const basis = !results.length ? `No current verified results for ${what}.` :
110
131
  `Ranked by ${by} for ${what} with a success-rate adjustment` +
111
- (load ? `, with readiness measured on batches of ${load.n}; providers that did not finish the batch are listed after` : "") +
112
- (job === "start" && !paired ? ". Single-request timings use the create response; the first command is measured separately" : "") + ".";
132
+ (load ? `, with readiness measured on batches of ${load.n}; providers not tested at that size, or that did not finish the batch, are listed after` : "") +
133
+ (job === "start" && !paired ? ". Single-request timings use the create response; the first command is measured separately" : "") +
134
+ (cohort && results.some((r) => r.otherSize) ? `. Compared at ${sizeLabel(cohort)}; providers measured at another size are listed after, not ranked against the rest` : "") + ".";
113
135
  return { job, count, priority, reuse, basis, dataThrough: data.dataThrough, results };
114
136
  }
package/dist/router.d.ts CHANGED
@@ -2,7 +2,11 @@ import { type ProviderInfo } from "./catalog.js";
2
2
  import { type ComputerRoute, RoutedComputer, type ComputerOs, type ComputerProvider, type ComputerProviderId, type ComputerSpec } from "./computers.js";
3
3
  import { Ledger } from "./ledger.js";
4
4
  import { type CopyOptions, type CopyResult, type FileBox, type MoveOptions } from "./move.js";
5
+ import { type AttachOptions, type Spawned, type SpawnOptions } from "./spawn.js";
6
+ import { type Terminal, type TerminalAttachOptions, type TerminalOptions } from "./terminal.js";
5
7
  import { type Keeper, type KeepOptions, type RecoverOptions, type RestoreOptions, type RestoreResult, type Saved, type SaveOptions, type SaveStore } from "./save.js";
8
+ import { type Lingering, type LingerOptions, type ResumeOptions, type Resumed, type Suspended, type SuspendOptions } from "./lifecycle.js";
9
+ import { type PreviewLink, type PreviewOptions } from "./preview.js";
6
10
  import { type Attempt, type ExecOptions, type ExecResult, type Provider, type ProviderId, type ProviderSandbox, type RouteOptions, type SandboxProcess, type SandboxSpec, type StartOptions } from "./types.js";
7
11
  /** vCPUs and memory a sandbox gets. */
8
12
  export interface Size {
@@ -269,6 +273,17 @@ export declare class Router {
269
273
  }>;
270
274
  /** Reattach to a sandbox by its routed id (`provider:nativeId`). */
271
275
  get(id: string): Promise<RoutedSandbox>;
276
+ /**
277
+ * Bring back a sandbox from the handle `sbx.suspend()` returned. A "paused" handle wakes the same
278
+ * sandbox. A "saved" one needs `store`: a new sandbox is started, on the provider it was on when
279
+ * that provider can take it and on another otherwise, and the saved folder is put back.
280
+ *
281
+ * const handle = await sbx.suspend({ store }); // JSON: keep it anywhere
282
+ * sbx = await router.resume(handle, { store });
283
+ */
284
+ resume(handle: Suspended, opts?: ResumeOptions): Promise<RoutedSandbox & {
285
+ resumed: Resumed;
286
+ }>;
272
287
  }
273
288
  /** What a sandbox costs and its size, as the router priced it when it was created. */
274
289
  export interface SandboxPrice {
@@ -292,9 +307,18 @@ export declare class RoutedSandbox {
292
307
  readonly listHourlyUsd?: number;
293
308
  /** The size it was created at (see `Candidate.size`). */
294
309
  readonly size?: Size;
310
+ /** The spec it was created with. Undefined for a handle from `get()`. */
311
+ readonly spec?: SandboxSpec;
312
+ /** When the lifetime given at create runs out (ISO), when this machine knows it. */
313
+ private readonly createEndsAt?;
314
+ /** Provider-issued preview links made through this object, so `linger` and `revokePreviews` can end them. */
315
+ private links;
295
316
  constructor(provider: ProviderId, box: ProviderSandbox,
296
317
  /** Every create attempt, including failed fallbacks. */
297
- attempts: Attempt[], price?: SandboxPrice, ledger?: Ledger | undefined);
318
+ attempts: Attempt[], price?: SandboxPrice, ledger?: Ledger | undefined, origin?: {
319
+ spec?: SandboxSpec;
320
+ endsAt?: string;
321
+ });
298
322
  get nativeId(): string;
299
323
  /**
300
324
  * The provider SDK's own sandbox object for provider-specific features such as snapshots. Narrow it
@@ -311,8 +335,67 @@ export declare class RoutedSandbox {
311
335
  exec(cmd: string, opts?: ExecOptions): Promise<ExecResult>;
312
336
  /** Get the provider's HTTP preview URL for a service listening on this port. */
313
337
  url(port: number): Promise<string>;
338
+ /**
339
+ * A link to the app on `port` that only its holder can open and that stops working after
340
+ * `expiresInSeconds` (default one hour). `url(port)` is unchanged: the provider's plain URL.
341
+ * Where the provider issues private, expiring links itself that is used (`via: "native"`);
342
+ * elsewhere a small proxy is started in the sandbox in front of the app (`via: "gate"`), which
343
+ * needs node or python3 in the image. Bind the app to 127.0.0.1: see `previewLink`.
344
+ *
345
+ * const link = await sbx.previewUrl(3000, { expiresInSeconds: 900 });
346
+ * console.log(link.url, link.expiresAt, link.warnings);
347
+ * await link.revoke();
348
+ */
349
+ previewUrl(port: number, opts?: PreviewOptions): Promise<PreviewLink>;
350
+ /** Stop every preview link of this sandbox now: all gates in it, and the provider-issued links made through this object. */
351
+ revokePreviews(): Promise<void>;
352
+ /**
353
+ * Keep the sandbox `seconds` more, then have it end by itself, with no client alive: for a preview
354
+ * link that should outlive the run by a few minutes. The result says when it will really end and
355
+ * who ends it (`enforcedBy`): the provider, a command inside the sandbox, the lifetime given at
356
+ * create, or nobody. Preview links stop at the same time unless `previews: "keep"`.
357
+ * The sandbox stays in the local ledger until it is killed or `gc` finds it gone.
358
+ */
359
+ linger(seconds: number, opts?: LingerOptions): Promise<Lingering>;
360
+ /**
361
+ * Put the sandbox to sleep keeping its work, so a later run picks it up with `router.resume(handle)`.
362
+ * With a native pause (`canPause`) the provider keeps the sandbox: `kind: "paused"`. Without one the
363
+ * working folder is saved to `opts.store` and the sandbox is killed: `kind: "saved"`, which keeps
364
+ * that folder only (no processes, no memory, nothing installed outside it). `pause()` is unchanged.
365
+ */
366
+ suspend(opts?: SuspendOptions): Promise<Suspended>;
314
367
  /** Start a command and return a handle that stops it without stopping the sandbox. */
315
368
  start(cmd: string, opts?: StartOptions): Promise<SandboxProcess>;
369
+ /**
370
+ * Start a command and stay in touch with it: output arrives while it runs (`onStdout`), `write()`
371
+ * sends bytes to its standard input (with `stdin: true`), `kill()` stops it without stopping the
372
+ * sandbox, and `wait()` gives the result. Works on every provider. See `SpawnOptions`.
373
+ *
374
+ * const cmd = await sbx.spawn("python agent.py", { stdin: true, onStdout: (s) => process.stdout.write(s) });
375
+ * await cmd.write("first task\n");
376
+ * const { exitCode } = await cmd.wait();
377
+ *
378
+ * `kill()` on the sandbox stops following its commands: their `wait()` rejects.
379
+ */
380
+ spawn(cmd: string, opts?: SpawnOptions): Promise<Spawned>;
381
+ /** Follow a spawned command again by its id: its output is replayed from the start, then continues. */
382
+ attach(id: string, opts?: AttachOptions): Promise<Spawned>;
383
+ /**
384
+ * Open a live terminal in the sandbox, as if sitting at that computer: a real pseudo-terminal with
385
+ * the user's shell (or `cmd`) on it. Works on every provider. See `TerminalOptions`.
386
+ *
387
+ * const term = await sbx.terminal({ cols: 120, rows: 30, onData: (bytes) => process.stdout.write(bytes) });
388
+ * await term.write("ls -la\n");
389
+ * await term.resize(100, 40);
390
+ */
391
+ terminal(opts?: TerminalOptions): Promise<Terminal>;
392
+ /** Follow a terminal again by its id: its recent output is replayed, then it continues live. */
393
+ attachTerminal(id: string, opts?: TerminalAttachOptions): Promise<Terminal>;
394
+ private termBox?;
395
+ private terminalBox;
396
+ /** Spawned commands still being read, so `kill()` can stop reading them. */
397
+ private following;
398
+ private follow;
316
399
  writeFile(path: string, content: string | Uint8Array): Promise<void>;
317
400
  readFile(path: string): Promise<Uint8Array>;
318
401
  readText(path: string): Promise<string>;
package/dist/router.js CHANGED
@@ -6,7 +6,11 @@ import { PUBLISHED } from "./published.js";
6
6
  import { Ledger, defaultLedgerFile } from "./ledger.js";
7
7
  import { DEFAULT_EXEC_TIMEOUT_S, LIMIT_ERROR, SETUP_ERRORS, errorStatus, timeoutError, withDeadline } from "./util.js";
8
8
  import { copyFiles, moveSandbox } from "./move.js";
9
+ import { attachCommand, spawnCommand } from "./spawn.js";
10
+ import { attachTerminal, openTerminal } from "./terminal.js";
9
11
  import { keepSaved, recoverSandbox, restoreFiles, saveFiles } from "./save.js";
12
+ import { lingerSandbox, resumeSandbox, suspendSandbox } from "./lifecycle.js";
13
+ import { previewLink, revokeGates } from "./preview.js";
10
14
  import { BILLED_VS_LIST } from "./billing.js";
11
15
  import { FAILING, VERIFIED } from "./verified.js";
12
16
  import { isPort, validate, validateStart } from "./validate.js";
@@ -381,7 +385,7 @@ export class Router {
381
385
  attempts.push({ provider: c.provider, ok: true, ms: Date.now() - t0 });
382
386
  this.observe(c.provider, Date.now() - t0);
383
387
  this.noteSuccess(c.provider);
384
- const sbx = new RoutedSandbox(c.provider, box, attempts, price, this.ledger);
388
+ const sbx = new RoutedSandbox(c.provider, box, attempts, price, this.ledger, { spec, endsAt: new Date(Date.now() + (spec.timeoutMinutes ?? 30) * 60_000).toISOString() });
385
389
  this.record(sbx, price, spec.timeoutMinutes);
386
390
  return sbx;
387
391
  }
@@ -529,7 +533,18 @@ export class Router {
529
533
  // they're unknown (a guess at the default size would be wrong for anything bigger).
530
534
  const e = this.ledger?.list().find((x) => x.id === id);
531
535
  const price = e && e.listUsdHour !== undefined && e.size ? { estimatedHourlyUsd: e.usdHour, listHourlyUsd: e.listUsdHour, size: e.size } : undefined;
532
- return new RoutedSandbox(provider, box, [], price, this.ledger);
536
+ return new RoutedSandbox(provider, box, [], price, this.ledger, { endsAt: e?.expiresAt });
537
+ }
538
+ /**
539
+ * Bring back a sandbox from the handle `sbx.suspend()` returned. A "paused" handle wakes the same
540
+ * sandbox. A "saved" one needs `store`: a new sandbox is started, on the provider it was on when
541
+ * that provider can take it and on another otherwise, and the saved folder is put back.
542
+ *
543
+ * const handle = await sbx.suspend({ store }); // JSON: keep it anywhere
544
+ * sbx = await router.resume(handle, { store });
545
+ */
546
+ resume(handle, opts = {}) {
547
+ return resumeSandbox({ candidates: async (spec, route) => this.plan(spec, route), create: (spec, route) => this.create(spec, route), get: (id) => this.get(id) }, handle, opts);
533
548
  }
534
549
  }
535
550
  export class RoutedSandbox {
@@ -545,13 +560,21 @@ export class RoutedSandbox {
545
560
  listHourlyUsd;
546
561
  /** The size it was created at (see `Candidate.size`). */
547
562
  size;
563
+ /** The spec it was created with. Undefined for a handle from `get()`. */
564
+ spec;
565
+ /** When the lifetime given at create runs out (ISO), when this machine knows it. */
566
+ createEndsAt;
567
+ /** Provider-issued preview links made through this object, so `linger` and `revokePreviews` can end them. */
568
+ links = [];
548
569
  constructor(provider, box,
549
570
  /** Every create attempt, including failed fallbacks. */
550
- attempts, price, ledger) {
571
+ attempts, price, ledger, origin = {}) {
551
572
  this.provider = provider;
552
573
  this.box = box;
553
574
  this.attempts = attempts;
554
575
  this.ledger = ledger;
576
+ this.spec = origin.spec;
577
+ this.createEndsAt = origin.endsAt;
555
578
  this.id = `${provider}:${box.nativeId}`;
556
579
  this.estimatedHourlyUsd = price?.estimatedHourlyUsd;
557
580
  this.listHourlyUsd = price?.listHourlyUsd;
@@ -590,6 +613,73 @@ export class RoutedSandbox {
590
613
  }
591
614
  return preview;
592
615
  }
616
+ /**
617
+ * A link to the app on `port` that only its holder can open and that stops working after
618
+ * `expiresInSeconds` (default one hour). `url(port)` is unchanged: the provider's plain URL.
619
+ * Where the provider issues private, expiring links itself that is used (`via: "native"`);
620
+ * elsewhere a small proxy is started in the sandbox in front of the app (`via: "gate"`), which
621
+ * needs node or python3 in the image. Bind the app to 127.0.0.1: see `previewLink`.
622
+ *
623
+ * const link = await sbx.previewUrl(3000, { expiresInSeconds: 900 });
624
+ * console.log(link.url, link.expiresAt, link.warnings);
625
+ * await link.revoke();
626
+ */
627
+ async previewUrl(port, opts = {}) {
628
+ const box = this.box;
629
+ const link = await previewLink({
630
+ provider: this.provider,
631
+ exec: (cmd, o) => this.exec(cmd, o),
632
+ writeFile: (path, content) => this.writeFile(path, content),
633
+ spawn: (cmd, o) => this.spawn(cmd, o),
634
+ ...(box.url ? { url: (p) => this.url(p) } : {}),
635
+ ...(box.privateUrl ? { privateUrl: (p, s) => box.privateUrl(p, s) } : {}),
636
+ ports: this.spec?.ports,
637
+ }, port, opts);
638
+ if (link.via === "native") {
639
+ const issued = { expiresAt: new Date(link.expiresAt), revoke: () => link.revoke() };
640
+ this.links.push(issued);
641
+ const revoke = link.revoke;
642
+ link.revoke = async () => {
643
+ this.links = this.links.filter((l) => l !== issued);
644
+ await revoke();
645
+ };
646
+ }
647
+ return link;
648
+ }
649
+ /** Stop every preview link of this sandbox now: all gates in it, and the provider-issued links made through this object. */
650
+ async revokePreviews() {
651
+ const links = this.links;
652
+ this.links = [];
653
+ await Promise.all([revokeGates(this), ...links.map((l) => l.revoke())]);
654
+ }
655
+ /**
656
+ * Keep the sandbox `seconds` more, then have it end by itself, with no client alive: for a preview
657
+ * link that should outlive the run by a few minutes. The result says when it will really end and
658
+ * who ends it (`enforcedBy`): the provider, a command inside the sandbox, the lifetime given at
659
+ * create, or nobody. Preview links stop at the same time unless `previews: "keep"`.
660
+ * The sandbox stays in the local ledger until it is killed or `gc` finds it gone.
661
+ */
662
+ linger(seconds, opts = {}) {
663
+ const box = this.box;
664
+ return lingerSandbox({
665
+ provider: this.provider,
666
+ exec: (cmd, o) => this.exec(cmd, o),
667
+ spawn: (cmd, o) => this.spawn(cmd, o),
668
+ ...(box.endAfter ? { endAfter: (s) => box.endAfter(s) } : {}),
669
+ createEndsAt: this.createEndsAt,
670
+ links: this.links,
671
+ }, seconds, opts);
672
+ }
673
+ /**
674
+ * Put the sandbox to sleep keeping its work, so a later run picks it up with `router.resume(handle)`.
675
+ * With a native pause (`canPause`) the provider keeps the sandbox: `kind: "paused"`. Without one the
676
+ * working folder is saved to `opts.store` and the sandbox is killed: `kind: "saved"`, which keeps
677
+ * that folder only (no processes, no memory, nothing installed outside it). `pause()` is unchanged.
678
+ */
679
+ async suspend(opts = {}) {
680
+ const handle = await suspendSandbox(this, opts);
681
+ return handle;
682
+ }
593
683
  /** Start a command and return a handle that stops it without stopping the sandbox. */
594
684
  async start(cmd, opts = {}) {
595
685
  validateStart(cmd, opts);
@@ -612,6 +702,54 @@ export class RoutedSandbox {
612
702
  }),
613
703
  };
614
704
  }
705
+ /**
706
+ * Start a command and stay in touch with it: output arrives while it runs (`onStdout`), `write()`
707
+ * sends bytes to its standard input (with `stdin: true`), `kill()` stops it without stopping the
708
+ * sandbox, and `wait()` gives the result. Works on every provider. See `SpawnOptions`.
709
+ *
710
+ * const cmd = await sbx.spawn("python agent.py", { stdin: true, onStdout: (s) => process.stdout.write(s) });
711
+ * await cmd.write("first task\n");
712
+ * const { exitCode } = await cmd.wait();
713
+ *
714
+ * `kill()` on the sandbox stops following its commands: their `wait()` rejects.
715
+ */
716
+ spawn(cmd, opts = {}) {
717
+ return spawnCommand(this, cmd, opts, this.follow);
718
+ }
719
+ /** Follow a spawned command again by its id: its output is replayed from the start, then continues. */
720
+ attach(id, opts = {}) {
721
+ return attachCommand(this, id, opts, this.follow);
722
+ }
723
+ /**
724
+ * Open a live terminal in the sandbox, as if sitting at that computer: a real pseudo-terminal with
725
+ * the user's shell (or `cmd`) on it. Works on every provider. See `TerminalOptions`.
726
+ *
727
+ * const term = await sbx.terminal({ cols: 120, rows: 30, onData: (bytes) => process.stdout.write(bytes) });
728
+ * await term.write("ls -la\n");
729
+ * await term.resize(100, 40);
730
+ */
731
+ terminal(opts = {}) {
732
+ return openTerminal(this.terminalBox(), opts, this.follow);
733
+ }
734
+ /** Follow a terminal again by its id: its recent output is replayed, then it continues live. */
735
+ attachTerminal(id, opts = {}) {
736
+ return attachTerminal(this.terminalBox(), id, opts, this.follow);
737
+ }
738
+ termBox;
739
+ terminalBox() {
740
+ return (this.termBox ??= {
741
+ provider: this.provider,
742
+ exec: (cmd, opts) => this.exec(cmd, opts),
743
+ writeFile: (path, content) => this.writeFile(path, content),
744
+ ...(this.box.terminal ? { terminal: (opts) => this.box.terminal(opts) } : {}),
745
+ });
746
+ }
747
+ /** Spawned commands still being read, so `kill()` can stop reading them. */
748
+ following = new Set();
749
+ follow = (f) => {
750
+ this.following.add(f);
751
+ void f.settled.then(() => this.following.delete(f));
752
+ };
615
753
  writeFile(path, content) {
616
754
  return this.box.writeFile(path, content);
617
755
  }
@@ -622,6 +760,10 @@ export class RoutedSandbox {
622
760
  return new TextDecoder().decode(await this.box.readFile(path));
623
761
  }
624
762
  async kill() {
763
+ // Nothing reads a command in a sandbox that is going away.
764
+ for (const f of [...this.following]) {
765
+ f.stop(new RouterError(`sandbox ${this.id} was killed with kill(), and its commands with it`, [], "bad_request"));
766
+ }
625
767
  await this.box.kill();
626
768
  this.ledger?.close(this.id);
627
769
  }
@@ -0,0 +1,116 @@
1
+ import { type ExecOptions, type ExecResult } from "./types.js";
2
+ /** What spawn needs from a sandbox: a `RoutedSandbox` and a `RemoteSandbox` both fit. */
3
+ export interface SpawnBox {
4
+ readonly provider: string;
5
+ exec(cmd: string, opts?: ExecOptions): Promise<ExecResult>;
6
+ writeFile(path: string, content: string | Uint8Array): Promise<void>;
7
+ }
8
+ export interface SpawnOptions {
9
+ cwd?: string;
10
+ env?: Record<string, string>;
11
+ /**
12
+ * Keep standard input open, so `write()` reaches the command and `end()` closes it. Without it
13
+ * the command reads from /dev/null.
14
+ */
15
+ stdin?: boolean;
16
+ /**
17
+ * Called with each piece of stdout as it is read. Pieces arrive in order, about every `pollMs`.
18
+ * If it throws, `wait()` rejects with what it threw and the command is no longer followed.
19
+ */
20
+ onStdout?: (chunk: string) => void;
21
+ onStderr?: (chunk: string) => void;
22
+ /** How often the output is read, in ms (default 500, at least 50). */
23
+ pollMs?: number;
24
+ /**
25
+ * How long reads may keep failing before `wait()` gives up, in ms (default 60 000). Failed reads
26
+ * are retried with a growing pause; after this long without one good read `wait()` rejects, saying
27
+ * the connection was lost. The command is not touched: `attach(id)` follows it again.
28
+ */
29
+ lostAfterMs?: number;
30
+ /**
31
+ * Leave the command's files in the sandbox after it ends, so `attach(id)` can replay it later,
32
+ * from another process too. Default: removed once `wait()` has the result.
33
+ */
34
+ keep?: boolean;
35
+ }
36
+ export type AttachOptions = Pick<SpawnOptions, "onStdout" | "onStderr" | "pollMs" | "lostAfterMs" | "keep">;
37
+ /** A command running in a sandbox, started with `spawn`. */
38
+ export interface Spawned {
39
+ /** Names the command inside its sandbox. Pass it to `attach` to follow the command again. */
40
+ readonly id: string;
41
+ /**
42
+ * Resolves when the command has ended and all of its output has been read. Rejects when the
43
+ * command can no longer be followed: its process disappeared, the connection was lost for
44
+ * `lostAfterMs`, the sandbox is gone or was killed, or `detach()` was called.
45
+ */
46
+ wait(): Promise<ExecResult>;
47
+ /** Send bytes to the command's standard input. Needs `stdin: true`. Writes arrive in the order made. */
48
+ write(data: string | Uint8Array): Promise<void>;
49
+ /** Close standard input: the command reads end-of-file. */
50
+ end(): Promise<void>;
51
+ /** Stop the command and what it started: SIGTERM, then SIGKILL two seconds later. The sandbox keeps running. */
52
+ kill(): Promise<void>;
53
+ /**
54
+ * Stop reading the command's output and leave it running. `wait()` rejects, and nothing of this
55
+ * handle keeps the process alive. `attach(id)` follows the command again; `kill()` still stops it.
56
+ */
57
+ detach(): void;
58
+ }
59
+ /** How a sandbox object stops following its commands when it is killed. Not part of the public API. */
60
+ export interface Following {
61
+ /** Stop reading; `wait()` rejects with `error`. The command is not touched. */
62
+ stop(error: Error): void;
63
+ /** Resolves once `wait()` has settled either way. */
64
+ settled: Promise<void>;
65
+ }
66
+ /** Ways to carry bytes as text, in order of preference. The first one the sandbox has is used. */
67
+ export declare const ENCODERS: readonly ["base64", "openssl", "xxd", "od"];
68
+ export declare const ID: RegExp;
69
+ export declare const dirOf: (id: string) => string;
70
+ /** A pause that works where sleep takes whole seconds only. */
71
+ export declare const NAP: (s: string) => string;
72
+ /**
73
+ * True when the heartbeat in $D is fresh by the sandbox's clock. No pid is looked at: a later exec may
74
+ * not see the command's processes. A heartbeat that is not a number (a date without %s) cannot be judged and counts as fresh.
75
+ */
76
+ export declare const FRESH = "{ b=$(cat \"$D/beat\" 2> /dev/null); n=$(date +%s); case \"$b\" in '') false;; *[!0-9]*) true;; *) [ $((n - b)) -le 10 ];; esac; }";
77
+ /** Sets $m to the encoder to use and defines e, which encodes stdin on one line. */
78
+ export declare const ENCODE: string;
79
+ export declare const line: (text: string, key: string) => string | undefined;
80
+ /**
81
+ * Start a command and stay in touch with it: its output arrives while it runs, bytes can be written
82
+ * to its standard input, and it can be stopped without stopping the sandbox. `exec` is the simpler
83
+ * call for a command that just runs to its end.
84
+ *
85
+ * It works on every provider because it uses only `exec` and `writeFile`: the command runs detached
86
+ * in the sandbox with its output going to files, input coming from a named pipe, and this process
87
+ * reading the files on an interval. So output is delivered in pieces about every `pollMs`, not byte
88
+ * by byte. The sandbox needs `sh` and the usual file tools (checked first: a missing one is named in
89
+ * the error). `base64` and `mkfifo` are used where present, with `openssl`, `xxd` or `od` and a
90
+ * plain file standing in for them.
91
+ */
92
+ export declare function spawnCommand(box: SpawnBox, cmd: string, opts?: SpawnOptions, track?: (f: Following) => void): Promise<Spawned>;
93
+ /** What `launchCommand` takes beside the command. Not part of the public API: `terminal` starts its helper with it. */
94
+ export interface LaunchExtra {
95
+ /** Shell added to the first call, which looks at the sandbox's tools. What it prints is given to `files`. */
96
+ probe?: string;
97
+ /** More files for the command's folder, by name. It may throw to refuse the sandbox: nothing is left behind. */
98
+ files?: (d: string, found: string) => Record<string, string>;
99
+ }
100
+ /** Start a command the way `spawn` does, without reading it: its files are in `dirOf(id)`. */
101
+ export declare function launchCommand(box: SpawnBox, cmd: string, opts: Pick<SpawnOptions, "cwd" | "env" | "stdin">, extra?: LaunchExtra): Promise<{
102
+ id: string;
103
+ }>;
104
+ /**
105
+ * Stop a command and what it started. Asked for with a file: the command's side signals the command
106
+ * (SIGTERM, SIGKILL two seconds later) and everything it started, and this waits for the exit code.
107
+ * Only when that side does not answer is the command signalled from here, which needs this call to
108
+ * see its processes.
109
+ */
110
+ export declare function stopCommand(box: SpawnBox, id: string): Promise<void>;
111
+ /**
112
+ * Follow a command started with `spawn` again, by its id: its output is replayed from the start,
113
+ * then continues. From another process this needs the command to have been started with `keep`
114
+ * once it has ended. `write` and `end` work when it was started with `stdin`.
115
+ */
116
+ export declare function attachCommand(box: SpawnBox, id: string, opts?: AttachOptions, track?: (f: Following) => void): Promise<Spawned>;