google-adk-withruntime 0.1.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.
@@ -0,0 +1,8 @@
1
+ node_modules
2
+ dist
3
+ *.tsbuildinfo
4
+ .DS_Store
5
+ __pycache__/
6
+ *.pyc
7
+ *.egg-info/
8
+ .venv/
@@ -0,0 +1,55 @@
1
+ Apache License
2
+
3
+ Version 2.0, January 2004
4
+
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
16
+
17
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
18
+
19
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
20
+
21
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
22
+
23
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
24
+
25
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
26
+
27
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
28
+
29
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
30
+
31
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
32
+
33
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
34
+
35
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
36
+
37
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
38
+
39
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
40
+
41
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
42
+
43
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,72 @@
1
+ Metadata-Version: 2.5
2
+ Name: google-adk-withruntime
3
+ Version: 0.1.0
4
+ Summary: Runtime sandboxes for Google ADK: a code executor and a sandbox toolset in a Firecracker microVM
5
+ Project-URL: Homepage, https://withruntime.com
6
+ Project-URL: Documentation, https://withruntime.com/docs/frameworks#google-adk
7
+ Project-URL: Repository, https://github.com/withruntime/runtime/tree/main/integrations/google-adk
8
+ Author: Runtime LLC
9
+ License: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: adk,agent development kit,ai agents,code execution,code executor,firecracker,google adk,google-adk,microvm,runtime,sandbox
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: <4.0,>=3.10
22
+ Requires-Dist: google-adk>=2.9
23
+ Requires-Dist: withruntime<1.0,>=0.6.1
24
+ Description-Content-Type: text/markdown
25
+
26
+ # google-adk-withruntime
27
+
28
+ [Runtime](https://withruntime.com) sandboxes for
29
+ [Google ADK](https://google.github.io/adk-docs/). Each sandbox is a
30
+ Firecracker microVM with its own Linux kernel. There are two ways to use one:
31
+
32
+ ```bash
33
+ pip install google-adk-withruntime
34
+ npx withruntime login # or set RUNTIME_API_KEY
35
+ ```
36
+
37
+ ```python
38
+ from google.adk.agents import Agent
39
+ from google_adk_withruntime import RuntimeCodeExecutor, RuntimeToolset
40
+
41
+ # The model writes Python blocks; ADK runs them in the sandbox.
42
+ analyst = Agent(model="gemini-flash-latest", name="analyst", code_executor=RuntimeCodeExecutor())
43
+
44
+ # The model calls shell and file tools in the sandbox.
45
+ coder = Agent(model="gemini-flash-latest", name="coder", tools=[RuntimeToolset()])
46
+ ```
47
+
48
+ - **`RuntimeCodeExecutor`** is an ADK code executor, like
49
+ `ContainerCodeExecutor` or `GkeCodeExecutor`, with no Docker daemon or
50
+ cluster to run. Every block of one executor runs in the same sandbox, each
51
+ in a new `python3` process in `/workspace`, so files carry over. A block
52
+ past `timeout_seconds` (300 by default) is killed and reports exit code 124.
53
+ `create={...}` sets the sandbox (`vcpu`, `memory_mib`, `image`, `network`),
54
+ and `sandbox_id=` runs in one you own.
55
+ - **`RuntimeToolset`** gives the model `runtime_exec`, `runtime_read_file`,
56
+ `runtime_write_file` and `runtime_list_files`. It starts its sandbox on
57
+ first use and stops it when the runner closes it. Pass an `AsyncSandbox` to
58
+ use one you own instead; it is never stopped for you.
59
+
60
+ Both give their own sandbox a 30-minute lease that ends in a stop, so a
61
+ crashed process leaves nothing running. The executor keeps that lease
62
+ extended while it is open.
63
+
64
+ ## Tests
65
+
66
+ `tests/` runs both against fake clients;
67
+ `uv run --resolution lowest-direct --group test pytest` runs them at the lowest
68
+ versions `pyproject.toml` allows. `scripts/e2e.py` runs both through
69
+ ADK's own `Runner`, driven by a scripted model, against the real API with
70
+ `RUNTIME_API_KEY` set. It passed on 25 September 2026 with google-adk 2.10.0:
71
+ ADK ran the model's block in a sandbox, `runtime_exec` ran through function
72
+ calling, and both sandboxes were stopped.
@@ -0,0 +1,47 @@
1
+ # google-adk-withruntime
2
+
3
+ [Runtime](https://withruntime.com) sandboxes for
4
+ [Google ADK](https://google.github.io/adk-docs/). Each sandbox is a
5
+ Firecracker microVM with its own Linux kernel. There are two ways to use one:
6
+
7
+ ```bash
8
+ pip install google-adk-withruntime
9
+ npx withruntime login # or set RUNTIME_API_KEY
10
+ ```
11
+
12
+ ```python
13
+ from google.adk.agents import Agent
14
+ from google_adk_withruntime import RuntimeCodeExecutor, RuntimeToolset
15
+
16
+ # The model writes Python blocks; ADK runs them in the sandbox.
17
+ analyst = Agent(model="gemini-flash-latest", name="analyst", code_executor=RuntimeCodeExecutor())
18
+
19
+ # The model calls shell and file tools in the sandbox.
20
+ coder = Agent(model="gemini-flash-latest", name="coder", tools=[RuntimeToolset()])
21
+ ```
22
+
23
+ - **`RuntimeCodeExecutor`** is an ADK code executor, like
24
+ `ContainerCodeExecutor` or `GkeCodeExecutor`, with no Docker daemon or
25
+ cluster to run. Every block of one executor runs in the same sandbox, each
26
+ in a new `python3` process in `/workspace`, so files carry over. A block
27
+ past `timeout_seconds` (300 by default) is killed and reports exit code 124.
28
+ `create={...}` sets the sandbox (`vcpu`, `memory_mib`, `image`, `network`),
29
+ and `sandbox_id=` runs in one you own.
30
+ - **`RuntimeToolset`** gives the model `runtime_exec`, `runtime_read_file`,
31
+ `runtime_write_file` and `runtime_list_files`. It starts its sandbox on
32
+ first use and stops it when the runner closes it. Pass an `AsyncSandbox` to
33
+ use one you own instead; it is never stopped for you.
34
+
35
+ Both give their own sandbox a 30-minute lease that ends in a stop, so a
36
+ crashed process leaves nothing running. The executor keeps that lease
37
+ extended while it is open.
38
+
39
+ ## Tests
40
+
41
+ `tests/` runs both against fake clients;
42
+ `uv run --resolution lowest-direct --group test pytest` runs them at the lowest
43
+ versions `pyproject.toml` allows. `scripts/e2e.py` runs both through
44
+ ADK's own `Runner`, driven by a scripted model, against the real API with
45
+ `RUNTIME_API_KEY` set. It passed on 25 September 2026 with google-adk 2.10.0:
46
+ ADK ran the model's block in a sandbox, `runtime_exec` ran through function
47
+ calling, and both sandboxes were stopped.
@@ -0,0 +1,220 @@
1
+ """Runtime sandboxes for Google ADK.
2
+
3
+ Two ways in, both running in a Runtime sandbox (a Firecracker microVM):
4
+
5
+ from google.adk.agents import Agent
6
+ from google_adk_withruntime import RuntimeCodeExecutor, RuntimeToolset
7
+
8
+ # The model writes Python blocks; ADK runs them in the sandbox.
9
+ analyst = Agent(model="gemini-flash-latest", name="analyst", code_executor=RuntimeCodeExecutor())
10
+
11
+ # The model calls shell and file tools in the sandbox.
12
+ coder = Agent(model="gemini-flash-latest", name="coder", tools=[RuntimeToolset()])
13
+
14
+ The sandbox starts on first use and stops when the executor or toolset is
15
+ closed (``Runner.close()`` closes toolsets), or at the end of its lease if the
16
+ process dies first. Garbage collection also stops the executor's sandbox. The key comes
17
+ from ``RUNTIME_API_KEY`` or this machine's ``withruntime login``.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import asyncio
23
+ import logging
24
+ import weakref
25
+ from typing import Any
26
+
27
+ from google.adk.agents.readonly_context import ReadonlyContext
28
+ from google.adk.code_executors.base_code_executor import BaseCodeExecutor
29
+ from google.adk.code_executors.code_execution_utils import CodeExecutionInput, CodeExecutionResult
30
+ from google.adk.tools import BaseTool, FunctionTool
31
+ from google.adk.tools.base_toolset import BaseToolset
32
+ from pydantic import Field, PrivateAttr
33
+ from withruntime import AsyncRuntime, AsyncSandbox, Runtime, Sandbox
34
+ from withruntime.tools import DEFAULT_MAX_OUTPUT_CHARS, DEFAULT_TIMEOUT_SECONDS, WORKSPACE, sandbox_tools
35
+
36
+ __all__ = ["RuntimeCodeExecutor", "RuntimeToolset"]
37
+ __version__ = "0.1.0"
38
+
39
+ logger = logging.getLogger("google_adk_withruntime")
40
+
41
+ _TIMEOUT_EXIT_CODE = 124
42
+ _LEASE_SECONDS = 1800
43
+
44
+
45
+ def _create_fields(create: dict[str, Any], created_by: str) -> dict[str, Any]:
46
+ fields = {"timeout_seconds": _LEASE_SECONDS, "on_lease_end": "stop", **create}
47
+ fields["labels"] = {"created_by": created_by, **(fields.get("labels") or {})}
48
+ return fields
49
+
50
+
51
+ def _shell_exit_code(code: int | None, timed_out: bool) -> int | None:
52
+ """Runtime gives a command a signal ended as the negative signal number; a shell says 128 + n."""
53
+ if timed_out:
54
+ return _TIMEOUT_EXIT_CODE
55
+ if code is None:
56
+ return None
57
+ return 128 - code if code < 0 else code
58
+
59
+
60
+ def _stop_quietly(sandbox: Any) -> None:
61
+ try:
62
+ sandbox.stop(wait=False)
63
+ except Exception as error: # noqa: BLE001 - a finalizer must not raise; the lease stops it anyway
64
+ logger.warning("Runtime: could not stop sandbox %s: %s", sandbox.id, error)
65
+
66
+
67
+ class RuntimeCodeExecutor(BaseCodeExecutor):
68
+ """Runs the model's Python code blocks in a Runtime sandbox.
69
+
70
+ One sandbox serves every execution of this executor, so files written by
71
+ one block (and input files) are there for the next; each block runs in a
72
+ fresh ``python3`` process in ``/workspace``.
73
+
74
+ Attributes:
75
+ create: Fields for ``Runtime.sandboxes.create``, such as ``{"vcpu": 2}``
76
+ or ``{"image": "my-image:v1"}``. A 30-minute lease that ends in a
77
+ stop applies unless ``timeout_seconds`` is given there, and the lease
78
+ is kept ahead while the executor is open.
79
+ sandbox_id: Run in this existing sandbox instead. It is never stopped.
80
+ timeout_seconds: Wall-clock limit for one code block; it is killed
81
+ after it and reports exit code 124.
82
+ """
83
+
84
+ create: dict[str, Any] = Field(default_factory=dict)
85
+ sandbox_id: str | None = None
86
+ timeout_seconds: int = Field(default=300, gt=0)
87
+ stateful: bool = Field(default=False, frozen=True, exclude=True)
88
+ optimize_data_file: bool = Field(default=False, frozen=True, exclude=True)
89
+
90
+ _runtime: Runtime | None = PrivateAttr(default=None)
91
+ _sandbox: Sandbox | None = PrivateAttr(default=None)
92
+ _finalizer: weakref.finalize | None = PrivateAttr(default=None)
93
+
94
+ def __init__(self, *, runtime: Runtime | None = None, **data: Any) -> None:
95
+ if data.get("stateful"):
96
+ raise ValueError("RuntimeCodeExecutor runs each block in a new process; stateful=True is not supported.")
97
+ if data.get("optimize_data_file"):
98
+ raise ValueError("RuntimeCodeExecutor does not support optimize_data_file=True.")
99
+ super().__init__(**data)
100
+ self._runtime = runtime
101
+
102
+ @property
103
+ def sandbox(self) -> Sandbox:
104
+ """The sandbox, started on first use."""
105
+ if self._sandbox is None:
106
+ self._runtime = self._runtime or Runtime()
107
+ if self.sandbox_id:
108
+ self._sandbox = self._runtime.sandboxes.get(self.sandbox_id)
109
+ else:
110
+ self._sandbox = self._runtime.sandboxes.create(**_create_fields(self.create, "google-adk"))
111
+ self._sandbox.keep_alive(margin_seconds=600)
112
+ self._finalizer = weakref.finalize(self, _stop_quietly, self._sandbox)
113
+ return self._sandbox
114
+
115
+ def execute_code(
116
+ self,
117
+ invocation_context: Any,
118
+ code_execution_input: CodeExecutionInput,
119
+ ) -> CodeExecutionResult:
120
+ try:
121
+ sandbox = self.sandbox
122
+ for file in code_execution_input.input_files:
123
+ path = file.name if file.name.startswith("/") else f"{WORKSPACE}/{file.name}"
124
+ sandbox.files.write(path, file.content)
125
+ result = sandbox.exec(
126
+ ["python3", "-c", code_execution_input.code],
127
+ cwd=WORKSPACE,
128
+ timeout_ms=self.timeout_seconds * 1000,
129
+ )
130
+ except Exception as error: # noqa: BLE001 - reported to the model, as other executors do
131
+ return CodeExecutionResult(stderr=f"Runtime sandbox error: {error}")
132
+ stderr = result.stderr
133
+ if result.timed_out:
134
+ note = f"Timed out: the code ran past {self.timeout_seconds} seconds and was killed.\n"
135
+ stderr = f"{stderr}{'' if not stderr or stderr.endswith(chr(10)) else chr(10)}{note}"
136
+ return CodeExecutionResult(
137
+ stdout=result.stdout, stderr=stderr, exit_code=_shell_exit_code(result.exit_code, result.timed_out)
138
+ )
139
+
140
+ def close(self) -> None:
141
+ """Stops the sandbox this executor started. Safe to call twice."""
142
+ if self._finalizer is not None:
143
+ self._finalizer()
144
+ self._finalizer = None
145
+ self._sandbox = None
146
+
147
+
148
+ class RuntimeToolset(BaseToolset):
149
+ """``runtime_exec``, ``runtime_read_file``, ``runtime_write_file`` and
150
+ ``runtime_list_files`` as ADK tools, bound to one Runtime sandbox.
151
+
152
+ Args:
153
+ sandbox: An ``AsyncSandbox`` you created and own; it is never stopped.
154
+ create: Fields for ``AsyncRuntime.sandboxes.create`` when the toolset
155
+ makes its own sandbox, on the first ``get_tools``. A 30-minute lease
156
+ that ends in a stop applies unless you set ``timeout_seconds``.
157
+ runtime: The client to create it with. Default: ``AsyncRuntime()``.
158
+ root, timeout_seconds, max_output_chars: as for ``withruntime.tools``.
159
+ tool_filter, tool_name_prefix: as for any ADK toolset.
160
+ """
161
+
162
+ def __init__(
163
+ self,
164
+ sandbox: AsyncSandbox | None = None,
165
+ *,
166
+ create: dict[str, Any] | None = None,
167
+ runtime: AsyncRuntime | None = None,
168
+ root: str = WORKSPACE,
169
+ timeout_seconds: int = DEFAULT_TIMEOUT_SECONDS,
170
+ max_output_chars: int = DEFAULT_MAX_OUTPUT_CHARS,
171
+ tool_filter: Any = None,
172
+ tool_name_prefix: str | None = None,
173
+ ) -> None:
174
+ super().__init__(tool_filter=tool_filter, tool_name_prefix=tool_name_prefix)
175
+ self._sandbox = sandbox
176
+ self._owned = sandbox is None
177
+ self._create = dict(create or {})
178
+ self._runtime = runtime
179
+ self._client: AsyncRuntime | None = None
180
+ self._options = {"root": root, "timeout_seconds": timeout_seconds, "max_output_chars": max_output_chars}
181
+ self._tools: list[BaseTool] | None = None
182
+ self._lock = asyncio.Lock()
183
+
184
+ @property
185
+ def sandbox(self) -> AsyncSandbox | None:
186
+ return self._sandbox
187
+
188
+ async def get_tools(self, readonly_context: ReadonlyContext | None = None) -> list[BaseTool]:
189
+ async with self._lock:
190
+ if self._tools is None:
191
+ try:
192
+ if self._sandbox is None:
193
+ if self._runtime is None:
194
+ self._client = AsyncRuntime()
195
+ client = self._runtime or self._client
196
+ self._sandbox = await client.sandboxes.create(**_create_fields(self._create, "google-adk"))
197
+ self._tools = [FunctionTool(f) for f in sandbox_tools(self._sandbox, **self._options)]
198
+ except BaseException:
199
+ try:
200
+ await self._close_owned()
201
+ except Exception as error: # noqa: BLE001 - preserve the initialization failure
202
+ logger.warning("Runtime: could not clean up failed toolset initialization: %s", error)
203
+ raise
204
+ return [tool for tool in self._tools if self._is_tool_selected(tool, readonly_context)]
205
+
206
+ async def close(self) -> None:
207
+ async with self._lock:
208
+ await self._close_owned()
209
+
210
+ async def _close_owned(self) -> None:
211
+ sandbox, self._tools = self._sandbox, None
212
+ if self._owned:
213
+ self._sandbox = None
214
+ try:
215
+ if self._owned and sandbox is not None:
216
+ await sandbox.stop()
217
+ finally:
218
+ client, self._client = self._client, None
219
+ if client is not None:
220
+ await client.close()
@@ -0,0 +1,51 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "google-adk-withruntime"
7
+ version = "0.1.0"
8
+ description = "Runtime sandboxes for Google ADK: a code executor and a sandbox toolset in a Firecracker microVM"
9
+ readme = "README.md"
10
+ license = { text = "Apache-2.0" }
11
+ authors = [{ name = "Runtime LLC" }]
12
+ keywords = ["google adk", "google-adk", "adk", "agent development kit", "code executor", "sandbox", "ai agents", "code execution", "firecracker", "microvm", "runtime"]
13
+ classifiers = [
14
+ "Intended Audience :: Developers",
15
+ "License :: OSI Approved :: Apache Software License",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3.10",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Programming Language :: Python :: 3.13",
21
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
22
+ "Typing :: Typed",
23
+ ]
24
+ requires-python = ">=3.10,<4.0"
25
+ dependencies = [
26
+ # CodeExecutionResult.exit_code.
27
+ "google-adk>=2.9",
28
+ "withruntime>=0.6.1,<1.0",
29
+ ]
30
+
31
+ [project.urls]
32
+ Homepage = "https://withruntime.com"
33
+ Documentation = "https://withruntime.com/docs/frameworks#google-adk"
34
+ Repository = "https://github.com/withruntime/runtime/tree/main/integrations/google-adk"
35
+
36
+ [dependency-groups]
37
+ test = ["pytest>=8", "pytest-asyncio>=1.0.0"]
38
+
39
+ [tool.hatch.build.targets.wheel]
40
+ packages = ["google_adk_withruntime"]
41
+
42
+ [tool.hatch.build.targets.sdist]
43
+ include = ["google_adk_withruntime", "tests", "scripts", "README.md", "LICENSE"]
44
+
45
+ [tool.pytest.ini_options]
46
+ addopts = "--strict-markers --strict-config"
47
+ testpaths = ["tests"]
48
+ asyncio_mode = "auto"
49
+
50
+ [tool.ruff]
51
+ line-length = 120
@@ -0,0 +1,108 @@
1
+ """End to end, against the real API: RuntimeCodeExecutor and RuntimeToolset in
2
+ ADK's own Runner, driven by a scripted model (a BaseLlm), so no model is called.
3
+
4
+ RUNTIME_API_KEY=... python scripts/e2e.py
5
+
6
+ 1. An agent with code_executor=RuntimeCodeExecutor(): the model answers with a
7
+ Python block, ADK runs it in the sandbox and feeds the output back.
8
+ 2. An agent with tools=[RuntimeToolset()]: the model calls runtime_exec.
9
+ Each makes one trial sandbox with a ten-minute lease, stopped at the end.
10
+ Then checks that nothing labelled with this run is still running."""
11
+
12
+ import asyncio
13
+ import os
14
+ import sys
15
+ import uuid
16
+ from collections.abc import AsyncGenerator
17
+
18
+ from google.adk.agents import Agent
19
+ from google.adk.models.base_llm import BaseLlm
20
+ from google.adk.models.llm_request import LlmRequest
21
+ from google.adk.models.llm_response import LlmResponse
22
+ from google.adk.runners import InMemoryRunner
23
+ from google.genai import types
24
+ from withruntime import AsyncRuntime
25
+
26
+ from google_adk_withruntime import RuntimeCodeExecutor, RuntimeToolset
27
+
28
+
29
+ class Scripted(BaseLlm):
30
+ """Replies with each part in `script` in turn, then echoes what came back."""
31
+
32
+ script: list
33
+
34
+ async def generate_content_async(
35
+ self, llm_request: LlmRequest, stream: bool = False
36
+ ) -> AsyncGenerator[LlmResponse, None]:
37
+ turns = sum(1 for c in llm_request.contents if c.role == "model")
38
+ if turns < len(self.script):
39
+ part = self.script[turns]
40
+ else:
41
+ last = llm_request.contents[-1]
42
+ part = types.Part(
43
+ text="DONE "
44
+ + " | ".join(str(p.text or p.function_response or p.code_execution_result) for p in last.parts)
45
+ )
46
+ yield LlmResponse(content=types.Content(role="model", parts=[part]))
47
+
48
+
49
+ async def ask(agent: Agent) -> str:
50
+ runner = InMemoryRunner(agent=agent, app_name="e2e")
51
+ session = await runner.session_service.create_session(app_name="e2e", user_id="u")
52
+ text = []
53
+ try:
54
+ async for event in runner.run_async(
55
+ user_id="u", session_id=session.id, new_message=types.Content(role="user", parts=[types.Part(text="go")])
56
+ ):
57
+ for part in event.content.parts if event.content else []:
58
+ text.append(str(part.text or part.code_execution_result or part.function_response or ""))
59
+ finally:
60
+ await runner.close()
61
+ return "\n".join(text)
62
+
63
+
64
+ async def main() -> int:
65
+ if not os.environ.get("RUNTIME_API_KEY"):
66
+ sys.exit("Set RUNTIME_API_KEY to a Runtime key (a test key).")
67
+ run = uuid.uuid4().hex[:8]
68
+ create = {"timeout_seconds": 600, "labels": {"e2e": run}}
69
+ failures = []
70
+
71
+ executor = RuntimeCodeExecutor(create=create, timeout_seconds=60)
72
+ code = "import platform, sys\nprint('kernel', platform.release(), 'python', sys.version_info[:2])"
73
+ analyst = Agent(
74
+ name="analyst",
75
+ model=Scripted(model="scripted", script=[types.Part(text=f"```python\n{code}\n```")]),
76
+ code_executor=executor,
77
+ )
78
+ try:
79
+ out = await ask(analyst)
80
+ finally:
81
+ executor.close()
82
+ ok = "kernel" in out and "python (3," in out
83
+ print(f"{'ok ' if ok else 'FAIL'} code executor: ADK ran the model's block in the sandbox", flush=True)
84
+ if not ok:
85
+ failures.append(out[:500])
86
+
87
+ call = types.Part(function_call=types.FunctionCall(name="runtime_exec", args={"command": "uname -sr && id -un"}))
88
+ coder = Agent(name="coder", model=Scripted(model="scripted", script=[call]), tools=[RuntimeToolset(create=create)])
89
+ out = await ask(coder)
90
+ ok = "Linux" in out and "exit_code" in out
91
+ print(f"{'ok ' if ok else 'FAIL'} toolset: runtime_exec ran through ADK's function calling", flush=True)
92
+ if not ok:
93
+ failures.append(out[:500])
94
+
95
+ async with AsyncRuntime() as runtime:
96
+ made = await (await runtime.sandboxes.list(labels={"e2e": run}, include_stopped=True)).to_list()
97
+ left = await (await runtime.sandboxes.list(labels={"e2e": run})).to_list()
98
+ left = [s for s in left if s.state not in ("stopped", "stopping")]
99
+ print(f"{'ok ' if len(made) == 2 else 'FAIL'} two sandboxes were made: {len(made)}")
100
+ print(f"{'ok ' if not left else 'FAIL'} none still running: {[s.id for s in left]}")
101
+ if len(made) != 2 or left:
102
+ failures.append("sandboxes")
103
+ print("All checks passed." if not failures else f"Failed: {failures}")
104
+ return 1 if failures else 0
105
+
106
+
107
+ if __name__ == "__main__":
108
+ sys.exit(asyncio.run(main()))
@@ -0,0 +1,239 @@
1
+ """The executor and the toolset against fake Runtime clients; nothing leaves the machine."""
2
+
3
+ import asyncio
4
+ import gc
5
+
6
+ import pytest
7
+ from google.adk.code_executors.code_execution_utils import CodeExecutionInput, File
8
+ from withruntime import CommandResult
9
+
10
+ from google_adk_withruntime import RuntimeCodeExecutor, RuntimeToolset
11
+
12
+
13
+ class FakeFiles:
14
+ def __init__(self):
15
+ self.data = {}
16
+
17
+ def write(self, path, content):
18
+ self.data[path] = content
19
+
20
+
21
+ class FakeSandbox:
22
+ def __init__(self, fields, result):
23
+ self.id, self.fields, self.result = "sbx_1", fields, result
24
+ self.files, self.commands, self.stopped, self.kept_alive = FakeFiles(), [], False, None
25
+
26
+ def exec(self, command, **options):
27
+ self.commands.append((command, options))
28
+ if isinstance(self.result, Exception):
29
+ raise self.result
30
+ return self.result
31
+
32
+ def keep_alive(self, margin_seconds=600, **_):
33
+ self.kept_alive = margin_seconds
34
+
35
+ def stop(self, wait=True):
36
+ self.stopped = True
37
+
38
+
39
+ class FakeRuntime:
40
+ def __init__(self, result=None):
41
+ self.sandboxes, self.made, self.got = self, [], []
42
+ self.result = result or CommandResult(exit_code=0, stdout="4\n", stderr="")
43
+
44
+ def create(self, **fields):
45
+ self.made.append(FakeSandbox(fields, self.result))
46
+ return self.made[-1]
47
+
48
+ def get(self, sandbox_id):
49
+ self.got.append(sandbox_id)
50
+ return FakeSandbox({"id": sandbox_id}, self.result)
51
+
52
+
53
+ def run(executor, code, files=()):
54
+ return executor.execute_code(None, CodeExecutionInput(code=code, input_files=list(files)))
55
+
56
+
57
+ def test_runs_each_block_with_python3_in_one_lazily_started_sandbox():
58
+ runtime = FakeRuntime()
59
+ executor = RuntimeCodeExecutor(runtime=runtime, create={"vcpu": 2}, timeout_seconds=30)
60
+ assert runtime.made == []
61
+ first = run(executor, "print(2 + 2)", [File(name="data.csv", content="a,b\n1,2\n")])
62
+ run(executor, "print('again')")
63
+ sandbox = runtime.made[0]
64
+ assert len(runtime.made) == 1
65
+ assert (first.stdout, first.stderr, first.exit_code) == ("4\n", "", 0)
66
+ assert sandbox.commands[0] == (["python3", "-c", "print(2 + 2)"], {"cwd": "/workspace", "timeout_ms": 30_000})
67
+ assert sandbox.files.data == {"/workspace/data.csv": "a,b\n1,2\n"}
68
+ assert sandbox.fields["vcpu"] == 2 and sandbox.fields["on_lease_end"] == "stop"
69
+ assert sandbox.fields["timeout_seconds"] == 1800 and sandbox.fields["labels"] == {"created_by": "google-adk"}
70
+ assert sandbox.kept_alive == 600
71
+ executor.close()
72
+ executor.close()
73
+ assert sandbox.stopped
74
+
75
+
76
+ def test_timeout_is_124_with_a_note_and_a_signal_is_128_plus_n():
77
+ runtime = FakeRuntime(CommandResult(exit_code=-9, stdout="partial", stderr="", timed_out=True))
78
+ result = run(RuntimeCodeExecutor(runtime=runtime, timeout_seconds=5), "while True: pass")
79
+ assert result.exit_code == 124 and result.stdout == "partial"
80
+ assert "ran past 5 seconds" in result.stderr
81
+ runtime = FakeRuntime(CommandResult(exit_code=-15, stdout="", stderr=""))
82
+ assert run(RuntimeCodeExecutor(runtime=runtime), "import os; os.kill(os.getpid(), 15)").exit_code == 143
83
+
84
+
85
+ def test_an_api_error_is_reported_to_the_model_not_raised():
86
+ runtime = FakeRuntime(ConnectionError("reset"))
87
+ result = run(RuntimeCodeExecutor(runtime=runtime), "print(1)")
88
+ assert "reset" in result.stderr and result.exit_code is None
89
+
90
+
91
+ def test_an_existing_sandbox_is_used_and_never_stopped():
92
+ runtime = FakeRuntime()
93
+ executor = RuntimeCodeExecutor(runtime=runtime, sandbox_id="sbx_mine")
94
+ run(executor, "print(1)")
95
+ executor.close()
96
+ assert runtime.got == ["sbx_mine"] and runtime.made == []
97
+
98
+
99
+ def test_garbage_collection_stops_the_sandbox():
100
+ runtime = FakeRuntime()
101
+ executor = RuntimeCodeExecutor(runtime=runtime)
102
+ run(executor, "print(1)")
103
+ sandbox = runtime.made[0]
104
+ del executor
105
+ gc.collect()
106
+ assert sandbox.stopped
107
+
108
+
109
+ def test_stateful_is_refused():
110
+ with pytest.raises(ValueError, match="stateful"):
111
+ RuntimeCodeExecutor(stateful=True)
112
+
113
+
114
+ class FakeAsyncSandbox:
115
+ def __init__(self, fields):
116
+ self.id, self.fields, self.stopped = "sbx_async", fields, False
117
+
118
+ async def exec(self, command, **options):
119
+ return CommandResult(exit_code=0, stdout=f"ran {command}\n", stderr="")
120
+
121
+ async def stop(self, **_):
122
+ self.stopped = True
123
+
124
+
125
+ class FakeAsyncRuntime:
126
+ def __init__(self):
127
+ self.sandboxes, self.made = self, []
128
+
129
+ async def create(self, **fields):
130
+ self.made.append(FakeAsyncSandbox(fields))
131
+ return self.made[-1]
132
+
133
+
134
+ async def test_toolset_starts_one_sandbox_gives_four_tools_and_stops_on_close():
135
+ runtime = FakeAsyncRuntime()
136
+ toolset = RuntimeToolset(runtime=runtime, create={"memory_mib": 2048})
137
+ tools = await toolset.get_tools()
138
+ await toolset.get_tools()
139
+ assert [t.name for t in tools] == ["runtime_exec", "runtime_read_file", "runtime_write_file", "runtime_list_files"]
140
+ assert len(runtime.made) == 1 and runtime.made[0].fields["memory_mib"] == 2048
141
+ result = await tools[0].run_async(args={"command": "ls"}, tool_context=None)
142
+ assert result["stdout"] == "ran ls\n" and result["exit_code"] == 0
143
+ await toolset.close()
144
+ assert runtime.made[0].stopped and toolset.sandbox is None
145
+
146
+
147
+ async def test_toolset_filter_and_a_sandbox_you_own():
148
+ sandbox = FakeAsyncSandbox({})
149
+ toolset = RuntimeToolset(sandbox, tool_filter=["runtime_exec"])
150
+ assert [t.name for t in await toolset.get_tools()] == ["runtime_exec"]
151
+ await toolset.close()
152
+ assert not sandbox.stopped and toolset.sandbox is sandbox
153
+
154
+
155
+ async def test_concurrent_tool_requests_share_one_created_sandbox():
156
+ class SlowRuntime(FakeAsyncRuntime):
157
+ async def create(self, **fields):
158
+ await asyncio.sleep(0)
159
+ return await super().create(**fields)
160
+
161
+ runtime = SlowRuntime()
162
+ toolset = RuntimeToolset(runtime=runtime)
163
+ first, second = await asyncio.gather(toolset.get_tools(), toolset.get_tools())
164
+ assert len(runtime.made) == 1
165
+ assert first == second
166
+ await toolset.close()
167
+ assert all(sandbox.stopped for sandbox in runtime.made)
168
+
169
+
170
+ async def test_close_waits_for_creation_and_stops_its_sandbox():
171
+ started, release = asyncio.Event(), asyncio.Event()
172
+
173
+ class SlowRuntime(FakeAsyncRuntime):
174
+ async def create(self, **fields):
175
+ started.set()
176
+ await release.wait()
177
+ return await super().create(**fields)
178
+
179
+ runtime = SlowRuntime()
180
+ toolset = RuntimeToolset(runtime=runtime)
181
+ request = asyncio.create_task(toolset.get_tools())
182
+ await started.wait()
183
+ closing = asyncio.create_task(toolset.close())
184
+ release.set()
185
+ await asyncio.gather(request, closing)
186
+ assert len(runtime.made) == 1 and runtime.made[0].stopped
187
+ assert toolset.sandbox is None
188
+
189
+
190
+ async def test_failed_binding_stops_the_guest_and_closes_its_owned_client(monkeypatch):
191
+ import google_adk_withruntime as adapter
192
+
193
+ class OwnedRuntime(FakeAsyncRuntime):
194
+ closed = False
195
+
196
+ async def close(self):
197
+ self.closed = True
198
+
199
+ runtime = OwnedRuntime()
200
+ monkeypatch.setattr(adapter, "AsyncRuntime", lambda: runtime)
201
+
202
+ def fail_binding(*args, **kwargs):
203
+ raise ValueError("bad binding")
204
+
205
+ monkeypatch.setattr(adapter, "sandbox_tools", fail_binding)
206
+ toolset = RuntimeToolset()
207
+ with pytest.raises(ValueError, match="bad binding"):
208
+ await toolset.get_tools()
209
+ assert runtime.made[0].stopped and runtime.closed
210
+ assert toolset.sandbox is None
211
+
212
+
213
+ async def test_failed_binding_does_not_stop_a_borrowed_guest(monkeypatch):
214
+ import google_adk_withruntime as adapter
215
+
216
+ def fail_binding(*args, **kwargs):
217
+ raise ValueError("bad binding")
218
+
219
+ monkeypatch.setattr(adapter, "sandbox_tools", fail_binding)
220
+ sandbox = FakeAsyncSandbox({})
221
+ toolset = RuntimeToolset(sandbox)
222
+ with pytest.raises(ValueError, match="bad binding"):
223
+ await toolset.get_tools()
224
+ assert not sandbox.stopped and toolset.sandbox is sandbox
225
+
226
+
227
+ def test_failed_input_upload_is_reported_to_the_model():
228
+ runtime = FakeRuntime()
229
+ executor = RuntimeCodeExecutor(runtime=runtime)
230
+ sandbox = executor.sandbox
231
+
232
+ def fail_write(*args):
233
+ raise ConnectionError("input upload reset")
234
+
235
+ sandbox.files.write = fail_write
236
+ result = run(executor, "print(1)", [File(name="input.txt", content="data")])
237
+ assert "input upload reset" in result.stderr and result.exit_code is None
238
+ assert sandbox.commands == []
239
+ executor.close()