lizard-adk 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.
- lizard_adk-0.1.0/.gitignore +15 -0
- lizard_adk-0.1.0/LICENSE +203 -0
- lizard_adk-0.1.0/PKG-INFO +86 -0
- lizard_adk-0.1.0/README.md +62 -0
- lizard_adk-0.1.0/examples/agent.py +46 -0
- lizard_adk-0.1.0/pyproject.toml +39 -0
- lizard_adk-0.1.0/src/lizard_adk/__init__.py +5 -0
- lizard_adk-0.1.0/src/lizard_adk/plugin.py +180 -0
- lizard_adk-0.1.0/src/lizard_adk/py.typed +1 -0
- lizard_adk-0.1.0/tests/test_live.py +83 -0
- lizard_adk-0.1.0/tests/test_plugin.py +159 -0
lizard_adk-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 Lizard
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
203
|
+
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: lizard-adk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: ADK tools and lifecycle hooks for Lizard Sandboxes.
|
|
5
|
+
Project-URL: Homepage, https://lizard.build/sandboxes
|
|
6
|
+
Project-URL: Repository, https://github.com/lizard-build/integrations
|
|
7
|
+
Project-URL: Issues, https://github.com/lizard-build/integrations/issues
|
|
8
|
+
Author: Lizard
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Requires-Python: >=3.11
|
|
12
|
+
Requires-Dist: anyio<5,>=4
|
|
13
|
+
Requires-Dist: google-adk<3,>=2.12.0
|
|
14
|
+
Requires-Dist: lizard-sdk<0.2,>=0.1.60
|
|
15
|
+
Provides-Extra: dev
|
|
16
|
+
Requires-Dist: build; extra == 'dev'
|
|
17
|
+
Requires-Dist: mypy>=1.14; extra == 'dev'
|
|
18
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
|
|
19
|
+
Requires-Dist: pytest-socket>=0.7; extra == 'dev'
|
|
20
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
21
|
+
Requires-Dist: ruff>=0.9; extra == 'dev'
|
|
22
|
+
Requires-Dist: twine; extra == 'dev'
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# lizard-adk
|
|
26
|
+
|
|
27
|
+
Lizard (lizard.build) connects ADK agents to Lizard Sandboxes. The plugin supplies four tools and releases each sandbox when its ADK invocation ends.
|
|
28
|
+
|
|
29
|
+
## Install
|
|
30
|
+
|
|
31
|
+
Requires Python 3.11+, ADK 2.12+, a Lizard project, and a project API key. The first PyPI release is pending. Install from source:
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
pip install 'lizard-adk @ git+https://github.com/lizard-build/integrations.git#subdirectory=packages/lizard-adk'
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Set `LIZARD_API_KEY` and `LIZARD_PROJECT_ID`. The [agent example](examples/agent.py) also needs `GOOGLE_API_KEY` for Gemini.
|
|
38
|
+
|
|
39
|
+
## Use
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from google.adk.agents import Agent
|
|
43
|
+
from google.adk.apps import App
|
|
44
|
+
from google.adk.runners import InMemoryRunner
|
|
45
|
+
from lizard_adk import LizardPlugin
|
|
46
|
+
|
|
47
|
+
plugin = LizardPlugin()
|
|
48
|
+
root_agent = Agent(
|
|
49
|
+
name="sandbox_agent",
|
|
50
|
+
model="gemini-flash-latest",
|
|
51
|
+
tools=plugin.get_tools(),
|
|
52
|
+
)
|
|
53
|
+
runner = InMemoryRunner(
|
|
54
|
+
app=App(name="sandbox_example", root_agent=root_agent, plugins=[plugin]),
|
|
55
|
+
plugin_close_timeout=120,
|
|
56
|
+
)
|
|
57
|
+
# Run the agent, then always await runner.close() in a finally block.
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Register the plugin in both places: `get_tools()` exposes the tools, and `App.plugins` runs cleanup. See [the complete example](examples/agent.py) for session creation, a prompt, and cleanup.
|
|
61
|
+
|
|
62
|
+
| Tool | Result |
|
|
63
|
+
| --- | --- |
|
|
64
|
+
| `lizard_execute_command` | Shell stdout, stderr, and exit code |
|
|
65
|
+
| `lizard_execute_code` | Python output, display results, and a structured error |
|
|
66
|
+
| `lizard_read_file` | UTF-8 text, up to 1 MiB |
|
|
67
|
+
| `lizard_write_file` | Write UTF-8 text, up to 1 MiB |
|
|
68
|
+
|
|
69
|
+
Python variables and files persist across calls within one invocation. A later user message starts a new invocation and gets a fresh sandbox. The host keeps the Lizard API key; it does not put it in session state or tool results.
|
|
70
|
+
|
|
71
|
+
## Options and limits
|
|
72
|
+
|
|
73
|
+
Pass `project_id`, `api_key`, `api_url`, `size`, `lifetime_ms`, or `command_timeout_ms` to `LizardPlugin`. Defaults are the small interpreter template, a 15-minute lifetime, and a 60-second command timeout. The maximum command timeout is 120 seconds. The command tool defaults to `/home/user`.
|
|
74
|
+
|
|
75
|
+
Shell output follows the Lizard SDK response limits. Use files for larger results. This plugin does not persist a sandbox between invocations or support custom Docker images. Always close the runner after errors or cancelled runs. If cleanup fails, retry `plugin.close()`; it retains the sandbox handle until deletion succeeds.
|
|
76
|
+
|
|
77
|
+
## Checks
|
|
78
|
+
|
|
79
|
+
Unit tests cover schemas, invocation isolation, files, errors, cancellation, and cleanup retries. Cloud tests exercise each tool and a real ADK runner with a scripted model, so they do not call a paid model API.
|
|
80
|
+
|
|
81
|
+
```sh
|
|
82
|
+
pip install -e '.[dev]'
|
|
83
|
+
pytest tests -m 'not live' --disable-socket --allow-unix-socket
|
|
84
|
+
# With Lizard credentials:
|
|
85
|
+
LIZARD_LIVE_TESTS=1 pytest tests -m live
|
|
86
|
+
```
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# lizard-adk
|
|
2
|
+
|
|
3
|
+
Lizard (lizard.build) connects ADK agents to Lizard Sandboxes. The plugin supplies four tools and releases each sandbox when its ADK invocation ends.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
Requires Python 3.11+, ADK 2.12+, a Lizard project, and a project API key. The first PyPI release is pending. Install from source:
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
pip install 'lizard-adk @ git+https://github.com/lizard-build/integrations.git#subdirectory=packages/lizard-adk'
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Set `LIZARD_API_KEY` and `LIZARD_PROJECT_ID`. The [agent example](examples/agent.py) also needs `GOOGLE_API_KEY` for Gemini.
|
|
14
|
+
|
|
15
|
+
## Use
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
from google.adk.agents import Agent
|
|
19
|
+
from google.adk.apps import App
|
|
20
|
+
from google.adk.runners import InMemoryRunner
|
|
21
|
+
from lizard_adk import LizardPlugin
|
|
22
|
+
|
|
23
|
+
plugin = LizardPlugin()
|
|
24
|
+
root_agent = Agent(
|
|
25
|
+
name="sandbox_agent",
|
|
26
|
+
model="gemini-flash-latest",
|
|
27
|
+
tools=plugin.get_tools(),
|
|
28
|
+
)
|
|
29
|
+
runner = InMemoryRunner(
|
|
30
|
+
app=App(name="sandbox_example", root_agent=root_agent, plugins=[plugin]),
|
|
31
|
+
plugin_close_timeout=120,
|
|
32
|
+
)
|
|
33
|
+
# Run the agent, then always await runner.close() in a finally block.
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Register the plugin in both places: `get_tools()` exposes the tools, and `App.plugins` runs cleanup. See [the complete example](examples/agent.py) for session creation, a prompt, and cleanup.
|
|
37
|
+
|
|
38
|
+
| Tool | Result |
|
|
39
|
+
| --- | --- |
|
|
40
|
+
| `lizard_execute_command` | Shell stdout, stderr, and exit code |
|
|
41
|
+
| `lizard_execute_code` | Python output, display results, and a structured error |
|
|
42
|
+
| `lizard_read_file` | UTF-8 text, up to 1 MiB |
|
|
43
|
+
| `lizard_write_file` | Write UTF-8 text, up to 1 MiB |
|
|
44
|
+
|
|
45
|
+
Python variables and files persist across calls within one invocation. A later user message starts a new invocation and gets a fresh sandbox. The host keeps the Lizard API key; it does not put it in session state or tool results.
|
|
46
|
+
|
|
47
|
+
## Options and limits
|
|
48
|
+
|
|
49
|
+
Pass `project_id`, `api_key`, `api_url`, `size`, `lifetime_ms`, or `command_timeout_ms` to `LizardPlugin`. Defaults are the small interpreter template, a 15-minute lifetime, and a 60-second command timeout. The maximum command timeout is 120 seconds. The command tool defaults to `/home/user`.
|
|
50
|
+
|
|
51
|
+
Shell output follows the Lizard SDK response limits. Use files for larger results. This plugin does not persist a sandbox between invocations or support custom Docker images. Always close the runner after errors or cancelled runs. If cleanup fails, retry `plugin.close()`; it retains the sandbox handle until deletion succeeds.
|
|
52
|
+
|
|
53
|
+
## Checks
|
|
54
|
+
|
|
55
|
+
Unit tests cover schemas, invocation isolation, files, errors, cancellation, and cleanup retries. Cloud tests exercise each tool and a real ADK runner with a scripted model, so they do not call a paid model API.
|
|
56
|
+
|
|
57
|
+
```sh
|
|
58
|
+
pip install -e '.[dev]'
|
|
59
|
+
pytest tests -m 'not live' --disable-socket --allow-unix-socket
|
|
60
|
+
# With Lizard credentials:
|
|
61
|
+
LIZARD_LIVE_TESTS=1 pytest tests -m live
|
|
62
|
+
```
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Run with GOOGLE_API_KEY, LIZARD_API_KEY, and LIZARD_PROJECT_ID set."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
|
|
5
|
+
from google.adk.agents import Agent
|
|
6
|
+
from google.adk.apps import App
|
|
7
|
+
from google.adk.runners import InMemoryRunner
|
|
8
|
+
from google.genai import types
|
|
9
|
+
|
|
10
|
+
from lizard_adk import LizardPlugin
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
async def main() -> None:
|
|
14
|
+
plugin = LizardPlugin()
|
|
15
|
+
root_agent = Agent(
|
|
16
|
+
model="gemini-flash-latest",
|
|
17
|
+
name="sandbox_agent",
|
|
18
|
+
instruction="Use the sandbox tools to run Python and check your answer.",
|
|
19
|
+
tools=plugin.get_tools(),
|
|
20
|
+
)
|
|
21
|
+
runner = InMemoryRunner(
|
|
22
|
+
app=App(name="sandbox_example", root_agent=root_agent, plugins=[plugin]),
|
|
23
|
+
plugin_close_timeout=120,
|
|
24
|
+
)
|
|
25
|
+
try:
|
|
26
|
+
session = await runner.session_service.create_session(
|
|
27
|
+
app_name="sandbox_example", user_id="example"
|
|
28
|
+
)
|
|
29
|
+
async for event in runner.run_async(
|
|
30
|
+
user_id="example",
|
|
31
|
+
session_id=session.id,
|
|
32
|
+
new_message=types.Content(
|
|
33
|
+
role="user",
|
|
34
|
+
parts=[types.Part.from_text(text="Use Python to sum the integers from 1 to 100.")],
|
|
35
|
+
),
|
|
36
|
+
):
|
|
37
|
+
if event.content:
|
|
38
|
+
for part in event.content.parts or []:
|
|
39
|
+
if part.text:
|
|
40
|
+
print(part.text)
|
|
41
|
+
finally:
|
|
42
|
+
await runner.close()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
if __name__ == "__main__":
|
|
46
|
+
asyncio.run(main())
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "lizard-adk"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "ADK tools and lifecycle hooks for Lizard Sandboxes."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
authors = [{name = "Lizard"}]
|
|
13
|
+
dependencies = ["lizard-sdk>=0.1.60,<0.2", "anyio>=4,<5", "google-adk>=2.12.0,<3"]
|
|
14
|
+
|
|
15
|
+
[project.urls]
|
|
16
|
+
Homepage = "https://lizard.build/sandboxes"
|
|
17
|
+
Repository = "https://github.com/lizard-build/integrations"
|
|
18
|
+
Issues = "https://github.com/lizard-build/integrations/issues"
|
|
19
|
+
|
|
20
|
+
[project.optional-dependencies]
|
|
21
|
+
dev = ["pytest>=8", "pytest-asyncio>=0.24", "pytest-socket>=0.7", "ruff>=0.9", "mypy>=1.14", "build", "twine"]
|
|
22
|
+
|
|
23
|
+
[tool.hatch.build.targets.wheel]
|
|
24
|
+
packages = ["src/lizard_adk"]
|
|
25
|
+
|
|
26
|
+
[tool.pytest.ini_options]
|
|
27
|
+
asyncio_mode = "auto"
|
|
28
|
+
markers = ["live: creates temporary cloud resources; requires LIZARD_LIVE_TESTS=1"]
|
|
29
|
+
|
|
30
|
+
[tool.ruff]
|
|
31
|
+
line-length = 100
|
|
32
|
+
|
|
33
|
+
[tool.ruff.lint]
|
|
34
|
+
select = ["E", "F", "I"]
|
|
35
|
+
|
|
36
|
+
[tool.mypy]
|
|
37
|
+
python_version = "3.11"
|
|
38
|
+
check_untyped_defs = true
|
|
39
|
+
ignore_missing_imports = true
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""One sandbox per ADK invocation, released when the invocation ends."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import os
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from typing import Any, TypeVar
|
|
9
|
+
|
|
10
|
+
import anyio
|
|
11
|
+
from google.adk.agents.invocation_context import InvocationContext
|
|
12
|
+
from google.adk.plugins.base_plugin import BasePlugin
|
|
13
|
+
from google.adk.tools import FunctionTool, ToolContext
|
|
14
|
+
from lizard import CodeSandbox
|
|
15
|
+
|
|
16
|
+
T = TypeVar("T")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
async def _blocking(fn: Callable[..., T], *args: Any, **kwargs: Any) -> T:
|
|
20
|
+
"""Finish an SDK call before allowing cleanup to race with it."""
|
|
21
|
+
task = asyncio.create_task(asyncio.to_thread(fn, *args, **kwargs))
|
|
22
|
+
try:
|
|
23
|
+
return await asyncio.shield(task)
|
|
24
|
+
except asyncio.CancelledError:
|
|
25
|
+
with anyio.CancelScope(shield=True):
|
|
26
|
+
try:
|
|
27
|
+
await task
|
|
28
|
+
except Exception:
|
|
29
|
+
pass # A failed SDK call must not replace the caller's cancellation.
|
|
30
|
+
raise
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class LizardPlugin(BasePlugin):
|
|
34
|
+
"""Give an ADK invocation shell, code, and file tools in its own sandbox.
|
|
35
|
+
|
|
36
|
+
Register both ``plugin.get_tools()`` on the agent and ``plugins=[plugin]``
|
|
37
|
+
on the ADK App. Close the runner in a ``finally`` block. No sandbox or key
|
|
38
|
+
is stored in ADK session state or returned in a tool response.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def __init__(
|
|
42
|
+
self,
|
|
43
|
+
*,
|
|
44
|
+
project_id: str | None = None,
|
|
45
|
+
api_key: str | None = None,
|
|
46
|
+
api_url: str | None = None,
|
|
47
|
+
size: str = "small",
|
|
48
|
+
lifetime_ms: int = 900_000,
|
|
49
|
+
command_timeout_ms: int = 60_000,
|
|
50
|
+
) -> None:
|
|
51
|
+
super().__init__(name="lizard_sandboxes")
|
|
52
|
+
self._project = project_id or os.environ.get("LIZARD_PROJECT_ID")
|
|
53
|
+
if not self._project:
|
|
54
|
+
raise ValueError("Set LIZARD_PROJECT_ID or pass project_id.")
|
|
55
|
+
if size not in {"small", "medium", "large"}:
|
|
56
|
+
raise ValueError("size must be small, medium, or large.")
|
|
57
|
+
if lifetime_ms <= 0 or not 0 < command_timeout_ms <= 120_000:
|
|
58
|
+
raise ValueError("Use a positive lifetime and a command timeout of 1–120000 ms.")
|
|
59
|
+
self._options = dict(
|
|
60
|
+
project_id=self._project,
|
|
61
|
+
api_key=api_key,
|
|
62
|
+
api_url=api_url,
|
|
63
|
+
size=size,
|
|
64
|
+
timeout_ms=lifetime_ms,
|
|
65
|
+
metadata={"integration": "adk"},
|
|
66
|
+
)
|
|
67
|
+
self._command_timeout_ms = command_timeout_ms
|
|
68
|
+
self._sandboxes: dict[str, CodeSandbox] = {}
|
|
69
|
+
self._lock = asyncio.Lock()
|
|
70
|
+
self._closed = False
|
|
71
|
+
|
|
72
|
+
def get_tools(self) -> list[FunctionTool]:
|
|
73
|
+
"""Return the four tools to pass to an ADK Agent."""
|
|
74
|
+
return [
|
|
75
|
+
FunctionTool(self.lizard_execute_command),
|
|
76
|
+
FunctionTool(self.lizard_execute_code),
|
|
77
|
+
FunctionTool(self.lizard_read_file),
|
|
78
|
+
FunctionTool(self.lizard_write_file),
|
|
79
|
+
]
|
|
80
|
+
|
|
81
|
+
async def _sandbox(self, invocation_id: str) -> CodeSandbox:
|
|
82
|
+
async with self._lock:
|
|
83
|
+
if self._closed:
|
|
84
|
+
raise RuntimeError("The Lizard plugin is closed.")
|
|
85
|
+
if invocation_id not in self._sandboxes:
|
|
86
|
+
task = asyncio.create_task(asyncio.to_thread(CodeSandbox.create, **self._options))
|
|
87
|
+
try:
|
|
88
|
+
sandbox = await asyncio.shield(task)
|
|
89
|
+
except asyncio.CancelledError:
|
|
90
|
+
with anyio.CancelScope(shield=True):
|
|
91
|
+
sandbox = await task
|
|
92
|
+
self._sandboxes[invocation_id] = sandbox
|
|
93
|
+
await _blocking(sandbox.kill)
|
|
94
|
+
del self._sandboxes[invocation_id]
|
|
95
|
+
raise
|
|
96
|
+
self._sandboxes[invocation_id] = sandbox
|
|
97
|
+
return self._sandboxes[invocation_id]
|
|
98
|
+
|
|
99
|
+
async def lizard_execute_command(
|
|
100
|
+
self, command: str, tool_context: ToolContext, cwd: str = "/home/user"
|
|
101
|
+
) -> dict[str, Any]:
|
|
102
|
+
"""Run a shell command in this invocation's sandbox.
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
command: Shell command to run in the sandbox.
|
|
106
|
+
cwd: Absolute working directory inside the sandbox.
|
|
107
|
+
"""
|
|
108
|
+
sandbox = await self._sandbox(tool_context.invocation_id)
|
|
109
|
+
result = await _blocking(
|
|
110
|
+
sandbox.process.exec_, command, workdir=cwd, timeout_ms=self._command_timeout_ms
|
|
111
|
+
)
|
|
112
|
+
return {"stdout": result.stdout, "stderr": result.stderr, "exit_code": result.exit_code}
|
|
113
|
+
|
|
114
|
+
async def lizard_execute_code(self, code: str, tool_context: ToolContext) -> dict[str, Any]:
|
|
115
|
+
"""Run Python code; variables persist within this invocation.
|
|
116
|
+
|
|
117
|
+
Args:
|
|
118
|
+
code: Python source code to run in the sandbox's Jupyter kernel.
|
|
119
|
+
"""
|
|
120
|
+
sandbox = await self._sandbox(tool_context.invocation_id)
|
|
121
|
+
result = await _blocking(sandbox.run_code, code, timeout_ms=self._command_timeout_ms)
|
|
122
|
+
return {
|
|
123
|
+
"stdout": result.stdout,
|
|
124
|
+
"stderr": result.stderr,
|
|
125
|
+
"results": [{"mime": item.mime, "data": item.data} for item in result.results],
|
|
126
|
+
"error": (
|
|
127
|
+
{"name": result.error.name, "message": result.error.message}
|
|
128
|
+
if result.error
|
|
129
|
+
else None
|
|
130
|
+
),
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async def lizard_read_file(self, path: str, tool_context: ToolContext) -> dict[str, Any]:
|
|
134
|
+
"""Read a UTF-8 file of at most 1 MiB from the sandbox.
|
|
135
|
+
|
|
136
|
+
Args:
|
|
137
|
+
path: Absolute file path inside the sandbox.
|
|
138
|
+
"""
|
|
139
|
+
sandbox = await self._sandbox(tool_context.invocation_id)
|
|
140
|
+
data = await _blocking(sandbox.fs.read_bytes, path)
|
|
141
|
+
if len(data) > 1_048_576:
|
|
142
|
+
raise ValueError("File exceeds 1 MiB; use a command to read a smaller part.")
|
|
143
|
+
return {"content": data.decode("utf-8")}
|
|
144
|
+
|
|
145
|
+
async def lizard_write_file(
|
|
146
|
+
self, path: str, content: str, tool_context: ToolContext
|
|
147
|
+
) -> dict[str, Any]:
|
|
148
|
+
"""Write a UTF-8 file, creating its parent directories if needed.
|
|
149
|
+
|
|
150
|
+
Args:
|
|
151
|
+
path: Absolute file path inside the sandbox.
|
|
152
|
+
content: Text to write. Replaces an existing file.
|
|
153
|
+
"""
|
|
154
|
+
if len(content.encode("utf-8")) > 1_048_576:
|
|
155
|
+
raise ValueError("Content exceeds the 1 MiB tool limit.")
|
|
156
|
+
sandbox = await self._sandbox(tool_context.invocation_id)
|
|
157
|
+
await _blocking(sandbox.fs.write, path, content)
|
|
158
|
+
return {"path": path, "written": True}
|
|
159
|
+
|
|
160
|
+
async def after_run_callback(self, *, invocation_context: InvocationContext) -> None:
|
|
161
|
+
"""Release this invocation's sandbox after the runner finishes it."""
|
|
162
|
+
async with self._lock:
|
|
163
|
+
key = invocation_context.invocation_id
|
|
164
|
+
if key in self._sandboxes:
|
|
165
|
+
await _blocking(self._sandboxes[key].kill)
|
|
166
|
+
del self._sandboxes[key]
|
|
167
|
+
|
|
168
|
+
async def close(self) -> None:
|
|
169
|
+
"""Release remaining sandboxes, including those from failed invocations."""
|
|
170
|
+
async with self._lock:
|
|
171
|
+
self._closed = True
|
|
172
|
+
failures = []
|
|
173
|
+
for key, sandbox in list(self._sandboxes.items()):
|
|
174
|
+
try:
|
|
175
|
+
await _blocking(sandbox.kill)
|
|
176
|
+
del self._sandboxes[key]
|
|
177
|
+
except Exception as exc:
|
|
178
|
+
failures.append(exc)
|
|
179
|
+
if failures:
|
|
180
|
+
raise ExceptionGroup("Sandbox cleanup failed; close() can be retried", failures)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from types import SimpleNamespace
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
from google.adk.agents import Agent
|
|
6
|
+
from google.adk.apps import App
|
|
7
|
+
from google.adk.models.base_llm import BaseLlm
|
|
8
|
+
from google.adk.models.llm_response import LlmResponse
|
|
9
|
+
from google.adk.runners import InMemoryRunner
|
|
10
|
+
from google.genai import types
|
|
11
|
+
|
|
12
|
+
from lizard_adk import LizardPlugin
|
|
13
|
+
|
|
14
|
+
pytestmark = [
|
|
15
|
+
pytest.mark.live,
|
|
16
|
+
pytest.mark.skipif(os.getenv("LIZARD_LIVE_TESTS") != "1", reason="Set LIZARD_LIVE_TESTS=1"),
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
async def test_tools_live():
|
|
21
|
+
plugin = LizardPlugin()
|
|
22
|
+
context = SimpleNamespace(invocation_id="live-tools")
|
|
23
|
+
try:
|
|
24
|
+
assert (await plugin.lizard_execute_command("printf hello", context))["stdout"] == "hello"
|
|
25
|
+
await plugin.lizard_write_file("/tmp/adk.txt", "a\r\nb", context)
|
|
26
|
+
assert (await plugin.lizard_read_file("/tmp/adk.txt", context))["content"] == "a\r\nb"
|
|
27
|
+
await plugin.lizard_execute_code("answer = 21", context)
|
|
28
|
+
result = await plugin.lizard_execute_code("print(answer * 2)", context)
|
|
29
|
+
assert result["stdout"] == "42\n"
|
|
30
|
+
error = await plugin.lizard_execute_code("raise ValueError('expected')", context)
|
|
31
|
+
assert error["error"]["name"] == "ValueError"
|
|
32
|
+
await plugin.after_run_callback(invocation_context=context)
|
|
33
|
+
assert not plugin._sandboxes
|
|
34
|
+
finally:
|
|
35
|
+
await plugin.close()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ScriptedModel(BaseLlm):
|
|
39
|
+
model: str = "scripted-test"
|
|
40
|
+
calls: int = 0
|
|
41
|
+
|
|
42
|
+
async def generate_content_async(self, llm_request, stream=False):
|
|
43
|
+
self.calls += 1
|
|
44
|
+
part = (
|
|
45
|
+
types.Part.from_function_call(name="lizard_execute_code", args={"code": "print(6 * 7)"})
|
|
46
|
+
if self.calls == 1
|
|
47
|
+
else types.Part.from_text(text="done")
|
|
48
|
+
)
|
|
49
|
+
yield LlmResponse(content=types.Content(role="model", parts=[part]))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
async def test_real_runner_calls_tool_and_cleans_up():
|
|
53
|
+
plugin = LizardPlugin()
|
|
54
|
+
model = ScriptedModel()
|
|
55
|
+
agent = Agent(name="sandbox_agent", model=model, tools=plugin.get_tools())
|
|
56
|
+
runner = InMemoryRunner(
|
|
57
|
+
app=App(name="lizard_test", root_agent=agent, plugins=[plugin]), plugin_close_timeout=120
|
|
58
|
+
)
|
|
59
|
+
try:
|
|
60
|
+
session = await runner.session_service.create_session(
|
|
61
|
+
app_name="lizard_test", user_id="test"
|
|
62
|
+
)
|
|
63
|
+
events = [
|
|
64
|
+
event
|
|
65
|
+
async for event in runner.run_async(
|
|
66
|
+
user_id="test",
|
|
67
|
+
session_id=session.id,
|
|
68
|
+
new_message=types.Content(
|
|
69
|
+
role="user", parts=[types.Part.from_text(text="Run Python")]
|
|
70
|
+
),
|
|
71
|
+
)
|
|
72
|
+
]
|
|
73
|
+
responses = [
|
|
74
|
+
part.function_response
|
|
75
|
+
for event in events
|
|
76
|
+
if event.content
|
|
77
|
+
for part in event.content.parts or []
|
|
78
|
+
if part.function_response
|
|
79
|
+
]
|
|
80
|
+
assert any(response.response.get("stdout") == "42\n" for response in responses)
|
|
81
|
+
assert not plugin._sandboxes
|
|
82
|
+
finally:
|
|
83
|
+
await runner.close()
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import threading
|
|
3
|
+
from types import SimpleNamespace
|
|
4
|
+
from unittest.mock import MagicMock, patch
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
from google.adk.agents import Agent
|
|
8
|
+
from lizard.code_interpreter.types import Execution, ExecutionError, ResultItem
|
|
9
|
+
|
|
10
|
+
from lizard_adk import LizardPlugin
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@pytest.fixture
|
|
14
|
+
def native():
|
|
15
|
+
sandbox = MagicMock()
|
|
16
|
+
sandbox.process.exec_.return_value = SimpleNamespace(stdout="out", stderr="err", exit_code=3)
|
|
17
|
+
sandbox.run_code.return_value = Execution(stdout="42\n", results=[ResultItem(data="42")])
|
|
18
|
+
sandbox.fs.read_bytes.return_value = b"a\r\nb\x00"
|
|
19
|
+
with patch("lizard_adk.plugin.CodeSandbox.create", return_value=sandbox) as create:
|
|
20
|
+
yield sandbox, create
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def ctx(value="run-1"):
|
|
24
|
+
return SimpleNamespace(invocation_id=value)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_config_requires_project(monkeypatch):
|
|
28
|
+
monkeypatch.delenv("LIZARD_PROJECT_ID", raising=False)
|
|
29
|
+
with pytest.raises(ValueError, match="LIZARD_PROJECT_ID"):
|
|
30
|
+
LizardPlugin()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@pytest.mark.parametrize(
|
|
34
|
+
"options", [{"size": "huge"}, {"lifetime_ms": 0}, {"command_timeout_ms": 0}]
|
|
35
|
+
)
|
|
36
|
+
def test_invalid_config(options):
|
|
37
|
+
with pytest.raises(ValueError):
|
|
38
|
+
LizardPlugin(project_id="project", **options)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def test_adk_tool_schemas_hide_context():
|
|
42
|
+
plugin = LizardPlugin(project_id="project")
|
|
43
|
+
tools = plugin.get_tools()
|
|
44
|
+
agent = Agent(name="test_agent", model="gemini-flash-latest", tools=tools)
|
|
45
|
+
assert len(agent.tools) == 4
|
|
46
|
+
for tool in tools:
|
|
47
|
+
declaration = tool._get_declaration()
|
|
48
|
+
schema = declaration.parameters_json_schema or declaration.parameters.model_dump()
|
|
49
|
+
assert "tool_context" not in schema["properties"]
|
|
50
|
+
assert schema["properties"]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
async def test_tools_share_invocation_and_forward_results(native):
|
|
54
|
+
sandbox, create = native
|
|
55
|
+
plugin = LizardPlugin(project_id="project")
|
|
56
|
+
result = await plugin.lizard_execute_command("false", ctx(), cwd="/tmp")
|
|
57
|
+
assert result == {"stdout": "out", "stderr": "err", "exit_code": 3}
|
|
58
|
+
sandbox.process.exec_.assert_called_once_with("false", workdir="/tmp", timeout_ms=60_000)
|
|
59
|
+
result = await plugin.lizard_execute_code("21 * 2", ctx())
|
|
60
|
+
assert result["results"] == [{"mime": "text/plain", "data": "42"}]
|
|
61
|
+
assert create.call_count == 1
|
|
62
|
+
await plugin.after_run_callback(invocation_context=ctx())
|
|
63
|
+
sandbox.kill.assert_called_once()
|
|
64
|
+
await plugin.close()
|
|
65
|
+
assert sandbox.kill.call_count == 1
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
async def test_parallel_tools_create_once(native):
|
|
69
|
+
_, create = native
|
|
70
|
+
plugin = LizardPlugin(project_id="project")
|
|
71
|
+
await asyncio.gather(*(plugin.lizard_execute_code("42", ctx()) for _ in range(4)))
|
|
72
|
+
assert create.call_count == 1
|
|
73
|
+
await plugin.close()
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
async def test_distinct_invocations_do_not_share_sandbox(native):
|
|
77
|
+
_, create = native
|
|
78
|
+
plugin = LizardPlugin(project_id="project")
|
|
79
|
+
await plugin.lizard_execute_code("42", ctx("a"))
|
|
80
|
+
await plugin.lizard_execute_code("42", ctx("b"))
|
|
81
|
+
assert create.call_count == 2
|
|
82
|
+
await plugin.close()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
async def test_python_error_is_structured(native):
|
|
86
|
+
native[0].run_code.return_value = Execution(error=ExecutionError("ValueError", "bad", "trace"))
|
|
87
|
+
plugin = LizardPlugin(project_id="project")
|
|
88
|
+
result = await plugin.lizard_execute_code("raise ValueError('bad')", ctx())
|
|
89
|
+
assert result["error"] == {"name": "ValueError", "message": "bad"}
|
|
90
|
+
await plugin.close()
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
async def test_files_preserve_text_and_reject_large_output(native):
|
|
94
|
+
sandbox, _ = native
|
|
95
|
+
plugin = LizardPlugin(project_id="project")
|
|
96
|
+
assert (await plugin.lizard_read_file("/tmp/a", ctx()))["content"] == "a\r\nb\x00"
|
|
97
|
+
await plugin.lizard_write_file("/tmp/a", "new", ctx())
|
|
98
|
+
sandbox.fs.write.assert_called_with("/tmp/a", "new")
|
|
99
|
+
sandbox.fs.read_bytes.return_value = b"x" * 1_048_577
|
|
100
|
+
with pytest.raises(ValueError, match="1 MiB"):
|
|
101
|
+
await plugin.lizard_read_file("/tmp/a", ctx())
|
|
102
|
+
with pytest.raises(ValueError, match="1 MiB"):
|
|
103
|
+
await plugin.lizard_write_file("/tmp/a", "x" * 1_048_577, ctx())
|
|
104
|
+
await plugin.close()
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
async def test_failed_cleanup_can_retry(native):
|
|
108
|
+
sandbox, _ = native
|
|
109
|
+
plugin = LizardPlugin(project_id="project")
|
|
110
|
+
await plugin.lizard_execute_code("42", ctx())
|
|
111
|
+
sandbox.kill.side_effect = [RuntimeError("network"), None]
|
|
112
|
+
with pytest.raises(ExceptionGroup):
|
|
113
|
+
await plugin.close()
|
|
114
|
+
await plugin.close()
|
|
115
|
+
assert sandbox.kill.call_count == 2
|
|
116
|
+
with pytest.raises(RuntimeError, match="closed"):
|
|
117
|
+
await plugin.lizard_execute_code("42", ctx())
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
async def test_cancelled_creation_releases_resource(native):
|
|
121
|
+
sandbox, create = native
|
|
122
|
+
started, release = threading.Event(), threading.Event()
|
|
123
|
+
|
|
124
|
+
def slow_create(**kwargs):
|
|
125
|
+
started.set()
|
|
126
|
+
release.wait(5)
|
|
127
|
+
return sandbox
|
|
128
|
+
|
|
129
|
+
create.side_effect = slow_create
|
|
130
|
+
plugin = LizardPlugin(project_id="project")
|
|
131
|
+
task = asyncio.create_task(plugin.lizard_execute_code("42", ctx()))
|
|
132
|
+
await asyncio.to_thread(started.wait, 5)
|
|
133
|
+
task.cancel()
|
|
134
|
+
release.set()
|
|
135
|
+
with pytest.raises(asyncio.CancelledError):
|
|
136
|
+
await task
|
|
137
|
+
sandbox.kill.assert_called_once()
|
|
138
|
+
await plugin.close()
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
async def test_cancelled_sdk_call_preserves_cancellation_after_error():
|
|
142
|
+
import threading
|
|
143
|
+
|
|
144
|
+
from lizard_adk.plugin import _blocking
|
|
145
|
+
|
|
146
|
+
started = threading.Event()
|
|
147
|
+
release = threading.Event()
|
|
148
|
+
|
|
149
|
+
def delayed_error():
|
|
150
|
+
started.set()
|
|
151
|
+
release.wait(3)
|
|
152
|
+
raise RuntimeError("transport failed")
|
|
153
|
+
|
|
154
|
+
task = asyncio.create_task(_blocking(delayed_error))
|
|
155
|
+
await asyncio.to_thread(started.wait, 3)
|
|
156
|
+
task.cancel()
|
|
157
|
+
release.set()
|
|
158
|
+
with pytest.raises(asyncio.CancelledError):
|
|
159
|
+
await task
|