@sandboxrouter/sdk 0.20.1 → 0.21.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/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 +26 -0
- 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 +41 -0
- package/dist/util.d.ts +7 -0
- package/dist/util.js +16 -1
- package/package.json +1 -1
package/dist/spawn.js
ADDED
|
@@ -0,0 +1,467 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { RouterError } from "./types.js";
|
|
3
|
+
import { errorStatus, shq } from "./util.js";
|
|
4
|
+
const DEFAULT_POLL_MS = 500;
|
|
5
|
+
const MIN_POLL_MS = 50;
|
|
6
|
+
const DEFAULT_LOST_AFTER_MS = 60_000;
|
|
7
|
+
/** The longest pause between two reads while reads are failing. */
|
|
8
|
+
const MAX_BACKOFF_MS = 5000;
|
|
9
|
+
/** Bytes of each stream read per poll. More is read on the next one. */
|
|
10
|
+
const READ_BYTES = 256 * 1024;
|
|
11
|
+
/** The command's side writes the sandbox's time to a file every second. Older than this, by the sandbox's own clock, and it is not running. */
|
|
12
|
+
const STALE_S = 10;
|
|
13
|
+
/** No heartbeat has to be seen for this long, over at least two reads, before the command counts as gone. */
|
|
14
|
+
const ORPHAN_CONFIRM_MS = 3000;
|
|
15
|
+
/** Tools the sandbox must have. Each of these is in every coreutils and busybox. */
|
|
16
|
+
const TOOLS = ["cat", "date", "head", "mkdir", "mv", "rm", "sleep", "tail", "tr", "wc"];
|
|
17
|
+
/** Ways to carry bytes as text, in order of preference. The first one the sandbox has is used. */
|
|
18
|
+
export const ENCODERS = ["base64", "openssl", "xxd", "od"];
|
|
19
|
+
export const ID = /^[a-z0-9]{6,32}$/;
|
|
20
|
+
export const dirOf = (id) => `/tmp/sr-run-${id}`;
|
|
21
|
+
/** A pause that works where sleep takes whole seconds only. */
|
|
22
|
+
export const NAP = (s) => `{ sleep ${s} 2> /dev/null || sleep 1; }`;
|
|
23
|
+
/**
|
|
24
|
+
* True when the heartbeat in $D is fresh by the sandbox's clock. No pid is looked at: a later exec may
|
|
25
|
+
* not see the command's processes. A heartbeat that is not a number (a date without %s) cannot be judged and counts as fresh.
|
|
26
|
+
*/
|
|
27
|
+
export const FRESH = `{ b=$(cat "$D/beat" 2> /dev/null); n=$(date +%s); case "$b" in '') false;; *[!0-9]*) true;; *) [ $((n - b)) -le ${STALE_S} ];; esac; }`;
|
|
28
|
+
/** Sets $m to the encoder to use and defines e, which encodes stdin on one line. */
|
|
29
|
+
export const ENCODE = `m=; for t in ${ENCODERS.join(" ")}; do command -v $t > /dev/null 2>&1 && { m=$t; break; }; done; ` +
|
|
30
|
+
`e() { case $m in base64) base64 | tr -d '\\n';; openssl) openssl base64 | tr -d '\\n';; xxd) xxd -p | tr -d '\\n';; od) od -An -v -tx1 | tr -d ' \\n';; esac; }`;
|
|
31
|
+
async function sh(box, what, cmd, timeoutSeconds = 60) {
|
|
32
|
+
const r = await box.exec(cmd, { timeoutSeconds });
|
|
33
|
+
if (r.exitCode !== 0) {
|
|
34
|
+
const detail = (r.stderr || r.stdout).trim().split("\n").slice(-3).join(" ");
|
|
35
|
+
throw new RouterError(`${what} failed on ${box.provider} (exit ${r.exitCode})${detail ? `: ${detail}` : ""}`, [], "all_failed");
|
|
36
|
+
}
|
|
37
|
+
return r.stdout;
|
|
38
|
+
}
|
|
39
|
+
export const line = (text, key) => new RegExp(`^${key}:(.*)$`, "m").exec(text)?.[1]?.trim();
|
|
40
|
+
function checkTiming(opts) {
|
|
41
|
+
for (const k of ["pollMs", "lostAfterMs"]) {
|
|
42
|
+
const v = opts[k];
|
|
43
|
+
if (v !== undefined && !(Number.isFinite(v) && v >= 0))
|
|
44
|
+
throw new RouterError(`${k} must be a number of milliseconds, 0 or more`, [], "bad_request");
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The script that runs the command inside the sandbox and outlives it to record the exit code.
|
|
49
|
+
* Next to the command it runs a supervisor, which is the only thing that ever signals the command
|
|
50
|
+
* or holds its input open, so nothing depends on a later exec seeing the command's processes:
|
|
51
|
+
* - it writes the sandbox's time to `beat` every second (how `wait()` knows the command is running),
|
|
52
|
+
* - it holds the input pipe open, and closes it when `eof` appears (`end()`),
|
|
53
|
+
* - it stops the command when `kill` appears (`kill()`),
|
|
54
|
+
* - it stops the command when this script or the command's folder disappears, so nothing is left behind.
|
|
55
|
+
* It ends with the command, so no process outlives it.
|
|
56
|
+
*/
|
|
57
|
+
function launcherScript(d, input) {
|
|
58
|
+
const run = {
|
|
59
|
+
none: `$G sh "$D/cmd.sh" < /dev/null > "$D/out" 2> "$D/err" &`,
|
|
60
|
+
// Opening the pipe waits for a writer: the supervisor, below.
|
|
61
|
+
fifo: `$G sh "$D/cmd.sh" < "$D/in" > "$D/out" 2> "$D/err" &`,
|
|
62
|
+
// No named pipes here: input is appended to a plain file, and feed copies what is new into the command.
|
|
63
|
+
file: `feed | $G sh "$D/cmd.sh" > "$D/out" 2> "$D/err" &`,
|
|
64
|
+
}[input];
|
|
65
|
+
return [
|
|
66
|
+
"#!/bin/sh",
|
|
67
|
+
`D=${shq(d)}`,
|
|
68
|
+
// Inherited by the command: it does not end when the call that started it does.
|
|
69
|
+
"trap '' HUP",
|
|
70
|
+
`echo $$ > "$D/run"`,
|
|
71
|
+
`date +%s > "$D/beat"`,
|
|
72
|
+
`nap() ${NAP("0.2")}`,
|
|
73
|
+
// The command gets its own process group where the image has setsid, so stopping it reaches everything it started.
|
|
74
|
+
"G=; command -v setsid > /dev/null 2>&1 && G=setsid",
|
|
75
|
+
"C=",
|
|
76
|
+
"sig() {",
|
|
77
|
+
` if [ -n "$G" ]; then kill "-$1" "-$P" 2> /dev/null; return 0; fi`,
|
|
78
|
+
// Without a group: the command and its children, listed before the first signal, while they are still its children.
|
|
79
|
+
` [ -z "$C" ] && command -v pgrep > /dev/null 2>&1 && C=$(pgrep -P "$P")`,
|
|
80
|
+
` kill "-$1" "$P" $C 2> /dev/null`,
|
|
81
|
+
" return 0",
|
|
82
|
+
"}",
|
|
83
|
+
`alive() { if [ -n "$G" ]; then kill -0 "-$P"; else kill -0 "$P"; fi 2> /dev/null; }`,
|
|
84
|
+
"stop() {",
|
|
85
|
+
" sig TERM",
|
|
86
|
+
` i=0; while alive && [ $i -lt 20 ]; do ${NAP("0.1")}; i=$((i + 1)); done`,
|
|
87
|
+
" alive && sig KILL",
|
|
88
|
+
" return 0",
|
|
89
|
+
"}",
|
|
90
|
+
// The command has not been started yet, or is still there. Once it is gone nothing reads what feed copies.
|
|
91
|
+
`running() { [ -s "$D/pid" ] || return 0; read -r q < "$D/pid" && kill -0 "$q" 2> /dev/null; }`,
|
|
92
|
+
"feed() {",
|
|
93
|
+
" o=0",
|
|
94
|
+
// It ends with the command: the shell waits for both sides of the pipe before it records the exit code.
|
|
95
|
+
` while kill -0 $$ 2> /dev/null && [ -d "$D" ] && [ ! -f "$D/code" ] && running; do`,
|
|
96
|
+
// Looked at before the size: when end() was called, everything written is already in the file.
|
|
97
|
+
` last=; [ -f "$D/eof" ] && last=1`,
|
|
98
|
+
` s=$(wc -c < "$D/in" 2> /dev/null | tr -d ' \\n'); s=\${s:-0}`,
|
|
99
|
+
` if [ "$s" -gt "$o" ]; then tail -c "+$((o + 1))" "$D/in" | head -c "$((s - o))"; o=$s; fi`,
|
|
100
|
+
` [ -n "$last" ] && break`,
|
|
101
|
+
" nap",
|
|
102
|
+
" done",
|
|
103
|
+
"}",
|
|
104
|
+
run,
|
|
105
|
+
"P=$!",
|
|
106
|
+
`[ -n "$G" ] && echo g > "$D/group"`,
|
|
107
|
+
"(",
|
|
108
|
+
// Open for reading too, so this never waits and a write never waits for a reader. Closing it is the pipe's end-of-file.
|
|
109
|
+
...(input === "fifo" ? [` exec 3<> "$D/in"`] : []),
|
|
110
|
+
" n=0",
|
|
111
|
+
` while kill -0 $$ 2> /dev/null && [ -d "$D" ] && [ ! -f "$D/code" ]; do`,
|
|
112
|
+
` [ $((n % 5)) -eq 0 ] && { date +%s > "$D/beat.tmp" && mv "$D/beat.tmp" "$D/beat"; } 2> /dev/null`,
|
|
113
|
+
" n=$((n + 1))",
|
|
114
|
+
...(input === "fifo" ? [` if [ -f "$D/eof" ] && [ ! -f "$D/eof.ack" ]; then exec 3>&-; : > "$D/eof.ack"; fi`] : []),
|
|
115
|
+
` if [ -f "$D/kill" ] && [ ! -f "$D/kill.ack" ]; then : > "$D/kill.ack"; stop; fi`,
|
|
116
|
+
" nap 3>&-",
|
|
117
|
+
" done",
|
|
118
|
+
// This script or the folder is gone, so nothing would record the end: the command is stopped, not left behind.
|
|
119
|
+
` [ -f "$D/code" ] || stop`,
|
|
120
|
+
") &",
|
|
121
|
+
"S=$!",
|
|
122
|
+
`echo $S > "$D/sup"`,
|
|
123
|
+
// The pid file is the sign the command was started.
|
|
124
|
+
`echo $P > "$D/pid.tmp" && mv "$D/pid.tmp" "$D/pid"`,
|
|
125
|
+
`wait "$P"`,
|
|
126
|
+
"c=$?",
|
|
127
|
+
`echo $c > "$D/code.tmp" && mv "$D/code.tmp" "$D/code"`,
|
|
128
|
+
// The supervisor sees the code and ends, having finished a stop it was in the middle of.
|
|
129
|
+
`wait "$S" 2> /dev/null`,
|
|
130
|
+
"exit 0",
|
|
131
|
+
].join("\n") + "\n";
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Start a command and stay in touch with it: its output arrives while it runs, bytes can be written
|
|
135
|
+
* to its standard input, and it can be stopped without stopping the sandbox. `exec` is the simpler
|
|
136
|
+
* call for a command that just runs to its end.
|
|
137
|
+
*
|
|
138
|
+
* It works on every provider because it uses only `exec` and `writeFile`: the command runs detached
|
|
139
|
+
* in the sandbox with its output going to files, input coming from a named pipe, and this process
|
|
140
|
+
* reading the files on an interval. So output is delivered in pieces about every `pollMs`, not byte
|
|
141
|
+
* by byte. The sandbox needs `sh` and the usual file tools (checked first: a missing one is named in
|
|
142
|
+
* the error). `base64` and `mkfifo` are used where present, with `openssl`, `xxd` or `od` and a
|
|
143
|
+
* plain file standing in for them.
|
|
144
|
+
*/
|
|
145
|
+
export async function spawnCommand(box, cmd, opts = {}, track) {
|
|
146
|
+
checkTiming(opts);
|
|
147
|
+
const { id } = await launchCommand(box, cmd, opts);
|
|
148
|
+
return follow(box, id, opts, opts.stdin === true, track);
|
|
149
|
+
}
|
|
150
|
+
/** Start a command the way `spawn` does, without reading it: its files are in `dirOf(id)`. */
|
|
151
|
+
export async function launchCommand(box, cmd, opts, extra = {}) {
|
|
152
|
+
const lines = [
|
|
153
|
+
...Object.entries(opts.env ?? {}).map(([k, v]) => {
|
|
154
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k))
|
|
155
|
+
throw new RouterError(`bad env name "${k}"`, [], "bad_request");
|
|
156
|
+
return `export ${k}=${shq(v)}`;
|
|
157
|
+
}),
|
|
158
|
+
...(opts.cwd ? [`cd ${shq(opts.cwd)} || exit 127`] : []),
|
|
159
|
+
cmd,
|
|
160
|
+
];
|
|
161
|
+
const id = randomUUID().replace(/-/g, "").slice(0, 12);
|
|
162
|
+
const d = dirOf(id);
|
|
163
|
+
// One call: which tools are there, and the folder if they all are.
|
|
164
|
+
const found = await sh(box, "preparing the command", `D=${shq(d)}; x=; for t in ${TOOLS.join(" ")}; do command -v $t > /dev/null 2>&1 || x="$x $t"; done; ${ENCODE}; ` +
|
|
165
|
+
`printf 'X:%s\\nM:%s\\n' "$x" "$m"; { [ -n "$x" ] || [ -z "$m" ]; } && exit 0; ` +
|
|
166
|
+
`mkdir -p "$D" && : > "$D/out" && : > "$D/err" || exit 1; ` +
|
|
167
|
+
(opts.stdin
|
|
168
|
+
? // A named pipe where the image and the disk have them, a plain file where not.
|
|
169
|
+
`if command -v mkfifo > /dev/null 2>&1 && mkfifo "$D/in" 2> /dev/null && [ -p "$D/in" ]; then echo I:fifo; else rm -f "$D/in"; : > "$D/in" && echo I:file; fi`
|
|
170
|
+
: "echo I:none") +
|
|
171
|
+
(extra.probe ? `; ${extra.probe}` : ""));
|
|
172
|
+
const missing = (line(found, "X") ?? "").split(/\s+/).filter(Boolean);
|
|
173
|
+
if (!line(found, "M"))
|
|
174
|
+
missing.push(`one of ${ENCODERS.join(", ")}`);
|
|
175
|
+
if (missing.length) {
|
|
176
|
+
throw new RouterError(`spawn needs ${missing.join(" and ")} in the sandbox, and this image on ${box.provider} does not have ${missing.length > 1 ? "them" : "it"}; use exec there`, [], "unsupported");
|
|
177
|
+
}
|
|
178
|
+
const input = line(found, "I");
|
|
179
|
+
try {
|
|
180
|
+
if (input !== "none" && input !== "fifo" && input !== "file")
|
|
181
|
+
throw new RouterError(`preparing the command failed on ${box.provider}: unexpected answer`, [], "all_failed");
|
|
182
|
+
const files = { ...extra.files?.(d, found), "cmd.sh": lines.join("\n") + "\n", "run.sh": launcherScript(d, input) };
|
|
183
|
+
await Promise.all(Object.entries(files).map(([name, text]) => box.writeFile(`${d}/${name}`, text)));
|
|
184
|
+
// Detached from this exec in every way a shell allows, so it keeps running after the call returns.
|
|
185
|
+
await sh(box, "starting the command",
|
|
186
|
+
// Run by sh itself: the provider's own shell may be zsh, which does not split "$p" into words.
|
|
187
|
+
`D=${shq(d)}; export D; sh -c 'p=; command -v setsid > /dev/null 2>&1 && p=setsid; command -v nohup > /dev/null 2>&1 && p="$p nohup"; ` +
|
|
188
|
+
`$p sh "$D/run.sh" > /dev/null 2>&1 < /dev/null &'; ` +
|
|
189
|
+
`i=0; while [ ! -s "$D/pid" ] && [ $i -lt 100 ]; do ${NAP("0.05")}; i=$((i+1)); done; [ -s "$D/pid" ]`);
|
|
190
|
+
}
|
|
191
|
+
catch (error) {
|
|
192
|
+
// Nothing is left behind: a launcher that did start stops the command when its folder goes.
|
|
193
|
+
await box.exec(`rm -rf ${shq(d)}`, { timeoutSeconds: 60 }).catch(() => { });
|
|
194
|
+
throw error;
|
|
195
|
+
}
|
|
196
|
+
return { id };
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Stop a command and what it started. Asked for with a file: the command's side signals the command
|
|
200
|
+
* (SIGTERM, SIGKILL two seconds later) and everything it started, and this waits for the exit code.
|
|
201
|
+
* Only when that side does not answer is the command signalled from here, which needs this call to
|
|
202
|
+
* see its processes.
|
|
203
|
+
*/
|
|
204
|
+
export async function stopCommand(box, id) {
|
|
205
|
+
// No "--" before a group: dash's kill does not take it, and with the signal named first a negative pid is a group in every sh.
|
|
206
|
+
const direct = (s) => `p=$(cat "$D/pid" 2> /dev/null); [ -n "$p" ] && { if [ -f "$D/group" ]; then kill -${s} "-$p"; else c=$(command -v pgrep > /dev/null 2>&1 && pgrep -P "$p"); kill -${s} "$p" $c; fi; } 2> /dev/null`;
|
|
207
|
+
// The folder going is an end too: a wait() that already has the result removes it.
|
|
208
|
+
const until = (n) => `i=0; while [ -d "$D" ] && [ ! -f "$D/code" ] && [ $i -lt ${n} ]; do ${NAP("0.1")}; i=$((i+1)); done`;
|
|
209
|
+
await box
|
|
210
|
+
.exec(`D=${shq(dirOf(id))}; [ -d "$D" ] || exit 0; [ -f "$D/code" ] && exit 0; : > "$D/kill"; ` +
|
|
211
|
+
`i=0; while [ ! -f "$D/code" ] && [ ! -f "$D/kill.ack" ] && [ $i -lt 15 ]; do ${NAP("0.1")}; i=$((i+1)); done; ` +
|
|
212
|
+
`if [ -f "$D/kill.ack" ]; then ${until(40)}; else ${direct("TERM")}; ${until(20)}; [ -f "$D/code" ] || [ ! -d "$D" ] || { ${direct("KILL")}; }; fi; exit 0`, { timeoutSeconds: 60 })
|
|
213
|
+
.catch(() => { });
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Follow a command started with `spawn` again, by its id: its output is replayed from the start,
|
|
217
|
+
* then continues. From another process this needs the command to have been started with `keep`
|
|
218
|
+
* once it has ended. `write` and `end` work when it was started with `stdin`.
|
|
219
|
+
*/
|
|
220
|
+
export async function attachCommand(box, id, opts = {}, track) {
|
|
221
|
+
if (!ID.test(id))
|
|
222
|
+
throw new RouterError(`bad command id "${id}"`, [], "bad_request");
|
|
223
|
+
checkTiming(opts);
|
|
224
|
+
const found = await box.exec(`[ -s ${shq(`${dirOf(id)}/pid`)} ] && { [ -e ${shq(`${dirOf(id)}/in`)} ] && echo stdin || echo plain; }`, { timeoutSeconds: 60 });
|
|
225
|
+
if (found.exitCode !== 0)
|
|
226
|
+
throw new RouterError(`no command ${id} in this sandbox (it may have ended without keep)`, [], "bad_request");
|
|
227
|
+
return follow(box, id, opts, found.stdout.includes("stdin"), track);
|
|
228
|
+
}
|
|
229
|
+
function follow(box, id, opts, stdin, track) {
|
|
230
|
+
const d = dirOf(id);
|
|
231
|
+
const D = `D=${shq(d)}; `;
|
|
232
|
+
const pollMs = Math.max(MIN_POLL_MS, opts.pollMs ?? DEFAULT_POLL_MS);
|
|
233
|
+
const lostAfterMs = opts.lostAfterMs ?? DEFAULT_LOST_AFTER_MS;
|
|
234
|
+
const started = Date.now();
|
|
235
|
+
const streams = {
|
|
236
|
+
out: { offset: 0, text: "", decoder: new TextDecoder(), emit: opts.onStdout },
|
|
237
|
+
err: { offset: 0, text: "", decoder: new TextDecoder(), emit: opts.onStderr },
|
|
238
|
+
};
|
|
239
|
+
/** The command has ended, or is gone. */
|
|
240
|
+
let ended = false;
|
|
241
|
+
/** wait() has settled: nothing is read any more. */
|
|
242
|
+
let settled = false;
|
|
243
|
+
let writes = Promise.resolve();
|
|
244
|
+
let seq = 0;
|
|
245
|
+
let resolve;
|
|
246
|
+
let reject;
|
|
247
|
+
const done = new Promise((res, rej) => {
|
|
248
|
+
resolve = res;
|
|
249
|
+
reject = rej;
|
|
250
|
+
});
|
|
251
|
+
// A caller that only streams and never calls wait() must not get an unhandled rejection.
|
|
252
|
+
done.catch(() => { });
|
|
253
|
+
// The pause between reads. It holds the process open only while someone is waiting for the result
|
|
254
|
+
// or being called with output; a handle nobody listens to does not.
|
|
255
|
+
let listening = Boolean(opts.onStdout || opts.onStderr);
|
|
256
|
+
let timer;
|
|
257
|
+
let wake;
|
|
258
|
+
const pause = (ms) => new Promise((res) => {
|
|
259
|
+
const finish = () => {
|
|
260
|
+
clearTimeout(timer);
|
|
261
|
+
timer = wake = undefined;
|
|
262
|
+
res();
|
|
263
|
+
};
|
|
264
|
+
timer = setTimeout(finish, ms);
|
|
265
|
+
if (!listening)
|
|
266
|
+
timer.unref?.();
|
|
267
|
+
wake = finish;
|
|
268
|
+
});
|
|
269
|
+
const settle = (how) => {
|
|
270
|
+
if (settled)
|
|
271
|
+
return;
|
|
272
|
+
settled = true;
|
|
273
|
+
how();
|
|
274
|
+
wake?.();
|
|
275
|
+
};
|
|
276
|
+
const fail = (error) => settle(() => reject(error));
|
|
277
|
+
const decode = (m, text) => {
|
|
278
|
+
if (!text)
|
|
279
|
+
return new Uint8Array(0);
|
|
280
|
+
const hex = m === "xxd" || m === "od";
|
|
281
|
+
// Checked whole, so an answer cut short is read again and never half taken.
|
|
282
|
+
const ok = hex ? text.length % 2 === 0 && /^[0-9a-f]+$/.test(text) : text.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(text);
|
|
283
|
+
if (!ok)
|
|
284
|
+
throw new RouterError(`reading the command's output failed on ${box.provider}: the answer was cut short or garbled`, [], "all_failed");
|
|
285
|
+
return Buffer.from(text, hex ? "hex" : "base64");
|
|
286
|
+
};
|
|
287
|
+
/** One read of the exit code and both streams. Nothing is taken from it here, so a failed read changes nothing. The code is read first, so output written before it is never missed. */
|
|
288
|
+
const read = async () => {
|
|
289
|
+
const part = (f, offset) => `tail -c +${offset + 1} "$D/${f}" 2> /dev/null | head -c ${READ_BYTES} | e`;
|
|
290
|
+
const size = (f) => `$(wc -c < "$D/${f}" 2> /dev/null | tr -d ' \\n')`;
|
|
291
|
+
const r = await box.exec(D +
|
|
292
|
+
`[ -d "$D" ] || { printf 'G:\\nZ:\\n'; exit 0; }; c=$(cat "$D/code" 2> /dev/null); so=${size("out")}; se=${size("err")}; ` +
|
|
293
|
+
`a=dead; ${FRESH} && a=alive; ${ENCODE}; ` +
|
|
294
|
+
`printf 'C:%s\\nA:%s\\nM:%s\\nS:%s %s\\nO:%s\\nE:%s\\nZ:\\n' "$c" "$a" "$m" "$so" "$se" "$(${part("out", streams.out.offset)})" "$(${part("err", streams.err.offset)})"`, { timeoutSeconds: 60 });
|
|
295
|
+
// Z is the last line: without it the answer is not whole.
|
|
296
|
+
if (r.exitCode !== 0 || line(r.stdout, "Z") === undefined)
|
|
297
|
+
throw new RouterError(`reading the command's output failed on ${box.provider} (exit ${r.exitCode})`, [], "all_failed");
|
|
298
|
+
if (line(r.stdout, "G") !== undefined)
|
|
299
|
+
return { alive: false, gone: true, out: new Uint8Array(0), err: new Uint8Array(0) };
|
|
300
|
+
const m = line(r.stdout, "M");
|
|
301
|
+
const code = line(r.stdout, "C") ?? "";
|
|
302
|
+
const s = /^(\d+) (\d+)$/.exec(line(r.stdout, "S") ?? "");
|
|
303
|
+
const p = {
|
|
304
|
+
...(/^\d+$/.test(code) ? { code: Number(code) } : {}),
|
|
305
|
+
alive: line(r.stdout, "A") === "alive",
|
|
306
|
+
gone: false,
|
|
307
|
+
...(s ? { sizes: { out: Number(s[1]), err: Number(s[2]) } } : {}),
|
|
308
|
+
out: decode(m, line(r.stdout, "O") ?? ""),
|
|
309
|
+
err: decode(m, line(r.stdout, "E") ?? ""),
|
|
310
|
+
};
|
|
311
|
+
// Bytes are waiting and none came: the encoder or the read failed in the sandbox. Not the same as nothing new.
|
|
312
|
+
for (const k of ["out", "err"]) {
|
|
313
|
+
if (p.sizes && p.sizes[k] > streams[k].offset && p[k].length === 0) {
|
|
314
|
+
throw new RouterError(`reading the command's output failed on ${box.provider}: ${p.sizes[k] - streams[k].offset} bytes are waiting and none were returned`, [], "all_failed");
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
return p;
|
|
318
|
+
};
|
|
319
|
+
const take = (s, bytes) => {
|
|
320
|
+
if (!bytes.length)
|
|
321
|
+
return;
|
|
322
|
+
s.offset += bytes.length;
|
|
323
|
+
// A streaming decoder: a character split across two reads comes out whole.
|
|
324
|
+
const text = s.decoder.decode(bytes, { stream: true });
|
|
325
|
+
if (text) {
|
|
326
|
+
s.text += text;
|
|
327
|
+
s.emit?.(text);
|
|
328
|
+
}
|
|
329
|
+
};
|
|
330
|
+
const remove = () => box.exec(`rm -rf ${shq(d)}`, { timeoutSeconds: 60 }).then(() => { }, () => { });
|
|
331
|
+
void (async () => {
|
|
332
|
+
let failures = 0;
|
|
333
|
+
let failingSince;
|
|
334
|
+
let goneAnswers = 0;
|
|
335
|
+
let deadSince;
|
|
336
|
+
let deadReads = 0;
|
|
337
|
+
while (!settled) {
|
|
338
|
+
let p;
|
|
339
|
+
try {
|
|
340
|
+
p = await read();
|
|
341
|
+
failures = goneAnswers = 0;
|
|
342
|
+
failingSince = undefined;
|
|
343
|
+
}
|
|
344
|
+
catch (error) {
|
|
345
|
+
if (settled)
|
|
346
|
+
return;
|
|
347
|
+
const why = error instanceof Error ? error.message : String(error);
|
|
348
|
+
// The provider says there is no such sandbox. Believed the second time in a row.
|
|
349
|
+
const status = errorStatus(error);
|
|
350
|
+
goneAnswers = status === 404 || status === 410 ? goneAnswers + 1 : 0;
|
|
351
|
+
if (goneAnswers >= 2) {
|
|
352
|
+
return fail(new RouterError(`the sandbox is gone on ${box.provider}, and command ${id} with it (${why})`, [], "all_failed"));
|
|
353
|
+
}
|
|
354
|
+
const now = Date.now();
|
|
355
|
+
failingSince ??= now;
|
|
356
|
+
const left = failingSince + lostAfterMs - now;
|
|
357
|
+
if (left <= 0) {
|
|
358
|
+
return fail(new RouterError(`lost the connection to command ${id} on ${box.provider}: reading its output has failed for ${Math.round((now - failingSince) / 1000)} s (last error: ${why}). ` +
|
|
359
|
+
`The command was not stopped and may still be running: attach("${id}") follows it again`, [], "all_failed"));
|
|
360
|
+
}
|
|
361
|
+
// A short blip costs one retry. A long one is retried less and less often, until lostAfterMs.
|
|
362
|
+
await pause(Math.min(pollMs * 2 ** failures++, MAX_BACKOFF_MS, left));
|
|
363
|
+
continue;
|
|
364
|
+
}
|
|
365
|
+
// detach() or sbx.kill() came while this read was on its way: it is dropped whole.
|
|
366
|
+
if (settled)
|
|
367
|
+
return;
|
|
368
|
+
if (p.gone) {
|
|
369
|
+
ended = true;
|
|
370
|
+
return fail(new RouterError(`command ${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"));
|
|
371
|
+
}
|
|
372
|
+
const got = p.out.length + p.err.length;
|
|
373
|
+
try {
|
|
374
|
+
take(streams.out, p.out);
|
|
375
|
+
take(streams.err, p.err);
|
|
376
|
+
// Ended and nothing more to read: the code was read before the sizes and the output, so this read saw it all.
|
|
377
|
+
const all = p.sizes ? streams.out.offset >= p.sizes.out && streams.err.offset >= p.sizes.err : got === 0;
|
|
378
|
+
if (p.code !== undefined && all) {
|
|
379
|
+
for (const s of [streams.out, streams.err]) {
|
|
380
|
+
const tail = s.decoder.decode();
|
|
381
|
+
if (tail) {
|
|
382
|
+
s.text += tail;
|
|
383
|
+
s.emit?.(tail);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
ended = true;
|
|
387
|
+
if (!opts.keep)
|
|
388
|
+
await remove();
|
|
389
|
+
return settle(() => resolve({ exitCode: p.code, stdout: streams.out.text, stderr: streams.err.text, durationMs: Date.now() - started }));
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
catch (error) {
|
|
393
|
+
// onStdout or onStderr threw. Not a failed read: retrying would call it again with later output.
|
|
394
|
+
return fail(error);
|
|
395
|
+
}
|
|
396
|
+
// No exit code and no heartbeat: the command and the script that records its end were stopped from
|
|
397
|
+
// outside. Seen over several reads and seconds, so a slow or just-resumed sandbox doesn't count.
|
|
398
|
+
if (p.code === undefined && !p.alive && got === 0) {
|
|
399
|
+
deadSince ??= Date.now();
|
|
400
|
+
if (++deadReads >= 2 && Date.now() - deadSince >= ORPHAN_CONFIRM_MS) {
|
|
401
|
+
ended = true;
|
|
402
|
+
if (!opts.keep)
|
|
403
|
+
await remove();
|
|
404
|
+
return fail(new RouterError(`the command stopped without an exit code on ${box.provider}: nothing of it has run for ${STALE_S} s. Some providers stop what a call left running when the call returns; there, use exec`, [], "unsupported"));
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
else {
|
|
408
|
+
deadSince = undefined;
|
|
409
|
+
deadReads = 0;
|
|
410
|
+
}
|
|
411
|
+
// More waiting to be read: no pause.
|
|
412
|
+
if (got === 0)
|
|
413
|
+
await pause(pollMs);
|
|
414
|
+
}
|
|
415
|
+
})().catch(fail);
|
|
416
|
+
track?.({ stop: fail, settled: done.then(() => { }, () => { }) });
|
|
417
|
+
const needStdin = (what) => {
|
|
418
|
+
if (!stdin)
|
|
419
|
+
throw new RouterError(`${what} needs a command started with stdin: true`, [], "bad_request");
|
|
420
|
+
};
|
|
421
|
+
return {
|
|
422
|
+
id,
|
|
423
|
+
wait() {
|
|
424
|
+
listening = true;
|
|
425
|
+
timer?.ref?.();
|
|
426
|
+
return done;
|
|
427
|
+
},
|
|
428
|
+
detach() {
|
|
429
|
+
fail(new RouterError(`detached from command ${id} on ${box.provider}: it was left running, and attach("${id}") follows it again`, [], "bad_request"));
|
|
430
|
+
},
|
|
431
|
+
write(data) {
|
|
432
|
+
needStdin("write");
|
|
433
|
+
const n = seq++;
|
|
434
|
+
const next = writes.then(async () => {
|
|
435
|
+
if (ended)
|
|
436
|
+
throw new RouterError("the command has ended: nothing reads its input", [], "bad_request");
|
|
437
|
+
const file = `${d}/w.${n}`;
|
|
438
|
+
await box.writeFile(file, data);
|
|
439
|
+
// Refused after the end or end(). A pipe is written only while the command's side is running: with
|
|
440
|
+
// nothing holding it open the write would wait forever.
|
|
441
|
+
const r = await box.exec(D +
|
|
442
|
+
`f=${shq(file)}; if [ -f "$D/code" ] || [ -f "$D/eof" ] || [ ! -e "$D/in" ]; then rm -f "$f"; exit 9; fi; ` +
|
|
443
|
+
`if [ -p "$D/in" ]; then ${FRESH} || { rm -f "$f"; exit 9; }; cat "$f" > "$D/in"; else cat "$f" >> "$D/in"; fi; r=$?; rm -f "$f"; exit $r`, { timeoutSeconds: 60 });
|
|
444
|
+
if (r.exitCode === 9)
|
|
445
|
+
throw new RouterError("the command has ended or its input is closed", [], "bad_request");
|
|
446
|
+
if (r.exitCode !== 0)
|
|
447
|
+
throw new RouterError(`writing to the command failed on ${box.provider} (exit ${r.exitCode})`, [], "all_failed");
|
|
448
|
+
});
|
|
449
|
+
writes = next.catch(() => { });
|
|
450
|
+
return next;
|
|
451
|
+
},
|
|
452
|
+
end() {
|
|
453
|
+
needStdin("end");
|
|
454
|
+
const next = writes.then(async () => {
|
|
455
|
+
// The command's side sees the file and closes the input: the command reads end-of-file.
|
|
456
|
+
await box.exec(D + `[ -d "$D" ] && [ ! -f "$D/code" ] && : > "$D/eof"; exit 0`, { timeoutSeconds: 60 });
|
|
457
|
+
});
|
|
458
|
+
writes = next.catch(() => { });
|
|
459
|
+
return next;
|
|
460
|
+
},
|
|
461
|
+
async kill() {
|
|
462
|
+
if (ended)
|
|
463
|
+
return;
|
|
464
|
+
await stopCommand(box, id);
|
|
465
|
+
},
|
|
466
|
+
};
|
|
467
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The programs `terminal` writes into the sandbox. They are text here so that the feature needs
|
|
3
|
+
* nothing installed beyond what the image already has.
|
|
4
|
+
*/
|
|
5
|
+
/** What the relay prints once its own terminal is raw: everything after it is frames. No command line can echo it. */
|
|
6
|
+
export declare const RELAY_MARK: Uint8Array;
|
|
7
|
+
/** Ways to get a pseudo-terminal, in order of preference. */
|
|
8
|
+
export declare const PTY_METHODS: readonly ["python3", "python", "script", "socat", "perl"];
|
|
9
|
+
export type PtyMethod = (typeof PTY_METHODS)[number];
|
|
10
|
+
/** Shell that prints `T:` and the methods this sandbox has, for the first call. */
|
|
11
|
+
export declare const PTY_PROBE: string;
|
|
12
|
+
/**
|
|
13
|
+
* The pseudo-terminal's owner, in Python 3 (standard library only). `run` starts the command on a
|
|
14
|
+
* new pty and copies: its own standard input to the pty, the pty to its standard output (the file
|
|
15
|
+
* `out`), and a line `r COLS ROWS` appended to the file `ctl` becomes the pty's new size. It also
|
|
16
|
+
* listens on the socket `sock`: `relay`, run from a provider's own terminal, connects there and
|
|
17
|
+
* carries the same bytes over the provider's live connection instead of the file.
|
|
18
|
+
*/
|
|
19
|
+
export declare const PTY_PY: string;
|
|
20
|
+
/** The same job as `script`, for an image whose only way to a pty is Perl's IO::Pty. */
|
|
21
|
+
export declare const PTY_PL: string;
|
|
22
|
+
/** Starts the pty's owner. This is the command `spawn`'s launcher runs: its standard input is the terminal's input, its output the file `out`. */
|
|
23
|
+
export declare function outerScript(d: string, method: PtyMethod, cols: number, rows: number): string;
|
|
24
|
+
/**
|
|
25
|
+
* Runs on the pty where its owner is not ours (`script`, `socat`, Perl): sets the size, notes the
|
|
26
|
+
* pty's name so a later call can change the size, runs the command, and notes its exit code. A
|
|
27
|
+
* watcher beside it stops everything on the pty when `kill()` is asked for or the folder goes.
|
|
28
|
+
*/
|
|
29
|
+
export declare function innerScript(d: string, cols: number, rows: number): string;
|
|
30
|
+
/** What runs on the pty: the caller's command, or the user's own shell. */
|
|
31
|
+
export declare function shellScript(cmd: string | undefined, opts: {
|
|
32
|
+
cwd?: string;
|
|
33
|
+
env?: Record<string, string>;
|
|
34
|
+
}): string;
|