kosa8 docs Dashboard
esc
↑ ↓ move↵ openRuns in your browser; nothing you type is sent anywhere.

Guides / Agent frameworks / OpenAI Agents SDK

OpenAI Agents SDK

openai-agents-kosa8 is a sandbox client for the OpenAI Agents SDK's sandbox feature. Pass Kosa8SandboxClient to SandboxRunConfig(client=...) and the runner creates, uses and deletes a kosa8 Cloud microVM sandbox for each run, so the agent's commands and file edits run there, not on your machine. This is the recommended way to use kosa8 with the Agents SDK. The function tools in kosa8[openai-agents] remain for the kosa8 daemon on your own machine and for SDK releases the client does not support; see Function tools on your machine.

How this page was checked

Against the README and source of openai-agents-kosa8 0.1.0 on PyPI (kosa8ai/openai-agents-kosa8), whose 12 live tests passed on kosa8 Cloud; its Runner test uses a scripted model, not a real one. The function tools section is checked against the source of kosa8 0.11.0 (kosa8/integrations/openai_agents.py and _common.py), whose tests run against the SDK's mock daemon.

Install#

$ pip install openai-agents-kosa8
$ export KOSA8_API_KEY=…          # a kosa8 Cloud API key
$ export OPENAI_API_KEY=sk-…      # read by the Agents SDK, on this machine only

The package needs openai-agents 0.26 (>=0.26,<0.27) and Python 3.10 or later. Create a kosa8 Cloud API key at app.kosa8.com, or run kosa8 login; the client uses KOSA8_API_KEY first, then the key kosa8 login saved. Plans are at kosa8.com/pricing.

A sandbox agent on kosa8 Cloud#

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. The agent loop and the model calls stay in your process.

Sessions you own#

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

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 it 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 the package is imported, BaseSandboxClientOptions.parse({"type": "kosa8", ...}) returns it.

OptionDefaultWhat it does
templateaccount defaultkosa8 template for the sandbox
imagenoneOCI image (a sized sandbox)
sizetemplate sizevCPU x GiB: 0.25x0.5, 0.5x1, 1x2, 2x4, 4x8, 8x16 or 16x32
regionchosen by kosa8Where the sandbox runs
ttl_snoneLifetime: kosa8 deletes the sandbox this many seconds after it starts (60 s to 90 days)
sleep_after_saccount settingIdle seconds before the sandbox sleeps; it wakes on its next command
persistentoffRun every command in one long-lived container, so the whole filesystem and background processes last between commands
envnoneEnvironment for every command, kept on the sandbox (not in session state)
internetonFalse turns off the open internet
egress_allownoneHosts the sandbox may reach
egress_presetsnoneNamed host sets, such as pypi or npm
secretsnoneNames of org secrets the sandbox holds (set in the kosa8 dashboard or CLI)
labels, namenoneStored on the sandbox
exposed_portsnonePorts session.resolve_exposed_port(port) may open as kosa8 previews, an https URL each
public_portsFalseOpen 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-agentsWhere 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 featurekosa8
exec with timeoutYes; a command may run longer than one 90 s buffered exec, and output is byte-exact
read, write, read_boundedYes, through the kosa8 files API after the SDK's remote path check
ls, mkdir, rm, mv, extract, apply_patchYes (the SDK's shell implementations)
Manifest files, directories, local files, git repos, environmentYes
Workspace snapshots (persist_workspace / hydrate_workspace)Yes: a tar, or a kosa8 snapshot
Exposed portsYes, as kosa8 previews
Resume from saved stateYes
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.

Function tools on your machine#

The kosa8 Python SDK also has function tools for the Agents SDK, for a sandbox from the kosa8 daemon on your own machine, or an SDK release openai-agents-kosa8 does not support. kosa8.integrations.openai_agents.sandbox_tools() binds seven tools to one kosa8 sandbox, so the shell commands, code, file edits and git operations the model asks for run in a microVM with its own kernel.

$ curl -fsSL https://kosa8.com/install | sh
$ kosa8 daemon start
$ pip install 'kosa8[openai-agents]'
$ export OPENAI_API_KEY=sk-…      # read by the Agents SDK, on this machine only

The extra installs openai-agents. Sandboxes run on an Apple silicon Mac, an x86-64 Linux machine with KVM, or Windows 11 through WSL2 (preview). Kosa8Client() connects to the daemon at ~/.kosa8/run/kosa8.sock, or to a remote worker named by KOSA8_HOST and KOSA8_TOKEN.

An agent with sandbox tools#

from agents import Agent, Runner
from kosa8 import Kosa8Client
from kosa8.integrations.openai_agents import sandbox_tools

client = Kosa8Client()
sbx = client.create_sandbox(name="coder-1", ephemeral=True, auto_stop_min=15,
                            egress_allow=["pypi.org", "files.pythonhosted.org"])
sid = sbx["sandbox"]["id"]

agent = Agent(
    name="coder",
    instructions="You work in a Linux sandbox. Keep your files in /workspace.",
    tools=sandbox_tools(client, sid),
)
try:
    result = Runner.run_sync(agent, "Write fizzbuzz.py, run it for 1..15 and show the output.")
    print(result.final_output)
finally:
    client.stop_sandbox(sid)   # ephemeral: stopping deletes it

The tools#

ToolWhat it does
sandbox_run_codeRuns Python, JavaScript or TypeScript, starting in /workspace. Reports charts it drew and a timeout.
sandbox_shellRuns a command line with sh. cd and export carry to the next call.
sandbox_read_fileReads a text file under /workspace. A binary file is reported by size, not shown.
sandbox_write_fileCreates or replaces a file, making its folders.
sandbox_list_filesLists a folder; folders end in /.
sandbox_gitclone, status, add, commit, push, pull, checkout, branches, log, diff.
sandbox_previewA signed link, which expires, to a web server listening on a port in the sandbox.

Tool options#

sandbox_tools(client, sandbox, *, tools=None, session="agent", approval=None, name_prefix="sandbox_")
OptionDefaultWhat it does
toolsall sevenA subset of run_code, shell, read_file, write_file, list_files, git, preview. An unknown name raises ValueError.
session"agent"The shell session the tools share
approvalnoneA signed approval sent with every call
name_prefix"sandbox_"Prefix of each tool's name

The sandbox itself is set when you create it:

create_sandbox argumentWhat it does
egress_allow=[...]Only these hosts are reachable. Shorthand for egress={"allow": [...]}.
egress"deny", "any", "fakenet" or "allow:a.com,b.com". Left out, the org policy's default applies.
ephemeralDelete the sandbox whenever it stops
auto_stop_min, ttl_min, auto_delete_minStop after idle minutes, stop that long after creation, delete once stopped that long
cpus, mem_mb, disk_gbSize
mountsHost folders to share. Leave it out to share nothing.
templateStart from a template's image

Errors#

A tool never raises a kosa8 error into the run. It returns text that starts with error:, with the daemon's reason and, when it has one, a what to do: line, so the model can change course. A command that the sandbox's network rule blocks is not a kosa8 error: it fails inside the sandbox, and sandbox_shell returns its exit code and output. Output is cut to 20,000 characters, keeping the start and the end.

Other ways#

  • The SDK's Docker sandbox. Set DOCKER_HOST=unix://$HOME/.kosa8/run/kosa8.sock and DockerSandboxClient creates containers in kosa8's shared engine VM. See the local sandbox guide.
  • Plain functions. kosa8.integrations.sandbox_functions(client, sandbox) returns the same tools as Python functions with type hints and docstrings; see Agents SDK, LangChain.

What it does not cover#

  • The agent loop, the model calls and your own Python function tools run in your process, outside the VM.
  • Values you give the sandbox in env or secrets can be read by the commands in it.
  • kosa8 limits what model-written code can reach. It does not detect or stop prompt injection.
  • An allowed host that accepts uploads is still a way out; allow as few as the task needs.

The overview with steps and FAQs is on kosa8.com: Run the OpenAI Agents SDK in a microVM sandbox.

Something wrong or missing? Write to contact@kosa8.com.

The kosa8 newsletter

A short daily email with that day's article and one tip. Switch to weekly or unsubscribe in one click.

© 2026 kosa8 · kosa8.com · Zero Trust cybersecurity infrastructure for AI agents · Local models served by llamay · Agent gateway: MAQPNA