@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
|
@@ -0,0 +1,429 @@
|
|
|
1
|
+
import { shq } from "./util.js";
|
|
2
|
+
import { NAP } from "./spawn.js";
|
|
3
|
+
/**
|
|
4
|
+
* The programs `terminal` writes into the sandbox. They are text here so that the feature needs
|
|
5
|
+
* nothing installed beyond what the image already has.
|
|
6
|
+
*/
|
|
7
|
+
/** What the relay prints once its own terminal is raw: everything after it is frames. No command line can echo it. */
|
|
8
|
+
export const RELAY_MARK = new Uint8Array([0x1e, 0x1d, 0x73, 0x72, 0x2d, 0x72, 0x65, 0x6c, 0x61, 0x79, 0x1d, 0x1e]);
|
|
9
|
+
/** Ways to get a pseudo-terminal, in order of preference. */
|
|
10
|
+
export const PTY_METHODS = ["python3", "python", "script", "socat", "perl"];
|
|
11
|
+
/** Shell that prints `T:` and the methods this sandbox has, for the first call. */
|
|
12
|
+
export const PTY_PROBE = `t=; for p in python3 python; do command -v $p > /dev/null 2>&1 && $p -c 'import sys, pty, termios, fcntl, select, socket, struct; sys.exit(sys.version_info[0] < 3)' > /dev/null 2>&1 && t="$t $p"; done; ` +
|
|
13
|
+
`command -v script > /dev/null 2>&1 && t="$t script"; ` +
|
|
14
|
+
`command -v socat > /dev/null 2>&1 && t="$t socat"; ` +
|
|
15
|
+
`command -v perl > /dev/null 2>&1 && perl -MIO::Pty -e 1 > /dev/null 2>&1 && t="$t perl"; ` +
|
|
16
|
+
`command -v stty > /dev/null 2>&1 && t="$t stty"; ` +
|
|
17
|
+
`printf 'T:%s\\n' "$t"`;
|
|
18
|
+
/**
|
|
19
|
+
* The pseudo-terminal's owner, in Python 3 (standard library only). `run` starts the command on a
|
|
20
|
+
* new pty and copies: its own standard input to the pty, the pty to its standard output (the file
|
|
21
|
+
* `out`), and a line `r COLS ROWS` appended to the file `ctl` becomes the pty's new size. It also
|
|
22
|
+
* listens on the socket `sock`: `relay`, run from a provider's own terminal, connects there and
|
|
23
|
+
* carries the same bytes over the provider's live connection instead of the file.
|
|
24
|
+
*/
|
|
25
|
+
export const PTY_PY = String.raw `import fcntl, os, select, signal, socket, struct, sys, termios, time
|
|
26
|
+
|
|
27
|
+
MARK = b"\x1e\x1dsr-relay\x1d\x1e"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def put(fd, data):
|
|
31
|
+
data = memoryview(data)
|
|
32
|
+
while len(data):
|
|
33
|
+
try:
|
|
34
|
+
n = os.write(fd, data)
|
|
35
|
+
except BlockingIOError:
|
|
36
|
+
select.select([], [fd], [], 1)
|
|
37
|
+
continue
|
|
38
|
+
data = data[n:]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def resize(fd, cols, rows):
|
|
42
|
+
try:
|
|
43
|
+
fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0))
|
|
44
|
+
except Exception:
|
|
45
|
+
pass
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def in_session(sid):
|
|
49
|
+
if os.path.isdir("/proc/1"):
|
|
50
|
+
names = [n for n in os.listdir("/proc") if n.isdigit()]
|
|
51
|
+
else:
|
|
52
|
+
names = os.popen("ps -ax -o pid=").read().split()
|
|
53
|
+
found = []
|
|
54
|
+
for n in names:
|
|
55
|
+
try:
|
|
56
|
+
p = int(n)
|
|
57
|
+
if p != os.getpid() and os.getsid(p) == sid:
|
|
58
|
+
found.append(p)
|
|
59
|
+
except Exception:
|
|
60
|
+
pass
|
|
61
|
+
return found
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def signal_session(sid, sig):
|
|
65
|
+
for p in in_session(sid):
|
|
66
|
+
try:
|
|
67
|
+
os.kill(p, sig)
|
|
68
|
+
except Exception:
|
|
69
|
+
pass
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def frame(data):
|
|
73
|
+
return struct.pack(">I", len(data)) + data
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def run(d, cols, rows):
|
|
77
|
+
m, s = os.openpty()
|
|
78
|
+
resize(s, cols, rows)
|
|
79
|
+
pid = os.fork()
|
|
80
|
+
if pid == 0:
|
|
81
|
+
try:
|
|
82
|
+
os.setsid()
|
|
83
|
+
fcntl.ioctl(s, termios.TIOCSCTTY, 0)
|
|
84
|
+
for fd in (0, 1, 2):
|
|
85
|
+
os.dup2(s, fd)
|
|
86
|
+
os.closerange(3, 1024)
|
|
87
|
+
# What started this may have had these ignored. A terminal's programs get the defaults.
|
|
88
|
+
for g in (signal.SIGHUP, signal.SIGINT, signal.SIGQUIT, signal.SIGTERM, signal.SIGPIPE, signal.SIGCHLD):
|
|
89
|
+
signal.signal(g, signal.SIG_DFL)
|
|
90
|
+
os.execvp("sh", ["sh", d + "/shell.sh"])
|
|
91
|
+
except Exception as e:
|
|
92
|
+
os.write(2, ("terminal: " + str(e) + "\n").encode())
|
|
93
|
+
os._exit(127)
|
|
94
|
+
os.close(s)
|
|
95
|
+
fcntl.fcntl(m, fcntl.F_SETFL, fcntl.fcntl(m, fcntl.F_GETFL) | os.O_NONBLOCK)
|
|
96
|
+
|
|
97
|
+
stop = []
|
|
98
|
+
rp, wp = os.pipe()
|
|
99
|
+
for fd in (rp, wp):
|
|
100
|
+
fcntl.fcntl(fd, fcntl.F_SETFL, fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK)
|
|
101
|
+
signal.set_wakeup_fd(wp)
|
|
102
|
+
signal.signal(signal.SIGCHLD, lambda *a: None)
|
|
103
|
+
signal.signal(signal.SIGTERM, lambda *a: stop.append(1))
|
|
104
|
+
|
|
105
|
+
srv = None
|
|
106
|
+
try:
|
|
107
|
+
srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
108
|
+
srv.bind(d + "/sock")
|
|
109
|
+
srv.listen(4)
|
|
110
|
+
except Exception:
|
|
111
|
+
srv = None
|
|
112
|
+
|
|
113
|
+
clients = []
|
|
114
|
+
pending = bytearray()
|
|
115
|
+
state = {"ctl": 0, "total": 0}
|
|
116
|
+
|
|
117
|
+
def control():
|
|
118
|
+
try:
|
|
119
|
+
if os.stat(d + "/ctl").st_size <= state["ctl"]:
|
|
120
|
+
return
|
|
121
|
+
with open(d + "/ctl", "rb") as f:
|
|
122
|
+
f.seek(state["ctl"])
|
|
123
|
+
text = f.read()
|
|
124
|
+
except Exception:
|
|
125
|
+
return
|
|
126
|
+
end = text.rfind(b"\n")
|
|
127
|
+
if end < 0:
|
|
128
|
+
return
|
|
129
|
+
state["ctl"] += end + 1
|
|
130
|
+
for line in text[:end].split(b"\n"):
|
|
131
|
+
part = line.split()
|
|
132
|
+
if len(part) == 3 and part[0] == b"r":
|
|
133
|
+
try:
|
|
134
|
+
resize(m, int(part[1]), int(part[2]))
|
|
135
|
+
except Exception:
|
|
136
|
+
pass
|
|
137
|
+
|
|
138
|
+
def drop(c):
|
|
139
|
+
if c in clients:
|
|
140
|
+
clients.remove(c)
|
|
141
|
+
try:
|
|
142
|
+
c.close()
|
|
143
|
+
except Exception:
|
|
144
|
+
pass
|
|
145
|
+
|
|
146
|
+
def accept():
|
|
147
|
+
c, _ = srv.accept()
|
|
148
|
+
try:
|
|
149
|
+
c.settimeout(5)
|
|
150
|
+
line = b""
|
|
151
|
+
while not line.endswith(b"\n") and len(line) < 32:
|
|
152
|
+
b = c.recv(1)
|
|
153
|
+
if not b:
|
|
154
|
+
raise EOFError()
|
|
155
|
+
line += b
|
|
156
|
+
at = int(line)
|
|
157
|
+
# Everything from that byte on, as one piece of work: nothing is missed or sent twice.
|
|
158
|
+
with open(d + "/out", "rb") as f:
|
|
159
|
+
f.seek(at)
|
|
160
|
+
left = state["total"] - at
|
|
161
|
+
while left > 0:
|
|
162
|
+
data = f.read(min(left, 65536))
|
|
163
|
+
if not data:
|
|
164
|
+
break
|
|
165
|
+
c.sendall(frame(data))
|
|
166
|
+
left -= len(data)
|
|
167
|
+
clients.append(c)
|
|
168
|
+
except Exception:
|
|
169
|
+
drop(c)
|
|
170
|
+
|
|
171
|
+
status = None
|
|
172
|
+
over = None
|
|
173
|
+
killing = None
|
|
174
|
+
eof = False
|
|
175
|
+
stdin = True
|
|
176
|
+
while True:
|
|
177
|
+
if status is None:
|
|
178
|
+
try:
|
|
179
|
+
p, st = os.waitpid(pid, os.WNOHANG)
|
|
180
|
+
except ChildProcessError:
|
|
181
|
+
p, st = pid, 0
|
|
182
|
+
if p:
|
|
183
|
+
status = st
|
|
184
|
+
over = time.time() + 0.5
|
|
185
|
+
if stop and killing is None:
|
|
186
|
+
killing = time.time() + 1.0
|
|
187
|
+
signal_session(pid, signal.SIGHUP)
|
|
188
|
+
signal_session(pid, signal.SIGTERM)
|
|
189
|
+
signal_session(pid, signal.SIGCONT)
|
|
190
|
+
if killing is not None and time.time() > killing:
|
|
191
|
+
signal_session(pid, signal.SIGKILL)
|
|
192
|
+
killing = time.time() + 60
|
|
193
|
+
if over is None:
|
|
194
|
+
over = time.time() + 0.5
|
|
195
|
+
control()
|
|
196
|
+
r = [rp] + clients
|
|
197
|
+
if not eof:
|
|
198
|
+
r.append(m)
|
|
199
|
+
if srv is not None:
|
|
200
|
+
r.append(srv)
|
|
201
|
+
if stdin and len(pending) < (1 << 20):
|
|
202
|
+
r.append(0)
|
|
203
|
+
try:
|
|
204
|
+
rr, ww, _ = select.select(r, [m] if pending else [], [], 0.05 if (status is not None or stop) else 0.2)
|
|
205
|
+
except (OSError, ValueError):
|
|
206
|
+
rr, ww = [], []
|
|
207
|
+
if rp in rr:
|
|
208
|
+
try:
|
|
209
|
+
os.read(rp, 4096)
|
|
210
|
+
except OSError:
|
|
211
|
+
pass
|
|
212
|
+
if m in ww and pending:
|
|
213
|
+
try:
|
|
214
|
+
n = os.write(m, bytes(pending[:4096]))
|
|
215
|
+
del pending[:n]
|
|
216
|
+
except BlockingIOError:
|
|
217
|
+
pass
|
|
218
|
+
except OSError:
|
|
219
|
+
del pending[:]
|
|
220
|
+
got = False
|
|
221
|
+
if m in rr:
|
|
222
|
+
try:
|
|
223
|
+
data = os.read(m, 65536)
|
|
224
|
+
except BlockingIOError:
|
|
225
|
+
data = None
|
|
226
|
+
except OSError:
|
|
227
|
+
data = b""
|
|
228
|
+
if data:
|
|
229
|
+
got = True
|
|
230
|
+
put(1, data)
|
|
231
|
+
state["total"] += len(data)
|
|
232
|
+
for c in list(clients):
|
|
233
|
+
try:
|
|
234
|
+
c.sendall(frame(data))
|
|
235
|
+
except Exception:
|
|
236
|
+
drop(c)
|
|
237
|
+
elif data is not None:
|
|
238
|
+
eof = True
|
|
239
|
+
if 0 in rr:
|
|
240
|
+
try:
|
|
241
|
+
data = os.read(0, 65536)
|
|
242
|
+
except OSError:
|
|
243
|
+
data = b""
|
|
244
|
+
if data:
|
|
245
|
+
# A size change asked for before these bytes were written takes effect before they do.
|
|
246
|
+
control()
|
|
247
|
+
pending += data
|
|
248
|
+
else:
|
|
249
|
+
stdin = False
|
|
250
|
+
for c in list(clients):
|
|
251
|
+
if c in rr:
|
|
252
|
+
try:
|
|
253
|
+
data = c.recv(65536)
|
|
254
|
+
except Exception:
|
|
255
|
+
data = b""
|
|
256
|
+
if data:
|
|
257
|
+
control()
|
|
258
|
+
pending += data
|
|
259
|
+
else:
|
|
260
|
+
drop(c)
|
|
261
|
+
if srv is not None and srv in rr:
|
|
262
|
+
try:
|
|
263
|
+
accept()
|
|
264
|
+
except Exception:
|
|
265
|
+
pass
|
|
266
|
+
# The command has ended: what it last wrote is read, then this ends too.
|
|
267
|
+
if status is not None and (eof or not got or time.time() > over):
|
|
268
|
+
break
|
|
269
|
+
if status is None and over is not None and time.time() > over:
|
|
270
|
+
break
|
|
271
|
+
|
|
272
|
+
for c in list(clients):
|
|
273
|
+
try:
|
|
274
|
+
c.sendall(frame(b""))
|
|
275
|
+
except Exception:
|
|
276
|
+
pass
|
|
277
|
+
drop(c)
|
|
278
|
+
try:
|
|
279
|
+
os.unlink(d + "/sock")
|
|
280
|
+
except Exception:
|
|
281
|
+
pass
|
|
282
|
+
if status is None:
|
|
283
|
+
sys.exit(137)
|
|
284
|
+
sys.exit(os.WEXITSTATUS(status) if os.WIFEXITED(status) else 128 + os.WTERMSIG(status))
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def relay(d):
|
|
288
|
+
if os.isatty(0):
|
|
289
|
+
a = termios.tcgetattr(0)
|
|
290
|
+
a[0] = 0
|
|
291
|
+
a[1] = a[1] & ~termios.OPOST
|
|
292
|
+
a[2] = (a[2] & ~(termios.CSIZE | termios.PARENB)) | termios.CS8
|
|
293
|
+
a[3] = 0
|
|
294
|
+
a[6][termios.VMIN] = 1
|
|
295
|
+
a[6][termios.VTIME] = 0
|
|
296
|
+
termios.tcsetattr(0, termios.TCSAFLUSH, a)
|
|
297
|
+
put(1, MARK)
|
|
298
|
+
line = b""
|
|
299
|
+
while not line.endswith(b"\n"):
|
|
300
|
+
b = os.read(0, 1)
|
|
301
|
+
if not b or len(line) > 32:
|
|
302
|
+
return
|
|
303
|
+
line += b
|
|
304
|
+
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
305
|
+
s.connect(d + "/sock")
|
|
306
|
+
s.sendall(line)
|
|
307
|
+
while True:
|
|
308
|
+
rr, _, _ = select.select([0, s], [], [])
|
|
309
|
+
if s in rr:
|
|
310
|
+
data = s.recv(65536)
|
|
311
|
+
if not data:
|
|
312
|
+
break
|
|
313
|
+
put(1, data)
|
|
314
|
+
if 0 in rr:
|
|
315
|
+
data = os.read(0, 65536)
|
|
316
|
+
if not data:
|
|
317
|
+
break
|
|
318
|
+
s.sendall(data)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
if sys.argv[1] == "run":
|
|
322
|
+
run(sys.argv[2], int(sys.argv[3]), int(sys.argv[4]))
|
|
323
|
+
else:
|
|
324
|
+
try:
|
|
325
|
+
relay(sys.argv[2])
|
|
326
|
+
except Exception:
|
|
327
|
+
pass
|
|
328
|
+
`;
|
|
329
|
+
/** The same job as `script`, for an image whose only way to a pty is Perl's IO::Pty. */
|
|
330
|
+
export const PTY_PL = String.raw `use strict; use IO::Pty; use IO::Select; use POSIX ":sys_wait_h";
|
|
331
|
+
my $p = IO::Pty->new; my $pid = fork();
|
|
332
|
+
if (!$pid) {
|
|
333
|
+
$p->make_slave_controlling_terminal(); my $s = $p->slave(); close $p;
|
|
334
|
+
open(STDIN, "<&", $s); open(STDOUT, ">&", $s); open(STDERR, ">&", $s); close $s;
|
|
335
|
+
$SIG{$_} = "DEFAULT" for qw(HUP INT QUIT TERM PIPE CHLD);
|
|
336
|
+
exec @ARGV; exit 127;
|
|
337
|
+
}
|
|
338
|
+
$p->close_slave(); $| = 1; binmode(STDIN); binmode(STDOUT);
|
|
339
|
+
my $sel = IO::Select->new($p, \*STDIN); my $open = 1;
|
|
340
|
+
while ($open) {
|
|
341
|
+
for my $h ($sel->can_read(0.2)) {
|
|
342
|
+
my $buf;
|
|
343
|
+
if ($h == $p) { my $n = sysread($p, $buf, 65536); if (!$n) { $open = 0; last; } syswrite(STDOUT, $buf); }
|
|
344
|
+
else { my $n = sysread(STDIN, $buf, 65536); if (!$n) { $sel->remove(\*STDIN); next; } syswrite($p, $buf); }
|
|
345
|
+
}
|
|
346
|
+
last if waitpid($pid, WNOHANG) > 0 && !$sel->can_read(0.2);
|
|
347
|
+
}
|
|
348
|
+
`;
|
|
349
|
+
/** 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`. */
|
|
350
|
+
export function outerScript(d, method, cols, rows) {
|
|
351
|
+
const D = shq(d);
|
|
352
|
+
if (method === "python3" || method === "python")
|
|
353
|
+
return `exec ${method} ${D}/pty.py run ${D} ${cols} ${rows}\n`;
|
|
354
|
+
const inner = `sh ${D}/inner.sh`;
|
|
355
|
+
const start = {
|
|
356
|
+
// Three programs share the name. util-linux and busybox take the command with -c, BSD after the file.
|
|
357
|
+
script: `if script --version 2>&1 < /dev/null | grep -q util-linux; then script -qefc ${shq(inner)} /dev/null; ` +
|
|
358
|
+
`elif script -q -c true /dev/null > /dev/null 2>&1 < /dev/null; then script -q -c ${shq(inner)} /dev/null; ` +
|
|
359
|
+
// BSD's refuses a named pipe as its input, so a plain pipe is put in between. Nothing waits for that cat: it is stopped after.
|
|
360
|
+
// Its input goes by another number, since a shell gives a background command /dev/null as standard input.
|
|
361
|
+
`else { cat <&3 3<&- & echo $! > ${D}/cat; } 3<&0 | script -q /dev/null ${inner}; c=$?; kill "$(cat ${D}/cat)" 2> /dev/null; (exit $c); fi`,
|
|
362
|
+
socat: `socat STDIO EXEC:${shq(`sh ${d}/inner.sh`)},pty,setsid,ctty,stderr,sane`,
|
|
363
|
+
perl: `perl ${D}/pty.pl ${inner}`,
|
|
364
|
+
}[method];
|
|
365
|
+
// kill() is done from inside the pty (innerScript), which can still name everything on it. So the
|
|
366
|
+
// pty's holder sits out the signal the launcher sends, and ends when what it holds has ended.
|
|
367
|
+
return `trap '' TERM\n${start}\nc=$?; if [ -s ${D}/pcode ]; then c=$(cat ${D}/pcode); elif [ "$c" = 0 ]; then c=137; fi; exit "$c"\n`;
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Runs on the pty where its owner is not ours (`script`, `socat`, Perl): sets the size, notes the
|
|
371
|
+
* pty's name so a later call can change the size, runs the command, and notes its exit code. A
|
|
372
|
+
* watcher beside it stops everything on the pty when `kill()` is asked for or the folder goes.
|
|
373
|
+
*/
|
|
374
|
+
export function innerScript(d, cols, rows) {
|
|
375
|
+
return [
|
|
376
|
+
`D=${shq(d)}`,
|
|
377
|
+
`stty rows ${rows} cols ${cols} 2> /dev/null`,
|
|
378
|
+
`tty > "$D/tty" 2> /dev/null`,
|
|
379
|
+
`nap() ${NAP("0.2")}`,
|
|
380
|
+
// Every process on this pty but the watcher: by session where /proc says, by terminal elsewhere.
|
|
381
|
+
// Each process and its session. Not inside $( ): an old bash trips over the bracket there.
|
|
382
|
+
`sessions() { for f in /proc/[0-9]*/stat; do read -r l < "$f" 2> /dev/null || continue; p=\${l%% *}; l=\${l##*) }; set -- $l; echo "$p $4"; done; }`,
|
|
383
|
+
"others() {",
|
|
384
|
+
` self=$(sh -c 'echo $PPID')`,
|
|
385
|
+
" if [ -r /proc/self/stat ]; then",
|
|
386
|
+
` all=$(sessions)`,
|
|
387
|
+
` mine=$(echo "$all" | while read -r p s; do [ "$p" = "$self" ] && echo "$s"; done)`,
|
|
388
|
+
` [ -n "$mine" ] && echo "$all" | while read -r p s; do [ "$s" = "$mine" ] && [ "$p" != "$self" ] && echo "$p"; done`,
|
|
389
|
+
" else",
|
|
390
|
+
` t=$(cat "$D/tty" 2> /dev/null); [ -n "$t" ] && ps -o pid= -t "\${t#/dev/}" 2> /dev/null | while read -r p; do [ "$p" != "$self" ] && echo "$p"; done`,
|
|
391
|
+
" fi",
|
|
392
|
+
"}",
|
|
393
|
+
"(",
|
|
394
|
+
" trap '' HUP INT QUIT TSTP TTIN TTOU",
|
|
395
|
+
` while [ -d "$D" ] && [ ! -f "$D/kill" ] && [ ! -f "$D/pcode" ]; do nap; done`,
|
|
396
|
+
` [ -f "$D/pcode" ] && exit 0`,
|
|
397
|
+
" kill -HUP $(others) 2> /dev/null; kill -TERM $(others) 2> /dev/null; kill -CONT $(others) 2> /dev/null",
|
|
398
|
+
" nap; nap",
|
|
399
|
+
" kill -KILL $(others) 2> /dev/null",
|
|
400
|
+
") > /dev/null 2>&1 < /dev/null &",
|
|
401
|
+
// This script may have been started with the interrupt signals ignored, which a shell cannot undo
|
|
402
|
+
// for its own children. Perl, GNU env or Node can, so the terminal's programs are stopped by Ctrl-C.
|
|
403
|
+
`if command -v perl > /dev/null 2>&1; then perl -e '$SIG{$_} = "DEFAULT" for qw(HUP INT QUIT TERM PIPE); exec @ARGV; exit 127' sh "$D/shell.sh"`,
|
|
404
|
+
`elif env --default-signal=INT true > /dev/null 2>&1; then env --default-signal=HUP,INT,QUIT,TERM,PIPE sh "$D/shell.sh"`,
|
|
405
|
+
// Node starts programs with every signal at its default, and stays between as the one that waits.
|
|
406
|
+
`elif command -v node > /dev/null 2>&1; then node -e 'const r = require("child_process").spawnSync("sh", [process.argv[1]], { stdio: "inherit" }); process.exit(r.status === null ? 128 + (require("os").constants.signals[r.signal] || 0) : r.status)' "$D/shell.sh"`,
|
|
407
|
+
`else printf 'note: Ctrl-C may not stop programs in this terminal: the image has no python3, perl, node or GNU env to start them with.\r\n'; sh "$D/shell.sh"; fi`,
|
|
408
|
+
`echo $? > "$D/pcode.tmp" && mv "$D/pcode.tmp" "$D/pcode"`,
|
|
409
|
+
].join("\n") + "\n";
|
|
410
|
+
}
|
|
411
|
+
/** What runs on the pty: the caller's command, or the user's own shell. */
|
|
412
|
+
export function shellScript(cmd, opts) {
|
|
413
|
+
const env = { TERM: "xterm-256color", ...opts.env };
|
|
414
|
+
return [
|
|
415
|
+
...Object.entries(env).map(([k, v]) => `export ${k}=${shq(v)}`),
|
|
416
|
+
...(opts.cwd ? [`cd ${shq(opts.cwd)} || exit 127`] : []),
|
|
417
|
+
cmd ??
|
|
418
|
+
// The shell the account is set up with, then $SHELL, then bash, then sh.
|
|
419
|
+
[
|
|
420
|
+
`s=$(getent passwd "$(id -u)" 2> /dev/null | cut -d: -f7)`,
|
|
421
|
+
`case "$s" in */nologin|*/false) s=;; esac`,
|
|
422
|
+
`[ -n "$s" ] && [ -x "$s" ] || s=\${SHELL:-}`,
|
|
423
|
+
`[ -n "$s" ] && [ -x "$s" ] || s=$(command -v bash 2> /dev/null)`,
|
|
424
|
+
`[ -n "$s" ] && [ -x "$s" ] || s=$(command -v sh)`,
|
|
425
|
+
`SHELL=$s; export SHELL`,
|
|
426
|
+
`exec "$s"`,
|
|
427
|
+
].join("\n"),
|
|
428
|
+
].join("\n") + "\n";
|
|
429
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { type ProviderTerminal, type ProviderTerminalOptions } from "./types.js";
|
|
2
|
+
import { type Following, type SpawnBox } from "./spawn.js";
|
|
3
|
+
import { type PtyMethod } from "./terminal-helper.js";
|
|
4
|
+
/** What a terminal needs from a sandbox: `exec` and `writeFile`, and the provider's own terminal where it has one. */
|
|
5
|
+
export interface TerminalBox extends SpawnBox {
|
|
6
|
+
terminal?(opts: ProviderTerminalOptions): Promise<ProviderTerminal>;
|
|
7
|
+
}
|
|
8
|
+
export interface TerminalOptions {
|
|
9
|
+
/** What runs in the terminal, as a shell command. Default: the user's own shell (from the account, then `$SHELL`, then bash, then sh). */
|
|
10
|
+
cmd?: string;
|
|
11
|
+
/** Width in characters (default 80). */
|
|
12
|
+
cols?: number;
|
|
13
|
+
/** Height in lines (default 24). */
|
|
14
|
+
rows?: number;
|
|
15
|
+
cwd?: string;
|
|
16
|
+
/** Set for the command. `TERM` is `xterm-256color` unless given here. */
|
|
17
|
+
env?: Record<string, string>;
|
|
18
|
+
/**
|
|
19
|
+
* Called with the terminal's output as it is read: raw bytes, escape sequences included, in order.
|
|
20
|
+
* A character may be split across two calls, so decode with a streaming decoder or hand the bytes
|
|
21
|
+
* to a terminal emulator. If it throws, `wait()` rejects with what it threw.
|
|
22
|
+
*/
|
|
23
|
+
onData?: (bytes: Uint8Array) => void;
|
|
24
|
+
/** How often new output is looked for, in ms, while the terminal is in use (default 50, at least 20). Not used on the native path. */
|
|
25
|
+
pollMs?: number;
|
|
26
|
+
/** `false` keeps bytes on `exec` even where the provider has a terminal of its own. */
|
|
27
|
+
native?: boolean;
|
|
28
|
+
/** How long reads may keep failing before `wait()` gives up, in ms (default 60 000). The terminal is not touched: `attachTerminal(id)` follows it again. */
|
|
29
|
+
lostAfterMs?: number;
|
|
30
|
+
/** Leave the terminal's files in the sandbox after it ends, so `attachTerminal(id)` can replay its last output. Default: removed once `wait()` has the result. */
|
|
31
|
+
keep?: boolean;
|
|
32
|
+
}
|
|
33
|
+
export type TerminalAttachOptions = Pick<TerminalOptions, "onData" | "pollMs" | "native" | "lostAfterMs" | "keep"> & {
|
|
34
|
+
/** How much of the output already written is replayed first, in bytes from its end (default 65 536). */
|
|
35
|
+
replayBytes?: number;
|
|
36
|
+
};
|
|
37
|
+
/** A terminal open in a sandbox, started with `terminal`. */
|
|
38
|
+
export interface Terminal {
|
|
39
|
+
/** Names the terminal inside its sandbox. Pass it to `attachTerminal` to follow it again. */
|
|
40
|
+
readonly id: string;
|
|
41
|
+
/** How bytes travel right now: over the provider's own terminal connection ("native"), or by `exec` calls ("exec"). */
|
|
42
|
+
readonly path: "native" | "exec";
|
|
43
|
+
/** What holds the pseudo-terminal in the sandbox. */
|
|
44
|
+
readonly pty: PtyMethod;
|
|
45
|
+
/** Type into the terminal. Bytes arrive exactly as given and in the order written: "\x03" is Ctrl-C, "\x04" Ctrl-D. */
|
|
46
|
+
write(data: string | Uint8Array): Promise<void>;
|
|
47
|
+
/** Change the terminal's size. The program in it is told (SIGWINCH), as when a window is resized. */
|
|
48
|
+
resize(cols: number, rows: number): Promise<void>;
|
|
49
|
+
/** Close the terminal and stop everything running in it. The sandbox keeps running. */
|
|
50
|
+
kill(): Promise<void>;
|
|
51
|
+
/**
|
|
52
|
+
* Resolves when the terminal's command has ended and all of its output has been delivered.
|
|
53
|
+
* Rejects when it can no longer be followed: the connection was lost for `lostAfterMs`, the
|
|
54
|
+
* sandbox is gone or was killed, or `detach()` was called.
|
|
55
|
+
*/
|
|
56
|
+
wait(): Promise<{
|
|
57
|
+
exitCode: number;
|
|
58
|
+
}>;
|
|
59
|
+
/** Stop reading and leave the terminal open in the sandbox. `wait()` rejects; `attachTerminal(id)` follows it again. */
|
|
60
|
+
detach(): void;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Open a live terminal in the sandbox: a real pseudo-terminal with a shell (or `cmd`) on it, as if
|
|
64
|
+
* sitting at that computer. Prompts, colours, Ctrl-C, full-screen programs and window resizes work.
|
|
65
|
+
*
|
|
66
|
+
* It works on every provider, because it needs only `exec` and `writeFile`: a small program in the
|
|
67
|
+
* sandbox holds the pty (Python 3 where the image has it, else `script`, `socat` or Perl's IO::Pty),
|
|
68
|
+
* writes what the terminal prints to a file and reads what is typed from a named pipe. Output is
|
|
69
|
+
* read by calls that wait in the sandbox until there is something to read, so it arrives one round
|
|
70
|
+
* trip after it is printed. Where the provider has a terminal API of its own, the same bytes travel
|
|
71
|
+
* over that live connection instead, and `exec` takes over again if it drops.
|
|
72
|
+
*/
|
|
73
|
+
export declare function openTerminal(box: TerminalBox, opts?: TerminalOptions, track?: (f: Following) => void): Promise<Terminal>;
|
|
74
|
+
/**
|
|
75
|
+
* Follow a terminal again by its id, from any process that can reach the sandbox: the last
|
|
76
|
+
* `replayBytes` of what it printed come first, then it continues live. Once the terminal has ended
|
|
77
|
+
* this needs it to have been opened with `keep`.
|
|
78
|
+
*/
|
|
79
|
+
export declare function attachTerminal(box: TerminalBox, id: string, opts?: TerminalAttachOptions, track?: (f: Following) => void): Promise<Terminal>;
|