adk-code-mode-sandbox 0.1.0__tar.gz → 0.2.0__tar.gz

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.
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: adk-code-mode-sandbox
3
- Version: 0.1.0
4
- Summary: In-sandbox runtime shim for adk-code-mode. Stdlib-only. Installs inside the container image the host runtime launches.
3
+ Version: 0.2.0
4
+ Summary: In-sandbox runtime shim for adk-code-mode. Installs inside the container image the host runtime launches.
5
5
  Project-URL: Documentation, https://github.com/A2ANet/adk-code-mode#readme
6
6
  Project-URL: Issues, https://github.com/A2ANet/adk-code-mode/issues
7
7
  Project-URL: Source, https://github.com/A2ANet/adk-code-mode
@@ -16,6 +16,7 @@ Classifier: Programming Language :: Python :: 3.12
16
16
  Classifier: Programming Language :: Python :: 3.13
17
17
  Classifier: Programming Language :: Python :: Implementation :: CPython
18
18
  Requires-Python: >=3.10
19
+ Requires-Dist: websockets>=14.0
19
20
  Description-Content-Type: text/markdown
20
21
 
21
22
  # ADK Code Mode Sandbox
@@ -5,7 +5,7 @@ build-backend = "hatchling.build"
5
5
  [project]
6
6
  name = "adk-code-mode-sandbox"
7
7
  dynamic = ["version"]
8
- description = "In-sandbox runtime shim for adk-code-mode. Stdlib-only. Installs inside the container image the host runtime launches."
8
+ description = "In-sandbox runtime shim for adk-code-mode. Installs inside the container image the host runtime launches."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
11
11
  license = "Apache-2.0"
@@ -22,7 +22,9 @@ classifiers = [
22
22
  "Programming Language :: Python :: 3.13",
23
23
  "Programming Language :: Python :: Implementation :: CPython",
24
24
  ]
25
- dependencies = []
25
+ dependencies = [
26
+ "websockets>=14.0",
27
+ ]
26
28
 
27
29
  [project.urls]
28
30
  Documentation = "https://github.com/A2ANet/adk-code-mode#readme"
@@ -1,4 +1,4 @@
1
1
  # SPDX-FileCopyrightText: 2025-present A2A Net <hello@a2anet.com>
2
2
  #
3
3
  # SPDX-License-Identifier: Apache-2.0
4
- __version__ = "0.1.0" # x-release-please-version
4
+ __version__ = "0.2.0" # x-release-please-version
@@ -7,10 +7,10 @@ Invoked as ``python -m adk_code_mode_sandbox``. Three control-pipe transports
7
7
  are supported, chosen by env var (checked in order):
8
8
 
9
9
  - ``ADK_CODE_MODE_CONTROL_TCP`` → ``host:port`` TCP endpoint on the host
10
- (used by the Docker runtime; works on mac/Windows/Linux uniformly).
10
+ (used by ``UnsafeLocalDockerBackend``; works on mac/Windows/Linux uniformly).
11
11
  - ``ADK_CODE_MODE_CONTROL_SOCKET`` → Unix domain socket path (used by the
12
12
  in-process test ``FakeRuntime``; broken on Docker Desktop macOS so not
13
- used by ``DockerRuntime``).
13
+ used by ``UnsafeLocalDockerBackend``).
14
14
  - ``ADK_CODE_MODE_CONTROL_FD`` → inherited fd(s). Accepts one fd
15
15
  (bidirectional) or two comma-separated fds (read,write).
16
16
 
@@ -73,20 +73,51 @@ def _open_control_streams() -> tuple[Any, Any]:
73
73
  )
74
74
 
75
75
 
76
- def _prepare_sys_path() -> None:
76
+ def _prepare_sys_path(tools_dir: str | None = None) -> None:
77
77
  """Make the generated tools directory importable from user code."""
78
- if os.path.isdir(TOOLS_DIR):
79
- # TOOLS_DIR is the package directory itself (normally /tools), not a
78
+ target = tools_dir or TOOLS_DIR
79
+ if os.path.isdir(target):
80
+ # target is the package directory itself (normally /tools), not a
80
81
  # parent that contains tools/. Add the parent so `import tools` resolves
81
82
  # directly to /tools/__init__.py instead of requiring /tools/tools.
82
- package_parent = os.path.dirname(os.path.abspath(TOOLS_DIR)) or os.sep
83
+ package_parent = os.path.dirname(os.path.abspath(target)) or os.sep
83
84
  if package_parent not in sys.path:
84
85
  sys.path.insert(0, package_parent)
85
86
 
86
87
 
87
- def _prepare_workdir() -> None:
88
- os.makedirs(WORKDIR, exist_ok=True)
89
- os.chdir(WORKDIR)
88
+ def _prepare_workdir(workdir: str | None = None) -> None:
89
+ target = workdir or WORKDIR
90
+ os.makedirs(target, exist_ok=True)
91
+ os.chdir(target)
92
+
93
+
94
+ _ENV_ALLOWLIST = frozenset(
95
+ {
96
+ "PATH",
97
+ "HOME",
98
+ "USER",
99
+ "LANG",
100
+ "LANGUAGE",
101
+ "TERM",
102
+ "TMPDIR",
103
+ "TEMP",
104
+ "TMP",
105
+ "PYTHONHASHSEED",
106
+ "PYTHONDONTWRITEBYTECODE",
107
+ }
108
+ )
109
+
110
+
111
+ def _sanitize_environ() -> None:
112
+ """Strip sensitive env vars before user code runs.
113
+
114
+ Preserves only a known-safe allowlist plus LC_* locale vars. Everything
115
+ else (control tokens, platform credentials, extra_env from the host) is
116
+ removed so user code cannot read it.
117
+ """
118
+ for key in list(os.environ):
119
+ if key not in _ENV_ALLOWLIST and not key.startswith("LC_"):
120
+ del os.environ[key]
90
121
 
91
122
 
92
123
  def _make_globals() -> dict[str, Any]:
@@ -126,11 +157,22 @@ def _run_code(code: str) -> int:
126
157
 
127
158
 
128
159
  def main() -> int:
160
+ if os.environ.get("ADK_CODE_MODE_CONTROL_HTTP"):
161
+ import asyncio
162
+
163
+ from adk_code_mode_sandbox._http_server import AUTH_TOKEN_ENV, serve
164
+
165
+ port = int(os.environ.get("PORT", "8080"))
166
+ token = os.environ.get(AUTH_TOKEN_ENV)
167
+ asyncio.run(serve(port, token))
168
+ return 0
169
+
129
170
  reader, writer = _open_control_streams()
130
171
  client = RpcClient(reader=reader, writer=writer)
131
172
  _rpc_client.install(client)
132
173
  _prepare_sys_path()
133
174
  _prepare_workdir()
175
+ _sanitize_environ()
134
176
 
135
177
  client.send(ReadyFrame())
136
178
 
@@ -0,0 +1,292 @@
1
+ # SPDX-FileCopyrightText: 2025-present A2A Net <hello@a2anet.com>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ """HTTP/WebSocket server mode for the sandbox (single-use).
5
+
6
+ Activated by ``ADK_CODE_MODE_CONTROL_HTTP=1``. The container accepts exactly
7
+ one WebSocket connection, executes user code in-process, then exits. The
8
+ hosting platform (Cloud Run, Fargate, K8s, etc.) is expected to create a new
9
+ container for each request.
10
+
11
+ Files (tools and workspace) are transferred as tar archives over binary
12
+ WebSocket frames; control frames use the standard JSON-lines protocol
13
+ over text WebSocket frames.
14
+
15
+ Connection protocol::
16
+
17
+ 1. Client sends binary: tools tar.gz
18
+ 2. Client sends binary: workspace tar.gz
19
+ 3. Bidirectional text frames: JSON-lines control protocol
20
+ 4. After code execution, server sends text: OutputFrame
21
+ 5. Server sends binary: workspace tar.gz (updated files)
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import asyncio
27
+ import io
28
+ import logging
29
+ import os
30
+ import queue as queue_mod
31
+ import shutil
32
+ import sys
33
+ import tarfile
34
+ import tempfile
35
+ from http import HTTPStatus
36
+ from typing import Any
37
+
38
+ import websockets
39
+ import websockets.asyncio.server
40
+
41
+ from adk_code_mode_sandbox._entry import (
42
+ _prepare_sys_path,
43
+ _prepare_workdir,
44
+ _run_code,
45
+ _sanitize_environ,
46
+ )
47
+ from adk_code_mode_sandbox._rpc_client import RpcClient
48
+ from adk_code_mode_sandbox import _rpc_client
49
+ from adk_code_mode_sandbox.protocol import (
50
+ DoneFrame,
51
+ OutputFrame,
52
+ ReadyFrame,
53
+ RunFrame,
54
+ encode,
55
+ )
56
+
57
+ logger = logging.getLogger("adk_code_mode_sandbox.http_server")
58
+
59
+ CONTROL_HTTP_ENV = "ADK_CODE_MODE_CONTROL_HTTP"
60
+ AUTH_TOKEN_ENV = "ADK_CODE_MODE_AUTH_TOKEN"
61
+ MAX_UPLOAD_TOOLS_ENV = "ADK_CODE_MODE_MAX_UPLOAD_TOOLS"
62
+ MAX_UPLOAD_WORKSPACE_ENV = "ADK_CODE_MODE_MAX_UPLOAD_WORKSPACE"
63
+
64
+ _DEFAULT_MAX_TOOLS_BYTES = 100 * 1024 * 1024 # 100 MiB
65
+ _DEFAULT_MAX_WORKSPACE_BYTES = 100 * 1024 * 1024 # 100 MiB
66
+ _WS_MAX_SIZE = 256 * 1024 * 1024 # 256 MiB
67
+
68
+
69
+ class _WsBridgeReader:
70
+ """Sync reader backed by a thread-safe queue.
71
+
72
+ The async WS pump pushes incoming text frames; the ``RpcClient`` reader
73
+ thread consumes them via ``readline()``.
74
+ """
75
+
76
+ def __init__(self) -> None:
77
+ self._q: queue_mod.Queue[bytes] = queue_mod.Queue()
78
+
79
+ def feed(self, data: bytes) -> None:
80
+ self._q.put_nowait(data)
81
+
82
+ def close(self) -> None:
83
+ self._q.put_nowait(b"")
84
+
85
+ def readline(self) -> bytes:
86
+ return self._q.get()
87
+
88
+
89
+ class _WsBridgeWriter:
90
+ """Sync writer that sends to a WebSocket via the event loop."""
91
+
92
+ def __init__(self, loop: asyncio.AbstractEventLoop, ws: Any) -> None:
93
+ self._loop = loop
94
+ self._ws = ws
95
+
96
+ def write(self, data: bytes) -> None:
97
+ text = data.decode("utf-8")
98
+ future = asyncio.run_coroutine_threadsafe(self._ws.send(text), self._loop)
99
+ future.result()
100
+
101
+ def flush(self) -> None:
102
+ pass
103
+
104
+
105
+ async def serve(port: int, token: str | None) -> None:
106
+ """Start the WebSocket server on *port* with optional bearer *token* auth.
107
+
108
+ Accepts exactly one WebSocket connection, runs user code, then returns.
109
+ """
110
+ stop = asyncio.Event()
111
+ accepted = False
112
+
113
+ def process_request(connection: Any, request: Any) -> websockets.http11.Response | None:
114
+ nonlocal accepted
115
+ if request.path == "/health":
116
+ return connection.respond(HTTPStatus.OK, "OK\n")
117
+ if accepted:
118
+ return connection.respond(HTTPStatus.SERVICE_UNAVAILABLE, "Busy\n")
119
+ if token is not None:
120
+ import hmac
121
+
122
+ auth = (request.headers.get("Authorization") or "").strip()
123
+ if not hmac.compare_digest(auth, f"Bearer {token}"):
124
+ return connection.respond(HTTPStatus.UNAUTHORIZED, "Unauthorized\n")
125
+ accepted = True
126
+ return None
127
+
128
+ async def handler(ws: Any) -> None:
129
+ try:
130
+ await _handle_connection(ws)
131
+ except websockets.ConnectionClosed:
132
+ logger.debug("client disconnected")
133
+ except Exception:
134
+ logger.exception("error handling WebSocket connection")
135
+ finally:
136
+ stop.set()
137
+
138
+ async with websockets.asyncio.server.serve(
139
+ handler,
140
+ "0.0.0.0",
141
+ port,
142
+ process_request=process_request,
143
+ max_size=_WS_MAX_SIZE,
144
+ ):
145
+ logger.info("sandbox HTTP server listening on port %d", port)
146
+ await stop.wait()
147
+
148
+
149
+ async def _handle_connection(ws: Any) -> None:
150
+ max_tools = int(os.environ.get(MAX_UPLOAD_TOOLS_ENV, _DEFAULT_MAX_TOOLS_BYTES))
151
+ max_workspace = int(os.environ.get(MAX_UPLOAD_WORKSPACE_ENV, _DEFAULT_MAX_WORKSPACE_BYTES))
152
+
153
+ tools_base = tempfile.mkdtemp(prefix="adk-cm-tools-")
154
+ tools_dir = os.path.join(tools_base, "tools")
155
+ os.makedirs(tools_dir)
156
+ workspace_dir = tempfile.mkdtemp(prefix="adk-cm-ws-")
157
+
158
+ try:
159
+ # 1. Receive and extract tools tar
160
+ tools_data = await ws.recv()
161
+ if not isinstance(tools_data, (bytes, bytearray)):
162
+ raise ValueError("expected binary frame for tools tar")
163
+ if len(tools_data) > max_tools:
164
+ raise ValueError(
165
+ f"tools archive ({len(tools_data):,} bytes) exceeds limit ({max_tools:,} bytes)"
166
+ )
167
+ _extract_tar(tools_data, tools_dir)
168
+
169
+ # 2. Receive and extract workspace tar
170
+ ws_data = await ws.recv()
171
+ if not isinstance(ws_data, (bytes, bytearray)):
172
+ raise ValueError("expected binary frame for workspace tar")
173
+ if len(ws_data) > max_workspace:
174
+ raise ValueError(
175
+ f"workspace archive ({len(ws_data):,} bytes) exceeds limit ({max_workspace:,} bytes)"
176
+ )
177
+ _extract_tar(ws_data, workspace_dir)
178
+
179
+ # 3. Sanitize environment before user code can read it
180
+ _sanitize_environ()
181
+
182
+ # 4. Prepare sandbox (sys.path, workdir)
183
+ _prepare_sys_path(tools_dir)
184
+ _prepare_workdir(workspace_dir)
185
+
186
+ # 5. Set up async↔sync bridge and install RPC client
187
+ loop = asyncio.get_running_loop()
188
+ bridge_reader = _WsBridgeReader()
189
+ bridge_writer = _WsBridgeWriter(loop, ws)
190
+ client = RpcClient(reader=bridge_reader, writer=bridge_writer)
191
+ _rpc_client.install(client)
192
+
193
+ # 6. Run user code on a worker thread while pumping WS messages
194
+ pump_task = asyncio.create_task(_pump_ws_to_reader(ws, bridge_reader))
195
+
196
+ stdout_text, stderr_text, exit_code = await loop.run_in_executor(
197
+ None, _run_user_code, client
198
+ )
199
+
200
+ pump_task.cancel()
201
+ try:
202
+ await pump_task
203
+ except asyncio.CancelledError:
204
+ pass
205
+
206
+ # 7. Send OutputFrame + updated workspace tar
207
+ output = OutputFrame(
208
+ stdout=stdout_text,
209
+ stderr=stderr_text,
210
+ exit_code=exit_code,
211
+ )
212
+ await ws.send(encode(output).decode("utf-8"))
213
+ await ws.send(_create_tar(workspace_dir))
214
+
215
+ finally:
216
+ shutil.rmtree(tools_base, ignore_errors=True)
217
+ shutil.rmtree(workspace_dir, ignore_errors=True)
218
+
219
+
220
+ def _run_user_code(client: RpcClient) -> tuple[str, str, int]:
221
+ """Execute one RunFrame's code. Runs on a worker thread."""
222
+ client.send(ReadyFrame())
223
+ frame = client.recv()
224
+ if not isinstance(frame, RunFrame):
225
+ return ("", f"expected RunFrame, got {type(frame).__name__}", 1)
226
+
227
+ old_stdout, old_stderr = sys.stdout, sys.stderr
228
+ capture_out = io.StringIO()
229
+ capture_err = io.StringIO()
230
+ sys.stdout = capture_out
231
+ sys.stderr = capture_err
232
+ try:
233
+ exit_code = _run_code(frame.code)
234
+ finally:
235
+ sys.stdout = old_stdout
236
+ sys.stderr = old_stderr
237
+
238
+ client.send(DoneFrame(exit_code=exit_code))
239
+ return (capture_out.getvalue(), capture_err.getvalue(), exit_code)
240
+
241
+
242
+ async def _pump_ws_to_reader(ws: Any, reader: _WsBridgeReader) -> None:
243
+ """Forward incoming WS text frames to the bridge reader queue."""
244
+ try:
245
+ async for msg in ws:
246
+ if isinstance(msg, str):
247
+ data = msg.encode("utf-8")
248
+ if not data.endswith(b"\n"):
249
+ data += b"\n"
250
+ reader.feed(data)
251
+ except websockets.ConnectionClosed:
252
+ pass
253
+ finally:
254
+ reader.close()
255
+
256
+
257
+ def _extract_tar(data: bytes | bytearray, dest: str) -> None:
258
+ if not data:
259
+ return
260
+ dest_real = os.path.realpath(dest)
261
+ buf = io.BytesIO(data)
262
+ with tarfile.open(fileobj=buf, mode="r:gz") as tf:
263
+ members = []
264
+ for member in tf.getmembers():
265
+ if not (member.isfile() or member.isdir()):
266
+ continue
267
+ if member.linkname:
268
+ continue
269
+ normalized = os.path.normpath(member.name)
270
+ if normalized.startswith("/") or normalized.startswith(".."):
271
+ continue
272
+ if any(part == ".." for part in normalized.split(os.sep)):
273
+ continue
274
+ resolved = os.path.realpath(os.path.join(dest, normalized))
275
+ if not resolved.startswith(dest_real + os.sep) and resolved != dest_real:
276
+ continue
277
+ member.name = normalized
278
+ members.append(member)
279
+ tf.extractall(dest, members=members)
280
+
281
+
282
+ def _create_tar(source_dir: str) -> bytes:
283
+ buf = io.BytesIO()
284
+ with tarfile.open(fileobj=buf, mode="w:gz") as tf:
285
+ for root, _dirs, files in os.walk(source_dir, followlinks=False):
286
+ for fname in files:
287
+ abs_path = os.path.join(root, fname)
288
+ if os.path.islink(abs_path) or not os.path.isfile(abs_path):
289
+ continue
290
+ arcname = os.path.relpath(abs_path, source_dir)
291
+ tf.add(abs_path, arcname=arcname)
292
+ return buf.getvalue()
@@ -9,8 +9,8 @@ identical on every release.
9
9
 
10
10
  Design rules:
11
11
 
12
- - Zero dependencies outside the Python standard library. The sandbox wheel
13
- must remain stdlib-only so the container image does not pull ADK / google-genai.
12
+ - Zero dependencies outside the Python standard library (the sandbox wheel
13
+ has other dependencies, but this module must stay stdlib-only).
14
14
  - Frames are JSON objects, one per newline-terminated UTF-8 line.
15
15
  - Every frame carries a ``kind`` discriminator. Correlated pairs (e.g.
16
16
  ``tool_call`` / ``tool_result``) carry a string ``id``.
@@ -32,6 +32,7 @@ FrameKind = Literal[
32
32
  "tool_result",
33
33
  "log",
34
34
  "done",
35
+ "output",
35
36
  "shutdown",
36
37
  ]
37
38
 
@@ -100,6 +101,16 @@ class DoneFrame:
100
101
  kind: Literal["done"] = "done"
101
102
 
102
103
 
104
+ @dataclass(frozen=True)
105
+ class OutputFrame:
106
+ """Server → host. Captured stdout/stderr after subprocess exit (HTTP mode only)."""
107
+
108
+ stdout: str = ""
109
+ stderr: str = ""
110
+ exit_code: int = 0
111
+ kind: Literal["output"] = "output"
112
+
113
+
103
114
  @dataclass(frozen=True)
104
115
  class ShutdownFrame:
105
116
  """Host → sandbox. Graceful shutdown."""
@@ -108,7 +119,14 @@ class ShutdownFrame:
108
119
 
109
120
 
110
121
  Frame = (
111
- ReadyFrame | RunFrame | ToolCallFrame | ToolResultFrame | LogFrame | DoneFrame | ShutdownFrame
122
+ ReadyFrame
123
+ | RunFrame
124
+ | ToolCallFrame
125
+ | ToolResultFrame
126
+ | LogFrame
127
+ | DoneFrame
128
+ | OutputFrame
129
+ | ShutdownFrame
112
130
  )
113
131
 
114
132
 
@@ -119,6 +137,7 @@ _KIND_TO_CLS: dict[str, type] = {
119
137
  "tool_result": ToolResultFrame,
120
138
  "log": LogFrame,
121
139
  "done": DoneFrame,
140
+ "output": OutputFrame,
122
141
  "shutdown": ShutdownFrame,
123
142
  }
124
143
 
@@ -186,6 +205,7 @@ __all__ = [
186
205
  "ToolErrorPayload",
187
206
  "LogFrame",
188
207
  "DoneFrame",
208
+ "OutputFrame",
189
209
  "ShutdownFrame",
190
210
  "ProtocolError",
191
211
  "encode",