crewai-kosa8 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.
- crewai_kosa8-0.1.0/.gitignore +11 -0
- crewai_kosa8-0.1.0/CHANGELOG.md +8 -0
- crewai_kosa8-0.1.0/LICENSE +21 -0
- crewai_kosa8-0.1.0/PKG-INFO +138 -0
- crewai_kosa8-0.1.0/README.md +113 -0
- crewai_kosa8-0.1.0/crewai_kosa8/__init__.py +15 -0
- crewai_kosa8-0.1.0/crewai_kosa8/base.py +206 -0
- crewai_kosa8-0.1.0/crewai_kosa8/exec_tool.py +69 -0
- crewai_kosa8-0.1.0/crewai_kosa8/file_tool.py +290 -0
- crewai_kosa8-0.1.0/crewai_kosa8/py.typed +0 -0
- crewai_kosa8-0.1.0/crewai_kosa8/python_tool.py +100 -0
- crewai_kosa8-0.1.0/pyproject.toml +54 -0
- crewai_kosa8-0.1.0/tests/__init__.py +0 -0
- crewai_kosa8-0.1.0/tests/test_live.py +113 -0
- crewai_kosa8-0.1.0/tests/test_tools.py +328 -0
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
- First version: `Kosa8ExecTool`, `Kosa8PythonTool` and `Kosa8FileTool`, shaped like the E2B and Daytona sandbox tools in `crewai-tools`, on a shared `Kosa8BaseTool`.
|
|
6
|
+
- Ephemeral (default), persistent and attach lifecycles; every sandbox the tools create gets a `ttl_s` lifetime (default 3600 s) and an `integration: crewai` label.
|
|
7
|
+
- Python runs in kosa8's stateful code kernel, falling back to a `python3` script on an attached sandbox without a persistent container.
|
|
8
|
+
- File actions: read, write, append, list, delete, mkdir, info, exists, move, find, search, chmod, replace.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 kosa8
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: crewai-kosa8
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: kosa8 Cloud microVM sandboxes as CrewAI tools: shell exec, Python and files
|
|
5
|
+
Project-URL: Homepage, https://kosa8.com
|
|
6
|
+
Project-URL: Documentation, https://github.com/kosa8ai/crewai-kosa8#readme
|
|
7
|
+
Project-URL: Repository, https://github.com/kosa8ai/crewai-kosa8
|
|
8
|
+
Project-URL: Issues, https://github.com/kosa8ai/crewai-kosa8/issues
|
|
9
|
+
Author: kosa8
|
|
10
|
+
License: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: agents,code-interpreter,crewai,crewai-tools,kosa8,microvm,sandbox
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
21
|
+
Requires-Python: <3.14,>=3.10
|
|
22
|
+
Requires-Dist: crewai>=1.0
|
|
23
|
+
Requires-Dist: kosa8<1,>=0.12.0
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# crewai-kosa8
|
|
27
|
+
|
|
28
|
+
**[kosa8](https://kosa8.com): Zero Trust cybersecurity infrastructure for AI agents.** Every agent sealed in its own microVM. Every action verified and recorded.
|
|
29
|
+
|
|
30
|
+
Give a [CrewAI](https://www.crewai.com/) agent a [kosa8 Cloud](https://kosa8.com) microVM sandbox to run shell commands, Python and file edits in, instead of your machine.
|
|
31
|
+
|
|
32
|
+
Three tools, shaped like the E2B and Daytona sandbox tools in `crewai-tools`, so you can swap one for another:
|
|
33
|
+
|
|
34
|
+
- **`Kosa8ExecTool`** (`kosa8 Sandbox Exec`): run a shell command, get the exit code, stdout and stderr.
|
|
35
|
+
- **`Kosa8PythonTool`** (`kosa8 Sandbox Python`): run Python in a stateful kernel, get stdout, stderr, the last expression's value and any error.
|
|
36
|
+
- **`Kosa8FileTool`** (`kosa8 Sandbox Files`): read, write, append, list, delete, mkdir, info, exists, move, find (content grep), search (name glob), chmod and replace.
|
|
37
|
+
|
|
38
|
+
## Install
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install crewai-kosa8
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Set `KOSA8_API_KEY` to a kosa8 Cloud API key (create one at [app.kosa8.com](https://app.kosa8.com), or run `kosa8 login`). The Starter plan is free and needs no card; plans are at [kosa8.com/pricing](https://kosa8.com/pricing/).
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
export KOSA8_API_KEY="k8c_live_..."
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
`KOSA8_CLOUD_URL` overrides the API address (default `https://api.kosa8.com`).
|
|
51
|
+
|
|
52
|
+
## Example
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
import kosa8
|
|
56
|
+
from crewai import Agent, Crew, Task
|
|
57
|
+
from crewai_kosa8 import Kosa8ExecTool, Kosa8FileTool, Kosa8PythonTool
|
|
58
|
+
|
|
59
|
+
# One sandbox for the whole crew; `with` deletes it on the way out, error or not.
|
|
60
|
+
with kosa8.Cloud().sandboxes.create(template="python", persistent=True, ttl_s=3600) as box:
|
|
61
|
+
coder = Agent(
|
|
62
|
+
role="Engineer",
|
|
63
|
+
goal="Write and test small programs",
|
|
64
|
+
backstory="You work only inside the kosa8 sandbox.",
|
|
65
|
+
tools=[Kosa8ExecTool(sandbox_id=box.id), Kosa8FileTool(sandbox_id=box.id), Kosa8PythonTool(sandbox_id=box.id)],
|
|
66
|
+
)
|
|
67
|
+
task = Task(
|
|
68
|
+
description="Write /workspace/fizzbuzz.py, run it for 1..15 and report the output.",
|
|
69
|
+
expected_output="The program's output",
|
|
70
|
+
agent=coder,
|
|
71
|
+
)
|
|
72
|
+
print(Crew(agents=[coder], tasks=[task]).kickoff())
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Each tool can also be called directly:
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
from crewai_kosa8 import Kosa8PythonTool
|
|
79
|
+
|
|
80
|
+
print(Kosa8PythonTool().run(code="print(sum(range(10)))"))
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## Sandbox lifecycle
|
|
84
|
+
|
|
85
|
+
All three tools share the same lifecycle controls from `Kosa8BaseTool`:
|
|
86
|
+
|
|
87
|
+
| Mode | When the sandbox is created | When it is deleted |
|
|
88
|
+
| --- | --- | --- |
|
|
89
|
+
| **Ephemeral** (default, `persistent=False`) | On every call | At the end of that same call |
|
|
90
|
+
| **Persistent** (`persistent=True`) | Lazily on first use | At process exit (via `atexit`), or on `tool.close()` |
|
|
91
|
+
| **Attach** (`sandbox_id="sbx_..."`) | Never: the tool attaches to an existing sandbox | Never: the tool will not delete a sandbox it did not create |
|
|
92
|
+
|
|
93
|
+
Every sandbox a tool creates also gets a lifetime (`ttl_s`, default 3600 s): kosa8 Cloud deletes it then even if the process dies before cleanup runs.
|
|
94
|
+
|
|
95
|
+
Each persistent tool keeps its own sandbox. To share one between tools, attach the others to the first one's id:
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
exec_tool = Kosa8ExecTool(persistent=True)
|
|
99
|
+
exec_tool.run(command="pip install httpx")
|
|
100
|
+
files = Kosa8FileTool(sandbox_id=exec_tool.active_sandbox_id)
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Options
|
|
104
|
+
|
|
105
|
+
Every tool takes these:
|
|
106
|
+
|
|
107
|
+
| Option | Default | |
|
|
108
|
+
| --- | --- | --- |
|
|
109
|
+
| `api_key` | `KOSA8_API_KEY`, then the key `kosa8 login` saved | kosa8 Cloud API key |
|
|
110
|
+
| `base_url` | `KOSA8_CLOUD_URL`, then `https://api.kosa8.com` | API address |
|
|
111
|
+
| `persistent` | `False` | reuse one sandbox for every call of this tool |
|
|
112
|
+
| `sandbox_id` | none | attach to an existing sandbox |
|
|
113
|
+
| `template` | `"python"` | kosa8 template for new sandboxes |
|
|
114
|
+
| `ttl_s` | `3600` | lifetime of new sandboxes, in seconds |
|
|
115
|
+
| `labels` | none | labels on new sandboxes, merged over `{"integration": "crewai"}` |
|
|
116
|
+
| `create_params` | none | anything else for `cloud.sandboxes.create`: `size` (`0.25x0.5` to `16x32`), `image`, `region`, `env`, `egress` (for example `{"internet": False}`), `secrets`, `persistent`, ... |
|
|
117
|
+
| `workdir` | `/workspace` | where `Kosa8ExecTool` commands start when no `cwd` is given |
|
|
118
|
+
|
|
119
|
+
## How it maps to kosa8
|
|
120
|
+
|
|
121
|
+
- `Kosa8ExecTool` runs `cd <cwd> && <command>` with kosa8's buffered exec. A buffered command runs at most 90 s; a longer one comes back as `{"timed_out": true, ...}`. Each stream keeps its first and last 1 MiB (`"truncated": true` when the middle was dropped).
|
|
122
|
+
- `Kosa8PythonTool` uses kosa8's code kernel (`sandbox.run_code`), so variables persist per `context` within a sandbox. The kernel needs kosa8's long-lived container, so sandboxes this tool creates are made with `persistent=True`. Attached to a sandbox without one, it runs the code as a `python3` script instead. Images and other rich results are reported by type, not returned as bytes.
|
|
123
|
+
- `Kosa8FileTool` uses the kosa8 files API for read, write, append, list, delete, mkdir, info, exists and replace, and a shell command for move, find, search and chmod.
|
|
124
|
+
- Only `/workspace` is promised to persist between commands unless the sandbox was created with `create_params={"persistent": True}`.
|
|
125
|
+
- kosa8 Cloud errors (for example a payment or plan limit, with its `upgrade_url`) are raised as the SDK's typed errors, and CrewAI shows them to the agent.
|
|
126
|
+
|
|
127
|
+
## Tests
|
|
128
|
+
|
|
129
|
+
```bash
|
|
130
|
+
uv run --group test pytest # unit tests, against a mocked kosa8 client
|
|
131
|
+
KOSA8_API_KEY=... uv run --group test pytest tests/test_live.py # live tier, on kosa8 Cloud
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
The live tier (skipped without `KOSA8_API_KEY`) creates sandboxes with a 600 s lifetime and a `crewai-kosa8-test` label, runs every tool and a CrewAI `Agent` driven by a scripted LLM (no model provider is called), and checks that no sandbox it made is left behind.
|
|
135
|
+
|
|
136
|
+
## License
|
|
137
|
+
|
|
138
|
+
MIT
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
# crewai-kosa8
|
|
2
|
+
|
|
3
|
+
**[kosa8](https://kosa8.com): Zero Trust cybersecurity infrastructure for AI agents.** Every agent sealed in its own microVM. Every action verified and recorded.
|
|
4
|
+
|
|
5
|
+
Give a [CrewAI](https://www.crewai.com/) agent a [kosa8 Cloud](https://kosa8.com) microVM sandbox to run shell commands, Python and file edits in, instead of your machine.
|
|
6
|
+
|
|
7
|
+
Three tools, shaped like the E2B and Daytona sandbox tools in `crewai-tools`, so you can swap one for another:
|
|
8
|
+
|
|
9
|
+
- **`Kosa8ExecTool`** (`kosa8 Sandbox Exec`): run a shell command, get the exit code, stdout and stderr.
|
|
10
|
+
- **`Kosa8PythonTool`** (`kosa8 Sandbox Python`): run Python in a stateful kernel, get stdout, stderr, the last expression's value and any error.
|
|
11
|
+
- **`Kosa8FileTool`** (`kosa8 Sandbox Files`): read, write, append, list, delete, mkdir, info, exists, move, find (content grep), search (name glob), chmod and replace.
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pip install crewai-kosa8
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Set `KOSA8_API_KEY` to a kosa8 Cloud API key (create one at [app.kosa8.com](https://app.kosa8.com), or run `kosa8 login`). The Starter plan is free and needs no card; plans are at [kosa8.com/pricing](https://kosa8.com/pricing/).
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
export KOSA8_API_KEY="k8c_live_..."
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
`KOSA8_CLOUD_URL` overrides the API address (default `https://api.kosa8.com`).
|
|
26
|
+
|
|
27
|
+
## Example
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
import kosa8
|
|
31
|
+
from crewai import Agent, Crew, Task
|
|
32
|
+
from crewai_kosa8 import Kosa8ExecTool, Kosa8FileTool, Kosa8PythonTool
|
|
33
|
+
|
|
34
|
+
# One sandbox for the whole crew; `with` deletes it on the way out, error or not.
|
|
35
|
+
with kosa8.Cloud().sandboxes.create(template="python", persistent=True, ttl_s=3600) as box:
|
|
36
|
+
coder = Agent(
|
|
37
|
+
role="Engineer",
|
|
38
|
+
goal="Write and test small programs",
|
|
39
|
+
backstory="You work only inside the kosa8 sandbox.",
|
|
40
|
+
tools=[Kosa8ExecTool(sandbox_id=box.id), Kosa8FileTool(sandbox_id=box.id), Kosa8PythonTool(sandbox_id=box.id)],
|
|
41
|
+
)
|
|
42
|
+
task = Task(
|
|
43
|
+
description="Write /workspace/fizzbuzz.py, run it for 1..15 and report the output.",
|
|
44
|
+
expected_output="The program's output",
|
|
45
|
+
agent=coder,
|
|
46
|
+
)
|
|
47
|
+
print(Crew(agents=[coder], tasks=[task]).kickoff())
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Each tool can also be called directly:
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from crewai_kosa8 import Kosa8PythonTool
|
|
54
|
+
|
|
55
|
+
print(Kosa8PythonTool().run(code="print(sum(range(10)))"))
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Sandbox lifecycle
|
|
59
|
+
|
|
60
|
+
All three tools share the same lifecycle controls from `Kosa8BaseTool`:
|
|
61
|
+
|
|
62
|
+
| Mode | When the sandbox is created | When it is deleted |
|
|
63
|
+
| --- | --- | --- |
|
|
64
|
+
| **Ephemeral** (default, `persistent=False`) | On every call | At the end of that same call |
|
|
65
|
+
| **Persistent** (`persistent=True`) | Lazily on first use | At process exit (via `atexit`), or on `tool.close()` |
|
|
66
|
+
| **Attach** (`sandbox_id="sbx_..."`) | Never: the tool attaches to an existing sandbox | Never: the tool will not delete a sandbox it did not create |
|
|
67
|
+
|
|
68
|
+
Every sandbox a tool creates also gets a lifetime (`ttl_s`, default 3600 s): kosa8 Cloud deletes it then even if the process dies before cleanup runs.
|
|
69
|
+
|
|
70
|
+
Each persistent tool keeps its own sandbox. To share one between tools, attach the others to the first one's id:
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
exec_tool = Kosa8ExecTool(persistent=True)
|
|
74
|
+
exec_tool.run(command="pip install httpx")
|
|
75
|
+
files = Kosa8FileTool(sandbox_id=exec_tool.active_sandbox_id)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Options
|
|
79
|
+
|
|
80
|
+
Every tool takes these:
|
|
81
|
+
|
|
82
|
+
| Option | Default | |
|
|
83
|
+
| --- | --- | --- |
|
|
84
|
+
| `api_key` | `KOSA8_API_KEY`, then the key `kosa8 login` saved | kosa8 Cloud API key |
|
|
85
|
+
| `base_url` | `KOSA8_CLOUD_URL`, then `https://api.kosa8.com` | API address |
|
|
86
|
+
| `persistent` | `False` | reuse one sandbox for every call of this tool |
|
|
87
|
+
| `sandbox_id` | none | attach to an existing sandbox |
|
|
88
|
+
| `template` | `"python"` | kosa8 template for new sandboxes |
|
|
89
|
+
| `ttl_s` | `3600` | lifetime of new sandboxes, in seconds |
|
|
90
|
+
| `labels` | none | labels on new sandboxes, merged over `{"integration": "crewai"}` |
|
|
91
|
+
| `create_params` | none | anything else for `cloud.sandboxes.create`: `size` (`0.25x0.5` to `16x32`), `image`, `region`, `env`, `egress` (for example `{"internet": False}`), `secrets`, `persistent`, ... |
|
|
92
|
+
| `workdir` | `/workspace` | where `Kosa8ExecTool` commands start when no `cwd` is given |
|
|
93
|
+
|
|
94
|
+
## How it maps to kosa8
|
|
95
|
+
|
|
96
|
+
- `Kosa8ExecTool` runs `cd <cwd> && <command>` with kosa8's buffered exec. A buffered command runs at most 90 s; a longer one comes back as `{"timed_out": true, ...}`. Each stream keeps its first and last 1 MiB (`"truncated": true` when the middle was dropped).
|
|
97
|
+
- `Kosa8PythonTool` uses kosa8's code kernel (`sandbox.run_code`), so variables persist per `context` within a sandbox. The kernel needs kosa8's long-lived container, so sandboxes this tool creates are made with `persistent=True`. Attached to a sandbox without one, it runs the code as a `python3` script instead. Images and other rich results are reported by type, not returned as bytes.
|
|
98
|
+
- `Kosa8FileTool` uses the kosa8 files API for read, write, append, list, delete, mkdir, info, exists and replace, and a shell command for move, find, search and chmod.
|
|
99
|
+
- Only `/workspace` is promised to persist between commands unless the sandbox was created with `create_params={"persistent": True}`.
|
|
100
|
+
- kosa8 Cloud errors (for example a payment or plan limit, with its `upgrade_url`) are raised as the SDK's typed errors, and CrewAI shows them to the agent.
|
|
101
|
+
|
|
102
|
+
## Tests
|
|
103
|
+
|
|
104
|
+
```bash
|
|
105
|
+
uv run --group test pytest # unit tests, against a mocked kosa8 client
|
|
106
|
+
KOSA8_API_KEY=... uv run --group test pytest tests/test_live.py # live tier, on kosa8 Cloud
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
The live tier (skipped without `KOSA8_API_KEY`) creates sandboxes with a 600 s lifetime and a `crewai-kosa8-test` label, runs every tool and a CrewAI `Agent` driven by a scripted LLM (no model provider is called), and checks that no sandbox it made is left behind.
|
|
110
|
+
|
|
111
|
+
## License
|
|
112
|
+
|
|
113
|
+
MIT
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""kosa8 Cloud microVM sandboxes as CrewAI tools."""
|
|
2
|
+
|
|
3
|
+
from crewai_kosa8.base import Kosa8BaseTool
|
|
4
|
+
from crewai_kosa8.exec_tool import Kosa8ExecTool
|
|
5
|
+
from crewai_kosa8.file_tool import Kosa8FileTool
|
|
6
|
+
from crewai_kosa8.python_tool import Kosa8PythonTool
|
|
7
|
+
|
|
8
|
+
__version__ = "0.1.0"
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"Kosa8BaseTool",
|
|
12
|
+
"Kosa8ExecTool",
|
|
13
|
+
"Kosa8FileTool",
|
|
14
|
+
"Kosa8PythonTool",
|
|
15
|
+
]
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""Shared sandbox lifecycle for the kosa8 CrewAI tools."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import atexit
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
import threading
|
|
9
|
+
from typing import Any, ClassVar
|
|
10
|
+
|
|
11
|
+
from crewai.tools import BaseTool, EnvVar
|
|
12
|
+
from pydantic import ConfigDict, Field, PrivateAttr
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
DEFAULT_LABELS: dict[str, str] = {"integration": "crewai"}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Kosa8BaseTool(BaseTool):
|
|
20
|
+
"""Shared base for tools that act on a kosa8 Cloud sandbox.
|
|
21
|
+
|
|
22
|
+
Lifecycle modes:
|
|
23
|
+
- persistent=False (default): create a fresh sandbox per `_run` call and
|
|
24
|
+
delete it when the call returns. Nothing leaks if the agent forgets
|
|
25
|
+
cleanup.
|
|
26
|
+
- persistent=True: lazily create one sandbox on first use, cache it on
|
|
27
|
+
the instance, and delete it at process exit (or on `close()`). Files
|
|
28
|
+
and installed packages carry over between calls.
|
|
29
|
+
- sandbox_id=<existing>: attach to a sandbox the caller already owns.
|
|
30
|
+
Never deleted by the tool.
|
|
31
|
+
|
|
32
|
+
Every sandbox the tool creates also gets a `ttl_s` lifetime, so kosa8
|
|
33
|
+
Cloud deletes it even if the process dies before cleanup runs.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
model_config = ConfigDict(arbitrary_types_allowed=True)
|
|
37
|
+
|
|
38
|
+
package_dependencies: list[str] = Field(default_factory=lambda: ["kosa8"])
|
|
39
|
+
|
|
40
|
+
api_key: str | None = Field(
|
|
41
|
+
default_factory=lambda: os.getenv("KOSA8_API_KEY"),
|
|
42
|
+
description="kosa8 Cloud API key (k8c_live_...). Falls back to KOSA8_API_KEY, then the key `kosa8 login` saved.",
|
|
43
|
+
json_schema_extra={"required": False},
|
|
44
|
+
)
|
|
45
|
+
base_url: str | None = Field(
|
|
46
|
+
default_factory=lambda: os.getenv("KOSA8_CLOUD_URL"),
|
|
47
|
+
description="kosa8 Cloud API address. Falls back to KOSA8_CLOUD_URL, then https://api.kosa8.com.",
|
|
48
|
+
json_schema_extra={"required": False},
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
persistent: bool = Field(
|
|
52
|
+
default=False,
|
|
53
|
+
description=(
|
|
54
|
+
"If True, reuse one sandbox across all calls to this tool instance "
|
|
55
|
+
"and delete it at process exit. Default False creates and deletes a "
|
|
56
|
+
"fresh sandbox per call."
|
|
57
|
+
),
|
|
58
|
+
)
|
|
59
|
+
sandbox_id: str | None = Field(
|
|
60
|
+
default=None,
|
|
61
|
+
description=(
|
|
62
|
+
"Attach to an existing sandbox by id instead of creating a new one. The tool will never delete a sandbox it did not create."
|
|
63
|
+
),
|
|
64
|
+
)
|
|
65
|
+
template: str | None = Field(
|
|
66
|
+
default="python",
|
|
67
|
+
description="kosa8 template for sandboxes the tool creates (the `python` template has python3).",
|
|
68
|
+
)
|
|
69
|
+
ttl_s: int | None = Field(
|
|
70
|
+
default=3600,
|
|
71
|
+
description=(
|
|
72
|
+
"Lifetime in seconds for sandboxes the tool creates: kosa8 Cloud "
|
|
73
|
+
"deletes the sandbox this long after it starts, even if cleanup "
|
|
74
|
+
"never runs. None leaves it to the account default."
|
|
75
|
+
),
|
|
76
|
+
)
|
|
77
|
+
labels: dict[str, str] | None = Field(
|
|
78
|
+
default=None,
|
|
79
|
+
description="Labels stored on sandboxes the tool creates, merged over {'integration': 'crewai'}.",
|
|
80
|
+
)
|
|
81
|
+
create_params: dict[str, Any] | None = Field(
|
|
82
|
+
default=None,
|
|
83
|
+
description=(
|
|
84
|
+
"Extra keyword arguments forwarded to kosa8 `cloud.sandboxes.create` "
|
|
85
|
+
"(e.g. size, image, region, env, egress, secrets, persistent)."
|
|
86
|
+
),
|
|
87
|
+
)
|
|
88
|
+
workdir: str = Field(
|
|
89
|
+
default="/workspace",
|
|
90
|
+
description="Directory commands start in when no cwd is given. Files under /workspace persist for the sandbox's life.",
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
env_vars: list[EnvVar] = Field(
|
|
94
|
+
default_factory=lambda: [
|
|
95
|
+
EnvVar(
|
|
96
|
+
name="KOSA8_API_KEY",
|
|
97
|
+
description="API key for kosa8 Cloud sandboxes (create one at https://app.kosa8.com)",
|
|
98
|
+
required=True,
|
|
99
|
+
),
|
|
100
|
+
EnvVar(
|
|
101
|
+
name="KOSA8_CLOUD_URL",
|
|
102
|
+
description="kosa8 Cloud API address (optional)",
|
|
103
|
+
required=False,
|
|
104
|
+
),
|
|
105
|
+
]
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
_client: Any | None = PrivateAttr(default=None)
|
|
109
|
+
_persistent_sandbox: Any | None = PrivateAttr(default=None)
|
|
110
|
+
_lock: threading.Lock = PrivateAttr(default_factory=threading.Lock)
|
|
111
|
+
_cleanup_registered: bool = PrivateAttr(default=False)
|
|
112
|
+
|
|
113
|
+
# Python tools need kosa8's long-lived container for their stateful kernel.
|
|
114
|
+
_requires_persistent_container: ClassVar[bool] = False
|
|
115
|
+
|
|
116
|
+
def _get_client(self) -> Any:
|
|
117
|
+
if self._client is not None:
|
|
118
|
+
return self._client
|
|
119
|
+
try:
|
|
120
|
+
import kosa8
|
|
121
|
+
except ImportError as exc: # pragma: no cover - kosa8 is a dependency
|
|
122
|
+
raise ImportError("The 'kosa8' package is required for kosa8 sandbox tools. Install it with: pip install kosa8") from exc
|
|
123
|
+
self._client = kosa8.Cloud(self.api_key, base_url=self.base_url)
|
|
124
|
+
return self._client
|
|
125
|
+
|
|
126
|
+
def _create_kwargs(self) -> dict[str, Any]:
|
|
127
|
+
kwargs: dict[str, Any] = {}
|
|
128
|
+
if self.template is not None:
|
|
129
|
+
kwargs["template"] = self.template
|
|
130
|
+
if self.ttl_s is not None:
|
|
131
|
+
kwargs["ttl_s"] = self.ttl_s
|
|
132
|
+
kwargs["labels"] = {**DEFAULT_LABELS, **(self.labels or {})}
|
|
133
|
+
if self._requires_persistent_container:
|
|
134
|
+
kwargs["persistent"] = True
|
|
135
|
+
extra = dict(self.create_params or {})
|
|
136
|
+
if "labels" in extra:
|
|
137
|
+
kwargs["labels"] = {**kwargs["labels"], **(extra.pop("labels") or {})}
|
|
138
|
+
kwargs.update(extra)
|
|
139
|
+
return kwargs
|
|
140
|
+
|
|
141
|
+
def _create_sandbox(self) -> Any:
|
|
142
|
+
return self._get_client().sandboxes.create(**self._create_kwargs())
|
|
143
|
+
|
|
144
|
+
def _acquire_sandbox(self) -> tuple[Any, bool]:
|
|
145
|
+
"""Return (sandbox, should_delete_after_use)."""
|
|
146
|
+
if self.sandbox_id:
|
|
147
|
+
return self._get_client().sandboxes.get(self.sandbox_id), False
|
|
148
|
+
|
|
149
|
+
if self.persistent:
|
|
150
|
+
with self._lock:
|
|
151
|
+
if self._persistent_sandbox is None:
|
|
152
|
+
self._persistent_sandbox = self._create_sandbox()
|
|
153
|
+
if not self._cleanup_registered:
|
|
154
|
+
atexit.register(self.close)
|
|
155
|
+
self._cleanup_registered = True
|
|
156
|
+
return self._persistent_sandbox, False
|
|
157
|
+
|
|
158
|
+
return self._create_sandbox(), True
|
|
159
|
+
|
|
160
|
+
def _release_sandbox(self, sandbox: Any, should_delete: bool) -> None:
|
|
161
|
+
if not should_delete:
|
|
162
|
+
return
|
|
163
|
+
try:
|
|
164
|
+
sandbox.delete()
|
|
165
|
+
except Exception:
|
|
166
|
+
logger.warning(
|
|
167
|
+
"Could not delete kosa8 sandbox %s after use; its ttl_s will remove it.",
|
|
168
|
+
getattr(sandbox, "id", "?"),
|
|
169
|
+
exc_info=True,
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
def close(self) -> None:
|
|
173
|
+
"""Delete the cached persistent sandbox if one exists."""
|
|
174
|
+
with self._lock:
|
|
175
|
+
sandbox = self._persistent_sandbox
|
|
176
|
+
self._persistent_sandbox = None
|
|
177
|
+
if sandbox is None:
|
|
178
|
+
return
|
|
179
|
+
try:
|
|
180
|
+
sandbox.delete()
|
|
181
|
+
except Exception:
|
|
182
|
+
logger.warning(
|
|
183
|
+
"Could not delete persistent kosa8 sandbox %s at close(); its ttl_s will remove it.",
|
|
184
|
+
getattr(sandbox, "id", "?"),
|
|
185
|
+
exc_info=True,
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
@property
|
|
189
|
+
def active_sandbox_id(self) -> str | None:
|
|
190
|
+
"""The id of the sandbox this tool is bound to, if any.
|
|
191
|
+
|
|
192
|
+
Returns the attached `sandbox_id`, the id of the lazily created
|
|
193
|
+
persistent sandbox once a call has created it, or None in ephemeral
|
|
194
|
+
mode. Use it to share one sandbox between tools:
|
|
195
|
+
|
|
196
|
+
exec_tool = Kosa8ExecTool(persistent=True)
|
|
197
|
+
exec_tool.run(command="pip install httpx")
|
|
198
|
+
file_tool = Kosa8FileTool(sandbox_id=exec_tool.active_sandbox_id)
|
|
199
|
+
"""
|
|
200
|
+
if self.sandbox_id:
|
|
201
|
+
return self.sandbox_id
|
|
202
|
+
with self._lock:
|
|
203
|
+
sandbox = self._persistent_sandbox
|
|
204
|
+
if sandbox is None:
|
|
205
|
+
return None
|
|
206
|
+
return getattr(sandbox, "id", None)
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Run a shell command in a kosa8 Cloud sandbox."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import shlex
|
|
6
|
+
from builtins import type as type_
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from pydantic import BaseModel, Field
|
|
10
|
+
|
|
11
|
+
from crewai_kosa8.base import Kosa8BaseTool
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Kosa8ExecToolSchema(BaseModel):
|
|
15
|
+
command: str = Field(..., description="Shell command to execute in the sandbox.")
|
|
16
|
+
cwd: str | None = Field(
|
|
17
|
+
default=None,
|
|
18
|
+
description="Working directory to run the command in. Defaults to /workspace.",
|
|
19
|
+
)
|
|
20
|
+
env: dict[str, str] | None = Field(
|
|
21
|
+
default=None,
|
|
22
|
+
description="Optional environment variables to set for this command.",
|
|
23
|
+
)
|
|
24
|
+
timeout: int | None = Field(
|
|
25
|
+
default=None,
|
|
26
|
+
description="Maximum seconds to wait for the command to finish (a buffered command runs at most 90 s).",
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _shell_in(cwd: str, command: str) -> str:
|
|
31
|
+
return f"cd {shlex.quote(cwd)} && {command}"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Kosa8ExecTool(Kosa8BaseTool):
|
|
35
|
+
"""Run a shell command inside a kosa8 Cloud sandbox."""
|
|
36
|
+
|
|
37
|
+
name: str = "kosa8 Sandbox Exec"
|
|
38
|
+
description: str = (
|
|
39
|
+
"Execute a shell command inside a sealed kosa8 Cloud microVM sandbox and "
|
|
40
|
+
"return the exit code, stdout and stderr. Use this to run builds, package "
|
|
41
|
+
"installs, git operations, tests, or any one-off shell command."
|
|
42
|
+
)
|
|
43
|
+
args_schema: type_[BaseModel] = Kosa8ExecToolSchema
|
|
44
|
+
|
|
45
|
+
def _run(
|
|
46
|
+
self,
|
|
47
|
+
command: str,
|
|
48
|
+
cwd: str | None = None,
|
|
49
|
+
env: dict[str, str] | None = None,
|
|
50
|
+
timeout: int | None = None,
|
|
51
|
+
) -> Any:
|
|
52
|
+
from kosa8 import Kosa8ExecTimeoutError
|
|
53
|
+
|
|
54
|
+
sandbox, should_delete = self._acquire_sandbox()
|
|
55
|
+
try:
|
|
56
|
+
try:
|
|
57
|
+
result = sandbox.exec(_shell_in(cwd or self.workdir, command), env=env, timeout_s=timeout)
|
|
58
|
+
except Kosa8ExecTimeoutError as exc:
|
|
59
|
+
return {"exit_code": None, "stdout": "", "stderr": "", "timed_out": True, "error": str(exc)}
|
|
60
|
+
out: dict[str, Any] = {
|
|
61
|
+
"exit_code": result.exit_code,
|
|
62
|
+
"stdout": result.stdout,
|
|
63
|
+
"stderr": result.stderr,
|
|
64
|
+
}
|
|
65
|
+
if result.stdout_truncated or result.stderr_truncated:
|
|
66
|
+
out["truncated"] = True
|
|
67
|
+
return out
|
|
68
|
+
finally:
|
|
69
|
+
self._release_sandbox(sandbox, should_delete)
|