@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/README.md +29 -29
- package/dist/catalog.d.ts +34 -0
- package/dist/catalog.js +53 -1
- package/dist/cli-terminal.d.ts +15 -0
- package/dist/cli-terminal.js +52 -0
- package/dist/cli.js +33 -2
- package/dist/conformance.d.ts +22 -4
- package/dist/conformance.js +48 -6
- package/dist/gate-scripts.d.ts +28 -0
- package/dist/gate-scripts.js +482 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/leaderboard.d.ts +12 -0
- package/dist/leaderboard.js +10 -0
- package/dist/lifecycle.d.ts +158 -0
- package/dist/lifecycle.js +171 -0
- package/dist/preview.d.ts +104 -0
- package/dist/preview.js +209 -0
- package/dist/providers/blaxel.js +52 -0
- package/dist/providers/daytona.js +38 -0
- package/dist/providers/e2b.d.ts +23 -1
- package/dist/providers/e2b.js +29 -1
- package/dist/providers/modal.js +18 -0
- package/dist/providers/tensorlake.js +11 -0
- package/dist/published.js +48 -216
- package/dist/recommend.d.ts +20 -3
- package/dist/recommend.js +33 -11
- package/dist/router.d.ts +84 -1
- package/dist/router.js +145 -3
- package/dist/spawn.d.ts +116 -0
- package/dist/spawn.js +467 -0
- package/dist/terminal-helper.d.ts +34 -0
- package/dist/terminal-helper.js +429 -0
- package/dist/terminal.d.ts +79 -0
- package/dist/terminal.js +552 -0
- package/dist/types.d.ts +48 -0
- package/dist/util.d.ts +7 -0
- package/dist/util.js +16 -1
- package/package.json +1 -1
package/dist/terminal.js
ADDED
|
@@ -0,0 +1,552 @@
|
|
|
1
|
+
import { RouterError } from "./types.js";
|
|
2
|
+
import { errorStatus, shq, toBytes } from "./util.js";
|
|
3
|
+
import { dirOf, ENCODE, FRESH, ID, NAP, launchCommand, line, stopCommand } from "./spawn.js";
|
|
4
|
+
import { innerScript, outerScript, PTY_METHODS, PTY_PL, PTY_PROBE, PTY_PY, RELAY_MARK, shellScript } from "./terminal-helper.js";
|
|
5
|
+
const DEFAULT_POLL_MS = 50;
|
|
6
|
+
const MIN_POLL_MS = 20;
|
|
7
|
+
const DEFAULT_LOST_AFTER_MS = 60_000;
|
|
8
|
+
const MAX_BACKOFF_MS = 5000;
|
|
9
|
+
const READ_BYTES = 256 * 1024;
|
|
10
|
+
const DEFAULT_REPLAY_BYTES = 64 * 1024;
|
|
11
|
+
/** Input up to this size goes in the command itself, one call. More goes through a file, two calls. */
|
|
12
|
+
const INLINE_BYTES = 2048;
|
|
13
|
+
/** No heartbeat has to be seen for this long, over at least two reads, before the terminal counts as gone. */
|
|
14
|
+
const ORPHAN_CONFIRM_MS = 3000;
|
|
15
|
+
/** How long the provider's terminal has to show the relay is running before `exec` is used for good. */
|
|
16
|
+
const NATIVE_START_MS = 15_000;
|
|
17
|
+
/** How often the native path is checked against the output file, so a connection that went quiet is noticed. */
|
|
18
|
+
const NATIVE_WATCH_MS = 5000;
|
|
19
|
+
/** After this long without input or output, reads that cannot wait in the sandbox are made less often. */
|
|
20
|
+
const BUSY_MS = 2000;
|
|
21
|
+
const QUIET_MS = 10_000;
|
|
22
|
+
const isPython = (m) => m === "python3" || m === "python";
|
|
23
|
+
function check(opts) {
|
|
24
|
+
for (const k of ["cols", "rows"]) {
|
|
25
|
+
const v = opts[k];
|
|
26
|
+
if (v !== undefined && !(Number.isInteger(v) && v >= 1 && v <= 10_000))
|
|
27
|
+
throw new RouterError(`${k} must be a whole number from 1 to 10000`, [], "bad_request");
|
|
28
|
+
}
|
|
29
|
+
for (const k of ["pollMs", "lostAfterMs", "replayBytes"]) {
|
|
30
|
+
const v = opts[k];
|
|
31
|
+
if (v !== undefined && !(Number.isFinite(v) && v >= 0))
|
|
32
|
+
throw new RouterError(`${k} must be a number, 0 or more`, [], "bad_request");
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/** Whether two calls to this sandbox run at the same time. Asked once per sandbox object. */
|
|
36
|
+
const overlapping = new WeakMap();
|
|
37
|
+
function execsOverlap(box) {
|
|
38
|
+
let known = overlapping.get(box);
|
|
39
|
+
if (!known) {
|
|
40
|
+
const one = () => box.exec(NAP("0.4"), { timeoutSeconds: 60 }).then(() => Date.now());
|
|
41
|
+
// One after the other, the second ends a whole wait later than the first.
|
|
42
|
+
known = Promise.all([one(), one()]).then(([a, b]) => Math.abs(a - b) < 300, () => false);
|
|
43
|
+
overlapping.set(box, known);
|
|
44
|
+
}
|
|
45
|
+
return known;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Open a live terminal in the sandbox: a real pseudo-terminal with a shell (or `cmd`) on it, as if
|
|
49
|
+
* sitting at that computer. Prompts, colours, Ctrl-C, full-screen programs and window resizes work.
|
|
50
|
+
*
|
|
51
|
+
* It works on every provider, because it needs only `exec` and `writeFile`: a small program in the
|
|
52
|
+
* sandbox holds the pty (Python 3 where the image has it, else `script`, `socat` or Perl's IO::Pty),
|
|
53
|
+
* writes what the terminal prints to a file and reads what is typed from a named pipe. Output is
|
|
54
|
+
* read by calls that wait in the sandbox until there is something to read, so it arrives one round
|
|
55
|
+
* trip after it is printed. Where the provider has a terminal API of its own, the same bytes travel
|
|
56
|
+
* over that live connection instead, and `exec` takes over again if it drops.
|
|
57
|
+
*/
|
|
58
|
+
export async function openTerminal(box, opts = {}, track) {
|
|
59
|
+
check(opts);
|
|
60
|
+
if (opts.cmd !== undefined && !opts.cmd.trim())
|
|
61
|
+
throw new RouterError("cmd must not be empty", [], "bad_request");
|
|
62
|
+
const cols = opts.cols ?? 80;
|
|
63
|
+
const rows = opts.rows ?? 24;
|
|
64
|
+
const shell = shellScript(opts.cmd, opts);
|
|
65
|
+
let method;
|
|
66
|
+
let stty = true;
|
|
67
|
+
// The pty's owner is the command spawn's launcher runs: it gets the heartbeat, the input pipe and kill() from there.
|
|
68
|
+
const { id } = await launchCommand(box, `exec sh "$D/outer.sh"`, { stdin: true }, {
|
|
69
|
+
probe: PTY_PROBE,
|
|
70
|
+
files: (d, found) => {
|
|
71
|
+
const has = (line(found, "T") ?? "").split(/\s+/);
|
|
72
|
+
const m = PTY_METHODS.find((x) => has.includes(x));
|
|
73
|
+
if (!m) {
|
|
74
|
+
throw new RouterError(`a terminal needs python3, script, socat or perl with IO::Pty in the sandbox, and this image on ${box.provider} has none of them; use spawn or exec there`, [], "unsupported");
|
|
75
|
+
}
|
|
76
|
+
method = m;
|
|
77
|
+
stty = isPython(m) || has.includes("stty");
|
|
78
|
+
return {
|
|
79
|
+
"shell.sh": shell,
|
|
80
|
+
"outer.sh": `D=${shq(d)}\n` + outerScript(d, m, cols, rows),
|
|
81
|
+
method: `${m}${stty ? "" : " nostty"}\n`,
|
|
82
|
+
...(isPython(m) ? { "pty.py": PTY_PY } : { "inner.sh": innerScript(d, cols, rows) }),
|
|
83
|
+
...(m === "perl" ? { "pty.pl": PTY_PL } : {}),
|
|
84
|
+
};
|
|
85
|
+
},
|
|
86
|
+
});
|
|
87
|
+
return session(box, id, method, stty, 0, opts, track);
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Follow a terminal again by its id, from any process that can reach the sandbox: the last
|
|
91
|
+
* `replayBytes` of what it printed come first, then it continues live. Once the terminal has ended
|
|
92
|
+
* this needs it to have been opened with `keep`.
|
|
93
|
+
*/
|
|
94
|
+
export async function attachTerminal(box, id, opts = {}, track) {
|
|
95
|
+
if (!ID.test(id))
|
|
96
|
+
throw new RouterError(`bad terminal id "${id}"`, [], "bad_request");
|
|
97
|
+
check(opts);
|
|
98
|
+
const found = await box.exec(`D=${shq(dirOf(id))}; [ -s "$D/pid" ] && [ -f "$D/method" ] || exit 3; printf 'P:%s\\nS:%s\\n' "$(cat "$D/method")" "$(wc -c < "$D/out" 2> /dev/null | tr -d ' \\n')"`, { timeoutSeconds: 60 });
|
|
99
|
+
const [m, flag] = (line(found.stdout, "P") ?? "").split(/\s+/);
|
|
100
|
+
const method = PTY_METHODS.find((x) => x === m);
|
|
101
|
+
if (found.exitCode !== 0 || !method)
|
|
102
|
+
throw new RouterError(`no terminal ${id} in this sandbox (it may have ended without keep)`, [], "bad_request");
|
|
103
|
+
const size = Number(line(found.stdout, "S")) || 0;
|
|
104
|
+
return session(box, id, method, flag !== "nostty", Math.max(0, size - Math.floor(opts.replayBytes ?? DEFAULT_REPLAY_BYTES)), opts, track);
|
|
105
|
+
}
|
|
106
|
+
/** Splits what the relay sends into the pieces of output it carries. Before its mark, everything is the provider's shell talking and is dropped. */
|
|
107
|
+
function relayParser(onMark, onBytes, onEnd) {
|
|
108
|
+
let buf = Buffer.alloc(0);
|
|
109
|
+
let marked = false;
|
|
110
|
+
let left = 0;
|
|
111
|
+
let done = false;
|
|
112
|
+
return (chunk) => {
|
|
113
|
+
if (done)
|
|
114
|
+
return;
|
|
115
|
+
buf = buf.length ? Buffer.concat([buf, chunk]) : Buffer.from(chunk);
|
|
116
|
+
if (!marked) {
|
|
117
|
+
const i = buf.indexOf(RELAY_MARK);
|
|
118
|
+
if (i < 0) {
|
|
119
|
+
buf = buf.subarray(Math.max(0, buf.length - RELAY_MARK.length + 1));
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
marked = true;
|
|
123
|
+
buf = buf.subarray(i + RELAY_MARK.length);
|
|
124
|
+
onMark();
|
|
125
|
+
}
|
|
126
|
+
for (;;) {
|
|
127
|
+
if (left > 0) {
|
|
128
|
+
const n = Math.min(left, buf.length);
|
|
129
|
+
if (!n)
|
|
130
|
+
return;
|
|
131
|
+
const piece = new Uint8Array(buf.subarray(0, n));
|
|
132
|
+
buf = buf.subarray(n);
|
|
133
|
+
left -= n;
|
|
134
|
+
onBytes(piece);
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
if (buf.length < 4)
|
|
138
|
+
return;
|
|
139
|
+
left = buf.readUInt32BE(0);
|
|
140
|
+
buf = buf.subarray(4);
|
|
141
|
+
// An empty piece is the relay's goodbye. One this large is not something it sends.
|
|
142
|
+
if (left === 0 || left > 1 << 20) {
|
|
143
|
+
done = true;
|
|
144
|
+
return onEnd();
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
function session(box, id, method, stty, from, opts, track) {
|
|
150
|
+
const d = dirOf(id);
|
|
151
|
+
const D = `D=${shq(d)}; `;
|
|
152
|
+
const fast = Math.max(MIN_POLL_MS, opts.pollMs ?? DEFAULT_POLL_MS);
|
|
153
|
+
const lostAfterMs = opts.lostAfterMs ?? DEFAULT_LOST_AFTER_MS;
|
|
154
|
+
/** The next byte of the output to deliver. */
|
|
155
|
+
let offset = from;
|
|
156
|
+
let delivered = 0;
|
|
157
|
+
let lastActive = Date.now();
|
|
158
|
+
let ended = false;
|
|
159
|
+
let settled = false;
|
|
160
|
+
let seq = 0;
|
|
161
|
+
/** Calls to this sandbox overlap, so a read can wait in the sandbox for output while a write goes in. Unknown at first. */
|
|
162
|
+
let hold = false;
|
|
163
|
+
void execsOverlap(box).then((yes) => (hold = yes));
|
|
164
|
+
let resolve;
|
|
165
|
+
let reject;
|
|
166
|
+
const done = new Promise((res, rej) => {
|
|
167
|
+
resolve = res;
|
|
168
|
+
reject = rej;
|
|
169
|
+
});
|
|
170
|
+
// A caller that only streams and never calls wait() must not get an unhandled rejection.
|
|
171
|
+
done.catch(() => { });
|
|
172
|
+
let listening = Boolean(opts.onData);
|
|
173
|
+
let timer;
|
|
174
|
+
let wake;
|
|
175
|
+
const pause = (ms) => new Promise((res) => {
|
|
176
|
+
const finish = () => {
|
|
177
|
+
clearTimeout(timer);
|
|
178
|
+
timer = wake = undefined;
|
|
179
|
+
res();
|
|
180
|
+
};
|
|
181
|
+
timer = setTimeout(finish, ms);
|
|
182
|
+
if (!listening)
|
|
183
|
+
timer.unref?.();
|
|
184
|
+
wake = finish;
|
|
185
|
+
});
|
|
186
|
+
let native;
|
|
187
|
+
const settle = (how) => {
|
|
188
|
+
if (settled)
|
|
189
|
+
return;
|
|
190
|
+
settled = true;
|
|
191
|
+
how();
|
|
192
|
+
native?.end();
|
|
193
|
+
wake?.();
|
|
194
|
+
};
|
|
195
|
+
const fail = (error) => settle(() => reject(error));
|
|
196
|
+
const deliver = (bytes) => {
|
|
197
|
+
if (!bytes.length || settled)
|
|
198
|
+
return;
|
|
199
|
+
offset += bytes.length;
|
|
200
|
+
delivered += bytes.length;
|
|
201
|
+
lastActive = Date.now();
|
|
202
|
+
try {
|
|
203
|
+
opts.onData?.(bytes);
|
|
204
|
+
}
|
|
205
|
+
catch (error) {
|
|
206
|
+
// Not a failed read: reading again would call it with later output.
|
|
207
|
+
fail(error);
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
const decode = (m, text) => {
|
|
211
|
+
if (!text)
|
|
212
|
+
return new Uint8Array(0);
|
|
213
|
+
const hex = m === "xxd" || m === "od";
|
|
214
|
+
// Checked whole, so an answer cut short is read again and never half taken.
|
|
215
|
+
const ok = hex ? text.length % 2 === 0 && /^[0-9a-f]+$/.test(text) : text.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(text);
|
|
216
|
+
if (!ok)
|
|
217
|
+
throw new RouterError(`reading the terminal failed on ${box.provider}: the answer was cut short or garbled`, [], "all_failed");
|
|
218
|
+
return new Uint8Array(Buffer.from(text, hex ? "hex" : "base64"));
|
|
219
|
+
};
|
|
220
|
+
/**
|
|
221
|
+
* One read of the exit code and the output from `offset`. With `waiting`, the call stays in the
|
|
222
|
+
* sandbox until there is output or the terminal has ended, three seconds at most: looking every
|
|
223
|
+
* `fast` ms for the first second, then five times a second.
|
|
224
|
+
*/
|
|
225
|
+
const read = async (waiting) => {
|
|
226
|
+
const size = `$(wc -c < "$D/out" 2> /dev/null | tr -d ' \\n')`;
|
|
227
|
+
const steps = Math.max(1, Math.round(1000 / fast));
|
|
228
|
+
const r = await box.exec(D +
|
|
229
|
+
`[ -d "$D" ] || { printf 'G:\\nZ:\\n'; exit 0; }; o=${offset}; ` +
|
|
230
|
+
(waiting
|
|
231
|
+
? `i=0; while [ $i -lt ${steps + 10} ]; do [ -f "$D/code" ] && break; s=${size}; [ "\${s:-0}" -gt "$o" ] && break; ` +
|
|
232
|
+
`if [ $i -lt ${steps} ]; then ${NAP((fast / 1000).toFixed(3))}; else ${NAP("0.2")}; fi; i=$((i + 1)); done; `
|
|
233
|
+
: "") +
|
|
234
|
+
// The code is read first, so output written before it is never missed.
|
|
235
|
+
`c=$(cat "$D/code" 2> /dev/null); s=${size}; a=dead; ${FRESH} && a=alive; ${ENCODE}; ` +
|
|
236
|
+
`printf 'C:%s\\nA:%s\\nM:%s\\nS:%s\\nO:%s\\nZ:\\n' "$c" "$a" "$m" "$s" "$(tail -c +$((o + 1)) "$D/out" 2> /dev/null | head -c ${READ_BYTES} | e)"`, { timeoutSeconds: 60 });
|
|
237
|
+
// Z is the last line: without it the answer is not whole.
|
|
238
|
+
if (r.exitCode !== 0 || line(r.stdout, "Z") === undefined)
|
|
239
|
+
throw new RouterError(`reading the terminal failed on ${box.provider} (exit ${r.exitCode})`, [], "all_failed");
|
|
240
|
+
if (line(r.stdout, "G") !== undefined)
|
|
241
|
+
return { alive: false, gone: true, out: new Uint8Array(0) };
|
|
242
|
+
const code = line(r.stdout, "C") ?? "";
|
|
243
|
+
const s = line(r.stdout, "S") ?? "";
|
|
244
|
+
const p = {
|
|
245
|
+
...(/^\d+$/.test(code) ? { code: Number(code) } : {}),
|
|
246
|
+
alive: line(r.stdout, "A") === "alive",
|
|
247
|
+
gone: false,
|
|
248
|
+
...(/^\d+$/.test(s) ? { size: Number(s) } : {}),
|
|
249
|
+
out: decode(line(r.stdout, "M"), line(r.stdout, "O") ?? ""),
|
|
250
|
+
};
|
|
251
|
+
// Bytes are waiting and none came: the encoder or the read failed in the sandbox. Not the same as nothing new.
|
|
252
|
+
if (p.size !== undefined && p.size > offset && p.out.length === 0) {
|
|
253
|
+
throw new RouterError(`reading the terminal failed on ${box.provider}: ${p.size - offset} bytes are waiting and none were returned`, [], "all_failed");
|
|
254
|
+
}
|
|
255
|
+
return p;
|
|
256
|
+
};
|
|
257
|
+
const remove = () => box.exec(`rm -rf ${shq(d)}`, { timeoutSeconds: 60 }).then(() => { }, () => { });
|
|
258
|
+
const finish = async (code) => {
|
|
259
|
+
ended = true;
|
|
260
|
+
// Nothing was ever printed and it failed: the pty's owner did not start. What it said is the reason.
|
|
261
|
+
let why = "";
|
|
262
|
+
if (code !== 0 && delivered === 0 && from === 0) {
|
|
263
|
+
why = await box.exec(`tail -c 600 ${shq(`${d}/err`)} 2> /dev/null`, { timeoutSeconds: 60 }).then((r) => r.stdout.trim().replace(/\s+/g, " "), () => "");
|
|
264
|
+
}
|
|
265
|
+
if (!opts.keep)
|
|
266
|
+
await remove();
|
|
267
|
+
if (why)
|
|
268
|
+
return fail(new RouterError(`the terminal could not start on ${box.provider} (${method}, exit ${code}): ${why}`, [], "all_failed"));
|
|
269
|
+
settle(() => resolve({ exitCode: code }));
|
|
270
|
+
};
|
|
271
|
+
const queue = [];
|
|
272
|
+
let working = false;
|
|
273
|
+
const send = async (bytes) => {
|
|
274
|
+
if (ended)
|
|
275
|
+
throw new RouterError("the terminal has ended: nothing reads its input", [], "bad_request");
|
|
276
|
+
if (native?.state === "live" && native.t) {
|
|
277
|
+
try {
|
|
278
|
+
await native.t.write(bytes);
|
|
279
|
+
}
|
|
280
|
+
catch (error) {
|
|
281
|
+
native.end();
|
|
282
|
+
throw new RouterError(`writing to the terminal failed on ${box.provider}: ${error instanceof Error ? error.message : String(error)}`, [], "all_failed");
|
|
283
|
+
}
|
|
284
|
+
lastActive = Date.now();
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
let source;
|
|
288
|
+
let file = "";
|
|
289
|
+
if (bytes.length <= INLINE_BYTES) {
|
|
290
|
+
let oct = "";
|
|
291
|
+
for (const b of bytes)
|
|
292
|
+
oct += "\\" + b.toString(8).padStart(3, "0");
|
|
293
|
+
source = `printf '${oct}'`;
|
|
294
|
+
}
|
|
295
|
+
else {
|
|
296
|
+
file = `${d}/w.${seq++}`;
|
|
297
|
+
await box.writeFile(file, bytes);
|
|
298
|
+
source = `cat ${shq(file)}`;
|
|
299
|
+
}
|
|
300
|
+
// A pipe is written only while the terminal's side is running: with nothing holding it open the write would wait forever.
|
|
301
|
+
const r = await box.exec(D +
|
|
302
|
+
`r=9; if [ ! -f "$D/code" ] && [ -e "$D/in" ]; then if [ -p "$D/in" ]; then ${FRESH} && { ${source} > "$D/in"; r=$?; }; else ${source} >> "$D/in"; r=$?; fi; fi; ` +
|
|
303
|
+
(file ? `rm -f ${shq(file)}; ` : "") +
|
|
304
|
+
`exit $r`, { timeoutSeconds: 60 });
|
|
305
|
+
if (r.exitCode === 9)
|
|
306
|
+
throw new RouterError("the terminal has ended: nothing reads its input", [], "bad_request");
|
|
307
|
+
if (r.exitCode !== 0)
|
|
308
|
+
throw new RouterError(`writing to the terminal failed on ${box.provider} (exit ${r.exitCode})`, [], "all_failed");
|
|
309
|
+
lastActive = Date.now();
|
|
310
|
+
// The echo is on its way: a read that is pausing looks now.
|
|
311
|
+
wake?.();
|
|
312
|
+
};
|
|
313
|
+
const work = async () => {
|
|
314
|
+
if (working)
|
|
315
|
+
return;
|
|
316
|
+
working = true;
|
|
317
|
+
try {
|
|
318
|
+
while (queue.length) {
|
|
319
|
+
const first = queue.shift();
|
|
320
|
+
const batch = [first];
|
|
321
|
+
let what;
|
|
322
|
+
if ("run" in first) {
|
|
323
|
+
what = first.run();
|
|
324
|
+
}
|
|
325
|
+
else {
|
|
326
|
+
// Keys typed while a call was on its way go together in the next one.
|
|
327
|
+
const parts = [first.bytes];
|
|
328
|
+
while (queue.length && "bytes" in queue[0]) {
|
|
329
|
+
const next = queue.shift();
|
|
330
|
+
batch.push(next);
|
|
331
|
+
parts.push(next.bytes);
|
|
332
|
+
}
|
|
333
|
+
what = send(parts.length === 1 ? first.bytes : new Uint8Array(Buffer.concat(parts)));
|
|
334
|
+
}
|
|
335
|
+
await what.then(() => batch.forEach((j) => j.resolve()), (error) => batch.forEach((j) => j.reject(error)));
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
finally {
|
|
339
|
+
working = false;
|
|
340
|
+
}
|
|
341
|
+
};
|
|
342
|
+
const enqueue = (job) => new Promise((res, rej) => {
|
|
343
|
+
queue.push({ ...job, resolve: res, reject: rej });
|
|
344
|
+
void work();
|
|
345
|
+
});
|
|
346
|
+
if (box.terminal && opts.native !== false && isPython(method)) {
|
|
347
|
+
let end;
|
|
348
|
+
const over = new Promise((res) => (end = res));
|
|
349
|
+
const n = {
|
|
350
|
+
state: "starting",
|
|
351
|
+
marked: false,
|
|
352
|
+
over,
|
|
353
|
+
end: () => {
|
|
354
|
+
if (n.state === "over")
|
|
355
|
+
return;
|
|
356
|
+
n.state = "over";
|
|
357
|
+
clearTimeout(limit);
|
|
358
|
+
void n.t?.close().catch(() => { });
|
|
359
|
+
end();
|
|
360
|
+
wake?.();
|
|
361
|
+
},
|
|
362
|
+
};
|
|
363
|
+
native = n;
|
|
364
|
+
const limit = setTimeout(() => n.state === "starting" && n.end(), NATIVE_START_MS);
|
|
365
|
+
limit.unref?.();
|
|
366
|
+
const ready = () => {
|
|
367
|
+
if (n.state !== "starting" || !n.marked || !n.t)
|
|
368
|
+
return;
|
|
369
|
+
n.state = "ready";
|
|
370
|
+
clearTimeout(limit);
|
|
371
|
+
wake?.();
|
|
372
|
+
};
|
|
373
|
+
const parse = relayParser(() => {
|
|
374
|
+
n.marked = true;
|
|
375
|
+
ready();
|
|
376
|
+
}, deliver, n.end);
|
|
377
|
+
const onData = (bytes) => {
|
|
378
|
+
if (n.state !== "over")
|
|
379
|
+
parse(bytes);
|
|
380
|
+
};
|
|
381
|
+
// The relay puts its end of the provider's terminal in raw mode, so the size given here does not matter.
|
|
382
|
+
Promise.resolve()
|
|
383
|
+
.then(() => box.terminal({ cmd: `exec ${method} ${shq(`${d}/pty.py`)} relay ${shq(d)}`, cols: 80, rows: 24, onData, onClose: n.end }))
|
|
384
|
+
.then((t) => {
|
|
385
|
+
n.t = t;
|
|
386
|
+
if (n.state === "over")
|
|
387
|
+
void t.close().catch(() => { });
|
|
388
|
+
else
|
|
389
|
+
ready();
|
|
390
|
+
}, n.end);
|
|
391
|
+
}
|
|
392
|
+
/** Bytes travel over the provider's terminal until it ends or goes quiet. Then the reads below go on from the same byte. */
|
|
393
|
+
const overNative = async (n) => {
|
|
394
|
+
try {
|
|
395
|
+
// After this line the relay sends everything from that byte on, and what is typed goes through it.
|
|
396
|
+
await enqueue({
|
|
397
|
+
run: async () => {
|
|
398
|
+
await n.t.write(new TextEncoder().encode(`${offset}\n`));
|
|
399
|
+
if (n.state === "ready")
|
|
400
|
+
n.state = "live";
|
|
401
|
+
},
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
catch {
|
|
405
|
+
return n.end();
|
|
406
|
+
}
|
|
407
|
+
let behindAt = -1;
|
|
408
|
+
while (!settled && n.state === "live") {
|
|
409
|
+
await Promise.race([n.over, pause(NATIVE_WATCH_MS)]);
|
|
410
|
+
if (settled || n.state !== "live")
|
|
411
|
+
return;
|
|
412
|
+
const r = await box
|
|
413
|
+
.exec(D + `[ -d "$D" ] || { echo S:gone; exit 0; }; printf 'C:%s\\nS:%s\\n' "$(cat "$D/code" 2> /dev/null)" "$(wc -c < "$D/out" 2> /dev/null | tr -d ' \\n')"`, { timeoutSeconds: 60 })
|
|
414
|
+
.catch(() => undefined);
|
|
415
|
+
if (!r || r.exitCode !== 0)
|
|
416
|
+
continue;
|
|
417
|
+
const s = line(r.stdout, "S") ?? "";
|
|
418
|
+
const behind = s === "gone" || Boolean(line(r.stdout, "C")) || Number(s) > offset;
|
|
419
|
+
// Twice in a row with nothing delivered in between: the connection is not carrying the output.
|
|
420
|
+
if (behind && behindAt === offset)
|
|
421
|
+
return n.end();
|
|
422
|
+
behindAt = behind ? offset : -1;
|
|
423
|
+
}
|
|
424
|
+
};
|
|
425
|
+
void (async () => {
|
|
426
|
+
let failures = 0;
|
|
427
|
+
let failingSince;
|
|
428
|
+
let goneAnswers = 0;
|
|
429
|
+
let deadSince;
|
|
430
|
+
let deadReads = 0;
|
|
431
|
+
while (!settled) {
|
|
432
|
+
if (native?.state === "ready") {
|
|
433
|
+
await overNative(native);
|
|
434
|
+
continue;
|
|
435
|
+
}
|
|
436
|
+
// While the native path is still being set up nothing waits in the sandbox, so it can take over at once.
|
|
437
|
+
const waiting = hold && native?.state !== "starting";
|
|
438
|
+
const asked = Date.now();
|
|
439
|
+
let p;
|
|
440
|
+
try {
|
|
441
|
+
p = await read(waiting);
|
|
442
|
+
failures = goneAnswers = 0;
|
|
443
|
+
failingSince = undefined;
|
|
444
|
+
}
|
|
445
|
+
catch (error) {
|
|
446
|
+
if (settled)
|
|
447
|
+
return;
|
|
448
|
+
const why = error instanceof Error ? error.message : String(error);
|
|
449
|
+
// The provider says there is no such sandbox. Believed the second time in a row.
|
|
450
|
+
const status = errorStatus(error);
|
|
451
|
+
goneAnswers = status === 404 || status === 410 ? goneAnswers + 1 : 0;
|
|
452
|
+
if (goneAnswers >= 2)
|
|
453
|
+
return fail(new RouterError(`the sandbox is gone on ${box.provider}, and terminal ${id} with it (${why})`, [], "all_failed"));
|
|
454
|
+
const now = Date.now();
|
|
455
|
+
failingSince ??= now;
|
|
456
|
+
const left = failingSince + lostAfterMs - now;
|
|
457
|
+
if (left <= 0) {
|
|
458
|
+
return fail(new RouterError(`lost the connection to terminal ${id} on ${box.provider}: reading it has failed for ${Math.round((now - failingSince) / 1000)} s (last error: ${why}). ` +
|
|
459
|
+
`The terminal was not closed: attachTerminal("${id}") follows it again`, [], "all_failed"));
|
|
460
|
+
}
|
|
461
|
+
await pause(Math.min(fast * 2 ** failures++, MAX_BACKOFF_MS, left));
|
|
462
|
+
continue;
|
|
463
|
+
}
|
|
464
|
+
// detach() or sbx.kill() came while this read was on its way: it is dropped whole.
|
|
465
|
+
if (settled)
|
|
466
|
+
return;
|
|
467
|
+
if (p.gone) {
|
|
468
|
+
ended = true;
|
|
469
|
+
return fail(new RouterError(`terminal ${id} has no files in the sandbox on ${box.provider} any more: another wait() without keep removed them, or the sandbox was reset`, [], "bad_request"));
|
|
470
|
+
}
|
|
471
|
+
deliver(p.out);
|
|
472
|
+
if (settled)
|
|
473
|
+
return;
|
|
474
|
+
if (p.code !== undefined && (p.size !== undefined ? offset >= p.size : p.out.length === 0))
|
|
475
|
+
return finish(p.code);
|
|
476
|
+
// No exit code and no heartbeat: the terminal's side was stopped from outside. Seen over several reads and seconds.
|
|
477
|
+
if (p.code === undefined && !p.alive && p.out.length === 0) {
|
|
478
|
+
deadSince ??= Date.now();
|
|
479
|
+
if (++deadReads >= 2 && Date.now() - deadSince >= ORPHAN_CONFIRM_MS) {
|
|
480
|
+
ended = true;
|
|
481
|
+
if (!opts.keep)
|
|
482
|
+
await remove();
|
|
483
|
+
return fail(new RouterError(`the terminal stopped without an exit code on ${box.provider}: nothing of it has run for 10 s. Some providers stop what a call left running when the call returns`, [], "unsupported"));
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
else {
|
|
487
|
+
deadSince = undefined;
|
|
488
|
+
deadReads = 0;
|
|
489
|
+
}
|
|
490
|
+
// More waiting to be read: no pause.
|
|
491
|
+
if (p.out.length > 0)
|
|
492
|
+
continue;
|
|
493
|
+
// A read that waited in the sandbox was the pause. Others look often while the terminal is in use, and less when it is quiet.
|
|
494
|
+
const quiet = Date.now() - lastActive;
|
|
495
|
+
const gap = native?.state === "starting" || quiet < BUSY_MS ? fast : quiet < QUIET_MS ? Math.max(fast, 250) : Math.max(fast, 1000);
|
|
496
|
+
if (!waiting)
|
|
497
|
+
await pause(gap);
|
|
498
|
+
else if (Date.now() - asked < fast)
|
|
499
|
+
await pause(fast);
|
|
500
|
+
}
|
|
501
|
+
})().catch(fail);
|
|
502
|
+
track?.({ stop: fail, settled: done.then(() => { }, () => { }) });
|
|
503
|
+
return {
|
|
504
|
+
id,
|
|
505
|
+
pty: method,
|
|
506
|
+
get path() {
|
|
507
|
+
return native?.state === "live" ? "native" : "exec";
|
|
508
|
+
},
|
|
509
|
+
wait() {
|
|
510
|
+
listening = true;
|
|
511
|
+
timer?.ref?.();
|
|
512
|
+
return done;
|
|
513
|
+
},
|
|
514
|
+
detach() {
|
|
515
|
+
fail(new RouterError(`detached from terminal ${id} on ${box.provider}: it was left open, and attachTerminal("${id}") follows it again`, [], "bad_request"));
|
|
516
|
+
},
|
|
517
|
+
write(data) {
|
|
518
|
+
// Copied: the caller may reuse its buffer before this is sent.
|
|
519
|
+
const bytes = typeof data === "string" ? toBytes(data) : new Uint8Array(data);
|
|
520
|
+
if (!bytes.length)
|
|
521
|
+
return Promise.resolve();
|
|
522
|
+
return enqueue({ bytes });
|
|
523
|
+
},
|
|
524
|
+
async resize(cols, rows) {
|
|
525
|
+
check({ cols, rows });
|
|
526
|
+
return enqueue({
|
|
527
|
+
run: async () => {
|
|
528
|
+
if (ended)
|
|
529
|
+
throw new RouterError("the terminal has ended", [], "bad_request");
|
|
530
|
+
if (!stty)
|
|
531
|
+
throw new RouterError(`resize needs stty in the sandbox, and this image on ${box.provider} does not have it`, [], "unsupported");
|
|
532
|
+
const r = await box.exec(D +
|
|
533
|
+
`[ -d "$D" ] && [ ! -f "$D/code" ] || exit 9; ` +
|
|
534
|
+
(isPython(method)
|
|
535
|
+
? // The pty's owner reads this before it passes on anything typed after it.
|
|
536
|
+
`printf 'r %s %s\\n' ${cols} ${rows} >> "$D/ctl"`
|
|
537
|
+
: // No owner of ours to ask: the size is set on the pty itself, by name.
|
|
538
|
+
`t=$(cat "$D/tty" 2> /dev/null); [ -n "$t" ] && stty rows ${rows} cols ${cols} < "$t"`), { timeoutSeconds: 60 });
|
|
539
|
+
if (r.exitCode === 9)
|
|
540
|
+
throw new RouterError("the terminal has ended", [], "bad_request");
|
|
541
|
+
if (r.exitCode !== 0)
|
|
542
|
+
throw new RouterError(`resizing the terminal failed on ${box.provider} (exit ${r.exitCode}): ${r.stderr.trim().split("\n").pop() ?? ""}`, [], "all_failed");
|
|
543
|
+
},
|
|
544
|
+
});
|
|
545
|
+
},
|
|
546
|
+
async kill() {
|
|
547
|
+
if (ended)
|
|
548
|
+
return;
|
|
549
|
+
await stopCommand(box, id);
|
|
550
|
+
},
|
|
551
|
+
};
|
|
552
|
+
}
|
package/dist/types.d.ts
CHANGED
|
@@ -20,6 +20,13 @@ export interface SandboxSpec {
|
|
|
20
20
|
ports?: number[];
|
|
21
21
|
/** Hard lifetime in minutes (default 30). */
|
|
22
22
|
timeoutMinutes?: number;
|
|
23
|
+
/**
|
|
24
|
+
* Ask for the sandbox's port URLs to answer without the provider's own credentials, where that is
|
|
25
|
+
* a setting. E2B: a project can require its traffic access token on every sandbox URL, and this
|
|
26
|
+
* opens them for this one sandbox. Elsewhere it changes nothing. It never narrows routing: a
|
|
27
|
+
* provider's URLs are as public as that provider makes them (see `url`).
|
|
28
|
+
*/
|
|
29
|
+
publicPorts?: boolean;
|
|
23
30
|
/**
|
|
24
31
|
* How long you expect to use the sandbox, in seconds. Only a ranking hint: the sandbox still lives
|
|
25
32
|
* until you kill it or `timeoutMinutes` runs out. Without it, ranking assumes the whole lifetime.
|
|
@@ -116,6 +123,24 @@ export interface ProviderProcess {
|
|
|
116
123
|
export interface SandboxProcess extends ProviderProcess {
|
|
117
124
|
readonly id: string;
|
|
118
125
|
}
|
|
126
|
+
/** What the router asks of a provider's own terminal API: run one command on a terminal and carry its bytes. */
|
|
127
|
+
export interface ProviderTerminalOptions {
|
|
128
|
+
/** A shell command line. Where the API always starts a shell, it is typed into that shell. */
|
|
129
|
+
cmd: string;
|
|
130
|
+
cols: number;
|
|
131
|
+
rows: number;
|
|
132
|
+
/** Called with what the terminal prints, raw and in order. */
|
|
133
|
+
onData(bytes: Uint8Array): void;
|
|
134
|
+
/** Called once the terminal has ended or its connection is lost. */
|
|
135
|
+
onClose(): void;
|
|
136
|
+
}
|
|
137
|
+
/** A provider's terminal, open. */
|
|
138
|
+
export interface ProviderTerminal {
|
|
139
|
+
/** Type these bytes into the terminal. */
|
|
140
|
+
write(data: Uint8Array): Promise<void>;
|
|
141
|
+
/** Close the connection and stop what runs on the terminal. */
|
|
142
|
+
close(): Promise<void>;
|
|
143
|
+
}
|
|
119
144
|
/** A live sandbox as one provider sees it. Adapters implement this. */
|
|
120
145
|
export interface ProviderSandbox {
|
|
121
146
|
readonly nativeId: string;
|
|
@@ -134,6 +159,29 @@ export interface ProviderSandbox {
|
|
|
134
159
|
url?(port: number): string | Promise<string>;
|
|
135
160
|
/** Present on adapters with the "background" capability. */
|
|
136
161
|
start?(cmd: string, opts?: StartOptions): Promise<ProviderProcess>;
|
|
162
|
+
/**
|
|
163
|
+
* Present on adapters whose provider has a terminal (PTY) API of its own. `sbx.terminal()` uses it
|
|
164
|
+
* as a faster way to carry the terminal's bytes, and works without it.
|
|
165
|
+
*/
|
|
166
|
+
terminal?(opts: ProviderTerminalOptions): Promise<ProviderTerminal>;
|
|
167
|
+
/**
|
|
168
|
+
* Present where the provider itself issues a link to a port that only its holder can open, that
|
|
169
|
+
* stops working at the expiry, and that works when clicked (the secret is in the URL, not a header).
|
|
170
|
+
*/
|
|
171
|
+
privateUrl?(port: number, expiresInSeconds: number): Promise<{
|
|
172
|
+
url: string;
|
|
173
|
+
expiresAt: Date;
|
|
174
|
+
/** "interface": the provider connects to the sandbox's network interface, so an app listening on 127.0.0.1 only is not reached. */
|
|
175
|
+
reaches?: "interface";
|
|
176
|
+
revoke(): Promise<void>;
|
|
177
|
+
}>;
|
|
178
|
+
/**
|
|
179
|
+
* Present where the provider can be told, after create, to end the sandbox by itself: `seconds`
|
|
180
|
+
* from now, with no client alive. Returns when it will end (providers round to their own steps).
|
|
181
|
+
*/
|
|
182
|
+
endAfter?(seconds: number): Promise<{
|
|
183
|
+
endsAt: Date;
|
|
184
|
+
}>;
|
|
137
185
|
}
|
|
138
186
|
export interface Provider {
|
|
139
187
|
readonly id: ProviderId;
|
package/dist/util.d.ts
CHANGED
|
@@ -34,6 +34,13 @@ export declare function killedByTimeout(exitCode: number, elapsedMs: number, sec
|
|
|
34
34
|
export declare function guardTimeout(cmd: string, seconds: number): string;
|
|
35
35
|
export declare function toBytes(content: string | Uint8Array): Uint8Array;
|
|
36
36
|
export declare function dirname(path: string): string;
|
|
37
|
+
/**
|
|
38
|
+
* Hand the router a provider's package that you imported yourself, e.g.
|
|
39
|
+
* `provideModule("e2b", await import("e2b"))`. Adapters use it and never look the package up by name.
|
|
40
|
+
* For programs built into one file (`bun build --compile`, esbuild, a serverless bundle), where a
|
|
41
|
+
* package named only at run time is not in the file. Pass `undefined` to take it back.
|
|
42
|
+
*/
|
|
43
|
+
export declare function provideModule(pkg: string, module: unknown): void;
|
|
37
44
|
/** Load an optional peer dependency with a helpful error. */
|
|
38
45
|
export declare function optionalImport<T>(pkg: string, provider: string): Promise<T>;
|
|
39
46
|
/**
|
package/dist/util.js
CHANGED
|
@@ -70,8 +70,23 @@ export function dirname(path) {
|
|
|
70
70
|
const i = path.lastIndexOf("/");
|
|
71
71
|
return i <= 0 ? "/" : path.slice(0, i);
|
|
72
72
|
}
|
|
73
|
+
const provided = new Map();
|
|
74
|
+
/**
|
|
75
|
+
* Hand the router a provider's package that you imported yourself, e.g.
|
|
76
|
+
* `provideModule("e2b", await import("e2b"))`. Adapters use it and never look the package up by name.
|
|
77
|
+
* For programs built into one file (`bun build --compile`, esbuild, a serverless bundle), where a
|
|
78
|
+
* package named only at run time is not in the file. Pass `undefined` to take it back.
|
|
79
|
+
*/
|
|
80
|
+
export function provideModule(pkg, module) {
|
|
81
|
+
if (module === undefined)
|
|
82
|
+
provided.delete(pkg);
|
|
83
|
+
else
|
|
84
|
+
provided.set(pkg, module);
|
|
85
|
+
}
|
|
73
86
|
/** Load an optional peer dependency with a helpful error. */
|
|
74
87
|
export async function optionalImport(pkg, provider) {
|
|
88
|
+
if (provided.has(pkg))
|
|
89
|
+
return provided.get(pkg);
|
|
75
90
|
try {
|
|
76
91
|
return (await import(pkg));
|
|
77
92
|
}
|
|
@@ -80,7 +95,7 @@ export async function optionalImport(pkg, provider) {
|
|
|
80
95
|
// Bundlers and test runners (Vite, esbuild) report a missing package without Node's error code.
|
|
81
96
|
const missing = /Cannot find (module|package)|Could not resolve|Failed to (resolve|load url)/.test(String(err?.message));
|
|
82
97
|
if (code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND" || missing) {
|
|
83
|
-
throw new SetupError(`${provider} needs the "${pkg}" package: npm i ${pkg}`);
|
|
98
|
+
throw new SetupError(`${provider} needs the "${pkg}" package: npm i ${pkg} (in a bundled program, import it yourself and pass it to provideModule)`);
|
|
84
99
|
}
|
|
85
100
|
throw err;
|
|
86
101
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sandboxrouter/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.21.1",
|
|
4
4
|
"description": "One API for every sandbox provider: route AI agents' code by price, speed or capability, with automatic fallback. Free and open source.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|