agent-framework-kosa8 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.
- agent_framework_kosa8/__init__.py +13 -0
- agent_framework_kosa8/_exec.py +269 -0
- agent_framework_kosa8/_shell.py +527 -0
- agent_framework_kosa8/py.typed +0 -0
- agent_framework_kosa8-0.1.0.dist-info/METADATA +141 -0
- agent_framework_kosa8-0.1.0.dist-info/RECORD +8 -0
- agent_framework_kosa8-0.1.0.dist-info/WHEEL +4 -0
- agent_framework_kosa8-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""kosa8 Cloud microVM sandboxes for Microsoft Agent Framework.
|
|
2
|
+
|
|
3
|
+
``Kosa8ShellTool`` implements Agent Framework's ``ShellExecutor`` protocol on a kosa8 Cloud sandbox
|
|
4
|
+
and vends shell, Python and file tools bound to it.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from ._shell import Kosa8ShellTool
|
|
10
|
+
|
|
11
|
+
__version__ = "0.1.0"
|
|
12
|
+
|
|
13
|
+
__all__ = ["Kosa8ShellTool", "__version__"]
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
"""Run one command in a kosa8 Cloud sandbox over buffered exec requests.
|
|
2
|
+
|
|
3
|
+
kosa8 Cloud holds a buffered exec to 90 seconds and returns its output as text. To give
|
|
4
|
+
agent commands of any length and byte-exact output, a command runs like this:
|
|
5
|
+
|
|
6
|
+
- One request starts a POSIX ``sh`` wrapper in the background and returns at once.
|
|
7
|
+
- Further requests wait for the wrapper, each for at most ``WAIT_S`` seconds, so a command can
|
|
8
|
+
outlive one buffered exec.
|
|
9
|
+
- The wrapper starts the command in a process group of its own (``setsid``, or job control where
|
|
10
|
+
``setsid`` is missing), with stdin at EOF and stdout/stderr redirected to files in a per-command
|
|
11
|
+
run directory. It waits for the direct command only, so a background child that keeps its
|
|
12
|
+
output open does not hold the call up.
|
|
13
|
+
- ``timeout`` is enforced inside the sandbox by a watchdog that kills the process group.
|
|
14
|
+
Cancelling the call sends one more exec that kills it.
|
|
15
|
+
- The wrapper prints a status line and the two outputs in base64. Output too large for one
|
|
16
|
+
answer is read back in chunks by further execs.
|
|
17
|
+
- A command too large for one request body is staged in a file first.
|
|
18
|
+
|
|
19
|
+
Every request is a buffered exec: kosa8's streamed exec can run in a PID namespace and ``/tmp``
|
|
20
|
+
of its own, where a later request could not see or stop the processes it started.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import asyncio
|
|
26
|
+
import base64
|
|
27
|
+
import json
|
|
28
|
+
import math
|
|
29
|
+
import re
|
|
30
|
+
import time
|
|
31
|
+
import uuid
|
|
32
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
33
|
+
from dataclasses import dataclass
|
|
34
|
+
from typing import Protocol
|
|
35
|
+
|
|
36
|
+
# The API takes a 64 KiB JSON body per exec; past this the command is staged in a file.
|
|
37
|
+
BODY_LIMIT = 56_000
|
|
38
|
+
# Raw bytes the wrapper may print inline (base64 grows them by a third; a buffered exec keeps 1 MiB per stream).
|
|
39
|
+
INLINE_BYTES = 512 * 1024
|
|
40
|
+
CHUNK_BYTES = 384 * 1024
|
|
41
|
+
# Bytes of each stream kept from one command.
|
|
42
|
+
MAX_CAPTURE_BYTES = 16 * 1024 * 1024
|
|
43
|
+
# Raw bytes of a staged command per exec.
|
|
44
|
+
STAGE_CHUNK_BYTES = 30_000
|
|
45
|
+
# Seconds past `timeout` the client waits for the in-sandbox watchdog before it gives up itself.
|
|
46
|
+
SERVER_GRACE_S = 15
|
|
47
|
+
# Seconds one wait request polls for the wrapper to finish (under the 90 s buffered exec limit).
|
|
48
|
+
WAIT_S = 50
|
|
49
|
+
KILL_TIMEOUT_S = 15
|
|
50
|
+
|
|
51
|
+
_ENV_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
|
|
52
|
+
|
|
53
|
+
# $K8_RUN run dir, $K8_CMD (or the script file $K8_CMDFILE), $K8_CWD, $K8_TIMEOUT (whole seconds), $K8_INLINE.
|
|
54
|
+
# Prints "K8RUN <exit> <timed out> <stdout bytes> <stderr bytes>", then, when they fit inline, the two
|
|
55
|
+
# outputs in base64 separated by a K8SEP line. The command never sees the K8_* variables.
|
|
56
|
+
RUN = (
|
|
57
|
+
"r=$K8_RUN; c=$K8_CMD; cf=$K8_CMDFILE; w=$K8_CWD; t=$K8_TIMEOUT; n=$K8_INLINE; "
|
|
58
|
+
"unset K8_RUN K8_CMD K8_CMDFILE K8_CWD K8_TIMEOUT K8_INLINE; "
|
|
59
|
+
'mkdir -p "$r" 2>/dev/null || { echo "K8FAIL cannot create $r"; exit 0; }; '
|
|
60
|
+
'cd "$w" 2>/dev/null || { echo "K8FAIL cannot change to $w"; exit 0; }; '
|
|
61
|
+
'if [ -n "$cf" ]; then set -- "$cf"; else set -- -c "$c"; fi; '
|
|
62
|
+
'if command -v setsid >/dev/null 2>&1; then setsid sh "$@" </dev/null >"$r/o" 2>"$r/e" & '
|
|
63
|
+
'else set -m 2>/dev/null; sh "$@" </dev/null >"$r/o" 2>"$r/e" & fi; '
|
|
64
|
+
'p=$!; echo "$p" > "$r/pid"; '
|
|
65
|
+
"k8k(){ kill -KILL -- -$p 2>/dev/null || kill -KILL $p 2>/dev/null; }; "
|
|
66
|
+
"trap 'k8k' TERM HUP INT; "
|
|
67
|
+
'[ -f "$r/cancel" ] && k8k; '
|
|
68
|
+
'wd=; if [ -n "$t" ]; then ( sleep "$t"; : > "$r/to"; k8k ) </dev/null >/dev/null 2>&1 & wd=$!; fi; '
|
|
69
|
+
'wait "$p"; rc=$?; '
|
|
70
|
+
'while kill -0 "$p" 2>/dev/null && [ ! -f "$r/to" ] && [ ! -f "$r/cancel" ]; do wait "$p"; rc=$?; done; '
|
|
71
|
+
'[ -n "$wd" ] && kill "$wd" 2>/dev/null; '
|
|
72
|
+
'[ -n "$cf" ] && rm -f "$cf"; '
|
|
73
|
+
'to=0; [ -f "$r/to" ] && to=1; '
|
|
74
|
+
'os=$(wc -c < "$r/o"); es=$(wc -c < "$r/e"); os=$((os + 0)); es=$((es + 0)); '
|
|
75
|
+
'echo "K8RUN $rc $to $os $es"; '
|
|
76
|
+
'if [ $((os + es)) -le "$n" ]; then base64 < "$r/o"; echo K8SEP; base64 < "$r/e"; rm -rf "$r"; fi'
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
# $1 the wrapper script, $2 run dir: start the wrapper detached; it writes its answer to $2.out, then $2.done.
|
|
80
|
+
LAUNCH = (
|
|
81
|
+
'r=$2; mkdir -p "${r%/*}" 2>/dev/null; rm -f "$r.out" "$r.done"; '
|
|
82
|
+
"if command -v setsid >/dev/null 2>&1; then "
|
|
83
|
+
'setsid sh -c \'sh -c "$1" k8 >"$2.out" 2>/dev/null; : >"$2.done"\' k8 "$1" "$r" </dev/null >/dev/null 2>&1 & '
|
|
84
|
+
'else ( sh -c "$1" k8 >"$r.out" 2>/dev/null; : >"$r.done" ) </dev/null >/dev/null 2>&1 & fi; '
|
|
85
|
+
"echo K8STARTED"
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
# $1 run dir, $2 tenths of a second to wait: print the wrapper's answer once it is done, else K8WAIT.
|
|
89
|
+
WAIT = (
|
|
90
|
+
'r=$1; i=0; while [ ! -f "$r.done" ] && [ "$i" -lt "$2" ]; do sleep 0.1; i=$((i + 1)); done; '
|
|
91
|
+
'if [ -f "$r.done" ]; then cat "$r.out"; rm -f "$r.out" "$r.done"; else echo K8WAIT; fi'
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
# $1 run dir: mark it cancelled and kill the command's process group, if it started.
|
|
95
|
+
KILL = (
|
|
96
|
+
'r=$1; mkdir -p "$r" 2>/dev/null; : > "$r/cancel"; '
|
|
97
|
+
'p=$(cat "$r/pid" 2>/dev/null) && [ -n "$p" ] && { kill -KILL -- -"$p" 2>/dev/null || kill -KILL "$p" 2>/dev/null; }; '
|
|
98
|
+
"exit 0"
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
# $1 file, $2 chunk size, $3 chunk index: one chunk in base64.
|
|
102
|
+
CHUNK = 'dd if="$1" bs="$2" skip="$3" count=1 2>/dev/null | base64'
|
|
103
|
+
|
|
104
|
+
# $1 file, $2 w or a; data in K8_DATA (base64).
|
|
105
|
+
STAGE = (
|
|
106
|
+
'd=$K8_DATA; unset K8_DATA; mkdir -p "${1%/*}" || exit 1; '
|
|
107
|
+
'if [ "$2" = w ]; then : > "$1" || exit 1; fi; printf %s "$d" | base64 -d >> "$1"'
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class ExecAnswer(Protocol):
|
|
112
|
+
"""What one kosa8 buffered exec returns (``kosa8.CloudExecResult``)."""
|
|
113
|
+
|
|
114
|
+
exit_code: int | None
|
|
115
|
+
stdout: str
|
|
116
|
+
stderr: str
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
ExecFn = Callable[[list[str], Mapping[str, str]], Awaitable[ExecAnswer]]
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@dataclass(frozen=True)
|
|
123
|
+
class RunOutput:
|
|
124
|
+
exit_code: int
|
|
125
|
+
stdout: bytes
|
|
126
|
+
stderr: bytes
|
|
127
|
+
timed_out: bool = False
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class RunError(Exception):
|
|
131
|
+
"""The wrapper did not start or answered something this module does not understand."""
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class RunTimeout(Exception):
|
|
135
|
+
"""The command outlived its timeout and the in-sandbox watchdog did not report back in time."""
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def check_env(env: Mapping[str, str] | None) -> dict[str, str]:
|
|
139
|
+
out: dict[str, str] = {}
|
|
140
|
+
for key, value in (env or {}).items():
|
|
141
|
+
if not isinstance(key, str) or not _ENV_NAME_RE.match(key):
|
|
142
|
+
raise ValueError(f"invalid environment variable name: {key!r}")
|
|
143
|
+
if key.startswith("K8_"):
|
|
144
|
+
raise ValueError(f"environment variable names starting with K8_ are reserved: {key!r}")
|
|
145
|
+
if not isinstance(value, str):
|
|
146
|
+
raise TypeError(f"environment variable {key!r} must be a string, got {type(value).__name__}")
|
|
147
|
+
out[key] = value
|
|
148
|
+
return out
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def decode_b64(text: str) -> bytes:
|
|
152
|
+
cleaned = re.sub(r"[^A-Za-z0-9+/=]", "", text)
|
|
153
|
+
return base64.b64decode(cleaned) if cleaned else b""
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
class CommandRunner:
|
|
157
|
+
"""Runs commands through ``exec_fn`` (one buffered exec request per call)."""
|
|
158
|
+
|
|
159
|
+
def __init__(self, exec_fn: ExecFn, *, run_root: str) -> None:
|
|
160
|
+
self._exec = exec_fn
|
|
161
|
+
self._run_root = run_root.rstrip("/") or "/tmp"
|
|
162
|
+
|
|
163
|
+
async def run(
|
|
164
|
+
self,
|
|
165
|
+
script: str,
|
|
166
|
+
*,
|
|
167
|
+
cwd: str,
|
|
168
|
+
env: Mapping[str, str] | None = None,
|
|
169
|
+
timeout: float | None = None,
|
|
170
|
+
) -> RunOutput:
|
|
171
|
+
if timeout is not None and (isinstance(timeout, bool) or not math.isfinite(timeout)):
|
|
172
|
+
raise ValueError("timeout must be a finite number of seconds or None")
|
|
173
|
+
run_dir = f"{self._run_root}/{uuid.uuid4().hex}"
|
|
174
|
+
k8: dict[str, str] = {"K8_RUN": run_dir, "K8_CWD": cwd, "K8_INLINE": str(INLINE_BYTES), "K8_CMD": script}
|
|
175
|
+
secs: int | None = None
|
|
176
|
+
if timeout is not None:
|
|
177
|
+
secs = max(1, math.ceil(timeout))
|
|
178
|
+
k8["K8_TIMEOUT"] = str(secs)
|
|
179
|
+
argv = ["/bin/sh", "-c", LAUNCH, "k8", RUN, run_dir]
|
|
180
|
+
full_env = {**dict(env or {}), **k8}
|
|
181
|
+
try:
|
|
182
|
+
body = json.dumps({"cmd": argv, "env": [f"{k}={v}" for k, v in full_env.items()]})
|
|
183
|
+
if len(body) > BODY_LIMIT:
|
|
184
|
+
del full_env["K8_CMD"]
|
|
185
|
+
full_env["K8_CMDFILE"] = await self._stage(f"{run_dir}.sh", script.encode("utf-8"))
|
|
186
|
+
answer = await self._run_detached(argv, full_env, run_dir, secs)
|
|
187
|
+
return await self._result(answer, run_dir)
|
|
188
|
+
except BaseException:
|
|
189
|
+
await self.kill(run_dir)
|
|
190
|
+
raise
|
|
191
|
+
|
|
192
|
+
async def _run_detached(self, argv: list[str], env: Mapping[str, str], run_dir: str, secs: int | None) -> ExecAnswer:
|
|
193
|
+
started = await self._exec(argv, env)
|
|
194
|
+
if started.exit_code != 0 or started.stdout.strip() != "K8STARTED":
|
|
195
|
+
detail = (started.stderr or started.stdout).strip()[:300]
|
|
196
|
+
raise RunError(f"kosa8 could not start the command (exit {started.exit_code}): {detail}")
|
|
197
|
+
deadline = None if secs is None else time.monotonic() + secs + SERVER_GRACE_S
|
|
198
|
+
wait = ["/bin/sh", "-c", WAIT, "k8", run_dir, str(WAIT_S * 10)]
|
|
199
|
+
while True:
|
|
200
|
+
out = await self._exec(wait, {})
|
|
201
|
+
if out.exit_code == 0 and out.stdout.strip() == "K8WAIT":
|
|
202
|
+
if deadline is not None and time.monotonic() > deadline:
|
|
203
|
+
raise RunTimeout("the command outlived its timeout in the sandbox")
|
|
204
|
+
continue
|
|
205
|
+
return out
|
|
206
|
+
|
|
207
|
+
async def _result(self, out: ExecAnswer, run_dir: str) -> RunOutput:
|
|
208
|
+
head, _, rest = out.stdout.partition("\n")
|
|
209
|
+
fields = head.split()
|
|
210
|
+
if fields[:1] == ["K8FAIL"]:
|
|
211
|
+
raise RunError(f"kosa8 could not start the command: {head[7:]}")
|
|
212
|
+
if len(fields) != 5 or fields[0] != "K8RUN" or out.exit_code != 0:
|
|
213
|
+
detail = (out.stderr or out.stdout).strip()[:300]
|
|
214
|
+
raise RunError(f"kosa8 returned an unexpected answer for the command (exit {out.exit_code}): {detail}")
|
|
215
|
+
exit_code, timed_out, out_size, err_size = (int(value) for value in fields[1:])
|
|
216
|
+
if out_size + err_size <= INLINE_BYTES:
|
|
217
|
+
encoded_out, sep, encoded_err = rest.partition("K8SEP")
|
|
218
|
+
if not sep:
|
|
219
|
+
raise RunError("kosa8 returned incomplete command output")
|
|
220
|
+
stdout, stderr = decode_b64(encoded_out), decode_b64(encoded_err)
|
|
221
|
+
else:
|
|
222
|
+
try:
|
|
223
|
+
stdout = await self._read_back(f"{run_dir}/o", min(out_size, MAX_CAPTURE_BYTES))
|
|
224
|
+
stderr = await self._read_back(f"{run_dir}/e", min(err_size, MAX_CAPTURE_BYTES))
|
|
225
|
+
finally:
|
|
226
|
+
await self._exec(["rm", "-rf", run_dir], {})
|
|
227
|
+
if (len(stdout), len(stderr)) != (min(out_size, MAX_CAPTURE_BYTES), min(err_size, MAX_CAPTURE_BYTES)):
|
|
228
|
+
raise RunError("kosa8 returned incomplete command output")
|
|
229
|
+
return RunOutput(exit_code=exit_code, stdout=stdout, stderr=stderr, timed_out=bool(timed_out))
|
|
230
|
+
|
|
231
|
+
async def _read_back(self, path: str, size: int) -> bytes:
|
|
232
|
+
data = bytearray()
|
|
233
|
+
index = 0
|
|
234
|
+
while len(data) < size:
|
|
235
|
+
out = await self._exec(["/bin/sh", "-c", CHUNK, "k8", path, str(CHUNK_BYTES), str(index)], {})
|
|
236
|
+
if out.exit_code != 0:
|
|
237
|
+
raise RunError(f"could not read command output from kosa8: {out.stderr.strip()[:300]}")
|
|
238
|
+
chunk = decode_b64(out.stdout)
|
|
239
|
+
if not chunk:
|
|
240
|
+
break
|
|
241
|
+
data.extend(chunk)
|
|
242
|
+
index += 1
|
|
243
|
+
return bytes(data[:size])
|
|
244
|
+
|
|
245
|
+
async def kill(self, run_dir: str) -> None:
|
|
246
|
+
"""Best effort and shielded from cancellation: the caller's own error still propagates."""
|
|
247
|
+
task = asyncio.ensure_future(self._kill_once(run_dir))
|
|
248
|
+
try:
|
|
249
|
+
await asyncio.shield(task)
|
|
250
|
+
except BaseException:
|
|
251
|
+
pass
|
|
252
|
+
|
|
253
|
+
async def _kill_once(self, run_dir: str) -> None:
|
|
254
|
+
try:
|
|
255
|
+
await asyncio.wait_for(self._exec(["/bin/sh", "-c", KILL, "k8", run_dir], {}), KILL_TIMEOUT_S)
|
|
256
|
+
except Exception:
|
|
257
|
+
pass
|
|
258
|
+
|
|
259
|
+
async def _stage(self, path: str, data: bytes) -> str:
|
|
260
|
+
"""Put a command too large for one request body into a file in the sandbox; return its path."""
|
|
261
|
+
for index, start in enumerate(range(0, max(len(data), 1), STAGE_CHUNK_BYTES)):
|
|
262
|
+
part = data[start : start + STAGE_CHUNK_BYTES]
|
|
263
|
+
out = await self._exec(
|
|
264
|
+
["/bin/sh", "-c", STAGE, "k8", path, "w" if index == 0 else "a"],
|
|
265
|
+
{"K8_DATA": base64.b64encode(part).decode("ascii")},
|
|
266
|
+
)
|
|
267
|
+
if out.exit_code != 0:
|
|
268
|
+
raise RunError(f"could not stage a large command in the kosa8 sandbox: {out.stderr.strip()[:300]}")
|
|
269
|
+
return path
|
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
"""`Kosa8ShellTool`: a Microsoft Agent Framework shell executor backed by a kosa8 Cloud microVM.
|
|
2
|
+
|
|
3
|
+
Agent Framework's ``agent-framework-tools`` package defines :class:`~agent_framework_tools.shell.ShellExecutor`,
|
|
4
|
+
the swappable backend for shell tools (``LocalShellTool`` on the host, ``DockerShellTool`` in a
|
|
5
|
+
container). This module implements it on kosa8 Cloud:
|
|
6
|
+
|
|
7
|
+
- ``start`` / ``close`` / ``async with``: create the sandbox (or attach to one) and delete it.
|
|
8
|
+
- ``run(command, timeout=...)``: a buffered kosa8 exec that starts a small ``sh`` wrapper and waits
|
|
9
|
+
for it (see ``_exec.py``), returning the framework's :class:`ShellResult`.
|
|
10
|
+
- ``as_function()``: a ``FunctionTool`` with ``kind="shell"``, so ``client.get_shell_tool(func=...)``
|
|
11
|
+
recognises it, exactly like the built-in shell tools.
|
|
12
|
+
- ``as_code_function()`` and ``as_file_functions()``: optional Python and file tools on the same sandbox.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import asyncio
|
|
18
|
+
import base64
|
|
19
|
+
import errno
|
|
20
|
+
import logging
|
|
21
|
+
import posixpath
|
|
22
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
23
|
+
from typing import Any, Literal
|
|
24
|
+
|
|
25
|
+
from agent_framework import Content, FunctionTool, tool
|
|
26
|
+
from agent_framework._tools import SHELL_TOOL_KIND_VALUE
|
|
27
|
+
from agent_framework_tools.shell import ShellCommandError, ShellPolicy, ShellRequest, ShellResult
|
|
28
|
+
from kosa8 import AsyncCloud, AsyncCloudSandbox
|
|
29
|
+
from kosa8.errors import Kosa8ApiError, Kosa8NotFoundError
|
|
30
|
+
|
|
31
|
+
from ._exec import CommandRunner, RunError, RunTimeout, check_env
|
|
32
|
+
|
|
33
|
+
logger = logging.getLogger(__name__)
|
|
34
|
+
|
|
35
|
+
OnClose = Literal["delete", "sleep", "keep"]
|
|
36
|
+
ApprovalMode = Literal["always_require", "never_require"]
|
|
37
|
+
|
|
38
|
+
#: Files at or under this size go through the plain files endpoint; larger ones use the streamed one.
|
|
39
|
+
PLAIN_FILE_LIMIT = 8 * 1024 * 1024
|
|
40
|
+
#: Exit code reported for a command killed by its timeout (as GNU ``timeout`` does).
|
|
41
|
+
TIMEOUT_EXIT_CODE = 124
|
|
42
|
+
|
|
43
|
+
_SHELL_DESCRIPTION = (
|
|
44
|
+
"Execute a single shell command in an isolated kosa8 Cloud microVM sandbox (Linux, POSIX sh) and "
|
|
45
|
+
"return its stdout, stderr, and exit code. Files and installed packages persist in the sandbox between "
|
|
46
|
+
"calls; each command starts in a fresh shell in {workdir}, so `cd` and variables do not carry over."
|
|
47
|
+
)
|
|
48
|
+
_CODE_DESCRIPTION = (
|
|
49
|
+
"Run a Python 3 program in an isolated kosa8 Cloud microVM sandbox and return its stdout, stderr, and "
|
|
50
|
+
"exit code. Print what you want to see. Files written under {workdir} persist between calls."
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _egress_body(internet: bool | None, allow: Sequence[str] | None, presets: Sequence[str] | None) -> dict[str, Any] | None:
|
|
55
|
+
body: dict[str, Any] = {}
|
|
56
|
+
if internet is not None:
|
|
57
|
+
body["internet"] = internet
|
|
58
|
+
if allow is not None:
|
|
59
|
+
body["allow"] = list(allow)
|
|
60
|
+
if presets is not None:
|
|
61
|
+
body["presets"] = list(presets)
|
|
62
|
+
return body or None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _validate_limit(value: int, name: str) -> None:
|
|
66
|
+
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
|
|
67
|
+
raise ValueError(f"{name} must be a positive integer; got {value!r}")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _truncate(data: bytes, cap: int) -> tuple[str, bool]:
|
|
71
|
+
"""Keep the first and last halves of ``cap`` bytes, like the built-in shell tools."""
|
|
72
|
+
if len(data) <= cap:
|
|
73
|
+
return data.decode("utf-8", errors="replace"), False
|
|
74
|
+
head, tail = data[: cap // 2], data[-(cap - cap // 2) :]
|
|
75
|
+
omitted = len(data) - len(head) - len(tail)
|
|
76
|
+
text = head.decode("utf-8", errors="replace") + f"\n[... {omitted} bytes truncated ...]\n" + tail.decode("utf-8", errors="replace")
|
|
77
|
+
return text, True
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class _ShellText(str):
|
|
81
|
+
"""Model-facing text that keeps the structured :class:`ShellResult` for the result parser."""
|
|
82
|
+
|
|
83
|
+
shell_result: ShellResult
|
|
84
|
+
|
|
85
|
+
def __new__(cls, result: ShellResult) -> _ShellText:
|
|
86
|
+
value = super().__new__(cls, result.format_for_model())
|
|
87
|
+
value.shell_result = result
|
|
88
|
+
return value
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _parse_result(result: Any) -> str | list[Content]:
|
|
92
|
+
"""Keep stdout, stderr and the exit code next to the text, as the built-in shell tools do."""
|
|
93
|
+
if not isinstance(result, _ShellText):
|
|
94
|
+
return str(result)
|
|
95
|
+
r = result.shell_result
|
|
96
|
+
return [
|
|
97
|
+
Content.from_text(
|
|
98
|
+
str(result),
|
|
99
|
+
additional_properties={
|
|
100
|
+
"stdout": r.stdout,
|
|
101
|
+
"stderr": r.stderr,
|
|
102
|
+
"exit_code": r.exit_code,
|
|
103
|
+
"truncated": r.truncated,
|
|
104
|
+
"timed_out": r.timed_out,
|
|
105
|
+
},
|
|
106
|
+
)
|
|
107
|
+
]
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class Kosa8ShellTool:
|
|
111
|
+
"""Run an Agent Framework agent's shell commands in a kosa8 Cloud microVM sandbox.
|
|
112
|
+
|
|
113
|
+
Implements the ``ShellExecutor`` protocol from ``agent-framework-tools`` (``start``, ``close``,
|
|
114
|
+
``run``, ``async with``) and vends the shell as a ``FunctionTool``::
|
|
115
|
+
|
|
116
|
+
from agent_framework import Agent
|
|
117
|
+
from agent_framework.openai import OpenAIChatClient
|
|
118
|
+
from agent_framework_kosa8 import Kosa8ShellTool
|
|
119
|
+
|
|
120
|
+
client = OpenAIChatClient(model="gpt-5.4-nano")
|
|
121
|
+
async with Kosa8ShellTool(ttl_s=3600) as shell:
|
|
122
|
+
agent = Agent(client=client, tools=[client.get_shell_tool(func=shell.as_function())])
|
|
123
|
+
print(await agent.run("Write fizzbuzz.py, run it and show the output."))
|
|
124
|
+
|
|
125
|
+
The sandbox is created on first use (or by :meth:`start`) and deleted by :meth:`close`, so files
|
|
126
|
+
and installed packages last between commands. Each command runs in a fresh ``sh`` in ``workdir``.
|
|
127
|
+
|
|
128
|
+
**The microVM is the boundary.** Commands never run on your machine, so ``approval_mode``
|
|
129
|
+
defaults to ``"never_require"``. Pass ``"always_require"`` to have a person approve each command.
|
|
130
|
+
|
|
131
|
+
Args:
|
|
132
|
+
sandbox_id: Attach to an existing kosa8 sandbox instead of creating one.
|
|
133
|
+
api_key: kosa8 Cloud API key. Defaults to ``KOSA8_API_KEY``, then the key ``kosa8 login`` saved.
|
|
134
|
+
base_url: API address. Defaults to ``KOSA8_CLOUD_URL``, then ``https://api.kosa8.com``.
|
|
135
|
+
cloud: A ready ``kosa8.AsyncCloud`` to use instead (you close it).
|
|
136
|
+
template: kosa8 template for a new sandbox (default ``"python"``: Python 3.12 and a POSIX shell).
|
|
137
|
+
image: OCI image for a new sandbox, instead of a template.
|
|
138
|
+
size: vCPU x GiB for a new sandbox, such as ``"2x4"``.
|
|
139
|
+
region: ``"us-ash1"``, ``"eu-hel1"``, ``"us"`` or ``"eu"``. Chosen by kosa8 when unset.
|
|
140
|
+
ttl_s: Lifetime in seconds: kosa8 deletes the sandbox this long after it starts, even if
|
|
141
|
+
:meth:`close` never runs. Recommended.
|
|
142
|
+
sleep_after_s: Idle seconds before the sandbox sleeps; the next command wakes it.
|
|
143
|
+
persistent: Run every command in one long-lived container, so the whole filesystem and
|
|
144
|
+
background processes last between commands (otherwise only ``/workspace`` is promised).
|
|
145
|
+
env: Environment for every command. Sent with each command, never stored on the sandbox.
|
|
146
|
+
internet: ``False`` turns off the open internet for a new sandbox.
|
|
147
|
+
egress_allow: Hosts a new sandbox may reach.
|
|
148
|
+
egress_presets: Named host sets a new sandbox may reach, such as ``"pypi"``.
|
|
149
|
+
secrets: Names of org secrets a new sandbox holds (set in the kosa8 dashboard or CLI).
|
|
150
|
+
labels: Labels stored on a new sandbox.
|
|
151
|
+
name: Name stored on a new sandbox.
|
|
152
|
+
workdir: Directory commands start in, created when the sandbox starts. Relative file paths
|
|
153
|
+
resolve against it. Default ``/workspace``.
|
|
154
|
+
on_close: What :meth:`close` does with the sandbox: ``"delete"``, ``"sleep"`` or ``"keep"``.
|
|
155
|
+
Defaults to ``"delete"`` for a sandbox this object created and ``"keep"`` for one it attached to.
|
|
156
|
+
policy: A ``ShellPolicy`` applied before each command (a pre-filter, not a boundary).
|
|
157
|
+
timeout: Per-command timeout in seconds, enforced inside the sandbox. ``None`` disables. Default 30 s.
|
|
158
|
+
max_stdout_bytes: Bytes of stdout returned to the model (head and tail kept). Default 64 KiB.
|
|
159
|
+
max_stderr_bytes: Bytes of stderr returned to the model (head and tail kept). Default 64 KiB.
|
|
160
|
+
approval_mode: ``FunctionTool.approval_mode`` for the vended tools. Default ``"never_require"``.
|
|
161
|
+
on_command: Audit hook called with each command that passes the policy.
|
|
162
|
+
run_dir: Where the command wrapper keeps its run files inside the sandbox.
|
|
163
|
+
"""
|
|
164
|
+
|
|
165
|
+
def __init__(
|
|
166
|
+
self,
|
|
167
|
+
sandbox_id: str | None = None,
|
|
168
|
+
*,
|
|
169
|
+
api_key: str | None = None,
|
|
170
|
+
base_url: str | None = None,
|
|
171
|
+
cloud: AsyncCloud | None = None,
|
|
172
|
+
template: str | None = "python",
|
|
173
|
+
image: str | None = None,
|
|
174
|
+
size: str | None = None,
|
|
175
|
+
region: str | None = None,
|
|
176
|
+
ttl_s: int | None = None,
|
|
177
|
+
sleep_after_s: int | None = None,
|
|
178
|
+
persistent: bool | None = None,
|
|
179
|
+
env: Mapping[str, str] | None = None,
|
|
180
|
+
internet: bool | None = None,
|
|
181
|
+
egress_allow: Sequence[str] | None = None,
|
|
182
|
+
egress_presets: Sequence[str] | None = None,
|
|
183
|
+
secrets: Sequence[str] | None = None,
|
|
184
|
+
labels: Mapping[str, str] | None = None,
|
|
185
|
+
name: str | None = None,
|
|
186
|
+
workdir: str = "/workspace",
|
|
187
|
+
on_close: OnClose | None = None,
|
|
188
|
+
policy: ShellPolicy | None = None,
|
|
189
|
+
timeout: float | None = 30.0,
|
|
190
|
+
max_stdout_bytes: int = 64 * 1024,
|
|
191
|
+
max_stderr_bytes: int = 64 * 1024,
|
|
192
|
+
approval_mode: ApprovalMode = "never_require",
|
|
193
|
+
on_command: Callable[[str], None] | None = None,
|
|
194
|
+
run_dir: str = "/tmp/.agent-framework-kosa8",
|
|
195
|
+
) -> None:
|
|
196
|
+
if not workdir.startswith("/"):
|
|
197
|
+
raise ValueError(f"workdir must be an absolute path, got {workdir!r}")
|
|
198
|
+
if on_close not in (None, "delete", "sleep", "keep"):
|
|
199
|
+
raise ValueError(f"on_close must be 'delete', 'sleep' or 'keep', got {on_close!r}")
|
|
200
|
+
if approval_mode not in ("always_require", "never_require"):
|
|
201
|
+
raise ValueError(f"approval_mode must be 'always_require' or 'never_require', got {approval_mode!r}")
|
|
202
|
+
_validate_limit(max_stdout_bytes, "max_stdout_bytes")
|
|
203
|
+
_validate_limit(max_stderr_bytes, "max_stderr_bytes")
|
|
204
|
+
self.workdir = posixpath.normpath(workdir)
|
|
205
|
+
self._env = check_env(env)
|
|
206
|
+
self._sandbox_id = sandbox_id
|
|
207
|
+
self._attached = sandbox_id is not None
|
|
208
|
+
self.on_close: OnClose = on_close or ("keep" if self._attached else "delete")
|
|
209
|
+
create: dict[str, Any] = {
|
|
210
|
+
"template": None if image else template,
|
|
211
|
+
"image": image,
|
|
212
|
+
"size": size,
|
|
213
|
+
"region": region,
|
|
214
|
+
"ttl_s": ttl_s,
|
|
215
|
+
"sleep_after_s": sleep_after_s,
|
|
216
|
+
"persistent": persistent,
|
|
217
|
+
"egress": _egress_body(internet, egress_allow, egress_presets),
|
|
218
|
+
"secrets": list(secrets) if secrets is not None else None,
|
|
219
|
+
"labels": dict(labels) if labels else None,
|
|
220
|
+
"name": name,
|
|
221
|
+
}
|
|
222
|
+
self._create_kwargs = {k: v for k, v in create.items() if v is not None}
|
|
223
|
+
self._own_cloud = cloud is None
|
|
224
|
+
self._cloud = cloud if cloud is not None else AsyncCloud(api_key, base_url=base_url)
|
|
225
|
+
self._box: AsyncCloudSandbox | None = AsyncCloudSandbox(self._cloud, {"id": sandbox_id, "state": "running"}) if sandbox_id else None
|
|
226
|
+
self._policy = policy or ShellPolicy()
|
|
227
|
+
self._timeout = timeout
|
|
228
|
+
self._max_stdout_bytes = max_stdout_bytes
|
|
229
|
+
self._max_stderr_bytes = max_stderr_bytes
|
|
230
|
+
self._approval_mode: ApprovalMode = approval_mode
|
|
231
|
+
self._on_command = on_command
|
|
232
|
+
self._ready = False
|
|
233
|
+
self._closed = False
|
|
234
|
+
self._lock: asyncio.Lock | None = None
|
|
235
|
+
self._runner = CommandRunner(self._exec_request, run_root=run_dir)
|
|
236
|
+
|
|
237
|
+
def __repr__(self) -> str:
|
|
238
|
+
return f"Kosa8ShellTool(sandbox_id={self._sandbox_id!r}, workdir={self.workdir!r})"
|
|
239
|
+
|
|
240
|
+
# ------------------------------------------------------------------ kosa8 specifics
|
|
241
|
+
|
|
242
|
+
@property
|
|
243
|
+
def cloud(self) -> AsyncCloud:
|
|
244
|
+
"""The ``kosa8.AsyncCloud`` client this tool uses."""
|
|
245
|
+
return self._cloud
|
|
246
|
+
|
|
247
|
+
@property
|
|
248
|
+
def sandbox_id(self) -> str | None:
|
|
249
|
+
"""The kosa8 sandbox id (``sbx_...``), or ``None`` before the sandbox is created."""
|
|
250
|
+
return self._sandbox_id
|
|
251
|
+
|
|
252
|
+
@property
|
|
253
|
+
def sandbox(self) -> AsyncCloudSandbox | None:
|
|
254
|
+
"""The ``kosa8.AsyncCloudSandbox`` behind this tool, for kosa8 features the framework has no call for."""
|
|
255
|
+
return self._box
|
|
256
|
+
|
|
257
|
+
# ------------------------------------------------------------------ lifecycle (ShellExecutor)
|
|
258
|
+
|
|
259
|
+
async def start(self) -> None:
|
|
260
|
+
"""Create the kosa8 sandbox (or check the attached one) and its working directory. Idempotent."""
|
|
261
|
+
await self._ensure()
|
|
262
|
+
|
|
263
|
+
async def close(self) -> None:
|
|
264
|
+
"""Apply ``on_close`` to the sandbox (delete it by default) and close the HTTP client if this object opened it.
|
|
265
|
+
|
|
266
|
+
A sandbox that is already gone counts as deleted. Safe to call more than once.
|
|
267
|
+
"""
|
|
268
|
+
if self._closed:
|
|
269
|
+
return
|
|
270
|
+
self._closed = True
|
|
271
|
+
box, self._box = self._box, None
|
|
272
|
+
self._ready = False
|
|
273
|
+
try:
|
|
274
|
+
if box is not None:
|
|
275
|
+
if self.on_close == "delete":
|
|
276
|
+
try:
|
|
277
|
+
await box.delete()
|
|
278
|
+
except Kosa8NotFoundError:
|
|
279
|
+
pass
|
|
280
|
+
elif self.on_close == "sleep":
|
|
281
|
+
await box.sleep()
|
|
282
|
+
finally:
|
|
283
|
+
if self._own_cloud:
|
|
284
|
+
await self._cloud.aclose()
|
|
285
|
+
|
|
286
|
+
async def __aenter__(self) -> Kosa8ShellTool:
|
|
287
|
+
await self.start()
|
|
288
|
+
return self
|
|
289
|
+
|
|
290
|
+
async def __aexit__(self, *_exc: object) -> None:
|
|
291
|
+
await self.close()
|
|
292
|
+
|
|
293
|
+
async def _ensure(self) -> AsyncCloudSandbox:
|
|
294
|
+
if self._closed:
|
|
295
|
+
raise RuntimeError("this Kosa8ShellTool is closed")
|
|
296
|
+
if self._ready and self._box is not None:
|
|
297
|
+
return self._box
|
|
298
|
+
if self._lock is None:
|
|
299
|
+
self._lock = asyncio.Lock()
|
|
300
|
+
async with self._lock:
|
|
301
|
+
if self._ready and self._box is not None:
|
|
302
|
+
return self._box
|
|
303
|
+
if self._box is None:
|
|
304
|
+
self._box = await self._cloud.sandboxes.create(**self._create_kwargs)
|
|
305
|
+
self._sandbox_id = self._box.id
|
|
306
|
+
logger.debug("sandbox_id=<%s> | created kosa8 sandbox", self._box.id)
|
|
307
|
+
else:
|
|
308
|
+
# Checks the attached sandbox exists; a sleeping one wakes on the exec below.
|
|
309
|
+
await self._box.refresh()
|
|
310
|
+
out = await self._box.exec(["mkdir", "-p", "--", self.workdir])
|
|
311
|
+
if out.exit_code != 0:
|
|
312
|
+
raise OSError(f"could not create {self.workdir} in kosa8 sandbox {self._box.id}: {out.stderr.strip()}")
|
|
313
|
+
self._ready = True
|
|
314
|
+
return self._box
|
|
315
|
+
|
|
316
|
+
async def _exec_request(self, argv: list[str], env: Mapping[str, str]) -> Any:
|
|
317
|
+
box = await self._ensure()
|
|
318
|
+
return await box.exec(argv, env=dict(env) if env else None)
|
|
319
|
+
|
|
320
|
+
def _abs(self, path: str) -> str:
|
|
321
|
+
if not path:
|
|
322
|
+
raise ValueError("a path is required")
|
|
323
|
+
return posixpath.normpath(path if path.startswith("/") else posixpath.join(self.workdir, path))
|
|
324
|
+
|
|
325
|
+
# ------------------------------------------------------------------ execution (ShellExecutor)
|
|
326
|
+
|
|
327
|
+
async def run(self, command: str, *, timeout: float | None = None) -> ShellResult:
|
|
328
|
+
"""Run ``command`` under ``sh -c`` in ``workdir`` inside the sandbox and return its :class:`ShellResult`.
|
|
329
|
+
|
|
330
|
+
Applies the policy and the audit hook, not approval (the framework handles approval for the
|
|
331
|
+
tool returned by :meth:`as_function`). ``timeout`` overrides the configured one; it is enforced
|
|
332
|
+
inside the sandbox, where the command's whole process group is killed. A timed-out command
|
|
333
|
+
returns ``timed_out=True`` and exit code 124.
|
|
334
|
+
|
|
335
|
+
Raises:
|
|
336
|
+
ShellCommandError: If the policy rejects the command.
|
|
337
|
+
OSError: If kosa8 could not start the command or answered something unexpected.
|
|
338
|
+
kosa8.errors.Kosa8Error: If the kosa8 API refused the request.
|
|
339
|
+
"""
|
|
340
|
+
decision = self._policy.evaluate(ShellRequest(command=command, workdir=self.workdir))
|
|
341
|
+
if decision.decision == "deny":
|
|
342
|
+
raise ShellCommandError(f"Command rejected by policy: {decision.reason}")
|
|
343
|
+
if self._on_command is not None:
|
|
344
|
+
try:
|
|
345
|
+
self._on_command(command)
|
|
346
|
+
except Exception:
|
|
347
|
+
logger.exception("on_command hook raised")
|
|
348
|
+
effective = self._timeout if timeout is None else timeout
|
|
349
|
+
loop = asyncio.get_running_loop()
|
|
350
|
+
started = loop.time()
|
|
351
|
+
try:
|
|
352
|
+
out = await self._runner.run(command, cwd=self.workdir, env=self._env, timeout=effective)
|
|
353
|
+
except RunTimeout:
|
|
354
|
+
return ShellResult(
|
|
355
|
+
stdout="", stderr="", exit_code=TIMEOUT_EXIT_CODE, duration_ms=int((loop.time() - started) * 1000), timed_out=True
|
|
356
|
+
)
|
|
357
|
+
except RunError as e:
|
|
358
|
+
raise OSError(str(e)) from e
|
|
359
|
+
stdout, out_cut = _truncate(out.stdout, self._max_stdout_bytes)
|
|
360
|
+
stderr, err_cut = _truncate(out.stderr, self._max_stderr_bytes)
|
|
361
|
+
return ShellResult(
|
|
362
|
+
stdout=stdout,
|
|
363
|
+
stderr=stderr,
|
|
364
|
+
exit_code=TIMEOUT_EXIT_CODE if out.timed_out else out.exit_code,
|
|
365
|
+
duration_ms=int((loop.time() - started) * 1000),
|
|
366
|
+
truncated=out_cut or err_cut,
|
|
367
|
+
timed_out=out.timed_out,
|
|
368
|
+
)
|
|
369
|
+
|
|
370
|
+
async def run_python(self, code: str, *, timeout: float | None = None) -> ShellResult:
|
|
371
|
+
"""Run a Python 3 program in the sandbox (``python3 -`` in ``workdir``). The code is passed base64-encoded."""
|
|
372
|
+
encoded = base64.b64encode(code.encode("utf-8")).decode("ascii")
|
|
373
|
+
return await self.run(f"printf %s '{encoded}' | base64 -d | python3 -", timeout=timeout)
|
|
374
|
+
|
|
375
|
+
# ------------------------------------------------------------------ files (kosa8 files API)
|
|
376
|
+
|
|
377
|
+
async def read_file(self, path: str) -> bytes:
|
|
378
|
+
"""Read a file through the kosa8 files API. Relative paths resolve against ``workdir``.
|
|
379
|
+
|
|
380
|
+
Raises:
|
|
381
|
+
FileNotFoundError: If the file does not exist.
|
|
382
|
+
IsADirectoryError: If ``path`` is a directory.
|
|
383
|
+
PermissionError: If kosa8 refuses access to the path.
|
|
384
|
+
OSError: For other kosa8 errors.
|
|
385
|
+
"""
|
|
386
|
+
full = self._abs(path)
|
|
387
|
+
box = await self._ensure()
|
|
388
|
+
try:
|
|
389
|
+
try:
|
|
390
|
+
return await box.files.read(full)
|
|
391
|
+
except Kosa8ApiError as e:
|
|
392
|
+
if e.status != 413 and "too large" not in str(e).lower():
|
|
393
|
+
raise
|
|
394
|
+
return await box.files.read_raw(full)
|
|
395
|
+
except Kosa8ApiError as e:
|
|
396
|
+
raise self._file_error(e, path) from e
|
|
397
|
+
|
|
398
|
+
async def write_file(self, path: str, content: bytes | str) -> None:
|
|
399
|
+
"""Create or replace a file through the kosa8 files API. Parent directories are created."""
|
|
400
|
+
full = self._abs(path)
|
|
401
|
+
box = await self._ensure()
|
|
402
|
+
data = content.encode("utf-8") if isinstance(content, str) else bytes(content)
|
|
403
|
+
try:
|
|
404
|
+
if len(data) <= PLAIN_FILE_LIMIT:
|
|
405
|
+
await box.files.write(full, data)
|
|
406
|
+
else:
|
|
407
|
+
parent = posixpath.dirname(full)
|
|
408
|
+
if parent and parent != "/":
|
|
409
|
+
await box.files.mkdir(parent)
|
|
410
|
+
await box.files.write_raw(full, data)
|
|
411
|
+
except Kosa8ApiError as e:
|
|
412
|
+
raise self._file_error(e, path) from e
|
|
413
|
+
|
|
414
|
+
async def list_files(self, path: str = ".") -> list[dict[str, Any]]:
|
|
415
|
+
"""List a directory through the kosa8 files API: dicts with ``name``, ``path``, ``type`` and ``size``."""
|
|
416
|
+
full = self._abs(path)
|
|
417
|
+
box = await self._ensure()
|
|
418
|
+
try:
|
|
419
|
+
entries = await box.files.list(full)
|
|
420
|
+
except Kosa8ApiError as e:
|
|
421
|
+
raise self._file_error(e, path) from e
|
|
422
|
+
return [e for e in entries if e.get("name") not in (None, "", ".", "..")]
|
|
423
|
+
|
|
424
|
+
async def remove_file(self, path: str, *, recursive: bool = False) -> None:
|
|
425
|
+
"""Remove a file (or, with ``recursive=True``, a directory) through the kosa8 files API."""
|
|
426
|
+
full = self._abs(path)
|
|
427
|
+
box = await self._ensure()
|
|
428
|
+
try:
|
|
429
|
+
await box.files.delete(full, recursive=recursive)
|
|
430
|
+
except Kosa8ApiError as e:
|
|
431
|
+
raise self._file_error(e, path) from e
|
|
432
|
+
|
|
433
|
+
@staticmethod
|
|
434
|
+
def _file_error(e: Kosa8ApiError, path: str) -> OSError:
|
|
435
|
+
message = str(e)
|
|
436
|
+
lowered = message.lower()
|
|
437
|
+
if isinstance(e, Kosa8NotFoundError) or e.status == 404:
|
|
438
|
+
return FileNotFoundError(errno.ENOENT, "No such file or directory", path)
|
|
439
|
+
if "is a folder" in lowered or "is a directory" in lowered:
|
|
440
|
+
return IsADirectoryError(errno.EISDIR, "Is a directory", path)
|
|
441
|
+
if e.status == 403 and "permission" in lowered:
|
|
442
|
+
return PermissionError(errno.EACCES, "Permission denied", path)
|
|
443
|
+
return OSError(message)
|
|
444
|
+
|
|
445
|
+
# ------------------------------------------------------------------ Agent Framework wiring
|
|
446
|
+
|
|
447
|
+
def as_function(self, *, name: str = "run_shell", description: str | None = None) -> FunctionTool:
|
|
448
|
+
"""Return a ``FunctionTool`` bound to this sandbox, with ``kind="shell"``.
|
|
449
|
+
|
|
450
|
+
Provider factories such as ``OpenAIChatClient.get_shell_tool(func=...)`` recognise it as a
|
|
451
|
+
local shell; any chat client can also take it directly in ``tools=[...]``.
|
|
452
|
+
"""
|
|
453
|
+
|
|
454
|
+
async def _run_shell(command: str) -> str:
|
|
455
|
+
try:
|
|
456
|
+
result = await self.run(command)
|
|
457
|
+
except ShellCommandError as exc:
|
|
458
|
+
return str(exc)
|
|
459
|
+
return _ShellText(result)
|
|
460
|
+
|
|
461
|
+
text = description or _SHELL_DESCRIPTION.format(workdir=self.workdir)
|
|
462
|
+
_run_shell.__doc__ = text
|
|
463
|
+
return tool(
|
|
464
|
+
func=_run_shell,
|
|
465
|
+
name=name,
|
|
466
|
+
description=text,
|
|
467
|
+
approval_mode=self._approval_mode,
|
|
468
|
+
kind=SHELL_TOOL_KIND_VALUE,
|
|
469
|
+
result_parser=_parse_result,
|
|
470
|
+
)
|
|
471
|
+
|
|
472
|
+
def as_code_function(self, *, name: str = "execute_python", description: str | None = None) -> FunctionTool:
|
|
473
|
+
"""Return a ``FunctionTool`` that runs a Python 3 program in this sandbox."""
|
|
474
|
+
|
|
475
|
+
async def _execute_python(code: str) -> str:
|
|
476
|
+
try:
|
|
477
|
+
result = await self.run_python(code)
|
|
478
|
+
except ShellCommandError as exc:
|
|
479
|
+
return str(exc)
|
|
480
|
+
return _ShellText(result)
|
|
481
|
+
|
|
482
|
+
text = description or _CODE_DESCRIPTION.format(workdir=self.workdir)
|
|
483
|
+
_execute_python.__doc__ = text
|
|
484
|
+
return tool(func=_execute_python, name=name, description=text, approval_mode=self._approval_mode, result_parser=_parse_result)
|
|
485
|
+
|
|
486
|
+
def as_file_functions(self) -> list[FunctionTool]:
|
|
487
|
+
"""Return ``read_file``, ``write_file`` and ``list_files`` tools on this sandbox (paths relative to ``workdir``)."""
|
|
488
|
+
where = f"in the kosa8 sandbox (relative paths start at {self.workdir})"
|
|
489
|
+
cap = self._max_stdout_bytes
|
|
490
|
+
|
|
491
|
+
async def read_file(path: str) -> str:
|
|
492
|
+
try:
|
|
493
|
+
data = await self.read_file(path)
|
|
494
|
+
except OSError as exc:
|
|
495
|
+
return f"error: {exc}"
|
|
496
|
+
text, cut = _truncate(data, cap)
|
|
497
|
+
return text + ("\n[file truncated]" if cut else "")
|
|
498
|
+
|
|
499
|
+
async def write_file(path: str, content: str) -> str:
|
|
500
|
+
try:
|
|
501
|
+
await self.write_file(path, content)
|
|
502
|
+
except OSError as exc:
|
|
503
|
+
return f"error: {exc}"
|
|
504
|
+
return f"wrote {len(content.encode('utf-8'))} bytes to {self._abs(path)}"
|
|
505
|
+
|
|
506
|
+
async def list_files(path: str = ".") -> str:
|
|
507
|
+
try:
|
|
508
|
+
entries = await self.list_files(path)
|
|
509
|
+
except OSError as exc:
|
|
510
|
+
return f"error: {exc}"
|
|
511
|
+
lines = [f"{e.get('name')}{'/' if e.get('type') == 'dir' else ''}\t{e.get('size', '')}" for e in entries]
|
|
512
|
+
return "\n".join(lines) or "(empty)"
|
|
513
|
+
|
|
514
|
+
return [
|
|
515
|
+
tool(func=read_file, name="read_file", description=f"Read a UTF-8 text file {where}.", approval_mode=self._approval_mode),
|
|
516
|
+
tool(
|
|
517
|
+
func=write_file,
|
|
518
|
+
name="write_file",
|
|
519
|
+
description=f"Create or replace a text file {where}; parent folders are created.",
|
|
520
|
+
approval_mode=self._approval_mode,
|
|
521
|
+
),
|
|
522
|
+
tool(func=list_files, name="list_files", description=f"List a directory {where}.", approval_mode=self._approval_mode),
|
|
523
|
+
]
|
|
524
|
+
|
|
525
|
+
def as_tools(self) -> list[FunctionTool]:
|
|
526
|
+
"""All the tools: ``run_shell``, ``execute_python``, ``read_file``, ``write_file`` and ``list_files``."""
|
|
527
|
+
return [self.as_function(), self.as_code_function(), *self.as_file_functions()]
|
|
File without changes
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: agent-framework-kosa8
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: kosa8 Cloud microVM sandboxes for Microsoft Agent Framework: a ShellExecutor plus shell, Python and file tools
|
|
5
|
+
Project-URL: Homepage, https://kosa8.com
|
|
6
|
+
Project-URL: Documentation, https://github.com/kosa8ai/agent-framework-kosa8#readme
|
|
7
|
+
Project-URL: Repository, https://github.com/kosa8ai/agent-framework-kosa8
|
|
8
|
+
Project-URL: Issues, https://github.com/kosa8ai/agent-framework-kosa8/issues
|
|
9
|
+
Author: kosa8
|
|
10
|
+
License: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: agent-framework,agents,kosa8,microsoft-agent-framework,microvm,sandbox,shell
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
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.11
|
|
22
|
+
Requires-Dist: agent-framework-core<2,>=1.19.0
|
|
23
|
+
Requires-Dist: agent-framework-tools<2,>=1.0.0b261112
|
|
24
|
+
Requires-Dist: kosa8<1,>=0.12.0
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# agent-framework-kosa8
|
|
28
|
+
|
|
29
|
+
**[kosa8](https://kosa8.com): Zero Trust cybersecurity infrastructure for AI agents.** Every agent sealed in its own microVM. Every action verified and recorded.
|
|
30
|
+
|
|
31
|
+
Run a [Microsoft Agent Framework](https://github.com/microsoft/agent-framework) agent's shell commands, Python code and file edits in a [kosa8 Cloud](https://kosa8.com) microVM sandbox instead of on your machine.
|
|
32
|
+
|
|
33
|
+
`Kosa8ShellTool` implements Agent Framework's `ShellExecutor` protocol (from `agent-framework-tools`, the package behind `LocalShellTool` and `DockerShellTool`) on a kosa8 sandbox. Its `as_function()` returns the same kind of `kind="shell"` `FunctionTool` the built-in shell tools do, so it drops in wherever they go. Tested against `agent-framework-core` 1.26.0 and `agent-framework-tools` 1.0.0b261112 (Python).
|
|
34
|
+
|
|
35
|
+
## Install
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install agent-framework-kosa8
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
`agent-framework-tools` is still a beta on PyPI; this package asks for it by version, so `pip` installs it without `--pre`.
|
|
42
|
+
|
|
43
|
+
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, no card. Plans are at [kosa8.com/pricing](https://kosa8.com/pricing/).
|
|
44
|
+
|
|
45
|
+
## Example
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
import asyncio
|
|
49
|
+
|
|
50
|
+
from agent_framework import Agent
|
|
51
|
+
from agent_framework.openai import OpenAIChatClient
|
|
52
|
+
from agent_framework_kosa8 import Kosa8ShellTool
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
async def main() -> None:
|
|
56
|
+
client = OpenAIChatClient(model="gpt-5.4-nano")
|
|
57
|
+
async with Kosa8ShellTool(ttl_s=3600) as shell:
|
|
58
|
+
agent = Agent(
|
|
59
|
+
client=client,
|
|
60
|
+
instructions="You work in a Linux sandbox.",
|
|
61
|
+
tools=[client.get_shell_tool(func=shell.as_function())],
|
|
62
|
+
)
|
|
63
|
+
result = await agent.run("Write fizzbuzz.py in /workspace, run it and show the output.")
|
|
64
|
+
print(result.text)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
asyncio.run(main())
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
`async with` creates the sandbox and deletes it on the way out. Without it, the sandbox is created on the first command and deleted by `await shell.close()`.
|
|
71
|
+
|
|
72
|
+
Any chat client works: pass `shell.as_function()` in `tools=[...]` directly when the provider has no `get_shell_tool`.
|
|
73
|
+
|
|
74
|
+
## More tools on the same sandbox
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
agent = Agent(client=client, tools=shell.as_tools())
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
| Tool | What it does |
|
|
81
|
+
|---|---|
|
|
82
|
+
| `run_shell` (`as_function()`) | one command under `sh -c` in `workdir`; returns stdout, stderr and the exit code |
|
|
83
|
+
| `execute_python` (`as_code_function()`) | a Python 3 program, run with `python3` in `workdir` |
|
|
84
|
+
| `read_file`, `write_file`, `list_files` (`as_file_functions()`) | the kosa8 files API, no shell |
|
|
85
|
+
|
|
86
|
+
You can also call the sandbox from your own code: `await shell.run("make test")` returns the framework's `ShellResult`; `run_python`, `read_file`, `write_file`, `list_files` and `remove_file` work the same way. `shell.sandbox` is the `kosa8.AsyncCloudSandbox` for anything else kosa8 does (previews, snapshots, checkpoints, sleep).
|
|
87
|
+
|
|
88
|
+
## Approval
|
|
89
|
+
|
|
90
|
+
The microVM is the boundary: commands never run on your machine, so the tools default to `approval_mode="never_require"`. Pass `approval_mode="always_require"` to have a person approve each call through the framework's `user_input_requests`. `ShellPolicy` allow and deny lists and the `on_command` audit hook work as in the built-in shell tools; like there, the policy is a pre-filter, not a boundary.
|
|
91
|
+
|
|
92
|
+
## Options
|
|
93
|
+
|
|
94
|
+
| Option | Default | |
|
|
95
|
+
|---|---|---|
|
|
96
|
+
| `sandbox_id` | none | attach to an existing sandbox instead of creating one |
|
|
97
|
+
| `template` | `"python"` | kosa8 template (Python 3.12 and a POSIX shell) |
|
|
98
|
+
| `image` | none | OCI image, instead of a template |
|
|
99
|
+
| `size` | template size | vCPU x GiB: `0.25x0.5`, `0.5x1`, `1x2`, `2x4`, `4x8`, `8x16` or `16x32` |
|
|
100
|
+
| `region` | chosen by kosa8 | `us-ash1`, `eu-hel1`, `us` or `eu` |
|
|
101
|
+
| `ttl_s` | none | lifetime: kosa8 deletes the sandbox this many seconds after it starts, even if `close()` never runs. Recommended |
|
|
102
|
+
| `sleep_after_s` | account setting | idle seconds before the sandbox sleeps; it wakes on its next command |
|
|
103
|
+
| `persistent` | off | one long-lived container, so the whole filesystem and background processes last between commands |
|
|
104
|
+
| `env` | none | environment for every command, sent with each command and never stored on the sandbox |
|
|
105
|
+
| `internet` | on | `False` turns off the open internet |
|
|
106
|
+
| `egress_allow`, `egress_presets` | none | hosts, or named host sets such as `pypi`, the sandbox may reach |
|
|
107
|
+
| `secrets` | none | names of org secrets the sandbox holds (set in the kosa8 dashboard or CLI) |
|
|
108
|
+
| `labels`, `name` | none | stored on the sandbox |
|
|
109
|
+
| `workdir` | `/workspace` | where commands start; relative file paths resolve against it |
|
|
110
|
+
| `on_close` | `"delete"` (`"keep"` when attached) | what `close()` does: `"delete"`, `"sleep"` or `"keep"` |
|
|
111
|
+
| `policy` | allow all | a `ShellPolicy` checked before each command |
|
|
112
|
+
| `timeout` | 30 s | per-command timeout, enforced inside the sandbox; `None` disables |
|
|
113
|
+
| `max_stdout_bytes`, `max_stderr_bytes` | 64 KiB each | output returned to the model; the head and tail are kept |
|
|
114
|
+
| `approval_mode` | `"never_require"` | approval for every vended tool |
|
|
115
|
+
| `on_command` | none | audit hook called with each command |
|
|
116
|
+
| `api_key`, `base_url`, `cloud` | `KOSA8_API_KEY`, `https://api.kosa8.com` | or pass a ready `kosa8.AsyncCloud` (yours to close) |
|
|
117
|
+
|
|
118
|
+
## Limits
|
|
119
|
+
|
|
120
|
+
- Each command runs in a fresh `sh` in `workdir`: files and installed packages persist, `cd` and shell variables do not (like the built-in tools' stateless mode). There is no persistent-shell mode.
|
|
121
|
+
- Without `persistent=True`, only `/workspace` is promised to persist between commands.
|
|
122
|
+
- A timed-out command returns `timed_out=True` and exit code 124, with its whole process group killed in the sandbox.
|
|
123
|
+
- One tool instance is one sandbox: give each conversation or user its own and close it when done.
|
|
124
|
+
|
|
125
|
+
## How commands run
|
|
126
|
+
|
|
127
|
+
Each command is started by a small POSIX `sh` wrapper in a process group of its own, with stdin at EOF and its output redirected to files. A watchdog inside the sandbox enforces `timeout`; cancelling the call kills the command too. The client waits in polls of at most 50 s, so a command can run longer than one 90 s kosa8 request, and output comes back base64-encoded, so any bytes survive.
|
|
128
|
+
|
|
129
|
+
## Tests
|
|
130
|
+
|
|
131
|
+
```bash
|
|
132
|
+
uv run --group dev pytest # unit tests against a mocked kosa8 API
|
|
133
|
+
KOSA8_API_KEY=... uv run --group dev pytest tests/test_live.py # live tier on kosa8 Cloud
|
|
134
|
+
uv run --group dev ruff check .
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
The live tier gives each sandbox a 10-minute `ttl_s` and a label, deletes it, and checks it is gone. It also drives a real Agent Framework `Agent` with a scripted chat client, so no model is called.
|
|
138
|
+
|
|
139
|
+
## License
|
|
140
|
+
|
|
141
|
+
MIT. kosa8 is not affiliated with Microsoft.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
agent_framework_kosa8/__init__.py,sha256=d4_rK9n1_qUE-ZOe8jQTySBshmcibeQcmebjxm2SKRM,361
|
|
2
|
+
agent_framework_kosa8/_exec.py,sha256=UjeDJInAbjjZkcyL3WMNq2sPCGoa4dfl4Vp_e7ieneE,12443
|
|
3
|
+
agent_framework_kosa8/_shell.py,sha256=VCAKykFlTiNuCJ8-Jt8qVlZoc9YFfAprfYKeFiJoQEg,24814
|
|
4
|
+
agent_framework_kosa8/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
agent_framework_kosa8-0.1.0.dist-info/METADATA,sha256=D9S8asBjS0xG31RISlHFZBR4pW6L87hYnrxqaPfg6AI,7913
|
|
6
|
+
agent_framework_kosa8-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
7
|
+
agent_framework_kosa8-0.1.0.dist-info/licenses/LICENSE,sha256=RI1rC32bmO4K8wrw02bAUVNYa1DUnItwV_FUTberox8,1062
|
|
8
|
+
agent_framework_kosa8-0.1.0.dist-info/RECORD,,
|
|
@@ -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.
|