# kosa8 docs, in full > kosa8 is Zero Trust cybersecurity infrastructure for AI agents. It gives every AI agent a sealed sandbox of its own: a microVM you can checkpoint, rewind and fork, memory and processes included. kosa8 Cloud runs them on kosa8's hosts (https://api.kosa8.com, region us-ash1, Ashburn, Virginia) from a CLI, an HTTP API, an MCP server and SDKs for Python, JavaScript, Go, Ruby and Java. kosa8d runs the same sandboxes on Mac, Linux and Windows, on your own servers, or air-gapped. # kosa8 for AI agents You are an AI agent, and the person you work for wants you to use kosa8: Zero Trust cybersecurity infrastructure for AI agents. Code you run goes into a microVM of its own, not onto their machine. On their own Mac (or Linux or Windows machine) any mistake can be rewound to a checkpoint; kosa8 Cloud runs sandboxes on kosa8's hosts. This page is written for you. Follow it in order. Every step is a command you can run, and the one step that needs the person says so. The path, in four steps: 1. Try with no account: `POST https://api.kosa8.com/v1/try/agent` (step 0 below). 2. Get the person's approval: they sign in or sign up, free (Starter, no card), and approve you. Over plain HTTP with no install: the device sign-in (`POST https://api.kosa8.com/v1/auth/device` with `{"client":"agent"}`, below). With the CLI installed: `kosa8 login` (step 3 below). 3. Use kosa8 with their account: the CLI, the REST API (https://api.kosa8.com/openapi.json), the SDKs, or the hosted MCP server at https://api.kosa8.com/mcp, with an API key (`KOSA8_API_KEY`). 4. When they need more: see "When the person needs to pay" below. ## 0. Try it now, no key, no install (optional) To see kosa8 run code before the person signs up, call the keyless agent trial. No API key, no CAPTCHA, no account: ``` curl -s https://api.kosa8.com/v1/try/agent \ -H 'Content-Type: application/json' \ -d '{"language":"python","code":"print(2+2)"}' ``` `language` is `python` (the default), `node` or `bash`; `code` is up to 8 KiB. Each run is up to 60 s in a fresh sandbox with no outbound network, deleted after the run. Each network address has a small budget: 5 minutes (300 s) of run time per 24 hours, 10 runs an hour and 100 a day (`GET https://api.kosa8.com/v1/try/agent` describes it and shows the quota left). When it is used up the answer is 402 `signup_required` with an `agent_message`: relay it to the person and go on to step 1. Don't try to get around the budget. ## Get the person's approval over HTTP (no install; this step needs the person) When you need an API key and the kosa8 CLI is not installed, start a device sign-in. No key needed; `name` is optional (what you call yourself, up to 60 characters, shown to the person): ``` curl -s https://api.kosa8.com/v1/auth/device \ -H 'Content-Type: application/json' \ -d '{"client":"agent","name":"Claude Code"}' # {"device_code":"...","user_code":"BCDF-GH23","verification_uri_complete":"https://app.kosa8.com/device?code=BCDF-GH23", # "interval":2,"expires_in":600,"token_url":"https://api.kosa8.com/v1/auth/device/token","agent_message":"..."} ``` Give the person `verification_uri_complete`, or relay `agent_message` word for word. They open it, sign in or sign up free (Starter: $10 of usage, no card) and press Approve. Keep `device_code` to yourself. Poll every `interval` seconds: ``` curl -s https://api.kosa8.com/v1/auth/device/token \ -H 'Content-Type: application/json' \ -d '{"device_code":"DEVICE_CODE"}' ``` 428 `authorization_pending`: keep waiting. 429 `slow_down`: poll less often. 403 `access_denied`: the person said no; stop. 410 `expired_token`: ten minutes passed; start again only if the person asks. 200, exactly once: `{api_key, org, plan, starter, needs_plan, plan_url, ...}`. Use the key as `Authorization: Bearer ` (or `KOSA8_API_KEY`). It has the person's access without admin: it runs sandboxes and functions and can make a payment link (below), but cannot pay, change billing or the spend cap, or cancel. The person can revoke it under API keys. ## Pricing kosa8 is commercial software with a free Starter tier. One account covers every platform (kosa8 Cloud, the web app, the desktop app, the CLI). - Starter: free, no card, once the person confirms their sign-up email. $10 of one-time kosa8 Cloud usage, no time limit, 2 sandboxes running, each up to 2 vCPU and 4 GB, 60-minute sessions, outbound network to an allow-list (package registries, GitHub, Hugging Face, model APIs). It stops at the limit (402 `starter_limit`, 429 at the running limit) and never bills. - Plans from $29 a month (https://kosa8.com/pricing/) include Cloud sandbox-hours and differ by features and limits (sandboxes running at once, the largest size, persistent sandboxes, snapshots, forks). Above a plan's hours, usage is billed per second up to a spend cap the person sets, on by default at $50, with alerts at 50%, 75% and 100% (402 `spend_cap` at the cap). A new paid account runs at most $50 a month above its plan until 30 days after its first payment (402 `new_account_limit`). A failed renewal pauses new work at once, with no grace (402 `payment_failed`, with `portal_url`), until it is paid; running work and data are kept. Never add a card, raise a cap or buy a plan for the person: relay the 402's `agent_message` and `upgrade_url` to them. ### When the person needs to pay When the person outgrows Starter or reaches a limit, kosa8 answers 402 with `agent_message` and `upgrade_url` (a `plan_limit` also carries `options`, the cheapest monthly fix first). Relay `agent_message` word for word. A 402 `starter_limit` or `plan_required` names the cheapest plan that fits, with its price. To make a payment link for one plan, call `POST https://api.kosa8.com/v1/billing/checkout` with `{"plan":"solo"}` (or `pro`, `team`, `scale`; `"yearly":true` for yearly; Team and Scale also take `seats`) using an API key approved by the account owner, such as your agent key from the device sign-in: it answers `{"url", "plan", "agent_message"}`; give the person the link or relay `agent_message`. A key approved by anyone else gets 403: relay `upgrade_url` instead. The person pays; you never pay, enter card details or raise a cap. Which plan fits a workload: https://kosa8.com/pricing.md#which-plan-is-cheapest-for-a-workload Every price, limit, per-second rate, 402 code, refund and cancel term, with worked cost examples: https://kosa8.com/pricing.md (or https://kosa8.com/pricing.json). ## 1. Is kosa8 installed? ``` kosa8 version ``` If that works, go to step 3. If the command is not found, install it. **Check which release you have.** The current release is **v0.24.0**, and every command on this page is in it. If `kosa8 version` reports an older release and a command answers `unknown command` (or, for `kosa8 login`, asks for a registry password), the install is out of date. Don't retry it and don't look for a workaround: tell the person, and update with the install command in step 2. ## 2. Install macOS and Linux: ``` curl -fsSL https://kosa8.com/install | sh ``` Windows (PowerShell): ``` irm https://kosa8.com/install.ps1 | iex ``` Tell the person what you are installing before you run it, the same as any installer. Then run `kosa8 doctor`. It checks the machine and says what to fix, in plain words. On Windows 11 (x86-64), sandboxes run through WSL2 (preview): run `kosa8 wsl setup` once, and it sets up the Linux engine and connects the CLI to it. Windows 10 and Windows on ARM cannot run sandboxes themselves: use kosa8 Cloud, or drive a Mac or Linux machine (see the last section). A second Windows option (preview, in the download since v0.18.0): `kosa8d.exe` runs sandboxes as gVisor containers on Docker Desktop, which are not microVMs. ## 3. Sign up (this step needs the person) A new install needs the person to sign in (or sign up) before it runs. Commands that start sandboxes refuse until they have. Check first: ``` kosa8 signup --json ``` If it says `"signed_up": true`, go to step 4. If it says `"signed_up": false`, its answer says the next step is `kosa8 login`. Run it like this: ``` kosa8 login --no-browser ``` It prints a short code and a link (to stderr), then waits up to ten minutes. **Give the person both** and ask them to open the link on any device, sign in or create their account (Starter is free, with no card), and confirm the code. The command finishes by itself once they have, and the machine is signed up with their account's email. Run it with a long timeout or in the background. Never sign in on their behalf, never make up an email address, and never enter card details yourself. The account and the card belong to the person. Signing in puts the account's plan on this machine. An account with no card and no plan starts on the free Starter tier. If the person is at this machine with a browser, plain `kosa8 login` opens it for them. It is the one kosa8 account used by the CLI, the desktop app and app.kosa8.com. If they already have a licence key: `kosa8 license activate KEY`. ## 4. Start the daemon ``` kosa8 daemon start ``` It runs in the background and keeps running. `kosa8 doctor` confirms it is up. ## 5. Give a task to an agent in a sandbox The shortest path is one command, `kosa8 prompt`: ``` kosa8 prompt "add a test for parseConfig and make it pass" ``` That makes a fresh sandbox, shares the current directory into it at `/work`, runs Claude Code headless on the task, prints the agent's output, and removes the sandbox. The exit status is the agent's. The agent's network is limited to the hosts its kit allows. Its API key stays on the host, in kosa8's broker, and the sandbox only ever holds a placeholder. Every tool call is checked before it runs, and everything is in the audit log (`kosa8 audit ls`). - Another agent: `-a codex`, `-a gemini`, `-a qwen`, `-a opencode`, `-a crush`, `-a copilot`, or `-a shell` for a plain shell command. - Another folder: `-w ~/src/api`. - No network at all: `--no-network`. - Long input: pipe it in, `git diff | kosa8 prompt -`. - See the plan without running: `--dry-run`. - Keep the sandbox afterwards: `--keep`. `kosa8 sandbox ls` shows it, and `kosa8 sandbox rm NAME` removes it. The agent needs its provider's key on the host: for claude, either `CLAUDE_CODE_OAUTH_TOKEN` (the person's Claude subscription; they make it with `claude setup-token` in their own terminal) or `ANTHROPIC_API_KEY`; `OPENAI_API_KEY` for codex; `GEMINI_API_KEY` for gemini. If one is missing, `kosa8 prompt` warns. Ask the person to set it. Don't go looking for it in their files. ## 6. Or work in sandboxes yourself, with MCP tools To run code yourself in a sandbox, instead of handing a task to another agent: ``` kosa8 mcp install # adds kosa8's tools to every MCP client it finds (or name one: gemini, vscode, zed, ...) kosa8 skill install # teaches you when and how to use them (or name your agent: gemini, copilot, ...) ``` The same guidance is also an Agent Skill (`skills/kosa8/SKILL.md`, which adds kosa8 Cloud, fan-out and RL rollouts) for agents that install skills with the `skills` CLI: `npx skills add AzmxAI/kosa8`. That needs read access to the AzmxAI/kosa8 repository; if it fails, use `kosa8 skill install` above. The person may need to restart their agent for the tools to appear. The tools are `sandbox_create`, `sandbox_shell`, `sandbox_code_run`, the `sandbox_file_*` tools, `sandbox_git`, `sandbox_checkpoint`, `sandbox_rewind`, `sandbox_fork`, `sandbox_preview` and `sandbox_delete`. `kosa8 skill show` prints the guide. `kosa8 agent compat` lists every agent and client kosa8 supports and how. If the person runs Claude Code or Cursor on their own machine and wants each of its tool calls checked first, `kosa8 hooks install claude-code` (or `cursor`) adds kosa8's hook to that agent's settings; `kosa8 hooks status` shows it and `kosa8 hooks uninstall` removes it. Ask before installing it: once in, every checked call is refused while kosa8d is not running. To use someone else's Agent Skill, import it with `kosa8 skill add SOURCE`: it is scanned and pinned first, and anything risky is refused unless the person accepts it. ## When kosa8 says it needs a plan Every account needs a plan, and each plan has hard limits and a set of features. On kosa8 Cloud a refusal is a 402 with one of three codes, each with `message`, `upgrade_url` and `agent_message`: - `plan_required`: the account has no plan yet. - `plan_limit`: a limit of the plan is reached (`limit_name`, `limit`, `used`, `plan`, `next_plan`), for example "Solo includes 2 sandboxes running at once; Pro includes 10". When an add-on pack also lifts it (sandbox-hours, running at once), `options` lists both ways past it, cheapest monthly cost first: `{kind: "pack", addon, label, monthly_usd, url}` and `{kind: "upgrade", plan, label, monthly_usd, url}`, with `pack_url`. Tell the person both; the choice and the purchase are theirs. - `plan_feature`: the feature is on a higher plan (`feature`, `next_plan`). A `503 no_capacity` is different: kosa8's hosts are full for a moment (kosa8 adds hosts when it needs them). Wait the seconds in its `Retry-After` header and try again. It is not a plan limit; do not suggest an upgrade for it. Tell the person the `agent_message` word for word and stop; do not retry until they act, and never buy or upgrade a plan yourself. Locally, every refusal at a plan limit (too many forks, a sandbox disk over the plan's size, a product the plan does not carry, or no plan at all) ends in one line naming the plan that unlocks it, its price, and the command. Run with `--json` and the refusal is also written to stdout as data: ``` { "error": "Solo allows 4 forks at once; ...", "upgrade": { "plan": "pro", "kind": "plan", "name": "Pro", "price_usd": 89, "price": "$89 a month", "unlocks": "16 forks at once", "url": "https://buy.polar.sh/...", "command": "kosa8 upgrade pro" } } ``` `kind` is `plan`, `addon` (a capacity add-on; `plan` is its id) or `contract` (Enterprise: `price_usd` is 0 because it is quoted, and `url` is where to talk to a person). The exit code is 1. - Relay `upgrade` to the person as it is: what it unlocks, the price, and the command or link. Don't round the price or pick a different plan. - Check where the machine stands: `kosa8 license status --json`. It carries `plan` (`unlicensed` means no plan) and, with no plan, the same `upgrade` object for the plan that fits what this machine ran. A machine that started a trial before kosa8 stopped offering them keeps its remaining days (`plan: "trial"`, `trial_days_left`); no new trial starts. - Buying is the person's decision, and payment is theirs to make. Never run `kosa8 upgrade` without `--no-open` on their behalf: with `--no-open` it only prints the checkout link. The checkout takes their card and charges at once; nothing is charged until they complete it. Plans are compared at https://kosa8.com/pricing/ - After they pay, Polar emails them a licence key. Ask them for it, then run `kosa8 license activate KEY`. - More forks than the plan allows: tell the person the refusal's options (remove a fork, a $49 Burst Pass for 24 hours, the plan in `upgrade`, or overage, which they turn on with `kosa8 license overage on`). Never turn overage on yourself; it bills them by the hour. ## No sandbox engine on this machine? kosa8 runs sandboxes on Apple-silicon Macs, x86-64 Linux and Windows 11 on x86-64 (through WSL2, preview). On anything else, or in a CI job or hosted agent, use kosa8 Cloud: the person signs up at https://app.kosa8.com/, adds a payment method, and gives you an API key (`KOSA8_API_KEY`). Guide: https://docs.kosa8.com/guides/cloud.md . ## Using kosa8 Cloud Three ways in, all with the same key and the same rules (scopes, payment, the spending cap, the audit log): - MCP: `claude mcp add --transport http --scope user kosa8-cloud https://api.kosa8.com/mcp --header "Authorization: Bearer $KOSA8_API_KEY"` (or `kosa8 cloud mcp --install`). `tools/list` shows what the key allows: `sandbox_create`, `sandbox_exec`, `sandbox_exec_status`, `file_read`, `file_write`, `preview_create`, `snapshot_create`, `code_run`, `pipeline_run` and more. https://docs.kosa8.com/guides/cloud-mcp.md - The CLI, after `kosa8 cloud login` (`kosa8 cloud --help` lists what your version has; add `--json` to parse the output). - The REST API at https://api.kosa8.com (https://api.kosa8.com/openapi.json) or the SDKs (`Kosa8Cloud`). What to reach for: - Size, image, Docker, env: `kosa8 cloud sandbox create --size 4x8 --image kosa8-template/universal-24.04-20261115.2 --docker --env MODE=test --name build --label team=ml --disk-gb 40 --ttl 2h`. Sizes are 2x4, 4x8, 8x16 and 16x32 (vCPU x GiB). The universal image has common languages and build tools; `universal-full-24.04-20261115.2` has more. A sized or Docker sandbox may report `creating`: wait until it is `running`. `--persistent` keeps one long-lived container, so installs and `$HOME` survive between commands; `--docker` implies it. - Long commands: an exec stops after 90 s. Start installs, builds, test suites and servers detached with `kosa8 cloud sandbox exec --background ID -- make test`, then read the state, exit code and output with `kosa8 cloud sandbox exec-status ID bg_…` (MCP: `background: true`, then `sandbox_exec_status`). To bound a command you do not trust to finish, `--timeout 5m` (API and MCP: `timeout_s`) stops it in the sandbox (exit 124). - Limits: `kosa8 cloud limits` shows active sandboxes against the limit (429 `quota_exceeded` past it; sleep one, or ask the person to run `kosa8 cloud limits request N`). `kosa8 cloud cap` shows the month against the spending cap (none unless the owner set one); changing it is the person's decision, never yours. Relay any `agent_message` word for word. - Files: `kosa8 cloud files ls|get|put|rm|mkdir ID PATH`; for big files `kosa8 cloud files link ID PATH` gives a one-time URL. Terminal: `kosa8 cloud terminal ID`. - A web app in the sandbox: `kosa8 cloud preview open ID 3000` gives the port an https URL (private signed link unless public); `preview ls|link|rm`. - Save a set-up machine and start others from it: `kosa8 cloud snapshot create ID --name deps`, then `kosa8 cloud sandbox create --from-snapshot snap_…`; `snapshot ls|rm`. - Python with state between cells and charts: `kosa8 cloud code ID` (MCP `code_run`; the sandbox must be persistent). - What happened: `kosa8 cloud logs ID`, `kosa8 cloud metrics ID`. - CI: `kosa8 cloud pipelines run https://github.com/acme/app.git`, then `pipelines ls|get|logs|cancel|artifacts`; triggers with `kosa8 cloud pipelines hook create|ls|rm`. https://docs.kosa8.com/guides/cloud-pipelines.md - Network: `kosa8 cloud egress get|set|reset ID`. Change what a sandbox may reach only when the person asked for it. - Secrets are the person's: they store them with `kosa8 cloud secrets set NAME`, which reads the value from standard input, never from the command line. You refer to a secret by its name; never put a secret value in a command, a file, an env flag or a message. `kosa8 cloud secrets ls` shows names only. - A web browser: `kosa8 cloud browser create --ttl 300` prints a `cdp_url` for Playwright `chromium.connectOverCDP(cdp_url)` or Puppeteer; over MCP use `browser_open`, `browser_goto`, `browser_screenshot`, `browser_close`. It costs $0.12 per browser-hour, billed per second: close it when done (`kosa8 cloud browser rm brw_…`). https://docs.kosa8.com/guides/cloud-browsers.md - Delete what you made when you are done (`kosa8 cloud sandbox rm ID`, `kosa8 cloud snapshot rm snap_…`): running sandboxes use the plan's sandbox-hours, and snapshots count toward the plan's limit. ## Rules - If kosa8 refuses something for policy or approval reasons, tell the person what the refusal says. Don't look for a way around it. Approvals are for a human: `kosa8 mcp asks` lists any waiting. - Say which sandbox you used, so the person can look: `kosa8 sandbox ls`. - `--json` works on most commands and gives you output you can parse. - GitHub repos: once an admin connects GitHub (https://app.kosa8.com/auth/github/connect), pass `repo` ("owner/name" or "owner/name@ref") to `POST /v1/sandboxes` or `POST /v1/run` (MCP: `github_repos`, `sandbox_create` with `repo`, `open_pull_request`). No GitHub token is ever given to you or put in the sandbox; pushes go to `kosa8/*` branches and pull requests open as drafts. https://kosa8.com/github/ and https://docs.kosa8.com/guides/cloud-github.md ## More - If the person asks how kosa8 fits their AI security programme, or whether it suits their security team's own AI agents: https://kosa8.com/ai-security/ and https://kosa8.com/ai-for-cybersecurity/ (kosa8 is the isolation layer for agents, not a detection or SOC product); every topic (MCP, supply chain, zero trust, data loss, air-gapped AI) is indexed at https://kosa8.com/cybersecurity/ - If the person asks what AI agent security involves (threats, controls, a maturity checklist): https://kosa8.com/ai-agent-security/; for many agents working together (multi-agent or swarm security): https://kosa8.com/swarm-security/ - Every guide and command, as markdown: https://docs.kosa8.com/llms.txt - The whole manual in one file: https://docs.kosa8.com/llms-full.txt - Any docs page as markdown: add `.md` to its address, for example https://docs.kosa8.com/reference/prompt.md # kosa8 docs **kosa8 Cloud us-ash1 live # A sealed computer for every agent, *one call away*. kosa8 is Zero Trust cybersecurity infrastructure for AI agents: each agent, test run or RL rollout gets a microVM of its own. Start one in seconds, run anything in it, then checkpoint, rewind or fork it, memory and processes included. Use the CLI, plain `curl`, or an SDK. [Run your first sandbox](https://docs.kosa8.com/quickstart/) [HTTP API](https://docs.kosa8.com/api/) recorded on kosa8 Cloud, 2026-11-22 ``` $ kosa8 run --cloud python:3.12-slim python3 -c 'import platform; print("hello from", platform.machine())'On kosa8 Cloud: sandbox sbx_o3KdS0Ad4JvJ8oPeiMziA (python:3.12-slim), deleted when this endshello from x86_64 $ kosa8 cloud checkpoint create $IDk8ckpt-sbx_r7Des…-9eef9ce7 · 0.98 s$ kosa8 cloud sandbox exec $ID -- rm /workspace/notes.txt$ kosa8 cloud checkpoint rewind $ID $CKRewound sbx_r7Des… to k8ckpt-…-9eef9ce7. · 0.82 s$ kosa8 cloud sandbox exec $ID -- cat /workspace/notes.txtv1$ kosa8 cloud sandbox fork $ID -n 3sbx_rKn1KkMp05z4djYN8EMHjAsbx_RqkrO11I5HUZaAUt4VFVJgsbx_Q7uRZUndQ8cpkS8CA6drJQ · 4.63 s ``` Sixty seconds ## From nothing to a running sandbox ### Get a key [Sign up at app.kosa8.com](https://app.kosa8.com/signup) (free, no card) and make one under **API keys**. It starts with `k8c_live_`. Paste it here and every snippet on this page uses it. Your API key --- Source: https://docs.kosa8.com/ # Quickstart kosa8 is Zero Trust cybersecurity infrastructure for AI agents. Three steps, about a minute, to your first sandbox. Choose a language once: every tabbed example in these docs switches with it, and remembers. ## 1. Sign up (free) and get an API key [Sign up at app.kosa8.com](https://app.kosa8.com/signup): free, no card. The Starter tier gives $10 of usage, 2 sandboxes running at once, no time limit (see [pricing](https://kosa8.com/pricing/)). Then make a key under **API keys**. It is shown once and starts with `k8c_live_`. Every SDK and the CLI read it from `KOSA8_API_KEY`. Your API key --- Source: https://docs.kosa8.com/quickstart/ # API keys and auth One header on every request: `Authorization: Bearer `. The secret is an API key for your own code, or a short-lived token for someone else's. ## API keys Make a key in the dashboard under **API keys**, or with the API (a key with `keys:manage`). A key looks like `k8c_live_…`, is shown once, and only its hash is stored. The SDKs and the CLI read `KOSA8_API_KEY`. ``` curl -s https://api.kosa8.com/v1/me -H "Authorization: Bearer $KOSA8_API_KEY" ``` ## Scopes A key holds one or more scopes. A broader scope includes the narrower one beside it, so you never need both. | Scope | Lets the key | |---|---| | `sandboxes:read` | List and read sandboxes, files, logs and metrics | | `sandboxes:write` | Everything in read, plus create, exec, fork, checkpoint, rewind, sleep and delete | | `functions:invoke` | Call deployed functions | | `functions:deploy` | Deploy and delete functions, and call them | | `keys:manage` | Make, list and revoke keys | | `audit:read` | Read the audit log | | `admin` | Everything | Each endpoint in the [API reference](https://docs.kosa8.com/api/) says which scope it needs. A key without it gets `403 forbidden`. ## Capability tokens, for your users Building a product where your end users get a sandbox (a browser terminal, a notebook, a customer's agent)? Don't give them your key. Make a capability token: it starts with `k8c_tok_`, lives one hour by default (24 hours at most), holds a subset of `sandboxes:read`, `sandboxes:write` and `functions:invoke`, and can be held to some sandboxes or labels. ``` curl -s https://api.kosa8.com/v1/tokens \ -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' \ -d '{"scopes":["sandboxes:write"],"sandbox_ids":["sbx_…"],"ttl_s":900}' | jq -r .token.secret ``` A token is never worth more than what made it: revoke the key and its tokens stop. A token cannot make keys or tokens, and every call made with one is in the audit log as `token:{id}`. ## The CLI's sign-in `kosa8 login` signs the CLI in through the browser and stores the session in your home directory. For a machine with no browser, `kosa8 login --no-browser` prints a link and a code. `kosa8 cloud …` commands also work with just `KOSA8_API_KEY` set. Commands that run on this machine's own kosa8d need the browser sign-in, because an API key cannot hold a machine seat. An AI agent with no CLI starts the same sign-in over HTTP with `POST /v1/auth/device {"client": "agent"}`, gives the person the link, and polls for its key: see [the agent sign-in](https://docs.kosa8.com/quickstart/#agent-sign-in). ## Keeping keys safe - Give each program its own key with the fewest scopes it needs, and an expiry if it's temporary. - Never put a key inside a sandbox. Use [secrets](https://docs.kosa8.com/guides/cloud-secrets/), which are swapped in on the way out, or the [AI Gateway](https://docs.kosa8.com/guides/cloud-ai-gateway/) for model keys. - If a key leaks, revoke it in the dashboard. It stops at once, and so do the tokens it made. --- Source: https://docs.kosa8.com/concepts/auth/ # Install kosa8 Two ways in. Pick the Mac app if you want an icon to double-click; pick the one-line installer if you live in a terminal. They install the same thing. ## The Mac app Download `kosa8__macos_app.zip` (the newest release) from [the releases page](https://github.com/AzmxAI/kosa8-releases/releases/latest), unzip it, and drag **kosa8.app** to your Applications folder. The app carries the command-line tool and the background service inside it, so this is the only thing you need — there is nothing to install first. It is signed and notarized by Apple, so it opens without a warning. ## One line ``` $ curl -fsSL https://kosa8.com/install.sh | sh ``` The installer works out whether you have an Apple or Intel chip, checks the download against the published fingerprints before anything runs, and puts `kosa8` on your PATH. ### Homebrew ``` $ brew tap AzmxAI/kosa8 $ brew install kosa8 ``` ### From npm or PyPI, without installing ``` $ npx @kosa8/cli --help $ uvx kosa8-cli --help ``` Both fetch the released `kosa8` binary on first use and run it; any command works in place of `--help`. The npm package is `@kosa8/cli` (scoped: plain `kosa8` on npm is not ours). ### Windows ``` PS> irm https://kosa8.com/install.ps1 | iex ``` ### Linux The same one-line installer works, and there are `.deb`, `.rpm` and `.apk` packages on the releases page. **Which machines run sandboxes** Sandboxes are real virtual machines, so they need a hypervisor kosa8 can drive. - **Apple Silicon Mac** — on Apple's Virtualization framework. - **x86-64 Linux** — on KVM with Cloud Hypervisor. The installer puts the daemon in place and says what else to install: `cloud-hypervisor`, `virtiofsd`, and access to `/dev/kvm`. `kosa8 doctor` checks all of it. - **Windows 11 on x86-64** (preview) — in WSL2. After installing, run `kosa8 wsl setup` once: it sets up the Linux engine in an Ubuntu distribution and connects the CLI to it. A second Windows option (preview): `kosa8d.exe` runs sandboxes as gVisor containers on Docker, which are containers, not microVMs. Everything else — an Intel Mac, Windows 10, Windows on ARM, JioOS on a JioBook — drives one of those. On that machine run `kosa8 daemon start --listen 127.0.0.1:7440` and `kosa8 worker pair --url https://…`; here, `kosa8 worker join` with the code it prints. Every command then works normally. ## Check it worked ### Sign in, or sign up A new install asks you to sign in once, before anything else runs. `kosa8 login` shows a short code and opens your browser, where you sign in or create your account (free, no card) and confirm the code. A new account starts on the free Starter tier once its email is confirmed: $10 of usage, 2 sandboxes running at once, no time limit, with a hard stop at the limit. The machine then runs on your account's plan, and the same sign-in covers the desktop app and kosa8 Cloud. Plans differ by features and limits ([compare them](https://kosa8.com/pricing/#compare)); `kosa8 upgrade` opens the checkout for a higher one. Accounts made before 16 November 2026 keep working as they are until 1 December 2026, then need a plan for new work. Have a licence key already? Run `kosa8 license activate ` instead. ``` $ kosa8 login ``` No browser on this machine? `kosa8 login --no-browser` prints the link to open on any device, with a short code to confirm. Using kosa8 a lot on Solo or Pro? About once a week at most, after a command, kosa8 prints one line naming what the next plan adds and the `kosa8 upgrade` command for it. It never appears with `--json`, in CI, or off a terminal; set `KOSA8_NO_UPGRADE_HINTS=1` to turn it off. When a command asks for something this machine cannot do (a GPU on a Mac, more CPUs or memory than it has, no KVM), kosa8 prints one line after the error naming the [kosa8 Cloud](https://docs.kosa8.com/guides/cloud/#from-local) command for it; add `--cloud` to `kosa8 sandbox create` or `kosa8 run` to run it there. Same rules as above; `KOSA8_NO_CLOUD_HINTS=1` turns off just these. When one is shown, or you use `--cloud`, the CLI tells kosa8 Cloud only that it happened (the reason, the command, OS, CPU type, version and a random install ID; never your commands, paths or email); `KOSA8_NO_TELEMETRY=1` or `DO_NOT_TRACK=1` turns that off ([privacy](https://kosa8.com/privacy/#software)). ### Start the background service Nothing runs until the daemon is up. The Mac app starts it for you. ``` $ kosa8 daemon start ``` ### Run something The first run fetches the guest image for your release (a few hundred megabytes), checks it against the release's published checksum, and keeps it in `~/.kosa8/guest`. Later runs start straight away. With `KOSA8_OFFLINE=1` nothing is fetched: copy the guest image in from an air-gap bundle. ``` $ kosa8 run alpine echo hi hi ``` ### If anything looks wrong `kosa8 doctor` checks the parts that commonly go wrong — the daemon, the guest images, the virtualization entitlement — and tells you which one is missing. ``` $ kosa8 doctor ``` **Next** [Your first sandbox](https://docs.kosa8.com/guides/first-sandbox/) — make a sealed machine and run something inside it. **Using kosa8 from code?** For Node, install `@kosa8/sdk` (or `@kosa8/ai-sdk-sandbox` for the Vercel AI SDK) with the daemon running, and follow [Install and prerequisites](https://docs.kosa8.com/guides/js-install/) and the [Quickstart](https://docs.kosa8.com/guides/js-quickstart/). Docker clients such as dockerode and Testcontainers work by setting `DOCKER_HOST=unix://$HOME/.kosa8/run/kosa8.sock`. --- Source: https://docs.kosa8.com/guides/install/ # kosa8 Cloud The same sealed sandboxes, running on kosa8's hosts instead of your own machine. Nothing to install: sign in at [app.kosa8.com](https://app.kosa8.com/), make an API key, and create a sandbox from code in about a second. ## Create your account Open [app.kosa8.com](https://app.kosa8.com/). Under **New to kosa8 Cloud?** enter your email and a password (any address works, Gmail included; a team or company name is optional), and press **Create account**. From then on you sign in with that email and password; **Email me a link to set it** on the sign-in page resets a forgotten one. You also get the organization's first **admin API key** (it starts `k8c_live_`). It is shown once, so put it in your password manager before you continue. ## Start free, then pick a plan A new organization starts on the free **Starter** tier, no card, once the sign-up email is confirmed: $10 of usage, 2 sandboxes running at once, each up to 2 vCPU and 4 GB, 60-minute sessions, no time limit, with outbound network limited to an allow-list (package registries, GitHub, Hugging Face, model APIs). It stops hard at its limit (402 `starter_limit`, 429 at the running limit) and never sends a bill. For more, go to **Billing** and pick Solo, Pro, Team or Scale, monthly or yearly; checkout is through Polar (enter the 6-digit code we emailed first: checkout waits for a confirmed address). Each plan includes Cloud sandbox-hours each month and sets its limits ([compare them](https://kosa8.com/pricing/#compare)); use above the included hours is metered per second up to a spend cap you set, on by default at $50, with alerts at 50, 75 and 100%. A new account runs at most $50 a month above its plan until 30 days after its first payment. A failed renewal pauses new work at once, with no grace (402 `payment_failed`), until it is paid; running work and data are kept. Organizations made before 16 November 2026 keep working as they are until 1 December 2026, then need a plan for new work. ## Make an API key for your code In **API keys**, create a key for each app or agent, so you can revoke one without the others. The SDKs read it from `KOSA8_API_KEY`: ``` $ export KOSA8_API_KEY=k8c_live_… ``` From the terminal, `kosa8 login` signs this machine in without copying a key: it shows a short code, you confirm it in your browser, and the key it makes is kept in `~/.kosa8/cloud.json` for the `kosa8 cloud` commands and the desktop app. `kosa8 whoami` shows which account and organization are signed in. ``` $ kosa8 login ``` ## Create a sandbox and run something Python (`pip install kosa8`): ``` from kosa8 import Kosa8Cloud cloud = Kosa8Cloud() # reads KOSA8_API_KEY box = cloud.sandboxes.create(template="python", sleep_after_s=600) r = box.exec(["python3", "-c", "print(6 * 7)"]) print(r.exit_code, r.stdout) # 0 42 box.sleep() # costs only snapshot storage while asleep box.exec("ls /workspace") # wakes it, files and all box.delete() ``` JavaScript and TypeScript (`npm install @kosa8/sdk`): ``` import { Kosa8Cloud } from '@kosa8/sdk'; const cloud = new Kosa8Cloud(); // reads KOSA8_API_KEY const box = await cloud.sandboxes.create({ template: 'python' }); const r = await box.exec(['python3', '-c', 'print(6 * 7)']); console.log(r.exitCode, r.stdout); // 0 "42\n" await box.delete(); ``` Go, Ruby and Java have the same Cloud client under their own names: Go's `kosa8.NewCloud(kosa8.CloudOptions{})`, Ruby's `Kosa8::Cloud.new` and Java's `Kosa8Cloud` (Maven `com.kosa8:kosa8:0.6.0`). Python and JavaScript are at 0.7.0, Go at v0.6.1, Ruby and Java at 0.6.0; see [the SDKs](https://docs.kosa8.com/guides/sdks/). The Cloud clients create, list, run commands in, sleep, wake and delete sandboxes, and they checkpoint, rewind, fork and move files too (`POST /v1/sandboxes/{id}/checkpoints`, `/rewind`, `/fork` and `/files`). On kosa8 Cloud a sandbox keeps up to 10 checkpoints, forks up to 1,000 copies a call (100 at a time on the sandbox's host, the rest on other hosts when there are any; see [fork](https://docs.kosa8.com/guides/rl-training/#fork)); files stream at any size (100 MB a request through the API; send parts with `offset=`, or use the direct `files_url`). ## Plain HTTP The API is at `https://api.kosa8.com`. Send the key as a bearer token: ``` curl -s -X POST https://api.kosa8.com/v1/sandboxes \ -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' \ -d '{"template":"python"}' # {"sandbox":{"id":"sbx_…","state":"running","template":"python","region":"us-ash1",…}} curl -s -X POST https://api.kosa8.com/v1/sandboxes/sbx_…/exec \ -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' \ -d '{"cmd":["python3","-c","print(6 * 7)"]}' # {"exit":0,"stdout":"42\n","stderr":"",…} curl -s -X DELETE https://api.kosa8.com/v1/sandboxes/sbx_… \ -H "Authorization: Bearer $KOSA8_API_KEY" ``` Each `exec` in the template's image, streamed or not, runs in the sandbox's long-lived exec container on the sandbox's disk: files under `/workspace` persist between commands, and later commands see the same `/tmp` and the processes earlier ones left running. That container is not guaranteed: if it has to be replaced, or an exec names another `image`, the command runs in a fresh container that shares only `/workspace` (a [persistent] sandbox never does). An exec answered as one JSON object runs at most **90 seconds**; past that the command is stopped and the answer is **504** `exec_timeout`. For longer commands (installs, test suites, builds) add `"stream": true`: the answer is NDJSON lines as the command prints (`{"stream":"stdout","data":""}`, then `{"done":true,"exit":0}`), and it is not held to the 90-second limit. While the command prints nothing, an empty stdout frame with `"heartbeat":true` arrives every 15 seconds, so a silent build or benchmark step keeps its connection; skip those frames. An exec answered as one JSON object keeps the first and the last 1 MiB of each of stdout and stderr. When a stream was longer, its middle is replaced by a line `[k8agent: N bytes of output dropped]` and the answer says so: `"stdout_truncated":true` (or `stderr_truncated`), with `stdout_bytes` and `stderr_bytes`, what the command printed in all. A streamed exec is never cut; for big output stream it, or write it to a file and download that. Three more create and exec fields are in [Snapshots, background commands and env](https://docs.kosa8.com/guides/cloud-snapshots-background/): `"env":{…}` at create sets variables for every command, `"background":true` on an exec answers **202** at once and leaves the command running (its output read later from `GET /v1/sandboxes/{id}/exec/{exec_id}`), and `POST /v1/sandboxes/{id}/snapshots` saves a snapshot that outlives the sandbox, to create new ones from with `{"snapshot":"snap_…"}`. ### Persistent sandboxes For agents, CI jobs and anything that sets a machine up in several steps, create the sandbox with `"persistent": true`. Every command, streamed or not, then runs in one long-lived container: packages from `apt-get` or `apk`, `$HOME`, `/var/lib` and the rest of the filesystem stay between commands, and a process started in the background keeps running after the command returns, until you delete the sandbox. While one runs, the sandbox does not go to sleep. ``` curl -s -X POST https://api.kosa8.com/v1/sandboxes \ -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' \ -d '{"template":"node","persistent":true}' # install once, use later -d '{"cmd":["sh","-c","apk add --no-cache jq && jq --version"]}' # start a server in the background; the exec returns at once -d '{"cmd":["sh","-c","nohup node server.js >/tmp/server.log 2>&1 &"]}' # a later command still sees it -d '{"cmd":["sh","-c","wget -qO- localhost:3000"]}' ``` A persistent sandbox's commands take no `image`: they all run in its own. If a command kills the container itself, the next command starts it again from the image; `/workspace` is kept, the rest starts over. ### Sizes, images and disk A template's sandboxes are small (1 vCPU) and start warm. For bigger work, name a `size`, an OCI `image` and a `disk_gb` at create: ``` curl -s -X POST https://api.kosa8.com/v1/sandboxes \ -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' \ -d '{"size":"4x8","image":"debian:13-slim","disk_gb":40,"persistent":true,"name":"build-1"}' # 202 {"sandbox":{"id":"sbx_…","state":"creating","cpus":4,"mem_mb":8192,"disk_gb":40,…}} ``` Sizes are `0.25x0.5`, `0.5x1`, `1x2`, `2x4`, `4x8`, `8x16` and `16x32` (vCPU x GiB). The three small sizes are for fleets of mostly idle sandboxes (RL rollouts, evals): the guest has one whole vCPU (two for `1x2`), of which 0.25, 0.5 or 1 is reserved and billed, and it bursts to the whole vCPU while the host has idle CPU, unbilled. They keep fork, checkpoints, sleep and persistence, and start warm from their own pools. Unless the size and image match a pool a host keeps warm (then it is **201** `running` at once; see [warm sized starts](https://docs.kosa8.com/guides/cloud-snapshots-background/)), the sandbox boots cold, so the answer is **202** with `"state":"creating"`: poll `GET /v1/sandboxes/{id}` until it says `running` (a command sent sooner gets **409** `starting`). A small image is up in seconds; a large one is pulled on its first boot and can take a few minutes. The disk holds `/` and `/workspace` (8 to 200 GB, default 32). It counts against the plan's sandbox-hours by its vCPUs, from when it is up. Each host keeps a quarter of its CPUs for small sandboxes, so it runs at most 24 vCPUs of sized ones (six `4x8`); past that a create answers **503** `no_capacity`. `GET /v1/sandboxes?name=build-1` finds a sandbox by its `name`. **git.** The `python` and `node` templates have git (and bash). The `base` template is plain Alpine without it: add it with `apk add --no-cache git` in a persistent sandbox, use the `python` or `node` template, or create from an image that has it (Debian and Ubuntu based CI and toolchain images usually do, for example `ghcr.io/starslingdev/sandbox-benchmarks-toolchain:v8`). ### Dedicated cores Add `"cpu":"dedicated"` to a sized create and every vCPU is a whole physical core of its own: pinned to the core, its second hardware thread left idle rather than given to another sandbox, on the host's fastest cores, with the guest seeing N cores of one thread and its memory on 2 MiB hugepages. It is for work whose timing matters, such as benchmarks and latency-sensitive builds. ``` curl -s -X POST https://api.kosa8.com/v1/sandboxes \ -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' \ -d '{"size":"4x8","cpu":"dedicated","image":"debian:13-slim"}' # 501 {"error":"not_available","message":"dedicated cores are not offered yet; …",…} ``` A host has only a few cores to give this way, so when none are free the create answers **503** `no_capacity` instead of sharing them. A dedicated sandbox never sleeps and cannot be checkpointed, rewound or forked (**409** `dedicated`); delete it when you are done. Dedicated cores are not offered yet: until they are, the create answers **501** `not_available`. Other routes: `GET /v1/sandboxes` (newest first, at most 500 a page: pass `limit`, and follow `next_cursor` as `cursor` until it is `null`), `GET /v1/sandboxes/{id}`, `POST /v1/sandboxes/{id}/sleep` and `/wake`. Errors are JSON with a stable `code`. The ones that stop a create, a wake or a command, and what to do: | Answer | Means | Next step | |---|---|---| | **402** `plan_required` | The organization has no plan yet. | In [app.kosa8.com](https://app.kosa8.com/#billing), **Billing** → pick a plan. | | **402** `plan_limit` | A limit of the plan is reached: sandbox-hours this month, sandboxes running at once, the largest size, persistent sandboxes or snapshots kept. The body names it (`limit_name`, `limit`, `used`) and the plan that includes more (`next_plan`). For sandbox-hours and sandboxes running at once, `options` lists both ways past it, cheapest monthly cost first: an add-on pack and the next plan up (`kind`, `label`, `monthly_usd`, `url`), with `pack_url`. | Free one up (sleep or delete a sandbox, delete a snapshot), wait for next month's hours, add a pack, or upgrade in **Billing**. | | **402** `plan_feature` | The feature is on a higher plan (`feature`, `next_plan`). | Upgrade in **Billing**. | | **402** `payment_required` | A renewal failed or a charge was declined. | Update the card in **Billing** → **Manage billing**. | | **402** `spending_cap_reached` | This month's spend reached the cap an owner set. The cap is optional and off by default. | Raise or clear the cap in **Settings**. | | **423** `org_frozen` | An owner or admin froze the organization in the Security Center. | An owner or admin unfreezes it there. Reads, deletes and sleeps still work. | | **429** `quota_exceeded` | The organization reached a running limit kosa8 set for it (its own `max_running`), or, before plan limits apply, the default limit of sandboxes running or paused (sleeping ones do not count, but waking one counts it again). | Delete or sleep one, or write to [contact@kosa8.com](mailto:contact@kosa8.com) for a higher limit. | | **503** `no_capacity` | The hosts are full right now. kosa8 adds hosts when it needs them; this is not a plan limit. | Wait the `Retry-After` seconds and try again. Do not upgrade for it. | | **503** `database_busy` | kosa8 Cloud's database was overloaded and the call did not finish. The body says `retryable: true` and `retry_after` (seconds), as does the `Retry-After` header. | Wait that long and send it again. The SDKs and the CLI do this for calls that are safe to repeat (GET, PUT, DELETE, and creates with an `Idempotency-Key`); check before you repeat a command. | | **504** `exec_timeout` | A command without `stream` ran past 90 seconds and was stopped. | Run it again with `"stream": true`, or split it into shorter commands. | Every 402 carries `upgrade_url` and `agent_message`, a sentence an AI agent relays to its person word for word. The SDKs raise these as their payment-required (402) and rate-limit (429) errors, for example Python's `Kosa8PaymentRequiredError` and `Kosa8RateLimitError`. ## Overflow capacity When kosa8's own hosts have no room, a plain create may run on kosa8's overflow capacity (Cloudflare Containers) instead of answering **503**. It is the same API, at the same price as the size you asked for. The sandbox's `region` reads `cf-auto`. It runs the `base`, `python` and `node` templates (or the `alpine`, `python:3.12-alpine` and `node:22-alpine` images) at up to 4 vCPUs and 12 GiB, from the plain Alpine images: there the `python` and `node` templates have no `bash`, `git` or `pytest`, with exec (buffered and streamed), files and `timeout_s`. It is the first choice for a small size only while no kosa8 host offers that size. What is the same there: create, delete, exec (buffered and streamed, with `timeout_s`), [background commands](https://docs.kosa8.com/guides/cloud-snapshots-background/) (start, status, stop and `timeout_s`), files at any path, env at create, sizes up to 4 vCPUs and 12 GiB, and billing. A hosted job's rollouts may run there too: the solver as a background command, and the grader in the solved sandbox itself after every other process in it is ended, under a seal that refuses every network socket (in place of a sealed fork). What differs on overflow capacity: - There is no fork, checkpoints, rewind, snapshots, sleep and wake, file links, ports, previews, terminal, metrics, logs or `POST /v1/sandboxes/{id}/grade` (it needs a fork). Those calls answer **501** `not_available`, saying why. - It never sleeps. A sandbox with no call and no command running for 3 minutes is ended, and its files are not kept; `GET /v1/sandboxes/{id}` says so in `last_error`. A running background command counts as work. Keep work that must survive on a kosa8 host. - Small sizes get their reserved CPU share and no burst: `0.25x0.5` runs at a quarter of a vCPU, where a kosa8 host lets it burst to a whole one. Memory is Cloudflare's next instance size up (at least what you asked for). - The whole container's filesystem lasts between commands (on a kosa8 host, only `/workspace` does, unless the sandbox is persistent). - Persistent, Docker, dedicated, GPU, secrets and egress-policy sandboxes, other images and templates (benchmark environments, desktop, `universal-*`, your own), a `disk_gb` over 20, a named region and benchmark jobs always wait for a kosa8 host. - Egress is capped at 5 GB per sandbox, and a sandbox lives at most 24 hours. **How much fits there.** Overflow capacity is bounded by the vCPUs and memory of the Cloudflare instances its sandboxes run on, so sizes mix: each sandbox counts as the instance it gets (`0.25x0.5` a basic instance, a quarter of a vCPU and 1 GiB; `0.5x1` half a vCPU and 4 GiB; `1x2` and the templates 1 vCPU and 6 GiB; `2x4` 2 vCPUs and 8 GiB). It also holds at most a set number of sandboxes at once, and takes no new ones once its monthly spend limit is reached. When it is full, a create answers **503** as it would without it. ## Templates and regions | Template | What is in it | Size | |---|---|---| | `base` | Alpine Linux (the default) | 1 vCPU, 256 MiB | | `python` | Python 3.12 on Debian (`python:3.12-slim`) with bash, git, curl, pip, pytest and uv | 1 vCPU, 256 MiB | | `node` | Node.js 22 on Alpine with bash, git and the GNU tools | 1 vCPU, 384 MiB | A template creates a small sandbox of the size above; for a bigger one, name a `size` (see [Sizes, images and disk]). `GET /v1/templates` returns each template's current size and the regions that offer it. **What the `base` template has.** It is plain Alpine: the shell is busybox `sh`, and there is no `bash`, `python3` or `git`. Run commands as `["sh", "-c", "…"]`, not `bash -c`, and use the `python` or `node` template when you need those. Unless the sandbox is [persistent], only `/workspace` persists from one exec to the next, so install into `/workspace` (for example `pip install --target /workspace/lib`), or install and use it in the same exec. Sandboxes are kept warm, so creating one takes about a second. They run in one region today: `us-ash1` (Ashburn, Virginia, US). A sandbox placed on [overflow capacity] reports the region `cf-auto`. ## What it costs kosa8 Cloud is part of every plan. Each plan includes **Cloud sandbox-hours** each month: an hour of a standard 2 vCPU / 4 GB sandbox running is one sandbox-hour, and other sizes count by vCPU (a 1 vCPU sandbox, such as one from the `base` or `python` template, uses half an hour an hour; a 4 vCPU one, two). Function calls count the same way. A sleeping sandbox uses none; the next command wakes it. Hours reset each month and do not roll over; on Team and Scale they are per person and pooled. Use above the included hours is metered per second ($0.048 per vCPU-hour and $0.0154 per GiB-hour of memory) up to your spend cap, which is on by default at $50 and which you can raise or lower in **Billing**; alerts go out at 50, 75 and 100%. At the cap new sandboxes are refused and running work keeps going. If your first bill surprises you, [write to us](mailto:contact@kosa8.com?subject=kosa8%20bill): we forgive a first surprise bill. The free Starter tier has no overage: it stops at its limit. **Browser sandboxes** ([headless Chromium over CDP](https://docs.kosa8.com/guides/cloud-browsers/)) are billed per second at the browser-hour rate on [the pricing page](https://kosa8.com/pricing/), and each browser-hour also counts as an hour of the smallest sandbox (0.25 vCPU) against the plan's sandbox-hours. | | Solo | Pro | Team | Scale | |---|---|---|---|---| | Sandbox-hours a month | 100 | 500 | 500 a person | 1,000 a person | | Sandboxes running at once | 2 | 10 | 25 | up to 1,000 | | Largest sandbox | 2 vCPU / 4 GB | 4 vCPU / 8 GB | 8 vCPU / 16 GB | 16 vCPU / 32 GB | | Persistent sandboxes | 1 | 5 | 25 | 100 | | Snapshots kept | 5 | 50 | 250 | 1,000 | Limits are hard: past one, new work is refused with `402 plan_limit`, and a feature on a higher plan with `402 plan_feature`. Upgrade any time in **Billing**; the new limits apply at once. Swarms, pipelines and functions come with Pro; single sign-on (OIDC), audit export and SIEM, members and roles with Team; SAML and SCIM, dedicated cores and capacity held for you with Scale. The limits apply from December 2026. **Billing** in the dashboard shows the month's hours and sandboxes against the plan. Plans, their prices and the yearly discount are at [kosa8.com/pricing](https://kosa8.com/pricing/#compare). Each plan is sold monthly or yearly. ### Add-on packs To raise one limit without changing plan, add a pack: **+100 sandbox-hours** or **+10 sandboxes running at once**, priced on [the pricing page](https://kosa8.com/pricing/). Packs are monthly, work on any plan and stack: a limit is the plan's plus every pack held. Add or remove them in **Billing**, with `kosa8 cloud addons add hours_100`, or through the API (`GET`/`POST /v1/billing/addons`, `DELETE /v1/billing/addons/{addon}`). The first pack of a kind opens a checkout; more are added to it and charged now. A removed pack stops at the end of the period it is paid for. When the hosts are full, a create or a wake answers `503 no_capacity` with a `Retry-After` header: kosa8 adds hosts when it needs them, so wait and retry. It is not a plan limit, and upgrading does not change it. ## The dashboard | Tab | For | |---|---| | Sandboxes | What is running, asleep or stopped, and what each has cost. | | Functions | Deploy a handler and call it; each call runs in its own sandbox. | | API keys | Make and revoke keys. A leaked key: revoke it here first. | | Own hosts | Run sandboxes on your own servers, managed from the same dashboard: [Bring your own cloud](https://docs.kosa8.com/guides/cloud-byoc/). | | Team & SSO | Invite people, or connect Okta, Entra ID or Google Workspace by OIDC or SAML 2.0, with SCIM 2.0 provisioning ([setup](https://docs.kosa8.com/guides/cloud-security/)). | | Settings / Usage | Default template and region, sleep timer, spending cap, the bill. | | Affiliate program | Apply for 20% of the payments of the teams you bring, for 12 months (referrals have closed); see [Affiliate program](https://docs.kosa8.com/guides/refer/). | ## Connect agents and tools - [MCP server](https://docs.kosa8.com/guides/cloud-mcp/): give Claude Code, Cursor or Codex cloud sandboxes with one command, `claude mcp add --transport http --scope user kosa8-cloud https://api.kosa8.com/mcp --header "Authorization: Bearer $KOSA8_API_KEY"`, or `kosa8 cloud mcp`. - [OpenAPI and llms.txt](https://docs.kosa8.com/guides/cloud-openapi/): the API described for code generators and AI agents. - [GitHub Action](https://docs.kosa8.com/guides/cloud-github-action/): run a command in a sandbox from a workflow. - [Browser sandboxes](https://docs.kosa8.com/guides/cloud-browsers/): a headless Chromium your agent drives with Playwright or Puppeteer over CDP, or through the MCP `browser_*` tools. - [AI Gateway](https://docs.kosa8.com/guides/cloud-ai-gateway/) (early access): model calls through kosa8 and Cloudflare AI Gateway, with provider keys that never enter the sandbox and spend per sandbox. - [Webhook recipes](https://docs.kosa8.com/guides/cloud-webhooks/): verify deliveries and forward failures and the spending cap to Slack. Plan events (`plan.purchased`, `plan.changed`, `plan_limit.near`, `plan_limit.reached`, `plan_feature.blocked`, `hours.reset`, `capacity.unavailable` and the rest) are listed under [Webhook events for plans](https://docs.kosa8.com/guides/cloud-webhooks/#plan-events); each is also an audit-log entry. ## Cloud or your own machine? kosa8 on your own computer ([Install](https://docs.kosa8.com/guides/install/)) is the same sandbox with no network hop and nothing leaving the machine. Use the cloud when your code runs somewhere without kosa8 installed (a server, a CI job, a hosted agent), or when you want many sandboxes at once without a big machine of your own. ## From a local command: `--cloud` When a local command asks for something this machine cannot give, add `--cloud` to run the same command on kosa8 Cloud. Not signed in yet, it runs `kosa8 login` first and then carries on. ``` $ kosa8 sandbox create --cloud --cpus 4 --memory 8192 --ttl 2h web On kosa8 Cloud: kosa8 cloud sandbox create --name web --size 4x8 --ttl 2h $ kosa8 run --cloud python:3.12-slim python3 -c 'print(1+1)' $ kosa8 run --cloud -it alpine sh ``` - `kosa8 sandbox create --cloud` is `kosa8 cloud sandbox create` with the flags translated: `--cpus` and `--memory` become the smallest Cloud size that holds them (2x4, 4x8, 8x16 or 16x32, vCPUs x GiB), `--auto-stop` becomes `--sleep-after`, `--egress deny` becomes `--no-internet`, `--egress-allow` becomes `--allow`, and the name, `--template`, `--disk`, `--ttl` and `KEY=VALUE` labels carry over. A flag Cloud has no equivalent for (`--mount`, `--gpu`, `--pcap`, `--backend`, `--auto-delete`, `--ephemeral`, `--egress fakenet`, a classification label) is refused by name, and nothing is created. - `kosa8 run --cloud IMAGE COMMAND` makes a cloud sandbox of IMAGE, runs the command (with `-it`, an interactive terminal), exits with its exit code and deletes the sandbox, as a foreground `kosa8 run` keeps nothing. `-e` carries over; `-p`, `-d`, `--name` and `--network` are refused (open a port with `kosa8 cloud preview open ID PORT`). - kosa8 Cloud has no GPUs yet, so `--gpu` with `--cloud` is refused. At the moment a local command hits one of these limits, kosa8 prints one line after the error naming the Cloud command for it: - **Too big:** a sandbox with more CPUs or memory than this machine has, refused by the engine (up to 16 vCPUs and 32 GiB on Cloud). - **Many at once:** the engine out of room with other sandboxes already running. - **Cannot run locally:** no `/dev/kvm`, an Intel Mac, or a Mac without the Hypervisor framework. - **GPU:** `--gpu` where no GPU can be handed over (every Mac). Cloud has none either, so the line says so and where to ask for one. - **Sharing:** a local `kosa8 sandbox preview` link opens only on this machine; at most once a day, kosa8 names `kosa8 cloud preview open` for a link that works anywhere. ``` $ kosa8 sandbox create --cpus 12 --memory 24576 big kosa8: invalid VM configuration: … “memorySize” is greater than “maximumAllowedMemorySize”. … This machine has 10 CPUs and 16 GiB of memory; kosa8 Cloud runs up to 16 vCPUs and 32 GiB. Run it on kosa8 Cloud: kosa8 cloud sandbox create --name big --size 16x32 (kosa8 login first, or add --cloud to the command you ran) ``` The line goes to stderr, only when both stdout and stderr are a terminal. It never appears with `--json`, in CI (`CI` set), or with `KOSA8_NO_UPGRADE_HINTS=1`; set `KOSA8_NO_CLOUD_HINTS=1` to turn off just these. A hint that is shown, and a `--cloud` run, is reported to kosa8 Cloud as a count (the reason, the command, OS, CPU type, version and a random install ID; never your commands, paths or email); set `KOSA8_NO_TELEMETRY=1` or `DO_NOT_TRACK=1` to turn that off. --- Source: https://docs.kosa8.com/guides/cloud/ # Let your agent set kosa8 up You don't have to read the install guide. Ask the coding agent you already use to do it. kosa8 publishes its setup as a page written for agents, and the agent asks you for the one thing it needs: you, signing in. It runs `kosa8 login` and hands you a short code and a link; you sign in or create your account in your browser and confirm the code. (No browser on that machine? You open the link on any device.) ## Ask your agent Paste this into Claude Code, Codex, Cursor or any agent that can run commands: ``` Set up kosa8 for me by following https://kosa8.com/AGENTS.md ``` The agent will: 1. check whether kosa8 is installed, and install it if not, telling you first; 2. run `kosa8 doctor` and fix what it reports, or tell you what it cannot fix; 3. run `kosa8 login --no-browser` and give you the link and code it prints, then wait while you sign in or create your account in your browser (free, no card: the Starter tier); 4. start the daemon, and run a first task with [`kosa8 prompt`](https://docs.kosa8.com/guides/prompt/). The page tells the agent never to sign in for you, never to enter card details, and never to work around a refusal, and never to buy or upgrade a plan. Signing in puts your account's plan on this machine: the free Starter tier until you pick a plan ([pricing](https://kosa8.com/pricing/)). ## Give the agent kosa8's tools To have the agent run its own code in sandboxes, not only hand tasks to another agent, add the tools and the guidance that goes with them. See [Connect Claude, Cursor or Codex](https://docs.kosa8.com/guides/connect-agents/). ``` $ kosa8 mcp install $ kosa8 skill install ``` ## Docs an agent can read Every page on this site is also published as markdown, which costs an agent far fewer tokens than the HTML. Add `.md` to a page's address: - [docs.kosa8.com/guides/prompt.md](https://docs.kosa8.com/guides/prompt.md) - [docs.kosa8.com/reference/sandbox-create.md](https://docs.kosa8.com/reference/sandbox-create.md) - [llms.txt](https://docs.kosa8.com/llms.txt): an index of every page - [llms-full.txt](https://docs.kosa8.com/llms-full.txt): the whole manual in one file --- Source: https://docs.kosa8.com/guides/agent-setup/ # Sandboxes A sandbox is a microVM with its own kernel, filesystem and network, made for one agent, one task or one rollout. You make it, run things in it, and delete it, or let its deadline delete it for you. **CLI** ``` # Create: deleted on its own after 30 minutes, asleep after 5 idle ID=$(kosa8 cloud sandbox create --template python --ttl 30m --sleep-after 5m --json | jq -r .sandbox.id) kosa8 cloud sandbox get $ID # state, size, region, timers kosa8 cloud sandbox exec $ID -- python3 --version kosa8 cloud sandbox rm $ID # its disk is wiped ``` **curl** ``` API=https://api.kosa8.com/v1 AUTH="Authorization: Bearer $KOSA8_API_KEY" # Create: deleted on its own after 30 minutes, asleep after 5 idle SBX=$(curl -s $API/sandboxes -H "$AUTH" -H 'Content-Type: application/json' \ -d '{"template":"python","ttl_s":1800,"sleep_after_s":300}' | jq -r .sandbox.id) curl -s $API/sandboxes/$SBX -H "$AUTH" | jq '.sandbox | {id, state, cpus, mem_mb, region}' # Push the deadline out to two hours from now curl -s -X PATCH $API/sandboxes/$SBX -H "$AUTH" -H 'Content-Type: application/json' \ -d '{"ttl_s":7200}' | jq '.sandbox.delete_after' curl -s -X DELETE $API/sandboxes/$SBX -H "$AUTH" ``` **Python** ``` from kosa8 import Kosa8Cloud cloud = Kosa8Cloud() box = cloud.sandboxes.create(template="python", ttl_s=1800, sleep_after_s=300) print(box.id, box.state) # sbx_… running box.update(ttl_s=7200) # push the deadline out to two hours same = cloud.sandboxes.get(box.id) # look it up again by id print(same.state) # running box.delete() ``` **JavaScript** ``` import { Kosa8Cloud } from '@kosa8/sdk'; const cloud = new Kosa8Cloud(); const box = await cloud.sandboxes.create({ template: 'python', ttlS: 1800, sleepAfterS: 300 }); console.log(box.id, box.state); // sbx_… running await box.update({ ttlS: 7200 }); // push the deadline out to two hours const same = await cloud.sandboxes.get(box.id); console.log(same.state); // running await box.delete(); ``` ## Create `POST /v1/sandboxes` with an empty body gives you a `base` sandbox (Alpine, 1 vCPU, 256 MiB). The fields you will use most: | Field | What it does | |---|---| | `template` | `base`, `python`, `node`, a `universal-*` size, or your own. See [sizes and templates](https://docs.kosa8.com/concepts/sizes/) | | `image` | Any public OCI image instead, such as `python:3.12-slim` | | `size` | `0.25x0.5` up to `16x32` (vCPUs x GiB) | | `ttl_s` | Delete it this many seconds from now: 60 s to 90 days, or `null` for never | | `sleep_after_s` | Put it to [sleep](https://docs.kosa8.com/concepts/sleep/) after this many idle seconds (0 = never, up to 7 days) | | `name`, `labels` | Find it again later: `GET /v1/sandboxes?label=team=ml` | | `env` | Environment for every command | | `persistent` | Keep one container across execs, so installed packages and running processes stay | | `snapshot` | Start from a [snapshot](https://docs.kosa8.com/concepts/snapshots/) instead | Send an `Idempotency-Key` header and a retried create returns the first sandbox instead of a second one. Every field is in the [API reference](https://docs.kosa8.com/api/sandboxes/). ## States **creating**The microVM is booting. **running**Ready for exec, files, fork and checkpoints. **sleeping**Saved and stopped. The next exec wakes it, memory included. **deleted**Gone, with its disk. Its record stays in the audit log. You may also see `expired` (its `ttl_s` ran out), `error`, and `paused` or `stopped`; the [API reference](https://docs.kosa8.com/api/sandboxes/) lists them all. ## What lives where Each exec runs in the sandbox's container. Files under `/workspace` are kept for the whole life of the sandbox, and are what checkpoints, forks and snapshots carry. For processes that keep running between commands, create with `persistent: true` or use a [background command](https://docs.kosa8.com/concepts/exec/#background). ## Limits How many sandboxes can run at once, and how big, depends on your plan. A create past a limit is refused with `402 plan_limit` and an `upgrade_url`, never silently queued. See [limits](https://docs.kosa8.com/limits/). --- Source: https://docs.kosa8.com/concepts/sandboxes/ # Sizes and templates A template is what is installed. A size is how much machine it gets. Pick both, or neither: every template has a sensible default size. **CLI** ``` kosa8 cloud sizes # what this organization can make # A half-vCPU, 1 GiB sandbox of any OCI image (boots cold, waits until it runs) ID=$(kosa8 cloud sandbox create --size 0.5x1 --image python:3.12-slim --ttl 15m --json | jq -r .sandbox.id) kosa8 cloud sandbox exec $ID -- nproc kosa8 cloud sandbox rm $ID ``` **curl** ``` API=https://api.kosa8.com/v1 AUTH="Authorization: Bearer $KOSA8_API_KEY" # A sized create may answer 202 "creating": poll until it runs SBX=$(curl -s $API/sandboxes -H "$AUTH" -H 'Content-Type: application/json' \ -d '{"size":"0.5x1","image":"python:3.12-slim","ttl_s":900}' | jq -r .sandbox.id) until [ "$(curl -s $API/sandboxes/$SBX -H "$AUTH" | jq -r .sandbox.state)" = running ]; do sleep 2; done curl -s $API/sandboxes/$SBX/exec -H "$AUTH" -H 'Content-Type: application/json' \ -d '{"cmd":["python3","-c","import os; print(os.cpu_count())"]}' | jq -r .stdout curl -s -X DELETE $API/sandboxes/$SBX -H "$AUTH" ``` **Python** ``` from kosa8 import Kosa8Cloud cloud = Kosa8Cloud() # create() waits for a sized sandbox to boot (wait=False to skip) with cloud.sandboxes.create(size="0.5x1", image="python:3.12-slim", ttl_s=900) as box: print(box.info["cpus"], box.info["mem_mb"]) # 0.5 1024 print(box.exec("nproc").stdout) # 1: bursts to a whole vCPU ``` **JavaScript** ``` import { Kosa8Cloud } from '@kosa8/sdk'; const cloud = new Kosa8Cloud(); // create() waits for a sized sandbox to boot const box = await cloud.sandboxes.create({ size: '0.5x1', image: 'python:3.12-slim', ttlS: 900 }); try { console.log(box.info.cpus, box.info.mem_mb); // 0.5 1024 console.log((await box.exec('nproc')).stdout); // 1: bursts to a whole vCPU } finally { await box.delete(); } ``` ## Templates | Template | What is in it | Default size | |---|---|---| | `base` | Alpine Linux with busybox `sh`. The default. | 1 vCPU, 256 MiB | | `python` | Python 3.12 on Debian slim, with bash, git, curl, pip, pytest and uv | 1 vCPU, 256 MiB | | `node` | Node.js 22 on Alpine, with bash and git | 1 vCPU, 384 MiB | | `universal-2x4` … `universal-16x32` | Ubuntu 24.04 with about 150 tools and runtimes. [The universal image](https://docs.kosa8.com/guides/cloud-images/) | As named | `GET /v1/templates` lists every template your organization can use, including prebuilt [benchmark environments](https://docs.kosa8.com/guides/benchmarks/) and the [gallery](https://docs.kosa8.com/guides/templates/). ## Sizes A size is `VCPUSxGIB`. `kosa8 cloud sizes` and the `sizes` list of `GET /v1/templates` show them. | Size | vCPUs | Memory | Sandbox-hours per hour | Kind | |---|---|---|---|---| | `0.25x0.5` | 0.25, bursts to 1 | 512 MiB | 0.125 | small | | `0.5x1` | 0.5, bursts to 1 | 1 GiB | 0.25 | small | | `1x2` | 1, bursts to 2 | 2 GiB | 0.5 | small | | `2x4` | 2 | 4 GiB | 1 | standard | | `4x8` | 4 | 8 GiB | 2 | standard | | `8x16` | 8 | 16 GiB | 4 | standard | | `16x32` | 16 | 32 GiB | 8 | standard | Your plan includes a number of sandbox-hours a month, counted against a `2x4`: an hour of `0.5x1` uses a quarter of one, an hour of `8x16` uses four. The largest size you can start also depends on the plan. Small sizes suit fleets of mostly idle sandboxes, such as RL rollouts and evals. Data disks go up to 500 GB with `disk_gb`. Plans and what they include are on [kosa8.com/pricing](https://kosa8.com/pricing/). ## Your own image Pass `image` with any public OCI reference (`python:3.12-slim`, `ghcr.io/you/tool:1.4`). The first start pulls it, and later starts are fast. To start with your dependencies already installed, set one up once and save it as a [snapshot](https://docs.kosa8.com/concepts/snapshots/). --- Source: https://docs.kosa8.com/concepts/sizes/ # Exec and streaming Three ways to run a command, chosen by how long it takes and whether you want to watch it. | | Buffered | Streamed | Background | |---|---|---|---| | Ask with | nothing extra | `"stream": true` | `"background": true` | | You get | one JSON answer at the end | NDJSON frames as it prints, or SSE | an id at once, to poll | | Longest run | 90 s | your `timeout_s`, up to 24 h | until it exits or the sandbox goes | | Use it for | quick commands, tool calls | builds, tests, training logs | servers, long jobs, fire and forget | ## Buffered exec `POST /v1/sandboxes/{id}/exec` with `cmd`, a list of strings such as `["sh", "-c", "make test"]`, and optionally `env` (`NAME=value` strings) and `timeout_s`. The answer holds `exit`, `stdout` and `stderr`. A command that exits non-zero is still a `200`: it ran, and it failed. A command still running at its limit is stopped and answers `504 exec_timeout`, with the output so far. ## Streaming **CLI** ``` ID=$(kosa8 cloud sandbox create --template python --ttl 15m --json | jq -r .sandbox.id) # Output streams as it is printed; the exit code is the command's own kosa8 cloud sandbox exec $ID -- sh -c 'for i in 1 2 3; do echo "step $i"; sleep 1; done' kosa8 cloud sandbox rm $ID ``` **curl** ``` API=https://api.kosa8.com/v1 AUTH="Authorization: Bearer $KOSA8_API_KEY" SBX=$(curl -s $API/sandboxes -H "$AUTH" -H 'Content-Type: application/json' \ -d '{"template":"python","ttl_s":900}' | jq -r .sandbox.id) # "stream": true answers NDJSON as the command prints, with no 90-second limit: # {"stream":"stdout","data":""} … then {"done":true,"exit":0} curl -sN $API/sandboxes/$SBX/exec -H "$AUTH" -H 'Content-Type: application/json' \ -d '{"cmd":["sh","-c","for i in 1 2 3; do echo step $i; sleep 1; done"],"stream":true}' | while read -r frame; do data=$(echo "$frame" | jq -r 'select(.stream == "stdout" and (.heartbeat | not)) | .data') [ -n "$data" ] && echo "$data" | base64 --decode echo "$frame" | jq -r 'select(.done) | "exit \(.exit)"' done curl -s -X DELETE $API/sandboxes/$SBX -H "$AUTH" ``` **Python** ``` from kosa8 import Kosa8Cloud cloud = Kosa8Cloud() with cloud.sandboxes.create(template="python", ttl_s=900) as box: # Buffered: one answer when the command ends (up to 90 s) r = box.exec("for i in 1 2 3; do echo step $i; done") print(r.exit_code, r.stdout) # Bound a command you do not trust to finish r = box.exec(["python3", "-c", "print('quick')"], timeout_s=10) print(r.stdout) ``` **JavaScript** ``` import { Kosa8Cloud } from '@kosa8/sdk'; const cloud = new Kosa8Cloud(); const box = await cloud.sandboxes.create({ template: 'python', ttlS: 900 }); try { // Buffered: one answer when the command ends (up to 90 s) const r = await box.exec('for i in 1 2 3; do echo step $i; done'); console.log(r.exitCode, r.stdout); } finally { await box.delete(); } ``` Each frame is `{"stream": "stdout" | "stderr", "data": ""}`; an empty heartbeat frame comes every 15 s while nothing prints, and the last line is `{"done": true, "exit": N}`. Send `Accept: text/event-stream` for server-sent events with the output already decoded as text, which is what a browser's `fetch` reader wants. ## Background commands **CLI** ``` ID=$(kosa8 cloud sandbox create --template python --ttl 15m --json | jq -r .sandbox.id) # -d starts it and returns at once with its id (bg_…) BG=$(kosa8 cloud sandbox exec -d $ID --json -- sh -c 'sleep 3; echo built' | jq -r .exec.id) # ...do other things, then wait for it and take its exit code kosa8 cloud sandbox exec-status $ID $BG --wait kosa8 cloud sandbox rm $ID ``` **curl** ``` API=https://api.kosa8.com/v1 AUTH="Authorization: Bearer $KOSA8_API_KEY" SBX=$(curl -s $API/sandboxes -H "$AUTH" -H 'Content-Type: application/json' \ -d '{"template":"python","ttl_s":900}' | jq -r .sandbox.id) # 202 at once; the command keeps running BG=$(curl -s $API/sandboxes/$SBX/exec -H "$AUTH" -H 'Content-Type: application/json' \ -d '{"cmd":["sh","-c","sleep 3; echo built"],"background":true}' | jq -r .exec.id) until [ "$(curl -s $API/sandboxes/$SBX/exec/$BG -H "$AUTH" | jq -r .exec.state)" = exited ]; do sleep 1; done curl -s $API/sandboxes/$SBX/exec/$BG -H "$AUTH" | jq '.exec | {state, exit, output}' curl -s -X DELETE $API/sandboxes/$SBX -H "$AUTH" ``` **Python** ``` from kosa8 import Kosa8Cloud cloud = Kosa8Cloud() with cloud.sandboxes.create(template="python", ttl_s=900) as box: job = box.exec_background("sleep 3; echo built") # returns at once print(job.id) # bg_… done = job.wait() # polls until it exits print(done["exit"], done["output"]) # 0 built ``` **JavaScript** ``` import { Kosa8Cloud } from '@kosa8/sdk'; const cloud = new Kosa8Cloud(); const box = await cloud.sandboxes.create({ template: 'python', ttlS: 900 }); try { const job = await box.execBackground('sleep 3; echo built'); // returns at once const done = await job.wait(); // polls until it exits console.log(done.exit, done.output); // 0 built } finally { await box.delete(); } ``` A background command keeps running after the request ends. Read its status and output with `GET /v1/sandboxes/{id}/exec/{exec_id}`, or stop it with `POST …/exec/{exec_id}/stop`. [More on background commands](https://docs.kosa8.com/guides/cloud-snapshots-background/). ## Whose fault was it? Every answer under `/v1/sandboxes` carries a `failure_class`: `ok`, `exit_nonzero` (your code), `timeout`, `oom` (killed for memory), `infra` (kosa8's side, usually retryable), `quota` or `client`. An RL trainer can mask infra failures instead of scoring them as reward 0. See [errors and retries](https://docs.kosa8.com/errors/). --- Source: https://docs.kosa8.com/concepts/exec/ # Files Files go in and out as raw bytes, no base64 and no multipart. Keep what matters under `/workspace`, the part of the sandbox that lasts. A sleeping sandbox wakes for a file call. **CLI** ``` ID=$(kosa8 cloud sandbox create --template python --ttl 15m --json | jq -r .sandbox.id) echo 'print("hello from a file")' > hello.py kosa8 cloud files put $ID hello.py /workspace/hello.py kosa8 cloud sandbox exec $ID -- python3 /workspace/hello.py > out.txt kosa8 cloud files ls $ID /workspace kosa8 cloud files get $ID /workspace/hello.py # to stdout cat out.txt kosa8 cloud sandbox rm $ID ``` **curl** ``` API=https://api.kosa8.com/v1 AUTH="Authorization: Bearer $KOSA8_API_KEY" SBX=$(curl -s $API/sandboxes -H "$AUTH" -H 'Content-Type: application/json' \ -d '{"template":"python","ttl_s":900}' | jq -r .sandbox.id) # Upload: the request body is the file, streamed, any size curl -s -X PUT "$API/sandboxes/$SBX/files?path=/workspace/hello.py" -H "$AUTH" \ --data-binary 'print("hello from a file")' > /dev/null # Download, and list the folder curl -s "$API/sandboxes/$SBX/files?path=/workspace/hello.py" -H "$AUTH"; echo curl -s "$API/sandboxes/$SBX/files/list?path=/workspace" -H "$AUTH" | jq -c '.files[] | {name, size}' curl -s -X DELETE $API/sandboxes/$SBX -H "$AUTH" ``` **Python** ``` from kosa8 import Kosa8Cloud cloud = Kosa8Cloud() with cloud.sandboxes.create(template="python", ttl_s=900) as box: box.files.write("/workspace/hello.py", 'print("hello from a file")\n') print(box.exec(["python3", "/workspace/hello.py"]).stdout) # hello from a file print(box.files.read_text("/workspace/hello.py")) for f in box.files.list("/workspace"): print(f["name"], f["size"]) ``` **JavaScript** ``` import { Kosa8Cloud } from '@kosa8/sdk'; const cloud = new Kosa8Cloud(); const box = await cloud.sandboxes.create({ template: 'python', ttlS: 900 }); try { await box.files.write('/workspace/hello.py', 'print("hello from a file")\n'); console.log((await box.exec(['python3', '/workspace/hello.py'])).stdout); // hello from a file console.log(await box.files.readText('/workspace/hello.py')); for (const f of await box.files.list('/workspace')) console.log(f.name, f.size); } finally { await box.delete(); } ``` ## The calls | Call | Does | |---|---| | `PUT /v1/sandboxes/{id}/files?path=…` | Write a file; the body is its bytes, streamed (100 MB per request; larger files go in parts or by direct link) | | `GET /v1/sandboxes/{id}/files?path=…` | Read it back, streamed; `Range` headers work | | `GET /v1/sandboxes/{id}/files/list?path=…` | List a folder (default `/workspace`) as `{"files": [...]}` | | `POST /v1/sandboxes/{id}/files/mkdir` | Make a folder and its parents | | `DELETE /v1/sandboxes/{id}/files?path=…` | Remove a file, or a folder with `recursive=1` | The exact parameters are in the [API reference](https://docs.kosa8.com/api/sandbox-files/). For files of many megabytes, appends, offsets and direct upload links, see [terminal and large files](https://docs.kosa8.com/guides/cloud-terminal-files/). ## Tips - To send a whole project, tar it, put one file, and untar it with one exec. That is far faster than one call per file. - Results you want to keep must be read out before the sandbox is deleted, or saved in a [snapshot](https://docs.kosa8.com/concepts/snapshots/). --- Source: https://docs.kosa8.com/concepts/files/ # Fork, checkpoints and rewind A sandbox is a whole running machine, so you can save it, go back to it and copy it, memory and processes included. This is what lets an agent try something risky, or an RL loop branch a rollout, without setting anything up again. ## Checkpoint and rewind **CLI** ``` ID=$(kosa8 cloud sandbox create --template python --ttl 15m --json | jq -r .sandbox.id) kosa8 cloud sandbox exec $ID -- sh -c 'echo v1 > /workspace/state' CK=$(kosa8 cloud checkpoint create $ID --label "before the risky part" --json | jq -r .checkpoint.id) kosa8 cloud sandbox exec $ID -- sh -c 'echo broken > /workspace/state' kosa8 cloud checkpoint rewind $ID $CK # memory, processes and disk kosa8 cloud sandbox exec $ID -- cat /workspace/state # v1 kosa8 cloud sandbox rm $ID ``` **curl** ``` API=https://api.kosa8.com/v1 AUTH="Authorization: Bearer $KOSA8_API_KEY" JSON='Content-Type: application/json' SBX=$(curl -s $API/sandboxes -H "$AUTH" -H "$JSON" -d '{"template":"python","ttl_s":900}' | jq -r .sandbox.id) run() { curl -s $API/sandboxes/$SBX/exec -H "$AUTH" -H "$JSON" -d "{\"cmd\":[\"sh\",\"-c\",\"$1\"]}" | jq -r .stdout; } run 'echo v1 > /workspace/state' CK=$(curl -s $API/sandboxes/$SBX/checkpoints -H "$AUTH" -H "$JSON" \ -d '{"label":"before the risky part"}' | jq -r .checkpoint.id) run 'echo broken > /workspace/state' curl -s $API/sandboxes/$SBX/rewind -H "$AUTH" -H "$JSON" -d "{\"checkpoint\":\"$CK\"}" > /dev/null run 'cat /workspace/state' # v1 curl -s -X DELETE $API/sandboxes/$SBX -H "$AUTH" ``` **Python** ``` from kosa8 import Kosa8Cloud cloud = Kosa8Cloud() with cloud.sandboxes.create(template="python", ttl_s=900) as box: box.exec("echo v1 > /workspace/state") ck = box.checkpoint("before the risky part") # memory, processes and disk box.exec("echo broken > /workspace/state") box.rewind(ck["id"]) # the old state is saved first, as a backup print(box.exec("cat /workspace/state").stdout) # v1 ``` **JavaScript** ``` import { Kosa8Cloud } from '@kosa8/sdk'; const cloud = new Kosa8Cloud(); const box = await cloud.sandboxes.create({ template: 'python', ttlS: 900 }); try { await box.exec('echo v1 > /workspace/state'); const ck = await box.checkpoint('before the risky part'); // memory, processes and disk await box.exec('echo broken > /workspace/state'); await box.rewind(ck); // the old state is saved first console.log((await box.exec('cat /workspace/state')).stdout); // v1 } finally { await box.delete(); } ``` - **A checkpoint** saves memory, processes and disk. Take one with `POST /v1/sandboxes/{id}/checkpoints`, with an optional `label`. The newest 10 are kept; older ones are dropped and listed in `evicted`. - **Rewind** (`POST /v1/sandboxes/{id}/rewind` with `checkpoint_id`) puts the sandbox back. How it was just before is saved as an automatic checkpoint first, so a rewind can itself be undone. - Checkpoints belong to their sandbox and go when it is deleted. To keep a state for good, or start other sandboxes from it, take a [snapshot](https://docs.kosa8.com/concepts/snapshots/). ## Fork **CLI** ``` ID=$(kosa8 cloud sandbox create --template python --ttl 15m --json | jq -r .sandbox.id) kosa8 cloud sandbox exec $ID -- sh -c 'echo "set up once" > /workspace/ready' # Three live copies, memory and processes included kosa8 cloud sandbox fork $ID -n 3 --prefix try --json | jq -r '.sandboxes[].id' > forks.txt for F in $(cat forks.txt); do kosa8 cloud sandbox exec $F -- cat /workspace/ready done kosa8 cloud sandbox rm $ID $(cat forks.txt) ``` **curl** ``` API=https://api.kosa8.com/v1 AUTH="Authorization: Bearer $KOSA8_API_KEY" JSON='Content-Type: application/json' SBX=$(curl -s $API/sandboxes -H "$AUTH" -H "$JSON" -d '{"template":"python","ttl_s":900}' | jq -r .sandbox.id) curl -s $API/sandboxes/$SBX/exec -H "$AUTH" -H "$JSON" \ -d '{"cmd":["sh","-c","echo set up once > /workspace/ready"]}' > /dev/null # Three live copies of the sandbox as it is now FORKS=$(curl -s $API/sandboxes/$SBX/fork -H "$AUTH" -H "$JSON" -d '{"n":3}' | jq -r '.sandboxes[].id') for F in $FORKS; do curl -s $API/sandboxes/$F/exec -H "$AUTH" -H "$JSON" -d '{"cmd":["cat","/workspace/ready"]}' | jq -r .stdout done for S in $SBX $FORKS; do curl -s -X DELETE $API/sandboxes/$S -H "$AUTH" > /dev/null; done ``` **Python** ``` from kosa8 import Kosa8Cloud cloud = Kosa8Cloud() with cloud.sandboxes.create(template="python", ttl_s=900) as box: box.exec("echo 'set up once' > /workspace/ready") forks = box.fork(3) # three live copies, memory and processes included for f in forks: print(f.id, f.exec("cat /workspace/ready").stdout.strip()) f.delete() ``` **JavaScript** ``` import { Kosa8Cloud } from '@kosa8/sdk'; const cloud = new Kosa8Cloud(); const box = await cloud.sandboxes.create({ template: 'python', ttlS: 900 }); try { await box.exec("echo 'set up once' > /workspace/ready"); const forks = await box.fork(3); // three live copies, memory and processes included const outs = await Promise.all(forks.map((f) => f.exec('cat /workspace/ready'))); outs.forEach((r, i) => console.log(forks[i].id, r.stdout.trim())); await Promise.all(forks.map((f) => f.delete())); } finally { await box.delete(); } ``` `POST /v1/sandboxes/{id}/fork` with `n` makes that many running copies of the sandbox as it is now. Each copy is a full sandbox of its own, with its own id, billed and limited like a create. Copies land on the parent's host first, as copy-on-write restores, so they start fast. Up to 1,000 per call, made 100 at a time; when the parent's host is full the rest are restored on other hosts. The answer has `requested`, `created` and a `failed` list, so a partial fork tells you exactly what you got. Secrets are never copied into forks. ## Patterns [**Branching rollouts**Checkpoint at a decision point, fork n ways, score each, keep the best.](https://docs.kosa8.com/guides/rl-training/) [**Fan out a test suite**Install once, snapshot, then shard across copies.](https://docs.kosa8.com/guides/cloud-fan-out/) [**Undo for agents**Checkpoint before every risky tool call and rewind if it goes wrong.](https://docs.kosa8.com/guides/agent-hooks/) --- Source: https://docs.kosa8.com/concepts/fork-rewind/ # Sleep and wake A sandbox that is not doing anything can sleep: kosa8 saves its memory and disk and frees the machine. The next call wakes it where it left off, running processes included. **CLI** ``` ID=$(kosa8 cloud sandbox create --template python --ttl 30m --json | jq -r .sandbox.id) kosa8 cloud sandbox exec $ID -- sh -c 'echo "still here" > /workspace/note' kosa8 cloud sandbox sleep $ID # snapshot it and free its memory kosa8 cloud sandbox get $ID --json | jq -r .sandbox.state # sleeping kosa8 cloud sandbox exec $ID -- cat /workspace/note # the next exec wakes it kosa8 cloud sandbox rm $ID ``` **curl** ``` API=https://api.kosa8.com/v1 AUTH="Authorization: Bearer $KOSA8_API_KEY" JSON='Content-Type: application/json' SBX=$(curl -s $API/sandboxes -H "$AUTH" -H "$JSON" -d '{"template":"python","ttl_s":1800}' | jq -r .sandbox.id) curl -s $API/sandboxes/$SBX/exec -H "$AUTH" -H "$JSON" \ -d '{"cmd":["sh","-c","echo still here > /workspace/note"]}' > /dev/null curl -s -X POST $API/sandboxes/$SBX/sleep -H "$AUTH" | jq -r .sandbox.state # sleeping # Any exec wakes it first (or POST /wake to wake it now) curl -s $API/sandboxes/$SBX/exec -H "$AUTH" -H "$JSON" -d '{"cmd":["cat","/workspace/note"]}' | jq -r .stdout curl -s -X DELETE $API/sandboxes/$SBX -H "$AUTH" ``` **Python** ``` from kosa8 import Kosa8Cloud cloud = Kosa8Cloud() with cloud.sandboxes.create(template="python", ttl_s=1800) as box: box.exec("echo 'still here' > /workspace/note") box.sleep() # snapshot it and free its memory print(box.state) # sleeping print(box.exec("cat /workspace/note").stdout) # wakes it first: still here ``` **JavaScript** ``` import { Kosa8Cloud } from '@kosa8/sdk'; const cloud = new Kosa8Cloud(); const box = await cloud.sandboxes.create({ template: 'python', ttlS: 1800 }); try { await box.exec("echo 'still here' > /workspace/note"); await box.sleep(); // snapshot it, free its memory console.log(box.state); // sleeping console.log((await box.exec('cat /workspace/note')).stdout); // wakes it first: still here } finally { await box.delete(); } ``` ## How it works - Set `sleep_after_s` on create (0 means never, up to 7 days) and an idle sandbox sleeps on its own. Or call `POST /v1/sandboxes/{id}/sleep`. - A sleeping sandbox has state `sleeping`. Exec, file calls, checkpoints and snapshots wake it first; their answers carry `woke_ms`, how long that took. `POST /v1/sandboxes/{id}/wake` wakes it now. - A sleeping sandbox does not run, so it does not use your plan's sandbox-hours. Its `ttl_s` deadline still counts. - A [preview URL](https://docs.kosa8.com/guides/cloud-previews/) can wake its sandbox on the first request: [wake on request, and schedules](https://docs.kosa8.com/guides/cloud-wake-cron/). --- Source: https://docs.kosa8.com/concepts/sleep/ # Snapshots Set a sandbox up once (clone the repo, install the packages, warm the caches), save it, and start every later sandbox from there. **CLI** ``` ID=$(kosa8 cloud sandbox create --template python --ttl 15m --json | jq -r .sandbox.id) kosa8 cloud sandbox exec $ID -- sh -c 'pip install --quiet --target /workspace/lib six && echo ok' # A snapshot outlives the sandbox: start as many copies as you like from it SNAP=$(kosa8 cloud snapshot create $ID --name deps-installed --json | jq -r .snapshot.id) kosa8 cloud sandbox rm $ID COPY=$(kosa8 cloud sandbox create --from-snapshot $SNAP --ttl 15m --json | jq -r .sandbox.id) kosa8 cloud sandbox exec $COPY -- ls /workspace/lib kosa8 cloud sandbox rm $COPY kosa8 cloud snapshot rm $SNAP ``` **curl** ``` API=https://api.kosa8.com/v1 AUTH="Authorization: Bearer $KOSA8_API_KEY" JSON='Content-Type: application/json' SBX=$(curl -s $API/sandboxes -H "$AUTH" -H "$JSON" -d '{"template":"python","ttl_s":900}' | jq -r .sandbox.id) curl -s $API/sandboxes/$SBX/exec -H "$AUTH" -H "$JSON" \ -d '{"cmd":["sh","-c","echo warmed > /workspace/cache"]}' > /dev/null SNAP=$(curl -s $API/sandboxes/$SBX/snapshots -H "$AUTH" -H "$JSON" \ -d '{"name":"warm-cache"}' | jq -r .snapshot.id) curl -s -X DELETE $API/sandboxes/$SBX -H "$AUTH" > /dev/null # the snapshot stays COPY=$(curl -s $API/sandboxes -H "$AUTH" -H "$JSON" -d "{\"snapshot\":\"$SNAP\",\"ttl_s\":900}" | jq -r .sandbox.id) until [ "$(curl -s $API/sandboxes/$COPY -H "$AUTH" | jq -r .sandbox.state)" = running ]; do sleep 1; done curl -s $API/sandboxes/$COPY/exec -H "$AUTH" -H "$JSON" -d '{"cmd":["cat","/workspace/cache"]}' | jq -r .stdout curl -s -X DELETE $API/sandboxes/$COPY -H "$AUTH" > /dev/null curl -s -X DELETE $API/snapshots/$SNAP -H "$AUTH" ``` **Python** ``` from kosa8 import Kosa8Cloud cloud = Kosa8Cloud() with cloud.sandboxes.create(template="python", ttl_s=900) as box: box.exec("echo warmed > /workspace/cache") snap = box.snapshot("warm-cache") # kept until you delete it with cloud.sandboxes.create(snapshot=snap["id"], ttl_s=900) as copy: print(copy.exec("cat /workspace/cache").stdout) # warmed cloud.snapshots.delete(snap["id"]) ``` **JavaScript** ``` import { Kosa8Cloud } from '@kosa8/sdk'; const cloud = new Kosa8Cloud(); const box = await cloud.sandboxes.create({ template: 'python', ttlS: 900 }); await box.exec('echo warmed > /workspace/cache'); const snap = await box.snapshot('warm-cache'); // kept until you delete it await box.delete(); const copy = await cloud.sandboxes.create({ snapshot: snap.id, ttlS: 900 }); console.log((await copy.exec('cat /workspace/cache')).stdout); // warmed await copy.delete(); await cloud.snapshots.delete(snap.id); ``` ## Snapshots and checkpoints **Checkpoint** Belongs to one sandbox and goes with it. The newest 10 are kept. For undo. **Snapshot** Belongs to your organization and is kept until you delete it, whatever happens to the sandbox it came from. For starting new sandboxes. ## The calls | `POST /v1/sandboxes/{id}/snapshots` | Save it, with an optional `name`. The sandbox keeps running. | |---|---| | `POST /v1/sandboxes` `{"snapshot": "snap_…"}` | Start a new sandbox from it | | `GET /v1/snapshots` | List them, newest first, with `max`, how many you may keep | | `DELETE /v1/snapshots/{id}` | Delete it. Sandboxes made from it are not touched. | How many snapshots you can keep depends on your plan (past it: `402 plan_limit`), with at most 50 per organization at once (`429 snapshot_limit`). A snapshot's bytes are billed as storage until you delete it; see [pricing](https://kosa8.com/pricing/). Sandboxes with secrets, or on dedicated cores, cannot be snapshotted. For background commands, environment and warm pools built on snapshots, see [snapshots, background and env](https://docs.kosa8.com/guides/cloud-snapshots-background/). --- Source: https://docs.kosa8.com/concepts/snapshots/ # Functions Deploy a handler once and call it by name. Every call runs in a fresh microVM, so one call can never see another's data. Functions are on the Pro plan and up. **curl** ``` API=https://api.kosa8.com/v1 AUTH="Authorization: Bearer $KOSA8_API_KEY" JSON='Content-Type: application/json' # Deploy: code plus a runtime. Each call runs in a fresh microVM. curl -s -X PUT $API/functions/hello-fn -H "$AUTH" -H "$JSON" -d '{ "runtime": "python3.12", "code": "def handler(event):\n return {\"greeting\": \"hello \" + event[\"name\"]}\n" }' | jq '{name, version}' curl -s $API/functions/hello-fn/invoke -H "$AUTH" -H "$JSON" \ -d '{"event":{"name":"kosa8"}}' | jq '{ok, result}' curl -s -X DELETE $API/functions/hello-fn -H "$AUTH" ``` **Python** ``` from kosa8 import Kosa8Cloud cloud = Kosa8Cloud() cloud.functions.deploy("hello-fn", { "runtime": "python3.12", "code": "def handler(event):\n return {'greeting': 'hello ' + event['name']}\n", }) out = cloud.functions.invoke("hello-fn", {"name": "kosa8"}) # runs in a fresh microVM print(out["ok"], out["result"]) # True {'greeting': 'hello kosa8'} cloud.functions.delete("hello-fn") ``` **JavaScript** ``` import { Kosa8Cloud } from '@kosa8/sdk'; const cloud = new Kosa8Cloud(); await cloud.functions.deploy('hello-fn', { runtime: 'node22', code: "exports.handler = async (event) => ({ greeting: 'hello ' + event.name });\n", }); const out = await cloud.functions.invoke('hello-fn', { name: 'kosa8' }); // a fresh microVM per call console.log(out.ok, out.result); // true { greeting: 'hello kosa8' } await cloud.functions.delete('hello-fn'); ``` ## Deploy `PUT /v1/functions/{name}` with: | Field | What it does | |---|---| | `runtime` | `python3.12` or `node22` | | `code` | The source. Python defines `def handler(event)`; Node exports `exports.handler`. Up to 6 MiB. | | `env` | Environment for every call: up to 64 names (none starting `K8_`), 16 KiB in all | | `timeout_s` | How long one call may run: default 30 s, up to 90 s | | `web` | `off` (default), `public` or `key`: also answer plain HTTP requests at a URL, open or behind a key | | `schedule` | A five-field cron expression (UTC) to call it on a timetable, or `null` | Deploying again with the same name replaces it and bumps its `version`. Deploying needs a key with `functions:deploy`; calling needs `functions:invoke`. ## Call `POST /v1/functions/{name}/invoke` with `{"event": …}` answers with `ok`, `result`, logs and timings. `POST /v1/functions/{name}/map` with `{"events": [...]}` calls it on up to 100 events, up to 16 at a time. `GET …/invocations` lists recent calls. Every endpoint is in the [Functions API](https://docs.kosa8.com/api/functions/). ## Functions, one-call runs, or sandboxes? | You have | Use | |---|---| | The same handler, called again and again | A function | | Some code or a command to run once, maybe with files | [One-call run](https://docs.kosa8.com/guides/cloud-run/), `POST /v1/run` | | State that lasts between calls, or a long task | A [sandbox](https://docs.kosa8.com/concepts/sandboxes/) | --- Source: https://docs.kosa8.com/serverless/functions/ # One-call run Send code or a command, get its output. kosa8 takes a fresh sandbox from the warm pool, writes your files, runs it, streams stdout and stderr as it prints, sends back the files you ask for, and deletes the sandbox. There is nothing to create or clean up. It is billed per second, like any sandbox. ## From the terminal New here? `kosa8 init` signs you in, runs a first sandbox and prints what to try next. ``` kosa8 run "python3 -c 'print(6 * 7)'" # ▸ kosa8 run · python3 -c 'print(6 * 7)' # 42 # ✓ exit 0 · 640 ms · python # View run → https://app.kosa8.com/runs/sr_… kosa8 run train.py --epochs 3 # the language comes from the extension kosa8 run --upload data.csv --out chart.png plot.py kosa8 run --timeout 10m --size 4x8 bench.sh kosa8 run --share "pytest -q" # a public read-only run card kosa8 run --json "echo hi" | jq .status # one JSON object, no live output ``` - A single quoted argument with a space in it is a shell command. A file that exists with a `.py`, `.js`, `.mjs`, `.ts`, `.sh` or `.bash` extension is a script; anything after it goes to the script. `kosa8 run IMAGE COMMAND` is still the local engine's docker-style run. - `-e KEY=VALUE` sets env, `--upload` sends a local file into `/workspace`, `--out` brings a file back into the current directory (never over an existing file), `--template` and `--size` pick the sandbox, `--timeout` stops it (default 60 s, at most 1 h), `-q` prints only the command's own output. - It exits with the command's exit code, and 124 when it ran past `--timeout`. Flags go before the command or script. - Not signed in, it runs `kosa8 login` first. ## From the API ``` curl -s https://api.kosa8.com/v1/run \ -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' \ -d '{"code": "import sys\nprint(sys.version)", "language": "python"}' # {"run":{"id":"sr_…","status":"ok","exit":0,"stdout":"3.12…\n","stderr":"", # "duration_ms":612,"timing":{"sandbox_ms":180,"exec_ms":410,"total_ms":612}, # "template":"python","files":[],"view_url":"https://app.kosa8.com/runs/sr_…"}} curl -s https://api.kosa8.com/v1/run \ -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' \ -d '{"command": "wc -l data.csv && sort data.csv > sorted.csv", "files": {"data.csv": "b\na\nc\n"}, "outputs": ["sorted.csv"]}' # "files":[{"path":"/workspace/sorted.csv","bytes":6,"content_base64":"YQpiCmMK"}] ``` | Field | What it does | |---|---| | `code` | Source to run. It is written to `filename` (default `main.py`, `main.js`, …) in `/workspace` and run with the language's interpreter. | | `command` | A shell string, or a list of strings. Without `code`, it is what runs. With `code`, it runs instead of the interpreter (for example `pytest -q` on the file you sent). | | `language` | `python`, `node`, `typescript`, `bash` or `sh`. Default: from `filename`, else python. | | `template` | Default: the language's own (`python`, `node` or `base`); for a bare command, `node` when it starts with node, npm or npx, else `python`. | | `files` | `{"path": "text"}`, or `[{"path", "content", "encoding": "base64"}]` for bytes. Paths are under `/workspace`. The whole body is at most 6 MiB. | | `env` | `{"NAME": "value"}`. Values are hidden (`•••`) in the saved output and on run cards. | | `outputs` | Up to 16 paths to send back, base64, 4 MiB together. A missing one comes back with `error: "not_found"`. | | `timeout_s` | Default 60, at most 3600. Past it the run stops with `status: "timeout"`. | | `repo` | Run in a checkout of a repo of your connected GitHub: `"owner/name"`, `"owner/name@ref"` or `{"name", "ref", "path", "depth"}`. It is cloned into `/workspace/` and the command runs there. See [Work with your GitHub repos](https://docs.kosa8.com/guides/cloud-github/). | | `size` | A size name such as `2x4` (`kosa8 cloud sizes`, or the `sizes` list of `GET /v1/templates`). Default: the template's own. | | `stream` | `true` for NDJSON as it prints, `"sse"` for server-sent events. See below. | | `share` | `true` publishes the run card. `{"public": true, "code": true}` shows the code on it too. | A command that exits non-zero is still a `200`, with `status: "failed"` and its `exit`: it ran, and it failed. A `4xx` or `5xx` means it could not run. Every error carries `hint`, the next step, and `docs`, a link here. When the sandbox could not be made, `stage` is `create` and the status is the create's own (402 without a plan, 429 at the running limit, 503 when there is no room for a moment). ## Streaming With `"stream": true` the answer is NDJSON. The first line names the run, so a caller can show its link at once. Then come the exec stream's own frames, `{"stream": "stdout" | "stderr", "data": ""}`, with an empty `heartbeat` frame every 15 s while the command prints nothing. The last line is `{"done": true, "exit": N, "run": {…}}`. ``` curl -sN https://api.kosa8.com/v1/run \ -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' \ -d '{"command": "for i in 1 2 3; do echo $i; sleep 1; done", "stream": true}' # {"run":{"id":"sr_…","sandbox_id":"sbx_…","status":"running","view_url":"…"}} # {"stream":"stdout","data":"MQo="} # {"stream":"stdout","data":"Mgo="} # {"stream":"stdout","data":"Mwo="} # {"done":true,"exit":0,"run":{"status":"ok","duration_ms":3420,…}} ``` Send `Accept: text/event-stream` (or `"stream": "sse"`) for server-sent events instead, with the output already decoded as UTF-8 text. That is what a browser's `fetch` reader or an `EventSource` proxy wants. ``` event: run data: {"id":"sr_…","view_url":"…"} event: stdout data: {"text":"1\n"} : heartbeat event: done data: {"id":"sr_…","status":"ok","exit":0,"duration_ms":3420,…} ``` The same `Accept: text/event-stream` works on `POST /v1/sandboxes/{id}/exec` with `"stream": true`, for a sandbox you keep. A streamed run or exec is not held to the 90 s limit of a buffered exec. A run of more than 85 s without `stream` is still one JSON answer at the end; kosa8 streams it internally. ## Run links and run cards Every run answers with a `view_url`, and the CLI prints `View run →` with it. The page shows the command, its output, the exit code and how long it took. - It is private by default: only people signed in to your organization can open it. - Make one public with `share: true` on the run, `kosa8 run --share`, `POST /v1/runs/{id}/share {"public": true}`, or the Share button on the page. Make every new run public with the organization setting `public_runs` (`PATCH /v1/settings {"public_runs": true}`). It is never on by default. - A public card shows the command, the output and the duration. It never shows env or the files you sent. The code is shown only when you publish it with `{"public": true, "code": true}`. The values of the run's env, and strings shaped like kosa8, OpenAI, Anthropic, GitHub, AWS and Slack keys, are replaced by `•••` before the output is saved. - Hosted jobs and RL runs have cards too: their answers carry `view_url`, and `kosa8 job submit` and `kosa8 cloud rl runs create` print it. Publish one with `POST /v1/jobs/{id}/share` or `POST /v1/rl/runs/{id}/share` `{"public": true}`. A job with a grader, or an RL run with rollouts the sealed grader scored, shows a **graded by sealed grader** badge: the score came from a sealed copy of the sandbox the solver could not touch. A job or RL run card shows names, counts, reward and duration, never task inputs, output, env or files. - An exec answer carries `view_url` too: the sandbox's page in the dashboard. - `GET /v1/runs` lists the organization's runs; `GET /v1/runs/{id}` has the saved output (the last 32 KiB of stdout and 16 KiB of stderr). Runs are kept 30 days. ## The Run page [Run, in the kosa8 Cloud app](https://app.kosa8.com/app#run) (sign in first; app.kosa8.com/run takes you there): paste code, pick a language, press Run (or ⌘⏎), and watch the output stream in. Share publishes the card and copies its link. Below it, **Run it from your terminal** makes an API key for you and fills it into the install, sign-in, `kosa8 run` and `curl` commands, masked on screen and whole on the clipboard. ## How it works - A run is an ordinary sandbox: the same plan, payment, spending-cap and running-limit checks as `POST /v1/sandboxes`, the same per-second bill, and an audit record (`run.create`) with its language, template and exit, never its code or env. - Small files and code ride inside the command, so a run is two calls to the host: the create from the warm pool and the exec. Files over about 44 KiB in all are uploaded first. - The sandbox is deleted as soon as the output is read. It also carries a `ttl_s` past the run's timeout, so it goes even if that delete were lost. - For state that lasts between calls, use a sandbox (`POST /v1/sandboxes` and exec), the [code interpreter](https://docs.kosa8.com/guides/cloud-code-interpreter/), or a [background command](https://docs.kosa8.com/guides/cloud-snapshots-background/). For an event handler called again and again, deploy a function. --- Source: https://docs.kosa8.com/guides/cloud-run/ # RL training on kosa8 Cloud An RL or post-training run needs thousands of sealed copies of one environment, a reward the policy cannot tamper with, no sandboxes left running when the trainer dies, and a way to tell a policy failure from an infrastructure failure. This guide covers the kosa8 Cloud features built for that, and the limits that apply. **What is live and what comes next** **Live today:** create, exec, files, `fork` (up to 1,000 copies a call), snapshots, checkpoints and rewind, egress rules (`egress="deny"`), labels, TTLs and the audit log. The [RL rollouts and evals guide](https://docs.kosa8.com/guides/py-rl-eval/) builds a full rollout loop from those calls, and it works now. Everything below is live on api.kosa8.com and in `kosa8` 0.7.0 (Python), `@kosa8/sdk` 0.7.0 (JS) and the `kosa8` CLI v0.21.0. `https://api.kosa8.com/openapi.json` is the source of truth for fields. ## The shape of a run 1. **Prepare once.** Build the task's repository and dependencies into a template, or set up a sandbox and snapshot it. 2. **Fan out.** Create a batch of sandboxes, or fork the prepared one into a group (one GRPO group per prompt, say). Tag them all with the run's id. 3. **Roll out.** The policy acts by running commands in its own copy. 4. **Grade sealed.** Score the final state in a fork with no network and hidden tests the policy never saw. 5. **Mask, record, release.** Drop infra failures from the batch instead of scoring them 0, record each rollout to the run, and let the lease clean up whatever is left. **Rather not run the loop yourself?** [Hosted jobs](https://docs.kosa8.com/guides/cloud-jobs/) take your tasks, a solver command and a grader, and run every rollout on kosa8's side: retries, masking, the sealed grader, a budget, and the results in an RL run. ## Quickstart With `kosa8` 0.7.0 (`pip install kosa8==0.7.0`) and `KOSA8_API_KEY` set, this runs as it is. `run.map` forks the base sandbox for each rollout, runs your function, grades the copy in a sealed fork with the task's hidden files, records the result to the run and deletes the copy; infra failures are retried and then marked `masked=True` with reward `None` rather than given reward 0. Leaving the `async with AsyncRun` block marks the run finished and drains every sandbox it made, the base too. ``` import asyncio import random import kosa8 from kosa8.rl import AsyncRun # The hidden grader: it stays on your side until grading, then runs in a sealed # fork with no network. Its last stdout line {"reward": x} is the reward. GRADER = """ import json, sys sys.path.insert(0, "/workspace") try: from solution import add passed = sum(add(a, b) == a + b for a, b in [(1, 2), (-3, 3), (10, 5), (0, 0)]) except Exception: passed = 0 print(json.dumps({"reward": passed / 4, "metrics": {"passed": passed}})) """ tasks = [{"id": f"add-{i}", "prompt": "Write add(a, b) in /workspace/solution.py", "files": {"/grader/check.py": GRADER}} for i in range(4)] def policy(prompt): # stand-in for your model op = random.choice(["+", "+", "-"]) return f"def add(a, b):\n return a {op} b\n" async def solve(sbx, task): # the policy acts in its own copy await sbx.files.write("/workspace/solution.py", policy(task["prompt"])) async def main(): async with kosa8.AsyncCloud() as cloud: # reads KOSA8_API_KEY # The run heartbeats its sandboxes and drains them when the block ends, even on a crash. async with AsyncRun(cloud, "grpo-demo", lease_s=600) as run: base = await cloud.sandboxes.create(template="python") results = await run.map(base, tasks, solve, group_size=2, concurrency=4, grade_cmd=["python3", "/grader/check.py"]) print(results.rewards) # e.g. [1.0, 0.25, 1.0, 1.0, 0.25, 1.0, 1.0, 1.0] print(results.mean_reward, results.by_class) # masked (infra) rollouts are None, left out of the mean asyncio.run(main()) ``` It prints the 8 rewards (4 tasks, 2 samples each) and their mean, for example `0.90625 {'ok': 8}`, in under 20 seconds. The python template is Python 3.12 on Debian (`python:3.12-slim`) with `bash`, `git`, `curl`, `pip`, `pytest` and `uv` already in it, so a task can clone a repository and grade with pytest with no install step. Anything else your tasks need, install into the base in a [persistent](https://docs.kosa8.com/guides/cloud/#persistent) sandbox (or under `/workspace`) before the map, and the forks inherit it. Your function's return value is a reward only when there is no `grade_cmd`: return a number or `{"reward": x}`, or pass `reward=fn(sandbox, task, output)`. Open [app.kosa8.com](https://app.kosa8.com/), then **RL runs**, to watch it. ## Batch create `POST /v1/sandboxes/batch` makes up to 1,000 sandboxes in one call. The Cloud paces the creates across hosts itself (16 in flight), so your trainer does not have to back off from 429s and 503s. Every sandbox goes through the same plan, payment and size checks as `POST /v1/sandboxes`. ``` curl -s -X POST https://api.kosa8.com/v1/sandboxes/batch \ -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' \ -d '{"count": 64, "template": "python", "run_id": "run_…", "lease_s": 600, "labels": {"step": "12"}, "partial_ok": true}' # {"sandboxes":[{"id":"sbx_…","state":"running",…}, …], # "failed":[{"index":63,"code":"running_limit","message":"…","failure_class":"quota","retryable":false}], # "requested":64,"created":63,"run_id":"run_…"} ``` | Field | Meaning | |---|---| | `count` | 1 to 1,000. | | `template`, `image`, `cpus`, `mem_mb`, `region` | As on a single create. | | `labels` | Put on every sandbox. With `run_id`, `kosa8.run=` is added. | | `ttl_s` | Delete each sandbox this many seconds after it was made. | | `lease_s` | A lease: deleted unless a [heartbeat] extends it. | | `partial_ok` | Default `true`: keep what was made and list the rest in `failed`. With `false`, one failure deletes the ones made and the answer is that first error. | The plan's running limit holds: if `count` is more than the room left, kosa8 makes as many as fit and reports the rest as `running_limit` (class `quota`), or, with `partial_ok: false`, refuses before making any. ## Fork a prepared state `POST /v1/sandboxes/{id}/fork` is live: it snapshots the sandbox once and restores `n` live copies with memory, processes and disk as they were. It is the cheap reset for an episode and the natural unit for a GRPO group. It takes these options: ``` curl -s -X POST https://api.kosa8.com/v1/sandboxes/sbx_base/fork \ -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' \ -d '{"n": 16, "run_id": "run_…", "lease_s": 600, "labels": {"group": "prompt-41"}, "partial_ok": true}' # {"parent":"sbx_base","sandboxes":[{"id":"sbx_…",…},…],"host_ms":…,"requested":16,"created":16, # "failed":[],"hosts":1,"run_id":"run_…"} ``` - **Up to 1,000 copies a call**, made 100 at a time on the parent's host. - **How many fit on one host.** Copies share their parent's memory until they write to it, so for idle or light work one host holds the parent and 999 copies (1,000 sandboxes, the Scale plan's running limit); a fork of 999 took about 68 seconds. Copies that each do heavy work (about 150 MiB of memory written apiece) top out at about 700 to 770 on one host. Past what one host holds, copies go to other hosts when there are any (below); otherwise they come back in `failed`. - **When the parent's host is full**, the rest of a group go to other hosts: the parent is snapshotted once, the snapshot is copied to a host with room, and the remaining copies are restored there from the parent's exact state. They get the same `labels`, `run_id`, `lease_s` and `parent_id`, and names carry on (`roll-0054` and on). The answer's `hosts` says how many hosts hold the group. Copies on another host take longer to arrive (the parent's memory and disk are copied there first, so the time grows with its memory size and what it has written to disk), and count toward sandbox-hours like any sandbox of that size. - Every copy, on any host, counts toward the plan's running limit. - `labels`, `run_id` and `lease_s` are put on every child; `partial_ok` defaults to `true`. Copies that no host has room for are listed in `failed` (class `infra`, retryable). `false` keeps the all-or-nothing behaviour, on the parent's host only. - Dedicated sandboxes cannot be forked (**409** `dedicated`). ## Leases, heartbeat and drain A trainer that crashes or is pre-empted should not leave a thousand sandboxes using your sandbox-hours. Give them a lease, and keep it alive while the trainer is alive: ``` # every minute or so, while training runs curl -s -X POST https://api.kosa8.com/v1/sandboxes/heartbeat \ -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' \ -d '{"run_id": "run_…"}' # {"extended":63,"at":…} # at the end, or to stop a run now curl -s -X POST https://api.kosa8.com/v1/sandboxes/drain \ -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' \ -d '{"run_id": "run_…"}' # {"deleted":63,"ids":["sbx_…",…],"failed":[],"more":false} ``` - `lease_s` on create, batch or fork sets the sandbox to be deleted that many seconds from now. A heartbeat moves it to now plus `extend_s` (or the original `lease_s`) for every leased sandbox of your organisation that matches. - Heartbeat and drain select by `run_id`, `labels` or `ids`. Drain needs at least one, so it can never delete everything by accident. - Lapsed leases are deleted by the same expiry job as TTLs. In Python, a run does both: inside `with Run(cloud, "name")` (or `async with AsyncRun(cloud, "name")`) every sandbox made is labelled with the run and leased, a background thread heartbeats, and the run is drained when the block ends, the process exits or it gets SIGTERM. For sandboxes outside a run, `with kosa8.rl.lease(cloud, labels={"job": "exp-7"}):` does the same by label. ## Failure classes and masking A rollout that died because a host was full is not evidence that the policy was wrong. Scoring it 0 teaches the model noise. Every error answer under `/v1/sandboxes`, and every exec, carries `failure_class` and `retryable`, so the trainer can tell the two apart: | failure_class | When | retryable | What the trainer does | |---|---|---|---| | `ok` | Exec finished with exit 0. | — | Score it. | | `exit_nonzero` | Exec finished with a non-zero exit. | — | Score it: this is the policy's result. | | `timeout` | `exec_timeout` and other time limits. | no | Usually the policy's fault (a hang); decide per task. Raise `timeout_s` if it is the task's. | | `oom` | Exit 137 and the guest kernel killed for memory (its `oom_kill` count rose). A grade gets no reward. | no | Decide per task: give the sandbox more memory (`mem_mb` or a larger size) if the task needs it; mask it to keep it out of the batch. | | `infra` | Host failed, sandbox not ready, 5xx, no capacity, host gone. | yes | **Mask**: leave it out of the advantage, retry it. | | `quota` | Running or plan limits, **402** payment, **429** rate limit. | only 429 | Mask and slow down; a plan limit needs the person to act. | | `client` | **400** `invalid_*`, **404**, **409**. | no | A bug in the caller: fix the request. | ``` r = await sbx.exec(["sh", "-c", cmd]) if r.failure_class in ("infra", "quota"): rollout.masked = True # not reward 0: dropped from this step's batch elif r.failure_class == "timeout": rollout.reward = 0.0 ``` A 503 `no_capacity` is `infra`, not a plan limit: wait the seconds in `Retry-After` and retry. ## The sealed grader Reward hacking starts with a policy that can see or edit the tests, or reach the internet for an answer. `POST /v1/sandboxes/{id}/grade` forks one child from the solved sandbox, denies the child all egress, writes your hidden files into it, runs the grader, and deletes the child. The solver sandbox never sees the hidden files. ``` curl -s -X POST https://api.kosa8.com/v1/sandboxes/sbx_…/grade \ -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' \ -d '{"cmd": ["python3", "/grader/test_hidden.py"], "files": {"/grader/test_hidden.py": "'"$(base64 < test_hidden.py | tr -d '\n')"'"}, "timeout_s": 90, "run_id": "run_…", "rollout": {"step": 12, "group": "prompt-41", "index": 3}}' # {"reward":1,"metrics":null,"reward_from":"exit","exit":0,"stdout":"passed\n","stderr":"", # "failure_class":"ok","retryable":false,"ms":1037,"grader_id":"sbx_…","kept":false,"sandbox_id":"sbx_…", # "grader_fingerprint":"sha256:…","run_id":"run_…","recorded":true} ``` Here `test_hidden.py` is a plain script that exits non-zero when the solution is wrong: ``` import sys sys.path.insert(0, "/workspace") from solution import add assert add(2, 3) == 5 and add(-1, 1) == 0 print("passed") ``` The grader runs in a copy of the solved sandbox, with no network, so it can only use what that sandbox already has. The python template has pytest, so a grader can also be a test file run with `{"cmd": ["python3", "-m", "pytest", "-q", "/grader"]}`: exit 0 (every test passed) is reward 1.0. - **Reward:** the last line of stdout that is JSON with a numeric `reward` (and an optional `metrics` object), for example `{"reward": 0.75, "metrics": {"passed": 3}}`. With no such line, exit 0 is 1.0 and any other exit is 0.0. - `timeout_s` is 1 to 90 seconds; a longer grader is refused with **400**. - `stdout` and `stderr` come back as their last 64 KiB. - `keep: true` keeps the graded child for inspection. - With `run_id`, the result is recorded as a rollout of that run. ## RL runs A run groups the sandboxes and rollouts of one training job, so you can see it and export it. | Call | Does | |---|---| | `POST /v1/rl/runs` | Start a run: `{name, project?, config?}`. | | `GET /v1/rl/runs` | List runs (`?project=`, `?status=`) with summary counts. | | `GET /v1/rl/runs/{id}` | The run, its summary (rollouts, by failure class, reward mean, p50, min and max overall and per step, live sandboxes against the plan limit, sandbox-hours and cost so far, rollouts a minute) and its [recommended actions]. | | `PATCH /v1/rl/runs/{id}` | Rename, or set `status` to `finished` or `failed`. | | `POST /v1/rl/runs/{id}/rollouts` | Record up to 500 rollouts a call: step, group, index, sandbox, reward, failure class, exit, duration, tokens, cost, meta. | | `GET /v1/rl/runs/{id}/rollouts` | Page through them, filtered by `step`, `failure_class` or `min_reward`. | | `GET /v1/rl/runs/{id}/export?format=jsonl` | Every rollout, streamed as JSON lines. | Reading needs the `sandboxes:read` scope; changing needs `sandboxes:write`. ### The dashboard page In [app.kosa8.com](https://app.kosa8.com/), **RL runs** lists every run with its status, rollouts, success rate, mean reward, infra failure rate, live sandboxes and cost. A run's page shows: - Tiles for rollouts, mean reward, success rate, infra failures, live sandboxes against your limit, cost so far, cost per step and rollouts a minute. - Reward by step (mean, with the min-max band) and failures by class for each step. - A rollout table you can filter by step, failure class and reward. Click a row for its reward, metrics, exit, duration, stdout tail and meta, and, while its sandbox still exists, a terminal and a **Fork this state** button. - **Export JSONL**, **Drain run sandboxes** (asks first) and **Mark finished**. A running run refreshes every 5 seconds. ### Recommended actions The top of the run page lists what to fix, worked out from the run's own numbers. Each shows only when the data supports it: | When | It suggests | |---|---| | Infra failures are over 5% of the last 500 rollouts. | Mask infra failures and retry (see [failure classes]). | | Timeouts are over 10%. | Raise `timeout_s` or split the task; it shows the current p95 duration. | | Live run sandboxes are at 90% or more of the plan's running limit. | You are at your concurrency limit: a pack of +10 running at once, or a bigger plan. | | Sandbox-hours used are at 80% or more of the plan's allowance. | Add sandbox-hours: a pack of +100 a month. | | The run is finished but its sandboxes are alive, or nothing was recorded for 15 minutes. | Drain the idle sandboxes. | | Run sandboxes have no lease. | Use `lease()` so a crashed trainer does not leak sandboxes. | | Reward has not changed over the last 50 steps. | Check the grader, with a sample rollout to open. | | Rollouts were scored outside `/grade`. | Grade in a sealed fork to stop reward hacking. | ## Adapters The `kosa8.rl` module plugs kosa8 sandboxes into the common RL frameworks. Each adapter imports its framework only when you use it, so `kosa8` does not depend on any of them. | Module | For | What it gives you | |---|---|---| | `kosa8.rl.gym` | Gymnasium | An `Env` whose `reset()` makes or forks a sandbox and whose `step(action)` runs a shell action in it. | | `kosa8.rl.openenv` | OpenEnv | An OpenEnv-compatible environment with `reset`, `step` and `state`. | | `kosa8.rl.verifiers` | Prime Intellect `verifiers` | A `SandboxEnv`-style provider backed by kosa8 Cloud. | | `kosa8.rl.trl` | TRL `GRPOTrainer` | An `environment_factory` helper. | | `kosa8.rl.nemo_gym` | NeMo Gym | A sandbox provider (`Kosa8Provider`), found through the `nemo_gym.sandbox_providers` entry point. | | `kosa8.rl.swebench` | SWE-bench | Create from an instance's image, apply the model's patch, grade with the hidden tests through the sealed grader. | Worked examples (`quickstart.py`, `async_rollouts.py`, `grpo_trl.py`, `swebench_grade.py`, `verifiers_env.py`) are in the SDK's [`examples/rl/`](https://github.com/kosa8ai/kosa8-py/tree/main/examples/rl) folder. ## Run health signals A run's page in the web app and the desktop app checks the run for four problems as it goes. Each shows with a severity and a link back here. `GET /v1/rl/runs/{id}` returns them in `recommendations`, with ids `reward_hacking`, `grader_changed`, `timeouts_rising` and `group_no_signal`. ### Reward hacking Mean reward rose while rollouts got much shorter or produced much less output. A policy that scores more by doing less is often gaming the grader: it deletes the failing tests, prints what the checker looks for, or exits early. Read a few of the newest high-reward rollouts in the rollout drawer before you trust the curve. A sealed grader with hidden tests ([above]) closes most of these holes. ### Grader fingerprints Every rollout scored by the sealed grader records a fingerprint of the grader command and its hidden files. Hosted [jobs](https://docs.kosa8.com/guides/cloud-jobs/) do too. When you grade yourself, send `grader_fingerprint` on the rollout (any id up to 128 characters, such as a commit hash of your tests). When a run has more than one fingerprint, the grader changed mid-run, so rewards before and after are not the same measure. Compare runs within one grader, or start a new run. ### Timeouts The share of rollouts with failure class `timeout` is rising step by step. A policy that learns to run longer, or an environment that got slower, pushes rollouts past `timeout_s`. Read the newest timed-out rollouts, then cap the episode length or raise `timeout_s`. Timed-out rollouts carry no reward, and you can mask them. ### GRPO groups with no signal In most recent groups, every rollout got the same reward. GRPO learns from the differences within a group, so a group of all 0s or all 1s adds nothing. Give partial credit, pick tasks of the right difficulty for the current policy, or sample more rollouts per group. ### Alerts Rules at `/v1/rl/alerts`, also on a run's page, fire when infrastructure failures pass a rate, out-of-memory kills spike, cost passes a budget, or a run stops producing rollouts. They are checked every minute, at most once an hour per rule. Each one is sent as the `rl.alert` webhook, so subscribe an endpoint to that event. ## Limits From the plans in [pricing](https://kosa8.com/pricing/#compare). Limits are hard: past one, new work is refused with **402** `plan_limit`. The limits apply from December 2026. Plan prices are on [the pricing page](https://kosa8.com/pricing/). | | Solo | Pro | Team | Scale | |---|---|---|---|---| | Sandboxes running at once | 2 | 10 | 25 | up to 1,000 | | Cloud sandbox-hours a month | 100 | 500 | 500 a person, pooled | 1,000 a person, pooled | | Largest sandbox | 2 vCPU, 4 GB | 4 vCPU, 8 GB | 8 vCPU, 16 GB | 16 vCPU, 32 GB | | Snapshots kept | 5 | 50 | 250 | 1,000 | - **Packs**, monthly, on any plan, stackable: +100 sandbox-hours, or +10 sandboxes running at once (prices on [the pricing page](https://kosa8.com/pricing/)). - A sandbox-hour is an hour of a 2 vCPU / 4 GB sandbox; bigger sizes count by vCPU, so a 4 vCPU sandbox uses 2 an hour. - Fork makes at most 1,000 copies a call, 100 at a time, on the parent's host and then on others. One host holds about 1,000 light copies, or about 700 to 770 that each write about 150 MiB of memory ([fork]). - An exec answered as one JSON object runs at most 90 seconds; stream longer commands (`"stream": true`) or run them in the background. - Region: `us-ash1` (Ashburn, Virginia, US) is the only live region. Overflow capacity reports region `cf-auto`. - kosa8 Cloud has no GPUs. Run the policy and trainer on your own GPUs and the environments on kosa8 Cloud. ## What a run costs Arithmetic only, from the plan limits above; for the dollar figures, see [the pricing page](https://kosa8.com/pricing/). 10,000 rollouts of 3 minutes each on the standard 2 vCPU sandbox: ``` 10,000 rollouts x 3 min = 30,000 sandbox-minutes = 500 sandbox-hours ``` - **Pro:** 500 sandbox-hours are included, so this run uses the month's allowance. A second run of the same size takes 5 packs of +100. At 10 running at once it takes 10,000 / 10 x 3 min = 50 hours of wall-clock time. - **Scale:** 1,000 sandbox-hours a person are included, room for two such runs. At 1,000 running at once it takes 10 rounds of 3 minutes, 30 minutes of wall-clock time, plus the time to make the sandboxes (a fork of 999 takes about a minute). - On 4 vCPU sandboxes the same run is 1,000 sandbox-hours. The figures leave out create and grading time, retries and anything else the plan is used for; the run page shows the real sandbox-hours and cost as the run goes. ## See also - [RL rollouts and evals in Python](https://docs.kosa8.com/guides/py-rl-eval/): the loop with calls that are live today. - [Hosted jobs](https://docs.kosa8.com/guides/cloud-jobs/): kosa8 runs the rollouts for you. - [Benchmarks](https://docs.kosa8.com/guides/benchmarks/): SWE-bench Verified and Terminal-Bench, ready-made. - [kosa8 Cloud](https://docs.kosa8.com/guides/cloud/): keys, limits, errors and regions. - [Snapshots, background commands and env](https://docs.kosa8.com/guides/cloud-snapshots-background/). - [Egress controls](https://docs.kosa8.com/guides/cloud-egress/). - [The best sandbox for reinforcement learning](https://kosa8.com/best/reinforcement-learning/). --- Source: https://docs.kosa8.com/guides/rl-training/ # RL rollouts and evals An eval or an RL run needs many copies of one environment, each sealed from the others and from your machine, reset cheaply between episodes. A kosa8 sandbox is that copy; a snapshot is the reset. **Versions** Uses `Kosa8Client`, the Python client for the local kosa8 daemon (`kosa8d`), from `kosa8` 0.2.0 or later (the current release is 0.7.0): `run_code`, `shell`, files and lifecycle, plus `fork`, `checkpoint`, `rewind` and `explore`. The patterns below are built from those calls; they have not been benchmarked here, so measure the timings on your machine. ## The shape of it 1. **Prepare once.** Make a sandbox, install the task's dependencies, copy in the repo. Save it as a template or keep it as a snapshot. 2. **Fan out.** `fork(n)` makes *n* running copies of that state. 3. **Roll out.** Each policy or model works in its own copy through the toolbox. 4. **Score.** Run the hidden tests in the copy and read the exit code. 5. **Throw away.** Delete the copies. The prepared state is untouched. ## 1. Prepare the environment ``` from kosa8 import Kosa8Client client = Kosa8Client() base = client.create_sandbox(name="task-base", egress_allow=["pypi.org", "files.pythonhosted.org"]) sb = client.sandbox(base["id"]) sb.git("clone", url="https://github.com/pallets/click", path="repo") sb.shell("cd /workspace/repo && pip install -q -e . pytest") ``` For an environment you will reuse across runs, put the setup in a Dockerfile and build a template once: `client.build_template("click-env", "./env")`. Then every sandbox starts from it with `create_sandbox(template="click-env")`, with no install step. ## 2. Fork one rollout per sample ``` f = client.fork(base["id"], 8, prefix="ep-") episodes = [x["id"] for x in f["forks"]] # ep-1 … ep-8, all running, all identical ``` Forking snapshots the base once and restores it eight times. The base keeps running. Each fork has its own disk, memory and network rules, so one episode cannot see or spoil another. ## 3. Run the policy in each copy Give each episode its own tools. With the OpenAI Agents SDK (see [agent frameworks](https://docs.kosa8.com/guides/py-frameworks/)): ``` from concurrent.futures import ThreadPoolExecutor from agents import Agent, Runner from kosa8.integrations.openai_agents import sandbox_tools TASK = "Fix the failing test in /workspace/repo. Do not edit the tests." def rollout(sid): agent = Agent(name="solver", instructions=TASK, tools=sandbox_tools(client, sid)) return Runner.run_sync(agent, TASK, max_turns=30).final_output with ThreadPoolExecutor(8) as pool: transcripts = list(pool.map(rollout, episodes)) ``` The client is safe to share between threads; each call is its own request. ## 4. Score with a reward the agent cannot see Copy the grader in only after the rollout, so the policy cannot read or edit it, and score on the exit code: ``` GRADER = open("hidden_tests.py").read() def reward(sid): sb = client.sandbox(sid) sb.write_file("/workspace/.grader/test_hidden.py", GRADER) r = sb.shell("cd /workspace/repo && python -m pytest -q /workspace/.grader", timeout_s=300) return 1.0 if r.ok else 0.0 rewards = [reward(sid) for sid in episodes] ``` For a partial score, have the grader print JSON and parse `r.stdout`. With `run_code` you can score in Python directly and get back charts as PNG bytes in `r.artifacts`. ## 5. Clean up ``` for sid in episodes: client.delete_sandbox(sid) ``` Or let kosa8 do it: give the base `ttl_min=` or `auto_stop_min=`, and make throwaway sandboxes `ephemeral=True`, so they are deleted the moment they stop, even if your script crashes. ## Branching inside an episode For search (tree search, best-of-N per step, undoing a bad action), take a checkpoint before a risky step and rewind if it fails. The rest of the episode is unaffected: ``` client.checkpoint("ep-1", label="before migration") r = client.shell("ep-1", "cd /workspace/repo && ./migrate.sh") if not r.ok: client.rewind("ep-1") # back to the checkpoint: disk and memory ``` To try several next actions at once and keep the copy where one worked, fork the episode once per action, run each in its own copy, and keep the first that passes: ``` patches = ["patch-a.diff", "patch-b.diff", "patch-c.diff"] tries = [x["id"] for x in client.fork("ep-1", len(patches), prefix="ep-1-try")["forks"]] with ThreadPoolExecutor(len(tries)) as pool: oks = list(pool.map(lambda t: client.shell( t[0], f"cd /workspace/repo && git apply /workspace/{t[1]} && python -m pytest -q").ok, zip(tries, patches))) winner = next((sid for sid, ok in zip(tries, oks) if ok), None) for sid in tries: if sid != winner: client.delete_sandbox(sid) ``` `explore()` does this in one call for commands that need only an image, not the workspace: each variant runs in a fresh container of `image`, and it keeps the fastest copy that exits 0. See [explore in depth](https://docs.kosa8.com/guides/py-guide/#explore). ## Evals over a dataset The same pattern runs a benchmark: one forked sandbox per task, the model's answer applied, the task's tests run, the pass rate counted. ``` results = [] for task in dataset: # each: {"id", "setup", "check"} sid = client.fork(base["id"], 1, prefix=f"eval-{task['id']}-")["forks"][0]["id"] try: client.shell(sid, task["setup"]) answer = model_solve(task, sandbox_tools(client, sid)) results.append(client.shell(sid, task["check"]).ok) finally: client.delete_sandbox(sid) print(f"pass rate {sum(results)}/{len(results)}") ``` ## Things to watch - **Network:** a local sandbox starts with the network open (egress `any`) unless your organization's policy sets a default. Give the base `egress_allow=` with only what setup needs, and consider a separate base for rollouts with `egress="deny"`, so a policy cannot fetch answers. - **Resources:** every fork is a microVM with its own memory. Size `mem_mb` on the base, and keep the number of live forks to what the machine holds. - **Time:** pass `timeout_s` to `shell` and `run_code`, so a hung episode ends with `timed_out=True` rather than blocking the batch. - **Audit:** every command an agent ran is in the kosa8 audit log, which helps when a reward looks too good. On kosa8 Cloud, batch create, leases, failure classes, a sealed grader and an RL runs dashboard are live for this loop, with `kosa8.rl` in `kosa8` 0.7.0 to drive it: see [RL training](https://docs.kosa8.com/guides/rl-training/). See also: [explore and fork in depth](https://docs.kosa8.com/guides/py-guide/#explore) and [explore](https://docs.kosa8.com/guides/explore/). --- Source: https://docs.kosa8.com/guides/py-rl-eval/ # Fan out from one snapshot Install once, copy many times. Set up a sandbox the slow way a single time, save it, then start as many identical copies as the job needs: one shard of a test suite each, or one rollout each. Every copy starts with the installs done and the files in place. Everything on this page works on kosa8 Cloud today with the `kosa8` Python SDK 0.5.5 (`Kosa8Cloud`) or plain HTTP. For RL runs, batch create, leases and a sealed grader build on this pattern; see [RL training](https://docs.kosa8.com/guides/rl-training/). ## Two ways to copy | | `fork` | Create from a snapshot | |---|---|---| | Call | `POST /v1/sandboxes/{id}/fork {"n": N}` | `POST /v1/sandboxes {"snapshot": "snap_…"}`, once per copy | | Copies a call | 1 to 1,000; by default the copies that fit are kept and the rest listed in `failed` (`"partial_ok": false` for all or nothing) | One | | The source | A running sandbox, as it is now | A saved snapshot, which outlives its sandbox | | Best for | One job, right now | The same starting point reused across jobs and days | Both keep memory, processes and disk. Both start the copies on the host that holds the source (a fork that does not fit there goes on to other hosts, when there are any; see [fork](https://docs.kosa8.com/guides/rl-training/#fork)), and every copy counts toward your plan's sandboxes running at once (2, 10, 25 or up to 1,000; see [pricing](https://kosa8.com/pricing/#compare)). ## 1. Set up once and snapshot ``` from kosa8 import Kosa8Cloud cloud = Kosa8Cloud() # reads KOSA8_API_KEY base = cloud.sandboxes.create(template="python", name="suite-base", ttl_s=3600) # has git, bash and pytest base.exec("cd /workspace && git clone -q https://github.com/pallets/click repo") base.exec("cd /workspace/repo && pip install -q -e . pytest") snap = base.snapshot(name="click-deps") # {"id": "snap_…", "state": "ready", …} ``` Or with curl: ``` curl -s -X POST https://api.kosa8.com/v1/sandboxes/sbx_…/snapshots \ -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' -d '{"name":"click-deps"}' # 201 {"snapshot":{"id":"snap_…","state":"ready",…}} ``` Each `exec` answers with an `exit_code`: check it in your own script, since a failed step does not raise. An exec answered as one JSON object stops after 90 seconds. Run a long install in the background (see [background commands](https://docs.kosa8.com/guides/cloud-snapshots-background/)) and snapshot when it has finished. ## 2. Fan out With `fork`, from the running base: ``` N = 8 shards = base.fork(N) # N running copies ``` ``` curl -s -X POST https://api.kosa8.com/v1/sandboxes/sbx_…/fork \ -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' -d '{"n":8}' # {"parent":"sbx_…","sandboxes":[{"id":"sbx_…","state":"running",…}, …],"requested":8,"created":8,"failed":[],…} ``` Or from the snapshot, which still works after the base is gone: ``` from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor(N) as pool: shards = list(pool.map(lambda _: cloud.sandboxes.create(snapshot=snap["id"], ttl_s=3600), range(N))) ``` ``` curl -s -X POST https://api.kosa8.com/v1/sandboxes \ -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' -d '{"snapshot":"snap_…","ttl_s":3600}' ``` For more than 1,000 copies, fork again or create from the snapshot in more threads. Keep the thread count at or under your running limit: past it a create answers **402** `plan_limit`. ## 3. Shard the work Give each copy its slice. For a test suite, list the tests once and split them by index. Each argument of a command is at most 8,192 characters, so write a shard's test ids to a file and hand pytest the file (`@file`) rather than putting them on the command line: ``` from concurrent.futures import ThreadPoolExecutor out = base.exec("cd /workspace/repo && python -m pytest --collect-only -q").stdout ids = [t for t in out.splitlines() if "::" in t] # 2,653 tests for click def run_shard(i, sbx): sbx.files.write("/workspace/shard.txt", "\n".join(ids[i::N])) # every Nth test, starting at i r = sbx.exec("cd /workspace/repo && python -m pytest -q @/workspace/shard.txt") return {"shard": i, "id": sbx.id, "exit": r.exit_code, "tail": r.stdout[-2000:]} with ThreadPoolExecutor(N) as pool: results = list(pool.map(run_shard, range(N), shards)) ``` For rollouts, the slice is one task (or one sample of a group) per copy: ``` def rollout(task, sbx): r = sbx.exec(["bash", "-c", task["command"]]) # your policy's action return {"task": task["id"], "exit": r.exit_code, "stdout": r.stdout[-4000:]} with ThreadPoolExecutor(N) as pool: results = list(pool.map(rollout, tasks[:N], shards)) ``` ## 4. Collect and clean up ``` failed = [r for r in results if r["exit"] != 0] print(f"{N - len(failed)}/{N} shards passed") for r in failed: print(r["shard"], r["tail"]) for sbx in shards: sbx.delete() base.delete() # the snapshot stays until you delete it cloud.snapshots.delete(snap["id"]) # when you no longer need the starting point ``` The `ttl_s` on every sandbox is the safety net: if the script dies before this step, each copy is deleted when its TTL runs out, so it does not keep using your sandbox-hours. ## Things to watch - **One host first.** Copies start on the host that holds the source. A fork that does not fit there goes on to other hosts when there are any; copies no host has room for come back in `failed`. If the host is full, a create from a snapshot answers **503** `no_capacity` with `Retry-After`: wait and retry; it is not a plan limit. - **Snapshots count.** They count toward your plan's snapshot limit (5, 50, 250 or 1,000) until you delete them (see [snapshots](https://docs.kosa8.com/guides/cloud-snapshots-background/)). Delete the ones you are done with. - **Network.** A sandbox made from a snapshot gets your organisation's egress policy, not the source's. If the copies run untrusted code, set the policy on each copy, or on the organisation, before they run it. - **Not copyable.** A sandbox with brokered secrets or dedicated cores cannot be snapshotted (**409**), and a dedicated sandbox cannot be forked. See also: [snapshots, background commands and env](https://docs.kosa8.com/guides/cloud-snapshots-background/), [RL training](https://docs.kosa8.com/guides/rl-training/) and [RL rollouts and evals](https://docs.kosa8.com/guides/py-rl-eval/). --- Source: https://docs.kosa8.com/guides/cloud-fan-out/ # Benchmarks kosa8 Cloud offers SWE-bench Verified and Terminal-Bench as ready-made templates. Each instance's environment is its official image, pinned by digest, and kosa8 builds it the first time any organization uses it (or when you [prepare] it). Its grader is the benchmark's own: hidden tests, run in a sealed copy, reward 1 when the instance is resolved. You build and import nothing. Name an instance as a template to get a sandbox, or name the benchmark in a [hosted job](https://docs.kosa8.com/guides/cloud-jobs/) to run many. ## The benchmarks | Name | Instances | Source | Graded by | |---|---|---|---| | `swe-bench-verified` | 500 | Hugging Face `SWE-bench/SWE-bench_Verified`, images `swebench/sweb.eval.x86_64.*` | The harness's eval script and the repository's log parser (swebench 5.0.2): FAIL_TO_PASS and PASS_TO_PASS must all pass | | `terminal-bench-2.1` | 89 | `harbor-framework/terminal-bench-2-1`, the tasks' own prebuilt images | The task's `tests/test.sh`, its reward file | `GET /v1/benchmarks` gives each benchmark's dataset revision and the date kosa8 read it. Terminal-Bench 4.x is newer, but its tasks build their images from a Dockerfile, some grade in a separate verifier image, and some need GPUs, so it is not offered yet. ## A sandbox of one instance ``` curl -s https://api.kosa8.com/v1/sandboxes -H "Authorization: Bearer $KOSA8_API_KEY" \ -H 'Content-Type: application/json' -d '{"template": "swe-bench-verified/django__django-11099"}' # {"sandbox":{"id":"sbx_…","state":"running","template":"swe-bench-verified/django__django-11099", # "cpus":2,"mem_mb":4096,"source":"snapshot",…}} ``` The template is `/`. The sandbox has the instance's code checked out (SWE-bench: `/testbed`; Terminal-Bench: the task's working directory) and its size. The hidden tests are not in it. `GET /v1/benchmarks/{name}/instances/{id}` gives the problem statement or instruction. **The first use builds the environment.** Most instances are not built yet: on 22 November 2026, `GET /v1/benchmarks` showed `environments.ready` 3 of 500 for SWE-bench Verified and 4 of 89 for Terminal-Bench. Until an instance's environment is built, a create answers `409 template_building`. The answer is retryable and carries `eta_s`, `retry_after_s` and a `Retry-After` header: ``` {"error": "template_building", "template": "swe-bench-verified/django__django-11099", "state": "building", "eta_s": 240, "retry_after_s": 30, "retryable": true, "message": "…"} ``` **How long a build takes.** In our runs on 22 November 2026 a build took about 40 seconds (`django__django-11133` 37 s, `sympy__sympy-11618` 42 s, each about 4 GB). On a busy host it takes far longer: during a load test one build was still at phase `boot` after 7.8 minutes, against an `eta_s` of 30, and then failed. `eta_s` is an estimate, not a promise. kosa8 builds 4 environments at once, so a whole benchmark takes a while: the estimate for all 89 Terminal-Bench tasks put the build at `build_wall_s` 660 (11 minutes). A failed build answers **503** `template_build_failed` and is tried again after 30 minutes. So build ahead of a run with `POST /v1/benchmarks/{name}/prepare` `{"instances": ["…"] | "all" | 50}` (up to 100 a call), and poll `GET /v1/benchmarks/{name}/instances/{id}` until its `environment.state` is `ready`: ``` curl -s -X POST https://api.kosa8.com/v1/benchmarks/swe-bench-verified/prepare \ -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' \ -d '{"instances": ["django__django-11133"]}' # {"benchmark":"swe-bench-verified","instances":[{"id":"django__django-11133", # "template":"swe-bench-verified/django__django-11133","state":"building", # "phase":"starting","eta_s":30,…}],"builds_at_once":4} curl -s https://api.kosa8.com/v1/benchmarks/swe-bench-verified/instances/django__django-11133 \ -H "Authorization: Bearer $KOSA8_API_KEY" # {"instance":{…,"environment":{"state":"ready","bytes":4295054419,…}}} ``` After the build, a create restores the environment in a few seconds (1.1 s and 4.4 s from create to running in our runs), for every organization. Building is kosa8's cost. A sandbox made from an environment counts toward your plan like any other. ## A whole benchmark as a job ``` POST /v1/jobs {"name": "my-agent-v3", "benchmark": {"name": "swe-bench-verified", "instances": 50, "seed": 0}, "solver": {"cmd": "python /workspace/agent.py", "files": {"/workspace/agent.py": ""}}, "concurrency": 16, "budget_usd": 40} ``` `instances` is a list of ids, `"all"`, or `n` for a stable sample of n (set by `seed`). Leave out `template`, `tasks` and `grader`. The job builds the environments it needs first; its tasks wait while that happens. The solver takes one of three forms: - **`{"cmd": …, "timeout_s"?, "env"?, "files"?}`**: your agent. It gets the input in `/workspace/.kosa8-task/input.json`, the problem in `problem.md` (SWE-bench) or `instruction.md` (Terminal-Bench) next to it, and `KOSA8_BENCHMARK`, `KOSA8_INSTANCE_ID` and `KOSA8_TASK_WORKDIR`. `timeout_s` defaults to the benchmark's agent time (SWE-bench 1 hour; Terminal-Bench the task's own). - **`{"patches": {"django__django-11099": "diff --git …", …}}`** (SWE-bench): grade predictions you already have. A patch is applied the way the harness applies one (`git apply`, then `patch --fuzz`). `instances` defaults to the patches' ids. - **`{"oracle": true}`**: the reference solutions. It checks the environments and should score about 1. Each rollout's reward is 1 or 0. Its metrics include `fail_to_pass_passed`, `pass_to_pass_passed` and `patch_successfully_applied` (SWE-bench). The grader runs in the background, up to the benchmark's grading time (SWE-bench 30 minutes). When the environment is broken rather than the solution, the rollout is retried and then masked; it is never scored 0. Four Terminal-Bench tasks (`fix-ocaml-gc`, `pytorch-model-cli`, `sam-cell-seg`, `train-fasttext`) fetch files in their tests, so they are graded with the network. `GET /v1/benchmarks/{name}/instances/{id}` shows this as `grade_sealed: false`. `POST /v1/jobs/estimate` with the same body gives the sandbox-hours, the cost, and `environments`: how many are ready, how many are still to build, and the build time (`build_wall_s`), plus `wall_s`, the job's own time range: ``` {"tasks": 50, "basis": "timeout", "size": "per instance", "per_task_s": {"low": 930, "high": 5430}, "sandbox_hours": {"low": 12.9, "high": 75.4}, "usd_list": {"low": …, "high": …}, "environments": {"ready": 0, "building": 0, "queued": 0, "failed": 0, "not_built": 50, "to_build": 50, "build_s_each": 30, "builds_at_once": 4, "build_wall_s": 390}, "wall_s": {"low": 3750, "high": 21750}, "note": "…"} ``` ## CLI **An API key is enough** `kosa8 bench` and `kosa8 job` run on kosa8 Cloud, so they use your organization's plan through your API key: `KOSA8_API_KEY`, `kosa8 cloud login` or the browser sign-in, `kosa8 login`. This needs CLI v0.21.0 or later. Older versions asked for a plan on this machine even on a paid plan; there, use the HTTP API or the Python SDK's `cloud.jobs`, which work with the key. ``` kosa8 bench ls kosa8 bench instances swe-bench-verified --state ready kosa8 bench show swe-bench-verified/django__django-11099 --input kosa8 bench prepare swe-bench-verified 50 kosa8 cloud sandbox create --template swe-bench-verified/django__django-11099 kosa8 job submit --benchmark swe-bench-verified --instances 50 \ --solver "python /workspace/agent.py" --solver-file agent.py:/workspace/agent.py --watch kosa8 job submit --benchmark swe-bench-verified --patches preds.jsonl # {instance_id, model_patch} lines kosa8 job submit --benchmark terminal-bench-2.1 --instances all --oracle --estimate ``` ## The environment cache Built environments are kept on kosa8's hosts, in a cache of 100 GB (`cache.budget_gb` in `GET /v1/benchmarks`). When a new build needs room, the environments used least recently (and idle for at least 15 minutes) are dropped, and the next use builds them again. kosa8 keeps only a small sample of each benchmark built at all times, so `prepare` the instances you need before each run. ## See also - [Hosted jobs](https://docs.kosa8.com/guides/cloud-jobs/): retries, budgets and the job's RL run. - [RL training](https://docs.kosa8.com/guides/rl-training/): runs, failure classes, the sealed grader. --- Source: https://docs.kosa8.com/guides/benchmarks/ # Hosted jobs Send a list of tasks, the command that solves one and the command that grades it. kosa8 Cloud runs every rollout on its side: a sandbox per task, the solver for as long as it needs, the sealed grader, retries for infrastructure failures, and a record of each rollout in an [RL run](https://docs.kosa8.com/guides/rl-training/#runs). Nothing has to stay running on your machine. ## What a job does with each task 1. **A sandbox.** Made from the job's `template`, `image` or `snapshot` (and `size`), labelled with the job's run, and leased: if kosa8's driver ever stopped, the sandbox would go by itself after `lease_s`. 2. **The task's input.** `input` (any JSON, up to 32 KiB) is written to `/workspace/.kosa8-task/input.json` and given to the solver as `KOSA8_TASK_INPUT`; the task's `files` are written where they say. 3. **The solver.** `solver.cmd` runs as a background command, polled until it exits, so it can run for hours (`timeout_s` up to 24 hours). It also gets `KOSA8_TASK_ID`, `KOSA8_TASK_INPUT_FILE`, `KOSA8_JOB_ID`, `KOSA8_RUN_ID` and `KOSA8_ATTEMPT`. 4. **The sealed grader.** A copy of the solved sandbox with no network gets the hidden `grader.files`, which the solver never sees, and runs `grader.cmd` (up to 90 s). The reward is the last stdout line that is JSON with a numeric `reward` (`{"reward": 0.75, "metrics": {...}}`), else 1 for exit 0 and 0 otherwise. See [the sealed grader](https://docs.kosa8.com/guides/rl-training/#grader). 5. **The rollout.** Recorded to the job's run with step 0, group = the task's id, the reward and the failure class. The sandbox is deleted. ## Failures | What happened | What the job does | |---|---| | Infrastructure: a host failed, the sandbox was lost, the grader could not run | Deletes that try's sandbox and tries the task again, up to `retries_on_infra` more times (default 2). After that the rollout is recorded with `failure_class: "infra"`, no reward and `meta.masked: true`, never as reward 0. | | The solver was killed for memory | Recorded as `oom`, no reward. Use a larger `size`. | | The solver ran past `timeout_s` | Recorded as `timeout`, no reward. | | The solver exited non-zero | Still graded: the grader decides the reward. | | The org is at its running limit, or no host has room | The task waits in the queue; no try is used. | | A refusal every task would meet: no payment method, an unknown template, a host that cannot seal the grader | The job stops with status `failed` and the reason in `error`. | ## Submit a job A job that runs as it is: each task asks for the sum of two numbers, the solver writes its answer to `/workspace/answer.txt`, and a hidden grader checks it. The `python` template is Python 3.12 on Debian with `bash`, `git`, `pip`, `pytest` and `uv`; both commands here need only `python3`. The grader, `tests/test.py`: ``` import json task = json.load(open("/workspace/.kosa8-task/input.json")) got = open("/workspace/answer.txt").read().strip() print(json.dumps({"reward": 1.0 if got == str(task["a"] + task["b"]) else 0.0})) ``` Write the body to a file (the heredoc fills in the grader as base64), then submit it: ``` cat > job.json <