AskTim 0.1.0__py3-none-any.whl

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.
asktim/runner.py ADDED
@@ -0,0 +1,308 @@
1
+ """Running the agent's commands.
2
+
3
+ Each command runs in bash (sh if there is no bash), in the agent's folder, with no input
4
+ (stdin is /dev/null, so nothing can wait for typing), with a time limit, in a process group
5
+ of its own (so that a timeout or Ctrl+C stops everything it started). Secrets are taken out
6
+ of its environment (variables whose names hold KEY, TOKEN, SECRET, PASSWORD ...), so a
7
+ command cannot print the student's API keys.
8
+
9
+ The student sees everything a command prints, as it prints it. A bounded copy (the beginning
10
+ and the end) is kept for the data filter, which decides what the AI may see.
11
+
12
+ Sandbox: on Linux, when bubblewrap (bwrap) is installed and works, every command runs in a
13
+ sandbox where the whole file system is read-only except the agent's folder and a private
14
+ /tmp, and - unless the student allowed the internet - there is no network. Where there is
15
+ no sandbox, AskTim! compares the student's folder before and after each step and reports
16
+ any file that changed outside the agent's folder.
17
+ """
18
+
19
+ import os
20
+ import re
21
+ import shutil
22
+ import signal
23
+ import subprocess
24
+ import sys
25
+ import tempfile
26
+ import threading
27
+ import time
28
+ from collections import deque
29
+
30
+ SECRET_ENV = re.compile(r"KEY|TOKEN|SECRET|PASSW|CREDENTIAL|_AUTH|COOKIE|SESSION", re.I)
31
+ KEEP_ENV = {"SSH_AUTH_SOCK"} # not a secret itself, but give the agent no ssh either
32
+ SNAPSHOT_SKIP = {".git", "__pycache__", "node_modules", ".snakemake", ".nextflow", "work", ".ipynb_checkpoints", ".cache", ".conda", "asktim-runs"}
33
+
34
+
35
+ class RunResult(object):
36
+ def __init__(self):
37
+ self.exit_code = None
38
+ self.timed_out = False
39
+ self.interrupted = False
40
+ self.duration = 0.0
41
+ self.head = [] # first lines of the combined output
42
+ self.tail = deque(maxlen=400) # last lines
43
+ self.lines = 0
44
+ self.bytes = 0
45
+ self.stderr_lines = 0
46
+ self.error = None # could not start
47
+
48
+ def text(self):
49
+ """The output as kept: beginning and end, with a note of what is missing between them."""
50
+ head = list(self.head)
51
+ tail = list(self.tail)
52
+ if self.lines <= len(head) + len(tail):
53
+ # tail overlaps head: rebuild without duplicates
54
+ seen = len(head)
55
+ rest = tail[max(0, len(tail) - (self.lines - seen)):] if self.lines > seen else []
56
+ return "".join(head + rest)
57
+ gap = self.lines - len(head) - len(tail)
58
+ return "".join(head) + "[… %d lines not kept here …]\n" % gap + "".join(tail)
59
+
60
+ def last_lines(self, n=30):
61
+ lines = self.text().splitlines()
62
+ return "\n".join(lines[-n:])
63
+
64
+
65
+ def clean_env(extra=None, tmpdir=None):
66
+ env = {}
67
+ for k, v in os.environ.items():
68
+ if SECRET_ENV.search(k) and k not in KEEP_ENV:
69
+ continue
70
+ if k == "SSH_AUTH_SOCK":
71
+ continue
72
+ env[k] = v
73
+ env.update({
74
+ "PAGER": "cat", "MANPAGER": "cat", "GIT_PAGER": "cat", "SYSTEMD_PAGER": "", "LESS": "-FRX",
75
+ "TERM": "dumb", "NO_COLOR": "1", "CLICOLOR": "0", "PYTHONUNBUFFERED": "1", "MPLBACKEND": "Agg",
76
+ "DEBIAN_FRONTEND": "noninteractive", "GIT_TERMINAL_PROMPT": "0", "ASKTIM_AGENT": "1",
77
+ "R_DEFAULT_DEVICE": "png",
78
+ })
79
+ if tmpdir:
80
+ env["TMPDIR"] = tmpdir
81
+ if extra:
82
+ env.update(extra)
83
+ return env
84
+
85
+
86
+ def shell_path():
87
+ return shutil.which("bash") or shutil.which("sh")
88
+
89
+
90
+ class Sandbox(object):
91
+ """bubblewrap on Linux (sandbox-exec on macOS, only when asked for)."""
92
+
93
+ def __init__(self, kind, run_dir, student_dir, allow_network):
94
+ self.kind = kind
95
+ self.run_dir = os.path.realpath(run_dir)
96
+ self.student_dir = os.path.realpath(student_dir)
97
+ self.allow_network = allow_network
98
+ self.private_tmp = tempfile.mkdtemp(prefix="asktim-tmp-")
99
+ # a private /tmp would hide a student's folder that lies under /tmp: then the real /tmp
100
+ # stays (read-only, like everything else) and commands get a private scratch folder
101
+ tmp_root = os.path.realpath(tempfile.gettempdir())
102
+ self.overlay_tmp = not any(
103
+ p == tmp_root or p.startswith(tmp_root + os.sep) or p == "/tmp" or p.startswith("/tmp/")
104
+ for p in (self.student_dir, self.run_dir))
105
+
106
+ def describe(self):
107
+ if self.kind == "bwrap":
108
+ return "sandbox: bubblewrap – only the agent's folder can be written%s" % ("" if self.allow_network else "; no network")
109
+ if self.kind == "sandbox-exec":
110
+ return "sandbox: macOS sandbox-exec – only the agent's folder can be written%s" % ("" if self.allow_network else "; no network")
111
+ return "no sandbox"
112
+
113
+ def wrap(self, argv):
114
+ if self.kind == "bwrap":
115
+ a = [shutil.which("bwrap"), "--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--unshare-pid", "--die-with-parent"]
116
+ for d in sorted(os.listdir("/dev")) if os.path.isdir("/dev") else []:
117
+ if d.startswith("nvidia"):
118
+ a += ["--dev-bind", "/dev/" + d, "/dev/" + d]
119
+ if self.overlay_tmp:
120
+ a += ["--bind", self.private_tmp, "/tmp"]
121
+ else:
122
+ a += ["--bind", self.private_tmp, self.private_tmp]
123
+ a += ["--bind", self.run_dir, self.run_dir]
124
+ if not self.allow_network:
125
+ a += ["--unshare-net"]
126
+ a += ["--chdir", self.run_dir, "--"]
127
+ return a + argv
128
+ if self.kind == "sandbox-exec":
129
+ prof = [
130
+ "(version 1)", "(allow default)", "(deny file-write*)",
131
+ '(allow file-write* (subpath "%s") (subpath "/private/tmp") (subpath "/private/var/folders") (subpath "/dev"))' % self.run_dir,
132
+ ]
133
+ if not self.allow_network:
134
+ prof.append("(deny network*)")
135
+ return ["/usr/bin/sandbox-exec", "-p", "\n".join(prof)] + argv
136
+ return argv
137
+
138
+ def env_tmp(self):
139
+ if self.kind == "bwrap":
140
+ return "/tmp" if self.overlay_tmp else self.private_tmp
141
+ return None
142
+
143
+ def cleanup(self):
144
+ shutil.rmtree(self.private_tmp, ignore_errors=True)
145
+
146
+
147
+ def make_sandbox(mode, run_dir, student_dir, allow_network):
148
+ """A working sandbox, or (None, reason)."""
149
+ if mode == "off":
150
+ return None, "the sandbox is turned off in the settings"
151
+ if sys.platform.startswith("linux"):
152
+ if not shutil.which("bwrap"):
153
+ return None, "bubblewrap (bwrap) is not installed"
154
+ sb = Sandbox("bwrap", run_dir, student_dir, allow_network)
155
+ elif sys.platform == "darwin" and mode == "on" and os.path.exists("/usr/bin/sandbox-exec"):
156
+ sb = Sandbox("sandbox-exec", run_dir, student_dir, allow_network)
157
+ else:
158
+ return None, "there is no sandbox for this system"
159
+ # does it work here? (user namespaces can be switched off, for example on clusters)
160
+ try:
161
+ sh = shell_path() or "/bin/sh"
162
+ p = subprocess.run(sb.wrap([sh, "-c", "touch .asktim-sandbox-test && rm .asktim-sandbox-test"]), cwd=run_dir, stdin=subprocess.DEVNULL, capture_output=True, timeout=20)
163
+ if p.returncode != 0:
164
+ sb.cleanup()
165
+ return None, "the sandbox does not work here (%s)" % (p.stderr.decode("utf-8", "replace").strip().splitlines() or ["exit %d" % p.returncode])[-1][:200]
166
+ except Exception as e:
167
+ sb.cleanup()
168
+ return None, "the sandbox could not start (%s)" % e
169
+ return sb, None
170
+
171
+
172
+ def run(command, cwd, timeout=600, sandbox=None, on_output=None, env_extra=None):
173
+ """Run a command; on_output(stream, text) gets what it prints as it prints it."""
174
+ res = RunResult()
175
+ sh = shell_path()
176
+ if not sh:
177
+ res.error = "There is no bash or sh on this computer, so the agent cannot run commands."
178
+ res.exit_code = 127
179
+ return res
180
+ argv = [sh, "-c", command]
181
+ if sandbox is not None:
182
+ argv = sandbox.wrap(argv)
183
+ env = clean_env(env_extra, tmpdir=sandbox.env_tmp() if sandbox else None)
184
+ t0 = time.time()
185
+ kwargs = {}
186
+ if os.name == "posix":
187
+ kwargs["start_new_session"] = True
188
+ else:
189
+ kwargs["creationflags"] = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
190
+ try:
191
+ proc = subprocess.Popen(argv, cwd=cwd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, **kwargs)
192
+ except OSError as e:
193
+ res.error = "The command could not be started: %s" % e
194
+ res.exit_code = 126
195
+ return res
196
+ lock = threading.Lock()
197
+ head_limit = 300
198
+
199
+ def pump(stream, name):
200
+ for raw in iter(stream.readline, b""):
201
+ text = raw.decode("utf-8", "replace")
202
+ kept = text if len(text) <= 4000 else text[:4000] + "…[line cut]\n"
203
+ with lock:
204
+ res.lines += 1
205
+ res.bytes += len(raw)
206
+ if name == "stderr":
207
+ res.stderr_lines += 1
208
+ if len(res.head) < head_limit:
209
+ res.head.append(kept)
210
+ else:
211
+ res.tail.append(kept)
212
+ if on_output:
213
+ try:
214
+ on_output(name, text)
215
+ except Exception:
216
+ pass
217
+ stream.close()
218
+
219
+ threads = [threading.Thread(target=pump, args=(proc.stdout, "stdout")), threading.Thread(target=pump, args=(proc.stderr, "stderr"))]
220
+ for t in threads:
221
+ t.daemon = True
222
+ t.start()
223
+ try:
224
+ while True:
225
+ try:
226
+ proc.wait(timeout=0.2)
227
+ break
228
+ except subprocess.TimeoutExpired:
229
+ if timeout and time.time() - t0 > timeout:
230
+ res.timed_out = True
231
+ _kill(proc)
232
+ break
233
+ except KeyboardInterrupt:
234
+ res.interrupted = True
235
+ _kill(proc)
236
+ for t in threads:
237
+ t.join(timeout=5)
238
+ res.exit_code = proc.returncode if proc.returncode is not None else -9
239
+ res.duration = time.time() - t0
240
+ return res
241
+
242
+
243
+ def _kill(proc):
244
+ try:
245
+ if os.name == "posix":
246
+ os.killpg(proc.pid, signal.SIGTERM)
247
+ else:
248
+ proc.terminate()
249
+ except (OSError, ProcessLookupError):
250
+ pass
251
+ try:
252
+ proc.wait(timeout=3)
253
+ except subprocess.TimeoutExpired:
254
+ try:
255
+ if os.name == "posix":
256
+ os.killpg(proc.pid, signal.SIGKILL)
257
+ else:
258
+ proc.kill()
259
+ except (OSError, ProcessLookupError):
260
+ pass
261
+ try:
262
+ proc.wait(timeout=3)
263
+ except subprocess.TimeoutExpired:
264
+ pass
265
+
266
+
267
+ # ------------------------------------------------------------------------------------------------
268
+ # what changed outside the agent's folder (when there is no sandbox)
269
+ # ------------------------------------------------------------------------------------------------
270
+
271
+
272
+ def snapshot(root, exclude, limit=20000, max_depth=6):
273
+ """{path: (size, mtime_ns)} of the files under root, or None if there are too many."""
274
+ out = {}
275
+ exclude = os.path.realpath(exclude)
276
+ root = os.path.realpath(root)
277
+ stack = [(root, 0)]
278
+ while stack:
279
+ d, depth = stack.pop()
280
+ if d == exclude or d.startswith(exclude + os.sep):
281
+ continue
282
+ try:
283
+ it = os.scandir(d)
284
+ except OSError:
285
+ continue
286
+ with it:
287
+ for e in it:
288
+ try:
289
+ if e.is_dir(follow_symlinks=False):
290
+ if e.name not in SNAPSHOT_SKIP and depth < max_depth:
291
+ stack.append((e.path, depth + 1))
292
+ continue
293
+ st = e.stat(follow_symlinks=False)
294
+ out[e.path] = (st.st_size, st.st_mtime_ns)
295
+ except OSError:
296
+ continue
297
+ if len(out) > limit:
298
+ return None
299
+ return out
300
+
301
+
302
+ def changes(before, after):
303
+ if before is None or after is None:
304
+ return None
305
+ created = sorted(p for p in after if p not in before)
306
+ deleted = sorted(p for p in before if p not in after)
307
+ changed = sorted(p for p in after if p in before and after[p] != before[p])
308
+ return {"created": created, "changed": changed, "deleted": deleted}