# Run code in a live interpreter

> Let your agent do it: Run code in a Hermitbox sandbox with a persistent interpreter. Warm the templates with `hermitbox template create python-interpreter` and `hermitbox template create node-interpreter`, then run `hermitbox sandbox python -c 'print(2+2)'` and show me the output. When I want code from a program, use the page's TypeScript calls: a sandbox from the `python-interpreter` template, then a context that keeps its variables between runs. Follow the exact steps in https://docs.hermitbox.dev/v0.3.2/guides/code-interpreter.md.

Give your agent a Python or JavaScript session that remembers. Variables stay set between runs,
charts come back as PNG bytes, and the code runs in a container or process sandbox, not in your
program. A warm kernel answers `1+1` in 5.1 ms at p50 ([measurements](https://docs.hermitbox.dev/v0.3.2/reference/speed.md#interpreter-execution)).

Warm the two interpreter templates, then run Python:

```sh
# Warm the Python and Node interpreter templates.
hermitbox template create python-interpreter
hermitbox template create node-interpreter

# Run Python in a sandbox from the warmed template.
hermitbox sandbox python -c 'print(2+2)'
```

Without a sandbox ID, the CLI creates a container sandbox from the warmed Python template and
deletes it when it exits. Pass an ID to attach to that sandbox instead. Leave out `-c` for a
multiline prompt; Jupyter's `is_complete` reply decides when your input is submitted. Ctrl-C
interrupts the kernel.

## Run code in a context

A context is one live kernel with its own variables. These calls use `hb`, a client from
`new Hermitbox()`, which reads `HERMITBOX_API_URL` and `HERMITBOX_API_KEY` from the environment.

### Start a context

```ts
// A sandbox from the warmed Python template.
const box = await hb.sandbox({
  template: 'python-interpreter',
  isolation: 'container',
})

// The default Python context, already warming.
const py = await box.python()
```

### Run code

```ts
await box.write('sales.csv', 'sales\n10\n20\n')

// Variables live on between calls.
const summary = await py.run(`
import pandas as pd
df = pd.read_csv('sales.csv')
df.describe()
`)
console.log(summary.text)
```

The same result has `summary.html` and `summary.json` for its other representations.

### Save a chart

```ts
import { writeFile } from 'node:fs/promises'

// Plots come back as PNG bytes.
const chart = await py.run(`
import matplotlib.pyplot as plt
plt.plot([1, 2, 3])
plt.show()
`)
await writeFile('chart.png', chart.png!)
```

### Stream output

```ts
// Events arrive while the code runs.
for await (const event of py.stream('for i in range(3): print(i)')) {
  console.log(event)
}
```

### Use another context

```ts
// A named context keeps its own variables.
const analysis = await box.python({ context: 'analysis' })
await analysis.close()
```

### Interrupt, restart and close

```ts
// Interrupt running code, restart the kernel, then close the context.
await py.interrupt()
await py.restart()
await py.close()

// Delete the sandbox when you're done.
await box.delete()
```

### Python and Rust

Python and Rust have the same handles: synchronous and asynchronous in Python, Tokio async in
Rust. `result.png` is `bytes` in Python, `Uint8Array` in TypeScript and `Option<Vec<u8>>`
(`result.png()`) in Rust.

In Python's asynchronous client, `kernel.run` starts an eager task, so you can interrupt while
you await it. `stream` yields events as they arrive.

### What a result holds

`result.results` and `result.events` keep every MIME bundle and its metadata. The convenience
views (`text`, `html`, `json`, `png`) read the last representation of each MIME type. `stdout`,
`stderr` and a structured `error = {name, value, traceback}` stay separate.

## What a context keeps, and where it runs

- **Sleep and snapshots keep files, not variables.** Waking a stopped sandbox starts a fresh
  kernel; live state lasts only as long as that kernel.
- **Container and process sandboxes** run kernels. Wasm refuses native contexts.
- **Process kernels refuse `network: none`** for now, because their private channels can't yet be
  set up under that policy. Ordinary egress denial still applies.
- **Each sandbox holds at most 16 contexts.**

Startup measurements are in [speed.md](https://docs.hermitbox.dev/v0.3.2/reference/speed.md).

## Agent contract

The sandbox agent ([`hermitbox-agent`](https://docs.hermitbox.dev/v0.3.2/reference/sandbox-agent.md), the program that runs inside
each sandbox) owns the kernels. The interpreter templates start warming the default context when
the agent starts; `box.python()` or `box.javascript()` reuses it and waits for its Jupyter-ready
handshake. HTTP health stays responsive while scientific imports warm. Named contexts are
independent.

A context is a supervised process: it appears in `box.processes()`, and its ID and PID appear in
`box.kernels()`.

The [Rust-owned agent document](https://github.com/hermitbox/hermitbox/blob/cdd62e6c07e07c2b649b726729b4d8da6b25a737/agent/openapi.json) advertises `kernelsVersion: 1` on health,
separately from agent API version 2.

| Request under `/_hermitbox/kernels` | Effect |
| --- | --- |
| `POST {language: "python" or "javascript", context?: string}` | Start/reuse a context; return id, language, context, processId, pid, state. |
| `GET` | List contexts, including dead contexts. |
| `POST /{id}/execute {code, timeout?: seconds}` | NDJSON, one event per line, ending in `done`. |
| `POST /{id}/interrupt` | Signal the supervised kernel group independently of its execution queue. |
| `POST /{id}/restart` | Stop and reap the old kernel, then start a fresh process with the same context id. |
| `POST /{id}/complete {code}` | Jupyter input-completeness reply, for the REPL. |
| `DELETE /{id}` | Stop the context and remove it; idempotent after removal. |

| Event `type` | Other fields |
| --- | --- |
| `stream` | `stream: stdout or stderr`, `text` |
| `result` | `data` (all MIME representations), `metadata`, `executionCount` |
| `display` | `data`, `metadata`, nullable `displayId`, `update` |
| `error` | `name`, `value`, `traceback: string[]` |
| `done` | Nullable `executionCount`, `status` (`ok`, `error`, or an explicit transport/timeout state). |

### Errors, timeouts and limits

A language error is result data. A missing completion or a broken transport is an unknown
outcome, and neither SDK retries the code. A dead context stays dead until you restart it.

Each context runs one execution at a time; interrupt and close don't wait for it. Queues and
captured output are bounded, and timeouts enforce the capability's limits. A timeout kills the
kernel rather than letting its code carry on silently.

The default timeout is 30 seconds, or the token's lower ceiling when a project sets one. The SDKs
send a timeout only when you name one, so otherwise the agent's default applies.

MCP tools `run_python` and `run_javascript` use these same contexts. They return image output as
MCP image content, alongside the text events.

### Private channels

Connection files are mode 0600, in a private temporary directory outside persistent data.
Container Jupyter channels use a random HMAC key on sandbox-local loopback.

Process kernels use abstract Unix sockets inside the supervisor's enforced Landlock ABI 6 scope,
and add no TCP listener. A plain pathname socket would not be enough when sandboxes share a UID:
inside the scope, the owner's connection succeeds and a separate agent with the same UID can't
connect. Every managed peer must give fresh signed proof of its scope; an unverified legacy peer
or unknown process history keeps native tools off, with a reason.

The agent launches kernel executables directly, never through a `jupyter` command. Container
images run them as the sandbox user, within the sandbox's resource limits. Process kernels fetch
the [verified upstream bundle](https://docs.hermitbox.dev/v0.3.2/guides/browser-and-desktop.md#process-tools) on first use and run its
unchanged Python and Node builds, with the bundle's own libraries and host glibc >=2.34.

## Versions and licences

| Template/tool | Pinned version | Licence |
| --- | --- | --- |
| Python image | CPython 3.12.14, Debian bookworm | PSF-2.0 and historical grants; Debian package notices retained. |
| ipykernel | 7.4.0 | BSD-3-Clause |
| NumPy | 2.5.4 | BSD-3-Clause AND 0BSD AND MIT AND Zlib AND CC0-1.0; wheel notices include numerical runtimes. |
| pandas | 3.1.1 | BSD-3-Clause |
| matplotlib | 3.11.2 | Matplotlib permissive agreement and PSF-2.0; this is not Mozilla MPL. |
| SciPy | 1.18.1 | BSD-3-Clause and bundled numerical-library notices. |
| scikit-learn | 1.9.1 | BSD-3-Clause |
| requests | 2.34.2 | Apache-2.0 |
| Pillow | 13.0.0 | MIT-CMU |
| Node image | Node 24.22.1, Debian bookworm | MIT and bundled notices; Debian package notices retained. |
| IJavascript / jp-kernel / NEL | 5.2.1 / 2.0.0 / 1.3.0 | BSD-3-Clause |
| Chart.js / napi-rs canvas | 4.6.1 / 1.1.0 | MIT; bundled Skia/Chromium BSD-3-Clause notices retained. |
| ZeroMQ.js | 6.8.0 | MIT AND MPL-2.0, official v5 compatibility API for jmp. |
| Rust jupyter-zmq-client / jupyter-protocol | 3.0.1 / 2.0.3 | BSD-3-Clause |
| Rust zeromq | 0.7.0 | MIT |

The [Python](https://github.com/hermitbox/hermitbox/blob/cdd62e6c07e07c2b649b726729b4d8da6b25a737/templates/python-interpreter/README.md) and
[Node](https://github.com/hermitbox/hermitbox/blob/cdd62e6c07e07c2b649b726729b4d8da6b25a737/templates/node-interpreter/README.md) image descriptions list layer notices and source
availability. The resolved [Python](https://github.com/hermitbox/hermitbox/blob/cdd62e6c07e07c2b649b726729b4d8da6b25a737/docs/licences/python-interpreter.json),
[Node](https://github.com/hermitbox/hermitbox/blob/cdd62e6c07e07c2b649b726729b4d8da6b25a737/docs/licences/node-interpreter.json) and [base-package](https://github.com/hermitbox/hermitbox/blob/cdd62e6c07e07c2b649b726729b4d8da6b25a737/docs/licences/interpreter-base.json)
inventories record every version and licence. cargo-deny enforces the Rust dependency licences
([deny.toml](https://github.com/hermitbox/hermitbox/blob/cdd62e6c07e07c2b649b726729b4d8da6b25a737/deny.toml)). SHA-256 wheel hashes, npm integrity hashes and base manifest
digests are pinned. The Python lock targets Linux x86_64 / CPython 3.12, matching release builds.

Jupyter messaging 5.5 was read at jupyter_client 8.10.0 commit
`978361b3785dcd9cba6c733f4555e833e88fc0df`; the adapter uses the upstream Rust client.
IJavascript 5.2.1 is pinned to published commit `7011c92ebcb858d1aca4edca3adb4e0ea64db174`.

Neither JavaScript kernel we evaluated has a recent core release. TSLab 1.0.22 is not used,
because it emits values and errors as console text. IJavascript gives Jupyter rich results and
errors. Its legacy ZeroMQ dependency is routed to the current official compatibility API, without
copying upstream code or implementing a wire server.

Python preloads NumPy, pandas and pyplot, renders inline PNG/SVG with Agg, and registers JSON
representations for scalar values and DataFrame rows. Other installed scientific packages load
on demand. Measurements and their limits are in [speed.md](https://docs.hermitbox.dev/v0.3.2/reference/speed.md).

## How this is tested

CI runs both installed kernels through the TypeScript and sync/async Python SDKs, including state,
charts, errors, interrupt and restart. The
[acceptance suite](https://github.com/hermitbox/hermitbox/blob/cdd62e6c07e07c2b649b726729b4d8da6b25a737/control/e2e/interpreter.e2e.test.ts) covers both templates, both SDK modes,
state, named contexts, PNG, traceback, interrupt, restart, dead processes, MCP and the CLI.
