Metadata-Version: 2.5
Name: openai-agents-kosa8
Version: 0.1.0
Summary: kosa8 Cloud microVM sandboxes for the OpenAI Agents SDK
Project-URL: Homepage, https://kosa8.com
Project-URL: Documentation, https://github.com/kosa8ai/openai-agents-kosa8#readme
Project-URL: Repository, https://github.com/kosa8ai/openai-agents-kosa8
Project-URL: Issues, https://github.com/kosa8ai/openai-agents-kosa8/issues
Author: kosa8
License: MIT
License-File: LICENSE
Keywords: agents,kosa8,microvm,openai-agents,sandbox
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: <4.0,>=3.10
Requires-Dist: httpx>=0.25
Requires-Dist: kosa8<1,>=0.11.0
Requires-Dist: openai-agents<0.27,>=0.26.0
Description-Content-Type: text/markdown

# openai-agents-kosa8

Run an [OpenAI Agents SDK](https://openai.github.io/openai-agents-python/) sandbox agent's commands and file edits in a [kosa8 Cloud](https://kosa8.com) microVM sandbox instead of on your machine.

`Kosa8SandboxClient` is a sandbox client for the SDK's sandbox feature. Pass it to `SandboxRunConfig(client=...)` and the runner creates, uses and cleans up a kosa8 sandbox for each run. It follows the SDK's [Build a sandbox provider](https://openai.github.io/openai-agents-python/sandbox/custom-providers/) guide and is tested against `openai-agents` 0.26.

## Install

```bash
pip install openai-agents-kosa8
```

Set `KOSA8_API_KEY` to a kosa8 Cloud API key (create one at [app.kosa8.com](https://app.kosa8.com), or run `kosa8 login`). Plans are at [kosa8.com/pricing](https://kosa8.com/pricing/).

## Example

```python
import asyncio

from agents import RunConfig, Runner
from agents.sandbox import SandboxAgent, SandboxRunConfig
from agents.sandbox.capabilities import Shell
from openai_agents_kosa8 import Kosa8SandboxClient, Kosa8SandboxClientOptions


async def main() -> None:
    agent = SandboxAgent(name="coder", instructions="Work in the sandbox.", capabilities=[Shell()])
    async with Kosa8SandboxClient() as client:
        sandbox = SandboxRunConfig(client=client, options=Kosa8SandboxClientOptions(ttl_s=3600))
        result = await Runner.run(agent, "Write fizzbuzz.py, run it, show the output.", run_config=RunConfig(sandbox=sandbox))
        print(result.final_output)


asyncio.run(main())
```

The runner creates the sandbox when the run starts and deletes it when the run ends. Commands start in the manifest root, `/workspace` by default.

## Sessions you own

Create a session yourself to keep one sandbox across several runs. The runner uses it but does not close it:

```python
session = await client.create(options=Kosa8SandboxClientOptions(ttl_s=3600))
async with session:  # starts it; on the way out, persists (if a snapshot is configured) and deletes the sandbox
    config = RunConfig(sandbox=SandboxRunConfig(session=session))
    await Runner.run(agent, "Clone the repo.", run_config=config)
    await Runner.run(agent, "Now run the tests.", run_config=config)
```

`Kosa8SandboxClient()` opens its own HTTP pool; close it with `await client.aclose()` or `async with`. A `kosa8.AsyncCloud` you pass as `cloud=` is yours to close.

## Paused runs and resume

A run that stops for a tool approval saves the sandbox's session state in its `RunState`: the sandbox id and how the sandbox was created, never the API key or environment values. Resuming that state with a `Kosa8SandboxClient`:

- reconnects to the same sandbox if it still exists, waking it if it sleeps;
- otherwise starts a replacement, and the runner restores the workspace from the run's snapshot (`SandboxRunConfig(snapshot=LocalSnapshotSpec(base_path=...))`, or a remote snapshot).

With the default `on_exit="delete"` the sandbox is deleted when the paused run ends, so a resume restores from the snapshot. With `on_exit="sleep"` the sandbox sleeps between the pause and the resume, and kosa8 bills only its sleep storage meanwhile. Delete a sandbox that is never resumed with `await client.delete_sandbox(sandbox_id)`, or give it a `ttl_s`.

## Options

`Kosa8SandboxClientOptions` refuses unknown fields. Once this package is imported, `BaseSandboxClientOptions.parse({"type": "kosa8", ...})` returns it.

| Option | Default | |
|---|---|---|
| `template` | account default | kosa8 template for the sandbox |
| `image` | none | OCI image (a sized sandbox) |
| `size` | template size | vCPU x GiB: `0.25x0.5`, `0.5x1`, `1x2`, `2x4`, `4x8`, `8x16` or `16x32` |
| `region` | chosen by kosa8 | `us-ash1`, `eu-hel1`, `us` or `eu` |
| `ttl_s` | none | lifetime: kosa8 deletes the sandbox this many seconds after it starts (60 s to 90 days) |
| `sleep_after_s` | account setting | idle seconds before the sandbox sleeps; it wakes on its next command |
| `persistent` | off | run every command in one long-lived container, so the whole filesystem and background processes last between commands |
| `env` | none | environment for every command, kept on the sandbox (not in session state) |
| `internet` | on | `False` turns off the open internet |
| `egress_allow` | none | hosts the sandbox may reach |
| `egress_presets` | none | named host sets, such as `pypi` or `npm` |
| `secrets` | none | names of org secrets the sandbox holds (set in the kosa8 dashboard or CLI) |
| `labels`, `name` | none | stored on the sandbox |
| `exposed_ports` | none | ports `session.resolve_exposed_port(port)` may open as kosa8 previews, an https URL each |
| `public_ports` | `False` | open those previews as public URLs instead of signed links |
| `on_exit` | `"delete"` | what shutdown does with the sandbox: `"delete"`, `"sleep"` or `"keep"` |
| `workspace_persistence` | `"tar"` | `"tar"` archives the workspace root; `"snapshot"` takes a kosa8 snapshot of the whole sandbox and restores into a new sandbox started from it |
| `run_dir` | `/tmp/.kosa8-openai-agents` | where the command wrapper keeps its run files |

`Kosa8SandboxClient(api_key=None, base_url=None, cloud=None)` takes the key (default `KOSA8_API_KEY`, then the key `kosa8 login` saved), the API address (default `https://api.kosa8.com`), or a ready `kosa8.AsyncCloud`.

## What is supported

| SDK feature | kosa8 |
|---|---|
| `exec` with `timeout` | yes; a command may run longer than one 90 s buffered exec, and output is byte-exact |
| `read`, `write`, `read_bounded` | yes, through the kosa8 files API after the SDK's remote path check |
| `ls`, `mkdir`, `rm`, `mv`, `extract`, `apply_patch` | yes (the SDK's shell implementations) |
| manifest files, directories, local files, git repos, environment | yes |
| workspace snapshots (`persist_workspace` / `hydrate_workspace`) | yes: a tar, or a kosa8 snapshot |
| exposed ports | yes, as kosa8 previews |
| resume from saved state | yes |
| PTY sessions (`write_stdin`) | no: `supports_pty()` is `False`, so the Shell capability offers only `exec_command` |
| another user (`user=`, manifest `users` and `groups`) | no: refused with `ConfigurationError` |
| manifest mounts (S3, GCS and the like) | no: refused with `ConfigurationError` before any sandbox is created |

Errors from kosa8 Cloud become the SDK's sandbox errors (`WorkspaceStartError`, `ExecTransportError`, `ExecTimeoutError`, `WorkspaceArchiveReadError` and so on) with `retryable` set, and with the kosa8 `status`, `code`, `request_id` and, for a payment refusal, `upgrade_url` in `context`. The kosa8 error is the `cause`.

## Limits

- Without `persistent=True`, only `/workspace` is promised to persist between commands. Keep the manifest root under `/workspace` (the default).
- A command is a start request and then waits of at most 50 s each. Each output stream keeps its first 16 MiB.
- `"tar"` persistence stages the archive in `.kosa8-openai-agents/` under the workspace root (left out of the archive) and moves it through the files API; files over 8 MiB use the streamed endpoint.
- `"snapshot"` persistence makes a kosa8 snapshot each time the workspace is persisted, and kosa8 keeps it until you delete it.
- A replacement sandbox made on resume gets the saved creation settings but not the options' `env` values, which are never saved. The manifest environment is applied to every command either way.
- The sandbox image needs a POSIX `sh`, `base64`, `dd`, `tar` and the usual coreutils, which kosa8's templates include. The SDK's `mv` uses GNU `mv -T`.

## How commands run

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` and kills the process group; cancelling the call kills it too. The wrapper returns stdout and stderr base64-encoded, so any bytes survive, and reads large output back in chunks.

## Tests

```bash
uv run --group test pytest                                      # unit tests, against a fake kosa8 API
KOSA8_API_KEY=... uv run --group test pytest tests/test_live.py   # live tier, on kosa8 Cloud
```

The unit tests cover every session method this package implements, and the `Runner` path with `ScriptedModel`: client-owned sessions, app-owned sessions, persisted resume (restored from a snapshot, and reconnected to a sleeping sandbox), and cleanup after a tool error, a model error, a timeout, a cancellation and a partial start. The live tier (skipped without `KOSA8_API_KEY`) runs exec, files, a 9 MiB file, 3 MiB of output, a timeout, a command longer than one buffered exec, a workspace restored into a second (isolated) sandbox, egress on, off and allow-listed, a `Runner` run, kosa8 snapshot persistence and an exposed port.

## License

MIT
