agent-framework-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.
@@ -0,0 +1,11 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ venv/
5
+ dist/
6
+ build/
7
+ *.egg-info/
8
+ .pytest_cache/
9
+ .ruff_cache/
10
+ .env
11
+ .mypy_cache/
@@ -0,0 +1,9 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ - First version: `Kosa8ShellTool`, an Agent Framework `ShellExecutor` (from `agent-framework-tools`) on kosa8 Cloud microVMs, tested against `agent-framework-core` 1.26.0 and `agent-framework-tools` 1.0.0b261112.
6
+ - `as_function()` vends a `kind="shell"` `FunctionTool` (works with `client.get_shell_tool(func=...)`); `as_code_function()` adds `execute_python`; `as_file_functions()` adds `read_file`, `write_file` and `list_files`; `as_tools()` returns all five.
7
+ - Commands run over kosa8 buffered exec through a small `sh` wrapper, so they can outlive one 90 s request; `timeout` kills the command's process group inside the sandbox. `ShellPolicy`, `on_command`, and stdout/stderr byte limits work as in the built-in shell tools.
8
+ - Files through the kosa8 files API (the streamed endpoint past 8 MiB).
9
+ - The sandbox is created on first use and deleted by `close()` (or `async with`); attach to an existing one with `Kosa8ShellTool("sbx_...")`.
@@ -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,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,115 @@
1
+ # agent-framework-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
+ 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.
6
+
7
+ `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).
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pip install agent-framework-kosa8
13
+ ```
14
+
15
+ `agent-framework-tools` is still a beta on PyPI; this package asks for it by version, so `pip` installs it without `--pre`.
16
+
17
+ 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/).
18
+
19
+ ## Example
20
+
21
+ ```python
22
+ import asyncio
23
+
24
+ from agent_framework import Agent
25
+ from agent_framework.openai import OpenAIChatClient
26
+ from agent_framework_kosa8 import Kosa8ShellTool
27
+
28
+
29
+ async def main() -> None:
30
+ client = OpenAIChatClient(model="gpt-5.4-nano")
31
+ async with Kosa8ShellTool(ttl_s=3600) as shell:
32
+ agent = Agent(
33
+ client=client,
34
+ instructions="You work in a Linux sandbox.",
35
+ tools=[client.get_shell_tool(func=shell.as_function())],
36
+ )
37
+ result = await agent.run("Write fizzbuzz.py in /workspace, run it and show the output.")
38
+ print(result.text)
39
+
40
+
41
+ asyncio.run(main())
42
+ ```
43
+
44
+ `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()`.
45
+
46
+ Any chat client works: pass `shell.as_function()` in `tools=[...]` directly when the provider has no `get_shell_tool`.
47
+
48
+ ## More tools on the same sandbox
49
+
50
+ ```python
51
+ agent = Agent(client=client, tools=shell.as_tools())
52
+ ```
53
+
54
+ | Tool | What it does |
55
+ |---|---|
56
+ | `run_shell` (`as_function()`) | one command under `sh -c` in `workdir`; returns stdout, stderr and the exit code |
57
+ | `execute_python` (`as_code_function()`) | a Python 3 program, run with `python3` in `workdir` |
58
+ | `read_file`, `write_file`, `list_files` (`as_file_functions()`) | the kosa8 files API, no shell |
59
+
60
+ 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).
61
+
62
+ ## Approval
63
+
64
+ 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.
65
+
66
+ ## Options
67
+
68
+ | Option | Default | |
69
+ |---|---|---|
70
+ | `sandbox_id` | none | attach to an existing sandbox instead of creating one |
71
+ | `template` | `"python"` | kosa8 template (Python 3.12 and a POSIX shell) |
72
+ | `image` | none | OCI image, instead of a template |
73
+ | `size` | template size | vCPU x GiB: `0.25x0.5`, `0.5x1`, `1x2`, `2x4`, `4x8`, `8x16` or `16x32` |
74
+ | `region` | chosen by kosa8 | `us-ash1`, `eu-hel1`, `us` or `eu` |
75
+ | `ttl_s` | none | lifetime: kosa8 deletes the sandbox this many seconds after it starts, even if `close()` never runs. Recommended |
76
+ | `sleep_after_s` | account setting | idle seconds before the sandbox sleeps; it wakes on its next command |
77
+ | `persistent` | off | one long-lived container, so the whole filesystem and background processes last between commands |
78
+ | `env` | none | environment for every command, sent with each command and never stored on the sandbox |
79
+ | `internet` | on | `False` turns off the open internet |
80
+ | `egress_allow`, `egress_presets` | none | hosts, or named host sets such as `pypi`, the sandbox may reach |
81
+ | `secrets` | none | names of org secrets the sandbox holds (set in the kosa8 dashboard or CLI) |
82
+ | `labels`, `name` | none | stored on the sandbox |
83
+ | `workdir` | `/workspace` | where commands start; relative file paths resolve against it |
84
+ | `on_close` | `"delete"` (`"keep"` when attached) | what `close()` does: `"delete"`, `"sleep"` or `"keep"` |
85
+ | `policy` | allow all | a `ShellPolicy` checked before each command |
86
+ | `timeout` | 30 s | per-command timeout, enforced inside the sandbox; `None` disables |
87
+ | `max_stdout_bytes`, `max_stderr_bytes` | 64 KiB each | output returned to the model; the head and tail are kept |
88
+ | `approval_mode` | `"never_require"` | approval for every vended tool |
89
+ | `on_command` | none | audit hook called with each command |
90
+ | `api_key`, `base_url`, `cloud` | `KOSA8_API_KEY`, `https://api.kosa8.com` | or pass a ready `kosa8.AsyncCloud` (yours to close) |
91
+
92
+ ## Limits
93
+
94
+ - 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.
95
+ - Without `persistent=True`, only `/workspace` is promised to persist between commands.
96
+ - A timed-out command returns `timed_out=True` and exit code 124, with its whole process group killed in the sandbox.
97
+ - One tool instance is one sandbox: give each conversation or user its own and close it when done.
98
+
99
+ ## How commands run
100
+
101
+ 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.
102
+
103
+ ## Tests
104
+
105
+ ```bash
106
+ uv run --group dev pytest # unit tests against a mocked kosa8 API
107
+ KOSA8_API_KEY=... uv run --group dev pytest tests/test_live.py # live tier on kosa8 Cloud
108
+ uv run --group dev ruff check .
109
+ ```
110
+
111
+ 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.
112
+
113
+ ## License
114
+
115
+ MIT. kosa8 is not affiliated with Microsoft.
@@ -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