quietrobot-sandboxes 0.2.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.
@@ -0,0 +1,28 @@
1
+ """Quiet Robot Sandboxes: governed sandboxes for AI agents."""
2
+
3
+ __version__ = "0.2.0"
4
+
5
+ from .client import (
6
+ CommandDeniedError,
7
+ Files,
8
+ Ports,
9
+ Process,
10
+ Sandbox,
11
+ Sandboxes,
12
+ SandboxesError,
13
+ Terminal,
14
+ verify_webhook,
15
+ )
16
+
17
+ __all__ = [
18
+ "Sandboxes",
19
+ "Sandbox",
20
+ "Files",
21
+ "Ports",
22
+ "Process",
23
+ "Terminal",
24
+ "SandboxesError",
25
+ "CommandDeniedError",
26
+ "verify_webhook",
27
+ "__version__",
28
+ ]
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,187 @@
1
+ """A small persistent Python kernel that runs inside a sandbox.
2
+
3
+ The SDKs' run_code() / runCode() copies this file into the sandbox once and
4
+ then runs each cell with a plain command:
5
+
6
+ python3 ~/.qr/kernel.py run <<'QR_CELL'
7
+ ...code...
8
+ QR_CELL
9
+
10
+ The first call starts a server process that keeps the variables between
11
+ cells, so a notebook-style session works the way Jupyter does. The code is in
12
+ the command itself, so the sandbox's policy and audit log see every cell.
13
+
14
+ Each cell answers one JSON line on stdout:
15
+ {"stdout", "stderr", "results": [{"text", "html", "png", "json"}], "error": {"name", "value", "traceback"} | null}
16
+
17
+ This file must run on any Python 3.8+, with only the standard library.
18
+ """
19
+
20
+ import ast
21
+ import base64
22
+ import contextlib
23
+ import io
24
+ import json
25
+ import os
26
+ import socket
27
+ import subprocess
28
+ import sys
29
+ import threading
30
+ import time
31
+ import traceback
32
+
33
+ SOCK = os.path.join(os.path.expanduser("~"), ".qr", "kernel.sock")
34
+ LOG = os.path.join(os.path.expanduser("~"), ".qr", "kernel.log")
35
+
36
+
37
+ def _recv_all(conn):
38
+ chunks = []
39
+ while True:
40
+ b = conn.recv(65536)
41
+ if not b:
42
+ break
43
+ chunks.append(b)
44
+ return b"".join(chunks)
45
+
46
+
47
+ def _rich(value):
48
+ """What a notebook would show for the cell's last expression."""
49
+ out = {"text": repr(value)}
50
+ for attr, key in (("_repr_html_", "html"), ("_repr_png_", "png"), ("_repr_json_", "json")):
51
+ fn = getattr(value, attr, None)
52
+ if callable(fn):
53
+ try:
54
+ v = fn()
55
+ except Exception:
56
+ continue
57
+ if v is None:
58
+ continue
59
+ if key == "png" and isinstance(v, bytes):
60
+ v = base64.b64encode(v).decode()
61
+ out[key] = v
62
+ return out
63
+
64
+
65
+ def _figures():
66
+ """PNGs of any open matplotlib figures, which are then closed."""
67
+ plt = sys.modules.get("matplotlib.pyplot")
68
+ if plt is None:
69
+ return []
70
+ out = []
71
+ for num in plt.get_fignums():
72
+ fig = plt.figure(num)
73
+ buf = io.BytesIO()
74
+ try:
75
+ fig.savefig(buf, format="png", bbox_inches="tight")
76
+ out.append({"text": "<Figure>", "png": base64.b64encode(buf.getvalue()).decode()})
77
+ except Exception:
78
+ pass
79
+ plt.close("all")
80
+ return out
81
+
82
+
83
+ class Kernel:
84
+ def __init__(self):
85
+ self.globals = {"__name__": "__main__"}
86
+ self.lock = threading.Lock()
87
+
88
+ def run(self, code):
89
+ stdout, stderr = io.StringIO(), io.StringIO()
90
+ results, error = [], None
91
+ with self.lock, contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):
92
+ try:
93
+ tree = ast.parse(code, "<cell>", "exec")
94
+ last = None
95
+ if tree.body and isinstance(tree.body[-1], ast.Expr):
96
+ last = ast.Expression(tree.body.pop().value)
97
+ exec(compile(tree, "<cell>", "exec"), self.globals)
98
+ if last is not None:
99
+ value = eval(compile(last, "<cell>", "eval"), self.globals)
100
+ if value is not None:
101
+ self.globals["_"] = value
102
+ results.append(_rich(value))
103
+ except BaseException as e: # a cell may raise anything, SystemExit included
104
+ error = {
105
+ "name": type(e).__name__,
106
+ "value": str(e),
107
+ "traceback": "".join(traceback.format_exception(type(e), e, e.__traceback__)),
108
+ }
109
+ results.extend(_figures())
110
+ return {"stdout": stdout.getvalue(), "stderr": stderr.getvalue(), "results": results, "error": error}
111
+
112
+
113
+ def serve():
114
+ os.makedirs(os.path.dirname(SOCK), exist_ok=True)
115
+ os.environ.setdefault("MPLBACKEND", "Agg")
116
+ with contextlib.suppress(FileNotFoundError):
117
+ os.unlink(SOCK)
118
+ kernel = Kernel()
119
+ srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
120
+ srv.bind(SOCK)
121
+ os.chmod(SOCK, 0o600)
122
+ srv.listen(8)
123
+ while True:
124
+ conn, _ = srv.accept()
125
+ try:
126
+ code = _recv_all(conn).decode("utf-8", "replace")
127
+ if code == "\0restart":
128
+ # The next cell starts a fresh kernel with no variables.
129
+ srv.close()
130
+ os.unlink(SOCK)
131
+ conn.sendall(b'{"restarted": true}')
132
+ conn.close()
133
+ os._exit(0)
134
+ conn.sendall(json.dumps(kernel.run(code)).encode())
135
+ except Exception:
136
+ pass
137
+ finally:
138
+ with contextlib.suppress(Exception):
139
+ conn.close()
140
+
141
+
142
+ def _connect():
143
+ s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
144
+ s.connect(SOCK)
145
+ return s
146
+
147
+
148
+ def _ensure_server():
149
+ try:
150
+ return _connect()
151
+ except OSError:
152
+ pass
153
+ os.makedirs(os.path.dirname(SOCK), exist_ok=True)
154
+ with open(LOG, "ab") as log:
155
+ subprocess.Popen(
156
+ [sys.executable, os.path.abspath(__file__), "serve"],
157
+ stdin=subprocess.DEVNULL,
158
+ stdout=log,
159
+ stderr=log,
160
+ start_new_session=True,
161
+ close_fds=True,
162
+ )
163
+ deadline = time.time() + 15
164
+ while time.time() < deadline:
165
+ try:
166
+ return _connect()
167
+ except OSError:
168
+ time.sleep(0.05)
169
+ raise SystemExit("kernel did not start; see " + LOG)
170
+
171
+
172
+ def client(code):
173
+ s = _ensure_server()
174
+ s.sendall(code.encode())
175
+ s.shutdown(socket.SHUT_WR)
176
+ sys.stdout.write(_recv_all(s).decode() + "\n")
177
+ s.close()
178
+
179
+
180
+ if __name__ == "__main__":
181
+ mode = sys.argv[1] if len(sys.argv) > 1 else "run"
182
+ if mode == "serve":
183
+ serve()
184
+ elif mode == "restart":
185
+ client("\0restart")
186
+ else:
187
+ client(sys.stdin.read())