google-adk-withruntime 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.
@@ -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()
File without changes
@@ -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,6 @@
1
+ google_adk_withruntime/__init__.py,sha256=wpayqLkWy7bhHBuyRN74WiiwzmylQqZEQ19ylXU9t8w,9586
2
+ google_adk_withruntime/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ google_adk_withruntime-0.1.0.dist-info/METADATA,sha256=6J_W2wbtodEdaDhbdXQEtbbcF6OsX1xkS6w76q-nEik,3338
4
+ google_adk_withruntime-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
5
+ google_adk_withruntime-0.1.0.dist-info/licenses/LICENSE,sha256=p9AL_VRSW8aUtuMvZMfrz15reuNle-XMEnZ7znRlSkc,9197
6
+ google_adk_withruntime-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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