# 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":"<base64>"} … 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": "<base64>"}`; 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/
