# inis.run — full documentation corpus > Raw text of every page listed in llms.txt, concatenated in the same order. Generated by scripts/gen/docs_manifest.py — do not hand-edit. Size policy: capped at 200,000 bytes (tripwire, not a hard product limit — see the generator source if this ever needs to grow past one file). --- ## Introduction URL: https://inis.run/docs inis.run is a code-execution sandbox. You call an API (or the CLI), each run gets its own isolated Linux machine — shell, files, packages, preview URLs — and persistent sessions when you need state across tool calls. ## How to connect Same API behind every surface. Pick what fits: | Surface | Install | Best for | |---------|---------|----------| | [CLI](/docs/integrations/cli) | `curl -fsSL https://inis.run/install.sh \| bash` | Scripts, CI, quick manual runs | | [HTTP API](/docs/api/overview) | Bearer token | Any language, custom integrations | | [Python SDK](/docs/integrations/python) | `pip install inis` | Python agents, data pipelines | | [TypeScript SDK](/docs/integrations/typescript) | `npm install @inis-run/sdk` | Next.js, Node agents | | [Remote MCP](/docs/integrations/mcp) | `https://mcp.inis.run/sse` + API key | Claude, Cursor, cloud-hosted agents | Framework helpers: [Pydantic AI](/docs/integrations/pydantic-ai), [AI SDK](/docs/integrations/ai-sdk), [LangChain](/docs/integrations/langchain), [OpenAI Agents SDK](/docs/integrations/openai-agents), [Strands Agents](/docs/integrations/strands-agents), [Mastra](/docs/integrations/mastra), [Google ADK](/docs/integrations/google-adk), [Microsoft Agent Framework](/docs/integrations/agent-framework). ## What you get - **Persistent sessions** — state survives across tool calls; auto-pause when idle, wake on the next op - **Full Linux** — arbitrary shell, file I/O, HTTPS preview URLs - **Templates, fork, checkpoints** — start from a known env, branch for parallel work, roll back when you need to ## Next steps - [Quickstart](/docs/quickstart) — install, sign in, run your first command - [Concepts](/docs/concepts) — sessions, previews, fork, checkpoints - [Session lifecycle](/docs/session-lifecycle) — templates, live/paused, hot/warm/cold resume - [Production best practices](/docs/production) — lifecycle knobs, bulk upload, idempotent creates, reconnecting after resume - [Building agents](/docs/integrations/mcp) — Claude, Cursor, or any remote MCP client - [llms.txt](https://inis.run/llms.txt) — curated docs index for agents --- ## Quickstart URL: https://inis.run/docs/quickstart ```bash curl -fsSL https://inis.run/install.sh | bash ``` The installer adds a static `inis` binary to your PATH (macOS and Linux). ```bash inis auth login ``` This opens [app.inis.run](https://app.inis.run) in your browser. After you sign in, the CLI creates an API key and saves it to `~/.inis/credentials`. For CI or scripts, set `INIS_API_KEY` instead — see [Authentication](/docs/authentication). Stateless execution — no session needed: ```bash inis run --language python -e 'print(42)' ``` Or run an arbitrary shell command in a fresh sandbox: ```bash inis exec -- python -c "print(42)" ``` Persistent sessions keep state between commands: ```bash SID=$(inis sessions create) inis exec --session "$SID" -- pip install httpx -q inis exec --session "$SID" -- python -c "import httpx; print(httpx.__version__)" inis sessions destroy "$SID" ``` Installed packages live under `/workspace` and persist for the session. Need a single run without tracking a session? Use the stateless-execution [`/v1/sessions/exec`](/docs/api/execute) endpoint, which creates a session, runs your command, and tears it down in one call. Building an agent? Read [Concepts](/docs/concepts) and [Session lifecycle](/docs/session-lifecycle), then pick an [integration](/docs/integrations/python). For terminal usage, see the [CLI reference](/docs/integrations/cli). For a complete, runnable Python or TypeScript script covering this same session/exec/reconnect/cleanup sequence, see [`examples/quickstart`](https://github.com/inis-run/sdk/tree/main/examples/quickstart) in the public SDK mirror — it's the canonical source every quickstart snippet on this site is checked against. --- ## Authentication URL: https://inis.run/docs/authentication All requests to the execution API require a bearer token: ```bash Authorization: Bearer inis_... ``` ## CLI (recommended for local use) ```bash inis auth login # opens app.inis.run, saves key to ~/.inis/credentials inis auth status # show whether credentials are configured inis auth logout # remove ~/.inis/credentials ``` `INIS_API_KEY` in the environment takes precedence over the credentials file. ## Dashboard and CI Create and revoke keys in the [dashboard](https://app.inis.run). For CI pipelines, store `INIS_API_KEY` in your secret store — do not commit it. Do not commit API keys. Use `inis auth login`, environment variables (`INIS_API_KEY`), or your platform's secret store. ## Base URL | Environment | URL | |-------------|-----| | Production | `https://api.inis.run` | | Local dev | `http://127.0.0.1:8080` | SDKs and the CLI accept `--api-url` / `base_url` / `INIS_BASE_URL` to override the default. --- ## Concepts URL: https://inis.run/docs/concepts ## Stateless execution vs session There is one primitive: the session. A stateless-execution run (`/v1/sessions/exec`, `inis run`) is just a session collapsed into a single call — it creates a session, runs your command, and tears it down for you. | | Stateless execution (`/v1/sessions/exec`, `inis run`) | Session (`/v1/sessions`, `inis exec --session`) | |---|--------------------------------------------|--------------------------------------------------| | **State** | None between calls | Files, installed packages, running processes persist | | **Best for** | Simple jobs, stateless tools | Multi-step agents, notebooks, RL rollouts | | **Startup** | Every call starts a fresh VM — you wait for the start each time (the startup itself is not billed) | Amortised across many execs — a paused session wakes warm, it does not boot | For agents making many sequential tool calls, keep a **session** alive. To run a single script without tracking a session, run code directly instead. ## Sessions A session is a persistent sandbox VM. Create it once, call exec/files/expose many times, destroy when done. - Compute is metered by the millisecond and billed only while **live** — starting and stopping a session is not billed. A paused session stops the compute charge; a small storage charge for its saved state continues while it sits paused. - Any operation on a paused session wakes it automatically. - `DELETE /v1/sessions/{id}` destroys immediately. States, timers (`idle_timeout_ms`, `paused_ttl_ms`, `on_pty_detach`, …), wake-on-op, and recipes live on [Session lifecycle](/docs/session-lifecycle). Endpoint details are in the [Sessions API](/docs/api/sessions). ## Preview URLs Expose a port inside the sandbox to get an HTTPS URL routed to your process: ```bash inis sessions expose "$SID" --port 8080 ``` Returns a URL like `https://8080-{session_id}.ams1.sb.inis.run` (exact host depends on your node). The guest must bind to `0.0.0.0`, not `127.0.0.1`. To lock a preview URL down, pass `--auth bearer`. The expose response then includes an `auth_token`, and inbound requests must carry an `Authorization: Bearer ` header. Expose is idempotent: asking for a port that is already exposed the same way returns the URL and token you already have, rather than minting new ones that would break whoever is holding the old one. Pass `--rotate` when you actually want a fresh token. Typical flow: start a server in the sandbox with exec, then call expose. ## Fork `POST /v1/sessions/{id}/fork` with `{"count": 10}` clones a live session into N independent children — useful for parallel eval or RL rollouts where each variant needs the same starting state. Each child gets its own session ID and can diverge independently. Forks keep the parent's paused TTL (`paused_ttl_ms`). ## Checkpoints A checkpoint is a named, retained save-point of a live session that you can restore from later. Where fork's copy is ephemeral (used once to seed children, then discarded), a checkpoint is **kept until you delete it** — and it **outlives the session it came from**. Destroying a session never deletes its checkpoints; deletion is always explicit. ```bash # Capture a clean baseline of a live session inis sessions checkpoint "$SID" --name clean # ...run some untrusted code... # Roll the same session back to the baseline, in place inis sessions restore "$SID" --checkpoint clean ``` Two ways to restore: - **In place** (`POST /v1/sessions/{id}/restore`): stop the session's current VM and bring it back at the checkpoint state, reusing the same session ID. This is the "run untrusted code, then roll back to a clean state" flow — give an agent or an untrusted script a fresh, known-good environment for every attempt. - **To a new session** (`POST /v1/checkpoints/{cid}/sessions`, or `inis checkpoints create-session `): start a brand-new session from the checkpoint. The new session diverges independently, so a checkpoint doubles as a **template**: prepare an environment once, then stamp out fresh sessions from it. Capturing a checkpoint does not interrupt the source session — it keeps running. Each checkpoint reports its `size_bytes`; delete checkpoints you no longer need with `inis checkpoints delete ` to free disk. For pause vs fork vs checkpoint (and when to use each), see [Session lifecycle](/docs/session-lifecycle#pause-vs-fork-vs-checkpoint). Checkpoints are node-local in this release: restore happens on the same node that holds the checkpoint, the same constraint as pause and resume. ## Where things run - **Execution API:** `https://api.inis.run` — sandboxes, sessions, exec. - **Control plane:** `https://app.inis.run` — sign-in, API keys, usage, billing. These are separate services. Your API key works against the execution API; account management uses a browser session on the app. --- ## Session lifecycle URL: https://inis.run/docs/session-lifecycle A **session** is one sandbox you create, use, pause, and destroy. Everything else — templates, checkpoints, fork, timers — is how you start it, save it, or copy it. ``` template ──► creating ──► live ⇄ paused (hot → warm → cold) ──► destroyed │ │ checkpoint wake on next op save as template ``` ## Starting — templates A [template](/docs/templates) is **where you start**. Official ones (`base`, `python`, `node`, …) or one you published from an earlier session. ```bash inis sessions create --template python # or pin an exact build: inis sessions create --template python@2026.07.10 ``` The first boot from a template is a **cold start** — the environment is brought up fresh. After that, if you pause and come back, you are waking the *same* session (files, packages, and running-process state from when you left), not starting over from the template. | Start path | What you get | |------------|--------------| | Template (official or yours) | New session from a known baseline | | Checkpoint → new session | New session branched from a save-point of an old one | | Stateless run (`inis run`, [`/v1/sessions/exec`](/docs/api/execute)) | Same create → run → destroy, no ID to keep | See [Concepts](/docs/concepts) for when to keep a session vs run code and throw it away. ## Live and paused | State | Meaning | Compute | |-------|---------|---------| | `creating` | Coming up; not ready for exec yet | Brief | | `live` | Running — exec, files, expose, PTY all work | Yes | | `unavailable` | Resident VM held while its network backend cannot serve requests; retry after recovery | No (held interval) | | `paused` | Saved and sleeping — no processes running | No (storage only) | | `destroyed` / `ended` | Gone; `ended` is history metadata only | No | An `unavailable` session still owns its VM resources and counts toward running concurrency limits. Operations, including destroy, return `503 network_backend_unavailable` while it is held. Cleanup must tear down the network lease before releasing reservations, so destroy waits for backend recovery or operator repair. If its node is lost, normal node-loss and recovery rules apply. **Live → paused** when you pause explicitly, when idle timeout fires, when `max_lifetime_ms` fires (auto-pause, not destroy — see Timers below), or when the last PTY client leaves (`on_pty_detach: pause`, the default). **Paused → live** on any operation (exec, files, expose, processes) or SSH/PTY attach — **wake-on-op**. One exception, added deliberately: an expose call that is already satisfied (the port is exposed with exactly the settings asked for) answers from the existing route and leaves the session asleep, so a loop re-asserting the exposure it wants doesn't wake and bill every sleeping session on every pass. You rarely need to call resume yourself. **Exception:** a session paused by its own `max_lifetime_ms` firing cannot wake again — resume (explicit or automatic) is refused. That pause is permanent; see `max_lifetime_ms` in Timers below. **Destroyed** when you delete it, when `paused_ttl_ms` fires, or when a detach policy / completion flag tears it down. A destroyed session's saved snapshot is deleted at the same time. If the session ended because the machine it ran on was lost, or that deletion fails, the snapshot is kept for 30 days after the session ended and then deleted. `max_lifetime_ms` only destroys as a fallback, if the auto-pause it triggers can't itself succeed (e.g. a wedged VM) — it never destroys a healthy session, it just permanently pauses it. ## Resume speed — hot, warm, cold A paused session is not one speed. The console and API expose `snapshot_tier` — how ready the session is to wake: | Tier | Where it sits | Wake feel | |------|---------------|-----------| | **hot** | Fast local copy | Instant (tens of ms after a slot is ready) | | **warm** | Compressed local copy | Quick (local decompress, typically ~1–2 s) | | **cold** | European object storage only | Slower (download + restore, often several seconds) | The platform demotes dormant sessions over time (and under disk pressure): **hot → warm → cold**. Any successful wake promotes back toward hot and resets that clock. You do not pick the tier yourself — you see it on the session while it is paused. Capacity in the console also talks about **running** (live) vs **warm** (paused, resumable). Same idea: warm quota is how many paused sessions you can hold. ## Saving — pause vs checkpoint vs template These sound alike. They are different jobs: | | Pause | Checkpoint | Template | |---|-------|------------|----------| | **Job** | Stop paying compute; come back to *this* session | Save-point you can roll back to or branch from | Named starting environment for *new* sessions | | **Outlives the session?** | No | Yes (until you delete it) | Yes | | **Typical use** | Agent idle between tool calls | Clean baseline / rollback after untrusted code | “Always start from this env” | ```bash # Pause this session (auto-wakes on next op) inis sessions pause "$SID" # Save-point on the same session inis sessions checkpoint "$SID" --name clean inis sessions restore "$SID" --checkpoint clean # Publish a reusable start environment (see Templates) # Console: Save as template — or create new sessions from a checkpoint ``` **Fork** is the parallel path: clone a live session into N children for eval / rollouts. Ephemeral — not a long-lived save. Forks keep the parent's paused TTL. Details in [Concepts](/docs/concepts#fork). ## Timers Set at create ([Sessions API](/docs/api/sessions) / CLI flags). Omit for server defaults. | Knob | Effect | |------|--------| | `idle_timeout_ms` | Auto-pause after this much idle time while **live** | | `on_pty_detach` | `pause` (default), `keep_live`, or `destroy` when the last terminal leaves (PTY only) | | `paused_ttl_ms` | Auto-destroy after sitting **paused** this long. Omit, `0` or negative = never (the default) | | `max_lifetime_ms` | Hard cap on session age (live or paused). Auto-pauses when reached — **permanently**: unlike every other trigger in this table, this pause can never be resumed from (any attempt refuses with `410`); destroy is only a fallback if the pause itself fails. `paused_ttl_ms` above is what actually bounds how long the paused data sticks around | | `destroy_on_completion` | Tear down after the first command (stateless-style) | `max_lifetime_ms` set together with `paused_ttl_ms` negative ("never") is rejected at create time (`400`): a session that `max_lifetime_ms` permanently pauses and can never resume from would otherwise sit paused and billed forever with no `paused_ttl_ms` to ever reclaim it. Whenever you set `max_lifetime_ms`, omitting `paused_ttl_ms` (or `0`) gives the session a 30-day paused TTL instead of never; set a positive value to choose another. Sessions created before November 2026 without a `paused_ttl_ms` keep a 30-day paused TTL; send `paused_ttl_ms: -1` with PATCH to keep one. **What counts as activity** (resets idle): exec, files, expose, process APIs, and an attached PTY. A background process alone does **not**, unless you start it with `keep_alive: true`. ```bash inis sessions create --on-detach pause --paused-ttl-ms 86400000 # drop after a day paused inis sessions create --on-detach keep_live # stay live after detach; idle still applies later ``` ## Limits Defaults and hard caps on the managed cloud today: | Knob | Default | Hard cap | |------|---------|----------| | `idle_timeout_ms` | Off (no auto-pause) | 1 hour | | `max_lifetime_ms` | Off (no cap of your own) | 24 hours | | Continuous-live backstop | Always on — 24 hours continuously live (6 hours on a new, unverified trial account), independent of `max_lifetime_ms`. Any pause/resume resets the clock | 24 hours (6 on trial) | | `paused_ttl_ms` | Never (30 days with `max_lifetime_ms`) | — | | `timeout_ms` (one exec) | 30 seconds | 1 hour | | Concurrent live sessions per account | 10 (1 on a new, unverified trial account) | — | | Cumulative disk across live + paused sessions | 512 GB (24 GB on trial) | — | | Session size (`vcpus` / `mem_mb` / `disk_gb`) | Trial: 1 vCPU / 2 GB per session, 2 live sessions, 16 GB disk in total. Funded: 8 vCPU / 16 GB across awake sessions, 200 GB disk | Raisable on request | A session lives until you destroy it, it idles out, or its own opt-in `max_lifetime_ms` fires — there is no default cap on total age. **The continuous-live backstop never destroys — and it doesn't leave you down, either.** When it fires it force-pauses (closing any attached PTY, tunnel, or in-flight operation), takes a fresh snapshot, and — normally — immediately resumes the session again: a few-second "blip," not a daily outage. That resume-from-fresh-snapshot cycle doubles as a daily durability checkpoint for a session that would otherwise never produce one. A `session.active_window_warning` event fires a few minutes ahead of the blip on the account event stream so you can quiesce in-guest work first — see [Execution log](/docs/execution-log#live-only-transitional-states). The one exception: if the backstop fires while your session's host node happens to be draining for a fleet cycle, it skips the immediate resume and leaves the session parked instead — the same behavior as before this cycling existed. That's rare and self-resolving: any later request resumes the session normally, same as any other paused session. No requests-per-second limit applies to the execution API itself — the concurrency cap is what bounds usage. Sign-in and CLI-pairing endpoints are separately rate-limited per IP/email as a brute-force guard. ## Keeping a session live To avoid idle pause while work continues without API traffic: - Keep a PTY attached (`inis ssh`) - Start a [named process](/docs/api/sessions#background-processes) with `keep_alive: true` - Use `on_pty_detach: keep_live` so disconnecting does not pause immediately Without `keep_alive`, a detached process can keep running until idle pause freezes the whole VM. ## Billing (short) - **Live** — compute, metered by the millisecond of run time; starting and stopping are not billed - **Paused** — storage for the saved session (tier may change; you still pay while it exists) - **Destroyed** — nothing ongoing Prefer pause over destroy when you will return: you keep the environment and avoid another template cold start. ## Recipes ### Agent — pause between model turns ```python session = client.sessions.create(template="python", idle_timeout_ms=60_000) session.exec(["pip", "install", "httpx", "-q"]) # ... tool calls ... session.pause() # optional; idle timeout would do this anyway session.exec(["python", "agent_step.py"]) # wakes automatically ``` ### Start from a template, save a baseline ```bash SID=$(inis sessions create --template data-science) # ... install project deps, seed data ... inis sessions checkpoint "$SID" --name ready # later: roll back in place, or stamp new sessions from the checkpoint ``` ### Preview server that should stay up ```python session.start_process("web", ["python3", "-m", "http.server", "8080"], keep_alive=True) session.expose(8080) ``` If the session later pauses, preview clients disconnect; after wake they reconnect to the same URL. ## If a node fails Sessions run on dedicated hardware, and hardware occasionally dies. If a session's host is unexpectedly lost, the session moves to a terminal `node_lost` state — it does not silently retry, and inis.run does not auto-restore it onto another node. Every operation against it (exec, files, pty, pause, fork, checkpoint, resume) returns the `session_node_lost` error, with two exceptions: `GET /v1/sessions/{id}` keeps working and reports `state: "node_lost"`, so you can detect it instead of guessing from a timeout, and `DELETE /v1/sessions/{id}` still works too — deleting a lost session always succeeds, so it never lingers, undeletable, in your session list. Recreate the session from its template, or restore from your last checkpoint if you took one — anything since that checkpoint is gone. See [Errors](/docs/api/errors) for the full code reference and [Production best practices](/docs/production#errors-and-retries) for a handler that branches on it. ## Gotchas - **Tier is informational** — you cannot force hot; long idle or disk pressure can move a session to cold before the next wake. - **Cold wake is slower** — treat it as normal for abandoned sessions, not an error. - **`on_pty_detach` is PTY-only** — API-only sessions use idle timeout / explicit pause. - **Previews drop on pause** — preview connections drop while the session is paused; reconnect after wake. - **Secrets in paused / checkpointed state** — values already in guest memory can be retained with the saved session. See [Sessions API](/docs/api/sessions#environment-and-secrets). - **Wake races** — a live-only call that hits a just-paused session may return `session_not_live` (409); refetch and retry. See [Errors](/docs/api/errors). ## Where to go next - [Templates](/docs/templates) — official set, versioning, pinning - [Best practices](/docs/best-practices) — persistence, resume/fork, templates, scoped credentials, egress - [Concepts](/docs/concepts) — fork, checkpoints, preview URLs - [Sessions API](/docs/api/sessions) — request/response reference - [CLI](/docs/integrations/cli) — `inis sessions`, `inis ssh` - [Networking](/docs/networking) — egress across pause / fork - [Production best practices](/docs/production) — which timer to reach for, why you don't need your own warm pool, reconnecting after resume --- ## Templates URL: https://inis.run/docs/templates ## What templates are A template is a named base environment a session starts from. There are two kinds: - **Official** templates are maintained by inis.run. You get them in every project, you cannot delete them, and each one is rebuilt on a schedule to pick up upstream security patches. - **Your** templates are saved from your own sessions. Configure a session, save it, and stamp new sessions from it. Create a session from a template by name: ```bash inis run --template python -- python3 script.py ``` ## The official set The official set is grouped into two lines: - **Language runtimes** track an upstream release — `python`, `node`, `go`, and the default `base` (Python, TypeScript, and agent tooling ready). These follow the upstream image and are rebuilt weekly. - **Use-case images** are composed environments for a task built from a maintained recipe — for example `data-science` (pandas, numpy, scikit-learn, Jupyter) or `headless-browser` (Playwright with Chromium). These are rebuilt at least monthly. The set grows over time, so the live list is the source of truth — not this page. See what is available, with the version and built date of each: ```bash inis templates ls ``` ``` NAME KIND VERSION BUILT DESCRIPTION base official 2026.07.09 2026-07-09 The default sandbox — Python 3, Node.js, bun, and common agent tooling on Debian python official 2026.07.10 2026-07-10 Python 3.12 with pip, venv, and the common data libraries. node official 2026.07.10 2026-07-10 Node.js 22 LTS with npm and pnpm. data-science official 2026.07.02 2026-07-02 Python + pandas, numpy, scikit-learn, and Jupyter. ``` The same list, with full provenance, is on the [Templates page](https://app.inis.run/templates) in the console. ## Versioning Every rebuild of an official template is published as a new **immutable version** — for example `python@2026.07.10`. A `(name, version)` pair, once published, never changes. Two ways to reference one: - The **bare name** (`python`) resolves to the currently promoted version. When a rebuild is promoted, the name points at the new version; every already-published version stays exactly as it was. - An **exact pin** — `python@2026.07.10` — always resolves to that one published version and never moves. ```bash # Follows the promoted version — always the latest patched build: inis run --template python -- ... # Pins an exact version — byte-identical every time, never moves: inis run --template python@2026.07.10 -- ... ``` Use the bare name when you want the latest patched build. Pin a version when you need a byte-identical baseline across a run — a reproducible evaluation, or a result you need to reproduce later. We **deprecate rather than delete**. When a version is retired it stops being offered for new sessions, but any version you have pinned or built on stays resolvable, so a pin never breaks under you. ## Patch cadence Official templates are rebuilt on a fixed cadence — language runtimes weekly, use-case images at least monthly — to pull in upstream security patches. The **built date** is shown next to every official template in `inis templates ls` and in the console. A stale built date is a visible signal that a rebuild is overdue, not something you have to take on trust. ## Provenance For each official template, the console records what a build is made of and what it resolves to: | Field | What it is | |---|---| | **Version** | The immutable published version the bare name currently resolves to. | | **Base image** | The upstream image the build was made from, with its content digest — pinning exactly what went in. | | **Built** | When this version's bundle was built, and its rebuild cadence. | | **Bundle hash** | The content hash of the published bundle, recomputed server-side at publish time and refused if it doesn't match the bytes uploaded. | --- ## Best practices URL: https://inis.run/docs/best-practices Short answers to "what's the right way to do this" for the choices that come up on nearly every integration. Each one links to the fuller reference for the mechanism behind it. ## Keep a session, don't recreate one A session holds its files, installed packages, and running processes across calls — destroying it and creating a new one throws all of that away and pays a full template start again. Pause it instead; any operation wakes it automatically, and idle sessions pause themselves. ```python session = client.sessions.create(template="python", idle_timeout_ms=60_000) session.exec(["pip", "install", "httpx", "-q"]) # ... later, same session, no manual pause/resume needed ... session.exec(["python3", "agent_step.py"]) # wakes automatically if paused ``` Set `idle_timeout_ms` so a session between tool calls pauses on its own instead of you tracking idle time yourself — see [Session lifecycle](/docs/session-lifecycle#timers) for the rest of the timer knobs and [Production best practices](/docs/production#skip-building-your-own-warm-pool) for why a client-side warm pool isn't needed here. ## Prefer resume and fork over cold starts Resuming a paused session restores its own retained state — tens of milliseconds when it's hot, a second or two when it's warm — rather than booting a template from scratch. Forking clones a *live* session into N independent children in one call, useful for parallel eval or rollouts that all need the same starting state: ```bash curl -X POST https://api.inis.run/v1/sessions/$SID/fork \ -H "Authorization: Bearer $INIS_API_KEY" \ -d '{"count": 4}' ``` Reach for a fresh template only when you actually want a clean baseline. To roll a session back to a known-good state without losing the session identity, checkpoint and restore instead — see [Concepts](/docs/concepts#checkpoints). ## Start from a template instead of installing on every run A [template](/docs/templates) is a saved starting environment — official (`python`, `node`, `data-science`, …) or one you published from your own session. Starting from one that already has your dependencies beats running the same install step at the top of every session. ```bash # One-time: configure a session, then save it as a template inis templates save "$SID" --name my-agent-env # Every later session starts with deps already installed inis sessions create --template my-agent-env ``` Pin an exact version (`my-agent-env@2026.08.01`) when a run needs a byte-identical baseline; use the bare name when you want the latest patched build. ## Scope third-party credentials with Connections Don't bake a provider API key into a template, an env var, or code the session can read directly. A [Connection](/docs/connections) binds a session to one external origin with a credential scoped to specific HTTP methods and paths — the platform injects it on the way out, so your code never holds the real value: ```bash curl -X POST https://api.inis.run/v1/sessions \ -H "Authorization: Bearer $INIS_API_KEY" \ -d '{ "connections": [{ "name": "stripe", "origin": "https://api.stripe.com", "authentication": { "type": "bearer", "secret": "sk_live_..." }, "allow": { "methods": ["GET", "POST"], "paths": ["/v1/*"] } }] }' ``` ```python import stripe stripe.api_key = "placeholder" # overwritten by the platform, never sent as-is customers = stripe.Customer.list() ``` **Know the limit before you rely on it:** if the destination reflects request headers back (a debug endpoint, an error body that echoes what it received), code in the session can read the credential it was just handed — response bodies aren't scrubbed, and scrubbing wouldn't hold up as a real boundary anyway. Use a scoped, short-lived upstream credential (a Stripe restricted key, a GitHub fine-grained token) so a leaked value can't do more than `allow.methods`/`allow.paths` already permitted, and keep `allow.paths` away from endpoints you know reflect requests. Full detail in [Connections — The limit](/docs/connections#the-limit). ## Lock down egress for untrusted code Sessions get full public egress by default. For code you don't fully trust — model-generated, third-party, anything you'd rather fail closed — set a deny-by-default allowlist instead of leaving egress open: ```python session = client.sessions.create( egress_default="deny", egress_allow=["api.openai.com", "*.githubusercontent.com"], ) ``` Enforcement matches on the TLS SNI, not just DNS, so hardcoding an IP to dodge the resolver doesn't get around it. Every allowed and denied attempt is recorded — see [Networking & egress](/docs/networking) and [Execution log](/docs/execution-log). Set an org or project default so callers don't have to opt in per session. ## Pass exec commands as an argv array, not a shell string `command` on exec is an array — each element is one argument, not a shell line to be parsed: ```json // Wrong — tries to exec a binary literally named "pip install httpx -q" { "command": ["pip install httpx -q"] } // Right { "command": ["pip", "install", "httpx", "-q"] } ``` If you need shell features — pipes, `&&`, globbing — wrap explicitly instead of hand-splitting them yourself: ```python session.exec(["bash", "-c", "pip install httpx -q && python3 -c 'import httpx'"]) ``` ## Use a volume for data that must outlive the session A session's own disk goes away with the session. For files that need to survive across sessions — a dataset, a build cache, accumulated output — create a [volume](/docs/volumes) once and attach it by id: ```bash curl -X POST https://api.inis.run/v1/volumes -H "Authorization: Bearer $INIS_API_KEY" \ -d '{"size_gb": 5}' # {"id": "vol_7f3ac21b9e4d", ...} curl -X POST https://api.inis.run/v1/sessions -H "Authorization: Bearer $INIS_API_KEY" \ -d '{"volume_id": "vol_7f3ac21b9e4d", "template": "python"}' ``` A volume's contents are durable as of the last time its session was **destroyed**, not continuously — writes during a live session exist only on the machine running it until then. Treat it as a working disk, not a live backup; see [Volumes — Durability](/docs/volumes#durability--whats-actually-guaranteed) for exactly what's guaranteed and when. ## Where to go next - [Session lifecycle](/docs/session-lifecycle) — full timer table, resume tiers, pause vs checkpoint vs template - [Production best practices](/docs/production) — idempotent creates, bulk file transfer, pagination, reconnecting after resume - [Connections](/docs/connections) — scoped credential brokering, full lifecycle and limits - [Networking & egress](/docs/networking) — allowlist mechanics, org/project defaults - [Volumes](/docs/volumes) — sizing, resizing, durability guarantees --- ## Volumes URL: https://inis.run/docs/volumes ## What a volume is A volume is a block of persistent disk storage you create once and attach to sessions as needed. A session's own disk goes away with the session; a volume doesn't — attach it to a later session and your files are still there. Create one, then attach it by id on session create: ```bash curl -X POST https://api.inis.run/v1/volumes \ -H "Authorization: Bearer $INIS_TOKEN" \ -H "Content-Type: application/json" \ -d '{"size_gb": 5}' ``` ```json { "id": "vol_7f3ac21b9e4d", "size_gb": 5, "created_at": "2026-08-07T10:00:00Z", "attached": false } ``` A brand-new volume has no `last_saved_at` — it's omitted entirely until the volume has actually been through a session that ended (see "Durability" below). ```bash curl -X POST https://api.inis.run/v1/sessions \ -H "Authorization: Bearer $INIS_TOKEN" \ -H "Content-Type: application/json" \ -d '{"volume_id": "vol_7f3ac21b9e4d"}' ``` `volume_id` also works on [one-shot exec](/docs/api/execute). A volume must exist before you can attach it — `volume_id` naming an id you don't own, or one that doesn't exist, is a `404`. Earlier versions of this API created a volume implicitly the first time an arbitrary name was attached; that no longer happens, so a typo in `volume_id` fails loudly instead of quietly provisioning a second, empty volume. Only one session can hold a volume attached at a time — a live or paused session that already has it makes it unavailable to attach elsewhere until that session ends. ## Managing volumes | Endpoint | What it does | |---|---| | `POST /v1/volumes` | Create one. `{"size_gb": 5}` — `size_gb` is optional, defaults to 1, capped at 10 | | `GET /v1/volumes` | List every volume you own | | `GET /v1/volumes/{id}` | Size, creation time, `last_saved_at`, and whether a live or paused session currently has it attached | | `PATCH /v1/volumes/{id}` | Grow it. `{"size_gb": 8}` — grow-only, refused while attached | | `DELETE /v1/volumes/{id}` | Permanently erase it | ```bash curl https://api.inis.run/v1/volumes \ -H "Authorization: Bearer $INIS_TOKEN" ``` ```json { "volumes": [ { "id": "vol_7f3ac21b9e4d", "size_gb": 5, "created_at": "2026-08-07T10:00:00Z", "attached": true, "session_id": "s_Lp93Vt0c", "last_saved_at": "2026-08-06T18:42:00Z" } ] } ``` The console's [Volumes page](https://app.inis.run/volumes) covers the same create/list/delete surface, and the session create form there offers your volumes as a picker instead of a typed-in id. ### Deleting ```bash curl -X DELETE https://api.inis.run/v1/volumes/vol_7f3ac21b9e4d \ -H "Authorization: Bearer $INIS_TOKEN" ``` Refused with `409` while the volume is attached to a live or paused session — end that session first. This is permanent: it erases both the local copy and the durable off-node copy described below, with no recovery. ## Sizing and resizing `size_gb` defaults to 1 GiB at creation and is capped at 10 GiB per volume. Grow it later: ```bash curl -X PATCH https://api.inis.run/v1/volumes/vol_7f3ac21b9e4d \ -H "Authorization: Bearer $INIS_TOKEN" \ -H "Content-Type: application/json" \ -d '{"size_gb": 8}' ``` A few things worth knowing before you rely on it: - **Grow-only.** `size_gb` must be strictly greater than the volume's current size — a request at or below the current size is rejected (`400`), not treated as a shrink or a silent no-op. There's no way to shrink a volume through the API; shrinking a filesystem that has data in it isn't safe, so this refuses rather than attempting it. If you need less space, create a new, smaller volume and copy the data across. - **Detach it first.** A resize is refused with `409` while the volume is attached to a live or paused session, or while an attach/detach is briefly in progress. Growing a disk image and its filesystem underneath a running VM isn't done live — end or pause-then-resume-elsewhere the session, resize, then reattach. - **Takes effect on the next attach, not instantly.** A successful `PATCH` updates the volume's registered size right away, but the physical disk image only grows the next time something actually attaches the volume — which, since resize is refused while attached, is the very next attach after the resize call returns. You won't see or need to wait for this separately; it just means the size change and the attach that uses it happen together. - Same total-provisioned-GB account ceiling as create applies to growth too — a resize that would push your account over its quota is rejected with `409`, naming the limit and your current usage, exactly like an over-quota create. ## Durability — what's actually guaranteed A volume's data is durable **as of the last time its session ended**, not continuously: - A volume's contents are pushed to EU object storage when the session using it is destroyed (not on pause — a paused session still holds the volume attached). The saved copy is encrypted with a key scoped to your account. - Attaching a volume on a node that doesn't already hold a local copy restores it from that durable copy first. - **Writes made during a session are only durable once the session ends.** While a session is running, its writes exist only on the machine running it. If that machine is lost mid-session, work since the volume's last push is lost with it. - Deleting a volume erases both the local image and the durable copy — the durable copy is crypto-shredded (its encryption key is destroyed), not just marked deleted. If you're writing something you cannot afford to lose, treat a volume like a working disk, not a backup: end the session (or checkpoint/copy the result out to your own storage) at the point you need the durability guarantee to apply. ### `last_saved_at` Every volume response carries `last_saved_at`: the timestamp of the most recent successful push described above. It answers "is my data actually safe, and as of when" directly — check it before trusting a volume with something you can't afford to lose. - It's **absent** (not present in the response at all — never a zeroed or fabricated timestamp) on a volume that has never gone through a session that ended. A missing `last_saved_at` means there is no durable copy yet; everything on that volume today exists only on whichever node it's currently attached to. - It updates on session **destroy**, same as the rest of this section — pausing a session does not move it forward. If a session has been running (or sitting paused) for a while, `last_saved_at` still reflects the last time it was actually destroyed and re-pushed, not "just now." - It is not a guarantee that nothing has changed since — a live or paused session can have written more to the volume than `last_saved_at` reflects. It only tells you when the durable copy was last confirmed complete. --- ## Networking & egress URL: https://inis.run/docs/networking ## Default: full egress By default a session has full public outbound network access. Lateral movement is always blocked — code in a session cannot reach the host, the local network, the cloud metadata endpoint, or other sessions. Only public internet egress is open by default. ## Egress source addresses All sandbox outbound traffic currently leaves through a fixed address: ``` 51.15.136.120 ``` This holds across nodes and pause/resume today — the address a session's guest is assigned internally can change, but the address your services see it come from does not. If you allowlist inbound traffic on your own infrastructure, this is the address to add. It may change as the fleet evolves; we'll announce it in advance. ## Per-session egress allowlist For untrusted code you can lock a session down to an explicit allowlist. Set the egress policy at create time, or change it on a live session. ```json { "egress": { "mode": "deny", "allow": ["api.openai.com", "*.githubusercontent.com", "pypi.org"] } } ``` - `mode: "allow"` (or omitted) — full public egress. Current behaviour. - `mode: "deny"` — block all outbound traffic except the domains in `allow`. - `allow` — domains only (no IP ranges in this version). Each entry is either an exact hostname (`api.openai.com`) or a single leading wildcard (`*.githubusercontent.com`, which matches any subdomain but not the apex). Up to 256 entries. ### On create ```bash inis sessions create --egress-deny \ --allow api.openai.com \ --allow '*.pypi.org' ``` ```python from inis import Client client = Client() session = client.sessions.create( egress_default="deny", egress_allow=["api.openai.com", "*.githubusercontent.com"], ) ``` ```typescript const session = await client.sessions.create({ egress: { mode: "deny", allow: ["api.openai.com", "*.githubusercontent.com"] }, }); ``` ### On a live session Read or replace the policy at any time: ```bash inis sessions egress # print active policy inis sessions egress --egress-deny \ --allow api.openai.com # replace policy ``` - `GET /v1/sessions/{id}/egress` — read the active policy. - `POST /v1/sessions/{id}/egress` — set or replace the policy. The active policy is also reflected on `GET /v1/sessions/{id}` under `egress`. ### Forks A forked child inherits its parent's egress policy. Each child gets its own isolated network, so the policy is applied independently to every child. ### Pause / resume The policy is stored with the session and survives pause/resume. It is re-applied automatically when the session resumes. ## Project & org defaults A session created without its own `egress` field inherits its project's default, if one is set. This is how a team standardizes on deny-by-default for a given project (or an entire org) without every caller specifying a policy on every `sessions.create` call: - `GET`/`PUT /v1/org/projects/{project_id}/egress-default` — a project's default. Any member may read it; owner/admin may set it. - `GET`/`PUT /v1/org/egress-default` — an org-level default. New projects created after this is set inherit it automatically; existing projects keep whatever they already had. It is a one-time template, not a live fallback — changing the org default later never retroactively changes an existing project. An explicit per-request `egress` field always wins over both. The fleet-wide default remains full public egress — deny-by-default is opt-in, per project (or per org, via the setting above), not a platform-wide default. ## Package installs in deny mode A locked-down session still needs to reach its package mirrors. Two mechanisms cover this, and they stack: 1. **Package-mirror env vars.** When the node is configured with `INIS_PYPI_INDEX_URL` or `INIS_NPM_REGISTRY_URL`, those mirror hosts are added to the allowlist automatically for `mode: "deny"` sessions, so `pip install` and `npm install` keep working without listing them yourself. 2. **Baseline allowlist presets.** A project's (or org's) egress default can enable a named preset — for example `standard-dev`, which covers PyPI, npm, GitHub, and Debian/Ubuntu apt mirrors — instead of hand-curating a list. Presets are configured server-side (an operator-updatable list, not compiled into the binary) and resolved live, so an update to a preset's domains takes effect immediately for sessions created afterwards. `GET /v1/org/egress-presets` lists what's available. If you rely on the public indexes instead, allow the hosts you need explicitly, for example: - pip: `pypi.org`, `files.pythonhosted.org` - npm: `registry.npmjs.org` ## How it works In deny mode, enforcement happens at the host, on the name itself, not just on whatever IP that name happens to resolve to: - **DNS is policy-aware.** A deny-mode session's guest talks to a resolver that only answers queries for names on the allowlist — an exact match, or a real subdomain of a wildcard entry. A query for anything else comes back as if the name doesn't exist (`NXDOMAIN`), and that includes the bare domain of a wildcard-only entry: `*.githubusercontent.com` resolves `raw.githubusercontent.com` and `gist.githubusercontent.com` — genuinely different hosts behind that CDN — but not `githubusercontent.com` itself. - **HTTPS is matched on the TLS handshake, not on DNS.** Outbound TLS connections are checked against the allowlist by the SNI in the `ClientHello`, independently of how the destination IP was obtained. A workload that hardcodes an IP to dodge the resolver is still stopped at the TLS layer: connecting straight to a wildcard-only domain's own IP with that domain as the SNI is rejected the same as an unresolvable name would be. Both checks run on the host, outside the guest, so code inside the session can't see or disable them. Anything that doesn't match is dropped, and the standard lateral-movement blocks stay in place regardless of egress mode. While a session is under an allowlist, every allowed and denied attempt is recorded — see [Execution log](/docs/execution-log) for the event types, payload shape, and how to read them back via the API. A session on the default full-egress policy has nothing to enforce and produces no network events. --- ## Security & data residency URL: https://inis.run/docs/security For a product built to run code you can't trust, the most important question is: how is it contained? ## Isolation & security ### Each run is its own machine Every session on inis.run gets a dedicated hardware-isolated environment — a clean slate, not a shared container. There is no way for code running in one session to read memory, files, or network traffic from another session. The boundary is enforced in hardware, not software. When a session ends, its memory and disk are destroyed. Nothing persists unless you explicitly asked for it to — a checkpoint, a template, a captured artifact, or an attached volume. ### Network egress is controlled Outbound network access from inside a session is controlled via an allowlist you can turn on per project (or per session). By default a session has full public egress; set a project — or your whole org — to deny-by-default and its sessions are restricted to an explicit allowlist instead. Either way, attempts to reach destinations outside an active allowlist are blocked at the network layer — not by the guest OS, which your code controls. While an allowlist is active, outbound attempts are logged, allowed and denied alike. A session left on the default full-egress policy is not filtered, and its outbound traffic is not recorded in the execution log at all — network logging is a property of running under an allowlist, not something that happens to every session. See [Networking & egress](/docs/networking) for the full policy model and [Execution log](/docs/execution-log) for how to read the logged events back. This means untrusted code running inside a locked-down session cannot use inis.run as a launchpad for outbound attacks or exfiltrate data to arbitrary destinations. ### One kernel per session Every session gets its own VM with its own kernel and its own memory — the boundary is enforced by the CPU, not by a shared kernel. Sessions belonging to different customers can be scheduled onto the same machine; what separates them is that virtualisation boundary, not physical separation. Each session also gets a flat outbound bandwidth cap, so one workload cannot starve another's network. ### We do not inspect your code or data inis.run does not store, log, or inspect the code you run or the data processed inside your sessions. We collect only the operational metadata needed to bill you and keep the service running: session duration, resource allocation size, and API request rates. See our [Privacy Policy](/privacy) for the full picture. The one exception is opt-in: if you configure a [Connection](/docs/connections) to inject a credential into requests your session makes to a specific origin, the platform terminates TLS on requests to that one bound origin so it can check the request and inject the credential — that's how the credential gets attached without your code ever holding it. Every other destination is passed through untouched; nothing outside the origins you've explicitly bound is ever decrypted. ### Abuse & misuse inis.run is infrastructure for legitimate code execution. We do not permit its use for generating malware, launching attacks, distributing illegal content, or circumventing other platforms' security controls. If you encounter misuse — of our API, our preview URL infrastructure, or anything running on our platform — report it to **abuse@inis.run**. We investigate every report and act on confirmed violations promptly, up to and including immediate account termination and cooperation with law enforcement where required. For security vulnerabilities in inis.run itself, see our [Security Policy](/security). ## Data residency & EU ownership ### EU-owned, EU infrastructure inis.run is Irish-owned and run from Ireland. Our infrastructure runs on bare-metal hardware hosted in the EU. Both our hosting provider and inis.run itself are genuinely EU-owned — there is no US parent company in the data path. Your workload data — the code you run, your files, your session contents — never leaves the EU, and neither does anything derived from it: the databases, operational logs, and stored session, checkpoint, and template state behind the service all sit on EU infrastructure. Account and billing metadata is the exception, and the [sub-processor list](/security/subprocessors) is the authoritative record of it: optional GitHub or Google sign-in and Stripe payments go through the providers named there, each with its processing location. ### Why ownership matters — the CLOUD Act The US CLOUD Act lets US authorities compel a US-owned company to hand over data stored anywhere in the world, including on servers physically located in the EU — so where a provider's data centres sit is not the deciding factor, ownership is. inis.run is EU-owned with no US parent, so a valid EU legal process is required to access any data we hold. ### What we don't claim We do not claim to be a compliance product. inis.run is execution infrastructure. Whether it meets your specific compliance requirements — GDPR processor obligations, sector-specific rules, internal data governance policies — is your call to make. We give you the facts; you decide whether they fit. If you need specifics for a procurement or legal review, write to **hello@inis.run**. --- General questions: hello@inis.run — abuse reports: abuse@inis.run — security vulnerabilities: security@inis.run --- ## Artifacts URL: https://inis.run/docs/artifacts ## What artifacts are A session is ephemeral — when it is torn down, its filesystem is gone. Artifacts let you keep the files a session produced. You name the paths to capture; inis.run tars them out of the session, writes them to durable storage, and hands back pre-signed download links. The links need no auth header and outlive the session. Typical uses: a generated report or chart, a model checkpoint, a CSV an agent built, the output of a batch job. ## Capture on demand Capture from a live session at any time. The call returns immediately with a `pending` artifact; the upload runs in the background. ```bash inis sessions artifacts capture \ --path '/workspace/output/**' \ --path '/workspace/*.csv' ``` ```python art = session.capture_artifacts(["/workspace/output/**", "/workspace/*.csv"]) # poll until ready art = client.artifacts.get(art.id) for f in art.files: print(f.path, f.url) ``` ```typescript let art = await session.captureArtifacts(["/workspace/output/**", "/workspace/*.csv"]); art = await client.artifacts.get(art.id); for (const f of art.files ?? []) console.log(f.path, f.url); ``` ### Path syntax - An exact path: `/workspace/report.pdf` - A bare directory, captured recursively: `/workspace/output` (same as `/workspace/output/**`) - A shallow glob: `/workspace/*.csv` - A recursive glob: `/workspace/output/**` - A bare relative path, resolved under the workspace: `output/**` (same as `/workspace/output/**`) Captures are scoped to the session workspace (`/workspace`) — the writable area where session files live. Paths outside it are rejected. A capture has a per-capture size cap (1 GiB by default) and a file-count cap (10,000). Exceeding either fails the capture rather than truncating it. ## Auto-capture on teardown Declare the paths at create time and they are captured automatically when the session is torn down — explicit destroy, idle timeout, or max-lifetime. Teardown holds the session live just long enough to finish the capture, with a time cap so it can never block forever; if the cap is hit the artifact is marked `failed` and teardown proceeds. ```bash inis sessions create --artifact-path '/workspace/output/**' ``` ```json { "artifacts": { "paths": ["/workspace/output/**"] } } ``` ## Manifest Getting an artifact returns its manifest: ```json { "id": "art_…", "session_id": "…", "status": "ready", "captured_at": "2026-06-23T18:00:00Z", "expires_at": "2026-06-30T18:00:00Z", "files": [ { "path": "output/chart.png", "url": "https://…", "size_bytes": 20480, "content_type": "image/png" } ] } ``` `status` is `pending`, `ready`, or `failed`. The `url` on each file is a pre-signed, direct-download link. ## Retention Artifacts are retained for 7 days by default, then purged from storage. Push the expiry forward (up to a 30-day cap) with extend: ```bash inis artifacts extend --ttl-days 30 ``` Delete early to free storage: ```bash inis artifacts delete ``` ## Where files are stored By default, files land in inis.run's object storage, which sits in the EU like the rest of the platform — see [Security & data residency](/docs/security). You can also send a capture to a bucket of your own: ```json { "paths": ["/workspace/output/**"], "destination": { "type": "s3", "bucket": "my-eu-bucket", "region": "eu-central-1" } } ``` Bring-your-own-bucket keeps captured data entirely in storage you control. The bucket still has to be in an EU region — that is enforced, not a default you can drift out of. ## Billing Artifact storage is billed by GB-days: the total size of your stored artifacts multiplied by the days they are retained. Captures count against per-capture and per-customer size limits; purged artifacts stop accruing storage charges. --- ## Agent recipes URL: https://inis.run/docs/agent-recipes Seven jobs an agent builder is usually trying to get done, each with the real, checked pattern and a link to executable source. If you haven't yet, start with the [Quickstart](/docs/quickstart) — everything below builds on its create/write/read/destroy shape and its one semantic rule: **you destroy the sessions you create, and never the ones you only attach to.** Runnable, tested versions of the patterns below live in [`examples/agent-harness`](https://github.com/inis-run/sdk/tree/main/examples/agent-harness) (Python and TypeScript) — read the source, don't retype it from here. If a *coding agent* (not your own runtime agent) is doing this integration work for you, point it at the [coding-agent skill](/docs/integrations/agent-skill) instead of this page — it routes to the same examples and adapters in a format built for that. ## Run model-written code in an isolated sandbox The base case: hand a session to an agent's tool-calling loop and let it run arbitrary code without touching your own infrastructure. - Canonical example: [Quickstart](/docs/quickstart) - Framework adapters: [Pydantic AI](/docs/integrations/pydantic-ai), [Vercel AI SDK](/docs/integrations/ai-sdk), [LangChain / Deep Agents](/docs/integrations/langchain) — each keeps the model-facing tool surface to bounded exec/file operations by default; session lifecycle administration (pause/resume/checkpoint/expose) is opt-in, not something the model can reach for on its own. - Limits: [Organisation limits](/docs/api/org) - Error recovery: [Errors](/docs/api/errors) - Cleanup: destroy an owned session in a `finally`/`with` block, on both the success and the failure path — see the Quickstart's own header for why that's non-negotiable. ## Keep state across agent turns One session per conversation/thread, persisted by ID so any later turn — same process or a different one — can pick it back up. - Canonical example: `persistent_tool_loop` in [`examples/agent-harness`](https://github.com/inis-run/sdk/tree/main/examples/agent-harness) — a host-side thread-ID-to-session-ID store (never a shared live session object), multiple tool calls in one turn, and a second turn served by a completely separate client proving the filesystem *and* a running background process both persisted. - Session lifecycle background: [Session lifecycle](/docs/session-lifecycle) - Limits: idle timeout / max lifetime knobs, same page - Error recovery: a `session_not_live` on a live-only call usually just means a wake race — see [Errors](/docs/api/errors) and retry - Cleanup: destroy the one session a thread owns when its conversation ends, not on every turn - Don't pre-build a pool of idle live sessions to dodge cold starts — [Production best practices](/docs/production#skip-building-your-own-warm-pool) covers why the platform's own resume tiers already do that job, and what to check before trusting a connection your code held open across a pause ## Explore several branches safely Fork a session once shared setup is done, run different candidates on the independent children, and grade outside the sandbox. - Canonical example: `branch_and_evaluate` in [`examples/agent-harness`](https://github.com/inis-run/sdk/tree/main/examples/agent-harness) — uses the real `fork(count=…)` signature (not an `n=` kwarg, not an iterable result), proves the concurrency claim with a wall-clock check instead of asserting it, and is explicit that the batch-exec helper is sequential server-side, not a parallelism primitive. - Concepts: [Fork](/docs/concepts#fork) - Why fork instead of one ever-growing conversation: forking clones a live session's filesystem to seed N children cheaply, so exploring several candidates costs a fast, warm clone per branch instead of repeating expensive setup or paying for N sessions live from the start. - Limits: a hard, account-independent cap of `count<=16` per fork call (`HardMaxForkCount`), and a lower default per-request cap of `count<=4` (`DefaultMaxForkCount`) unless an account has a raised limit — see the example's own README for how these two are easy to conflate - Error recovery: fork requests fail closed with a specific code per reason (over either count limit vs. an account's live-session concurrency cap) — branch on `code`, not the message - Cleanup: every forked child is its own independent, independently billed session — destroy each one explicitly, not just the parent ## Control or deny egress Lock a session to an explicit domain allowlist, or block outbound network access entirely, per session or per project/org. - Canonical guide: [Networking & egress](/docs/networking) — has real, checked Python/TypeScript/CLI samples already; not duplicated here - Limits: allowlist size cap, same page - Error recovery: [Errors](/docs/api/errors) - Cleanup: n/a — egress policy lives with the session and is torn down with it ## Transfer files and artifacts Get files a session produced out to durable storage with a link that outlives the session, or move files in. - Canonical guide: [Artifacts](/docs/artifacts) — real, checked Python/TypeScript/CLI samples already; not duplicated here - Limits: per-capture size/file-count caps, retention window, same page - Error recovery: a capture can land `failed`; poll and retry - Cleanup: artifacts outlive the session on purpose — delete explicitly when no longer needed, they aren't torn down with it ## Cancel or time out work Bound how long a command can run, or stop something already running. - Canonical example: `error_recovery_and_limits` in [`examples/agent-harness`](https://github.com/inis-run/sdk/tree/main/examples/agent-harness) — `exec(..., timeout_ms=…)` for a hard cap on one command, `kill_process()` for stopping a *named* background job on demand from anywhere. Also documents the real gap: there is no separate primitive to cancel an arbitrary in-flight `exec()` call from a different process — only disconnecting from `exec_stream()` cancels a foreground command, and only from the same calling process. True remote cancellation of an unrelated in-flight request is a real product gap, not a docs gap. - Limits: [Organisation limits](/docs/api/org) - Error recovery: `timed_out` on the result, not an exception — check it - Cleanup: `kill_process` before session teardown for a graceful stop; `destroy()` will SIGKILL everything regardless if you skip it ## Recover from a paused, expired, failed, or capacity-limited session - Canonical example: `error_recovery_and_limits` in [`examples/agent-harness`](https://github.com/inis-run/sdk/tree/main/examples/agent-harness) — branches on `InisError.code`/`.retryable`/`.retry_after` (never message text) for a 404 (gone), a 400 (invalid request, deterministic against the documented hard fork-count cap), and a 429 (capacity-limited, retryable — demonstrated against a scripted error sequence rather than forcing a real account over its limit). A session stuck in `state="failed"` is documented as a pattern (poll, read `status_reason`, recreate) rather than shown live — forcing a real provisioning failure on demand isn't something this example does. - Error codes reference: [Errors](/docs/api/errors) - Session lifecycle background (pause/resume, wake-on-op, hot/warm/cold): [Session lifecycle](/docs/session-lifecycle) - Cleanup: a gone session (404) needs a fresh replacement, not a retry; a retryable error (429/503) is safe to retry with backoff using the server's own `retryable`/`retry_after` signal --- ## Custom agent templates & MCP URL: https://inis.run/docs/mcp-guide This guide walks through creating a customized execution environment for your AI agents. You will set up the environment interactively using the CLI, save it as a reusable template, spawn sessions from it in your TypeScript backend, and connect your agent using the session-scoped MCP server. First, spin up a base session using the `inis` CLI, asking it to keep the session alive when you exit: ```bash # Create a fresh session and enter it interactively inis ssh --keep ``` This boots a clean sandbox and drops you into a shell. Install packages and system dependencies your agent needs: ```bash # (Inside the sandbox) pip install pandas scikit-learn sudo apt-get update && sudo apt-get install -y graphviz exit ``` Note the Session ID from the command output. With `--keep`, the default on-detach policy pauses the session after you exit so you can save it as a template. Save this environment as a reusable template: ```bash inis templates save 9hmquuxiz7qyqdqiwfvep --name data-science --description "Python + Pandas + Graphviz environment" ``` New sessions created with the `data-science` template start from that baseline. See [Templates](/docs/templates). Use the `@inis-run/sdk` TypeScript SDK to create a session from your template, then hand the **SSE** MCP URL to your agent: ```typescript import { Client } from "@inis-run/sdk"; const client = new Client({ token: process.env.INIS_API_KEY }); const session = await client.sessions.create({ template: "data-science", }); // mcp_url from the API is the session base — clients need the /sse path const { mcpUrl } = await session.get(); const sseUrl = mcpUrl.endsWith("/sse") ? mcpUrl : `${mcpUrl}/sse`; await agent.connect({ mcpUrl: sseUrl, headers: { Authorization: `Bearer ${process.env.INIS_API_KEY}`, }, }); ``` Session MCP tools operate on this session (`run_command`, files, expose, checkpoints, …). See [Remote MCP → Session MCP](/docs/integrations/mcp#session-mcp) for the full tool list and limits. To avoid paying for idle compute while the model thinks: ```typescript await session.pause(); ``` When the agent next calls a session tool (`run_command`, files, expose, …), the API resumes the session automatically (wake-on-op). Resume speed depends on whether the paused session is still hot/warm or has gone cold — see [Session lifecycle](/docs/session-lifecycle). --- ## Remote MCP URL: https://inis.run/docs/integrations/mcp inis.run exposes a **hosted remote MCP server** — no local binary, no subprocess. Point your MCP client at our endpoint with your API key and the sandbox tools appear automatically. Transport is **SSE** (not streamable HTTP): connect to `/sse`. ## Org endpoint ``` https://mcp.inis.run/sse ``` Authenticate with your API key: ``` Authorization: Bearer inis_... ``` ## Configure your MCP client ```json { "mcpServers": { "inis": { "url": "https://mcp.inis.run/sse", "headers": { "Authorization": "Bearer inis_..." } } } } ``` ```typescript import { streamText } from "ai"; import { experimental_createMCPClient as createMCPClient } from "ai"; const mcp = await createMCPClient({ transport: { type: "sse", url: "https://mcp.inis.run/sse", headers: { Authorization: `Bearer ${process.env.INIS_API_KEY}` }, }, }); const tools = await mcp.tools(); const result = streamText({ model, tools, maxSteps: 5, // ... }); ``` Works anywhere your agent runs — Vercel, Fly, a container, CI — because nothing needs to be installed on the host. ## Org tools | Group | Tools | |-------|-------| | Execution | `execute_code`, `run_command`, `batch_exec` | | Sessions | `create_session`, `list_sessions`, `get_session`, `destroy_session`, `pause_session`, `resume_session`, `update_session`, `fork_session`, `branch_session` | | Files | `read_file`, `write_file`, `write_files`, `list_files`, `find_files`, `grep_files`, `mkdir`, `remove`, `rename` | | Networking | `expose_port`, `unexpose_port`, `get_egress`, `set_egress` | | Connections | `list_connections`, `revoke_connection` | | Checkpoints | `create_checkpoint`, `list_checkpoints`, `get_checkpoint`, `delete_checkpoint`, `restore_session` | | Artifacts | `capture_artifacts`, `list_session_artifacts`, `get_artifact`, `extend_artifact`, `delete_artifact` | | Templates | `list_templates`, `save_as_template`, `delete_template` | `create_session` also takes an optional `connections` array — the same shape as the HTTP API's `connections[]` field (see [Connections](/docs/connections)) — to attach session-scoped credential leases at create time. `list_connections` and `revoke_connection` are read-only inspection and revoke; there is no rotate/replace tool on either MCP server, org or session — rotating a Connection takes a plaintext secret as input, and an MCP tool call's arguments are typically logged by the client and echoed into the agent's own transcript, which isn't a safe place for a credential to pass through a second time. Rotate from the CLI or console instead, or create a new session with a fresh Connection. ## Session MCP For an agent bound to one session (e.g. after you create from a template), use: ``` https://mcp.inis.run/sessions/{session_id}/sse ``` Same Bearer auth. `session_id` is implicit — tools operate on that session. The API returns `mcp_url` as the **base** (`…/sessions/{id}`); append `/sse` for the client connect URL. **Session tools (20):** `execute_code`, `run_command`, `read_file`, `write_file`, `list_files`, `write_files`, `find_files`, `grep_files`, `mkdir`, `remove`, `rename`, `expose_port`, `unexpose_port`, `get_egress`, `set_egress`, `get_session`, `list_connections`, `revoke_connection`, `create_checkpoint`, `list_checkpoints`. No destroy/pause/resume/fork/artifacts/templates on the session server. `run_command` / files / expose auto-resume a paused session via the normal API wake path. Note: `execute_code` on both org and session MCP is the **stateless-execution** code runner — it does not exec inside the bound session; use `run_command` for that. See [Custom templates & MCP](/docs/mcp-guide) for the create-template → session MCP flow. ## When to use MCP vs SDK | Use remote MCP when… | Use SDK when… | |----------------------|---------------| | Your runtime supports remote MCP (Cursor, Claude Code, AI SDK) | You need fine-grained session control in app code | | You want zero integration code and no local install | You are building a custom agent loop | | Your agent runs in the cloud, not on the user's laptop | You need custom retry / billing hooks | We do not ship a local stdio MCP server. Use the remote MCP endpoint above, or the SDK. --- ## CLI URL: https://inis.run/docs/integrations/cli The `inis` CLI is the fastest way to run sandboxes from a terminal or CI pipeline. It wraps the HTTP API — no SDK required. **Status:** `curl -fsSL https://inis.run/install.sh | bash` ## Install ```bash curl -fsSL https://inis.run/install.sh | bash ``` The installer downloads a static binary for your OS/arch and adds it to your PATH. To pin a version: ```bash curl -fsSL https://inis.run/install.sh | bash -s -- --version cli-v0.1.1 ``` ## Configure ```bash inis auth login ``` Or set `INIS_API_KEY` manually (CI, scripts). Optional override: `INIS_BASE_URL=https://api.inis.run`. ## Commands | Command | Description | |---------|-------------| | `inis run` | Stateless code execution (`--language`, `--file`, `-e`) | | `inis exec` | Run a shell command in a new or existing session — streams by default (`--no-stream`, `--cwd`, `--timeout-ms`) | | `inis ssh` | Interactive shell (`--keep`, `--pick`, `-c`) | | `inis sessions create` | Create a session (`--template`, `--size`, `--on-detach`, `--paused-ttl-ms`, …) | | `inis sessions get/list` | Inspect sessions (`--state`, `--all` for history) | | `inis sessions pause/resume/destroy` | Lifecycle | | `inis sessions expose/unexpose` | Preview URLs (`--port`, `--auth`) | | `inis sessions checkpoint/restore` | Named checkpoints | | `inis sessions egress` | Update egress allow/deny | | `inis sessions create --connection ...` | Bind a [Connection](/docs/connections) at create time (credential brokering) | | `inis connections inspect/rotate/revoke` | Inspect, rotate, or revoke a session's Connections | | `inis fork -n N` | Fork into N children | | `inis checkpoints …` | List/get/delete checkpoints; create session from one | | `inis templates ls/save/import/rm` | Templates | | `inis files read/write/list/mkdir/rm/mv/put/get/…` | Files (also `write-batch`, `find`, `grep`) | | `inis artifacts …` | Captured artifacts | | `inis org` / `registries` / `connectors` / `webhooks` / `domains` | Account & platform helpers | | `inis update` / `version` | CLI self-update / version | Run `inis --help` or `inis --help` for full flags. ## Interactive shell `inis ssh` attaches a raw interactive shell to a session — like `ssh` or `docker exec -it`. It forwards your keyboard, streams output back, tracks window size, and exits with the remote shell's exit code. ```bash inis ssh # create a fresh session, attach, destroy on exit inis ssh --keep # ...but keep it alive after you exit inis ssh 9hmquuxiz7qyqdqiwfvep # attach to an existing session by id inis ssh -c # reattach to your most recent session inis ssh --pick # choose from your live and paused sessions ``` A paused session is **resumed automatically** before attaching, so a session you left days ago picks up where it was. `--template` and `--size` apply only when creating a session. ### Detach vs. exit There are two ways to leave a shell, and they mean different things: - **Exit the shell** (`exit`, or Ctrl-D at an empty prompt) ends the remote shell. For an ad-hoc `inis ssh` (no `--keep`) this **destroys** the session. - **Detach** with the `~.` escape closes the connection but **keeps the session running**, so you can reattach later with `inis ssh -c`. Escape sequences (recognised only at the start of a line): | Escape | Action | |--------|--------| | `~.` | Detach — keep the session running | | `~~` | Send a literal `~` | | `~?` | List the available escapes | ## Examples ```bash # Stateless Python execution inis run --language python -e 'print(sum(range(10)))' # Run a script from disk inis run --language python --file ./analyze.py # Reuse a session across commands SID=$(inis sessions create) inis exec --session "$SID" -- pip install httpx -q inis exec --session "$SID" -- python -c "import httpx; print(httpx.__version__)" inis sessions destroy "$SID" # Pause to free compute, resume later (or just attach — attach auto-resumes) inis sessions pause "$SID" inis sessions resume "$SID" ``` ## Session lifecycle A session outlives any single connection. Detaching or disconnecting never destroys a session on its own — what happens next is governed by its **on-detach policy**, set at creation: ```bash inis sessions create --on-detach pause # default inis sessions create --on-detach keep_live # stay hot for fast reattach inis sessions create --on-detach destroy # tear down on detach ``` | Policy | On detach | |--------|-----------| | `pause` *(default)* | Pause immediately — near-zero cost, warm resume | | `keep_live` | Keep the VM running; auto-pause later on idle timeout | | `destroy` | Tear the session down | Destroyed sessions leave a lightweight **history** row (`inis sessions list --all` / `--state ended`) with an `end_reason`. Paused sessions are kept until you destroy them; cap how long with `--paused-ttl-ms`. States, timers, wake-on-op, and recipes: [Session lifecycle](/docs/session-lifecycle). ## Connections A [Connection](/docs/connections) binds a session to one external API origin with a credential the platform injects on the way out — code in the session calls the provider's real hostname and never holds the key. Set one at create time with a compact spec: ```bash inis sessions create --connection \ 'name=stripe,origin=https://api.stripe.com,auth=bearer,secret=env:STRIPE_KEY,methods=GET|POST,paths=/v1/*,ttl=1h' ``` `--connection` is repeatable (up to 16 per session). Fields: `name`, `origin` (must be `https://`), `auth` (`bearer` or `header:`), `secret`, `methods` (`|`-separated), `paths` (`|`-separated prefixes), and an optional `ttl` (a duration like `1h` or a plain number of seconds — defaults to the session's own lifetime, capped at 24h). For `secret`, prefer `env:VAR_NAME` (reads an environment variable) or `stdin` (reads one line from stdin) over a literal value — a literal works, but shell history keeps plain-text secrets around long after the command exits: ```bash STRIPE_KEY=sk_live_... inis sessions create --connection 'name=stripe,...,secret=env:STRIPE_KEY,...' echo "$STRIPE_KEY" | inis sessions create --connection 'name=stripe,...,secret=stdin,...' ``` Manage Connections already on a session — the CLI has no dedicated list/add endpoints to call yet, so `inspect` reads the same redacted data off `GET /v1/sessions/{id}`: ```bash inis connections inspect "$SID" # every Connection on the session inis connections inspect "$SID" stripe # just this one inis connections rotate "$SID" stripe --connection 'origin=...,auth=bearer,secret=env:NEW_KEY,methods=GET|POST,paths=/v1/*' inis connections revoke "$SID" stripe # fails closed, not open ``` Output is always redacted — no command ever prints a secret value. **The honest limit:** the credential is never in your code, image, or the session's environment, and it's scoped and revocable — but if the bound origin reflects request headers back (a debug/echo endpoint, an error body), code in the session can read it out that way. Prefer a scoped, short-lived upstream credential so a leak like that can do no more than `methods`/`paths` already permitted. Full detail: [Connections](/docs/connections). ## CI Use `INIS_API_KEY` from your CI secret store. The binary is self-contained — no runtime dependencies. ```yaml - run: curl -fsSL https://inis.run/install.sh | bash - run: inis run --language python -e "import sys; sys.exit(0)" env: INIS_API_KEY: ${{ secrets.INIS_API_KEY }} ``` --- ## Python SDK URL: https://inis.run/docs/integrations/python ## Install ```bash pip install inis ``` ## Quick example ```python import inis client = inis.Client(token="inis_...") with client.session() as session: session.exec(["pip", "install", "pandas", "-q"]) session.files.write("/workspace/data.csv", "a,b\n1,2\n") result = session.exec(["python3", "-c", """ import pandas as pd print(pd.read_csv('/workspace/data.csv').sum()) """]) print(result.stdout) preview = session.expose(port=8080) print(preview.preview_url) ``` ## API surface | Method | Description | |--------|-------------| | `Client.session()` | Context manager; creates and destroys a session | | `Client.sessions.create()` / `.attach(id)` / `.list()` / `.get(id)` | Create, reattach, list, inspect | | `session.exec(argv)` | Run a command; returns stdout/stderr/exit_code | | `session.exec_stream(argv)` | SSE stream of stdout/stderr (`data` is already a `str`) | | `session.run_code(code)` / `restart_context()` | Persistent Python interpreter in the session | | `session.read_file(path)` / `write_file` / `list_files` | File I/O (`encoding="base64"` on `read_file` for binary → `bytes`) | | `session.files.read/write/list` | Text-only convenience aliases (no `encoding=` on `files.read`) | | `session.write_files` / `find_files` / `grep_files` | Batch write, glob find, content grep | | `session.mkdir` / `remove` / `rename` | Path ops | | `session.upload_file` / `download_file` | Stream large files | | `session.start_process` / `list_processes` / `get_process` / `kill_process` | Named background processes | | `session.get_process_logs` / `stream_process_logs` | Buffered or live process output | | `session.expose` / `unexpose` | HTTPS preview URLs | | `session.pause` / `resume` / `fork` | Lifecycle | | `session.checkpoint` / `restore` / `checkpoints` | Named checkpoints | | `session.save_as_template` / `client.templates` | Templates | | `client.execute(language=..., code=...)` | Stateless run via `/v1/sessions/exec` | | `session.pty(...)` | Interactive PTY — see below | | `AsyncClient` / `AsyncSession` | Full async twin (`async with`, `await`, `async for`) | `sessions.create` / `Client.session` also take `template`, `size`, `env`, `secrets`, timers, and egress — see [Sessions API](/docs/api/sessions) and [Environment and secrets](/docs/api/sessions#environment-and-secrets). ## Async ```python import asyncio from inis import AsyncClient async def main(): async with AsyncClient(token="inis_...") as client: async with client.session(template="python") as session: result = await session.exec(["python3", "-c", "print(42)"]) print(result.stdout) asyncio.run(main()) ``` ## Streaming exec ```python for event in session.exec_stream(["python3", "-u", "train.py"]): if event.stream in ("stdout", "stderr"): print(event.data, end="") elif event.stream == "exit": print(f"exit={event.exit_code}") ``` ## Code interpreter ```python with client.session(template="python") as session: session.run_code("x = 41") for r in session.run_code("x + 1"): if r.type == "text": print(r.text) # 42 session.restart_context() # clear interpreter globals ``` ## Interactive terminal (PTY) ```python with client.session() as session: with session.pty(cols=80, rows=24) as term: term.write("python3 -c 'print(1 + 1)'\n") for chunk in term: print(chunk.decode(), end="") if b"2\n" in chunk: term.write("exit()\n") print(term.exit_code) ``` Async: `async with await session.pty(...) as term:` and `async for chunk in term`. Pass `command=["python3", "-i"]` for a REPL. `term.resize(cols, rows)` / `term.kill()` as needed. **Embedding a terminal in your own product.** The SDK authenticates with your `INIS_API_KEY` on the WebSocket — never send that key to a browser. Proxy PTY frames through your backend (same pattern as the console). ## Configuration ```python client = inis.Client( token="inis_...", base_url="https://api.inis.run", # default timeout=120.0, # seconds ) ``` Environment variables: `INIS_API_KEY`, `INIS_BASE_URL`. --- ## TypeScript SDK URL: https://inis.run/docs/integrations/typescript ## Install ```bash npm install @inis-run/sdk ``` ## Quick example ```typescript import { Client } from "@inis-run/sdk"; const client = new Client({ token: process.env.INIS_API_KEY! }); const session = await client.sessions.create(); try { const result = await session.exec(["bash", "-c", "echo hello"]); console.log(result.stdout); await session.writeFile("/workspace/script.py", "print('hello')"); await session.exec(["python3", "/workspace/script.py"]); const { previewUrl } = await session.expose(8080); console.log(previewUrl); } finally { await session.destroy(); } ``` Prefer `await using session = await client.sessions.create()` where your runtime supports `Symbol.asyncDispose` (destroys on scope exit). ## API surface | Method | Description | |--------|-------------| | `client.sessions.create()` / `.attach(id)` / `.list()` / `.get(id)` | Create, reattach, list, inspect | | `session.exec(argv)` | Run a command | | `session.execStream(argv)` | SSE stream of stdout/stderr | | `session.runCode(code)` / `restartContext()` | Persistent Python interpreter | | `session.readFile` / `writeFile` / `listFiles` | File I/O (`encoding: "base64"` for binary) | | `session.files.read/write/list` | Text-only convenience aliases | | `session.writeFiles` / `findFiles` / `grepFiles` | Batch write, glob find, content grep | | `session.mkdir` / `remove` / `rename` / `uploadFile` / `downloadFile` | Path ops and large-file streams | | `session.startProcess` / `listProcesses` / `getProcess` / `killProcess` | Named background processes | | `session.getProcessLogs` / `streamProcessLogs` | Buffered or live process output | | `session.expose` / `unexpose` | HTTPS preview URLs | | `session.pause` / `resume` / `fork` | Lifecycle | | `session.checkpoint` / `restore` / `checkpoints` | Named checkpoints | | `session.saveAsTemplate` / `client.templates` | Templates | | `client.execute({ language, code })` | Stateless run via `/v1/sessions/exec` | | `session.pty({ cols, rows, command? })` | Interactive PTY — see below | `sessions.create` also takes `template`, `size`, `env`, `secrets`, timers, and egress — see [Sessions API](/docs/api/sessions). ```typescript const client = new Client({ token: process.env.INIS_API_KEY, baseUrl: "https://api.inis.run", timeoutMs: 120_000, }); ``` Common response types are exported from `@inis-run/sdk`. Node 18+; **no browser bundle** — keep API keys server-side. ## Streaming exec ```typescript for await (const chunk of session.execStream(["python3", "-u", "train.py"])) { if (chunk.stream === "stdout") process.stdout.write(chunk.data); else if (chunk.stream === "exit") console.log(`exit code: ${chunk.exitCode}`); } ``` ## Interactive terminal (PTY) ```typescript const term = await session.pty({ cols: 80, rows: 24 }); try { await term.write("python3 -c 'print(1 + 1)'\n"); for await (const chunk of term) { process.stdout.write(chunk); if (Buffer.from(chunk).includes("2\n")) { await term.write("exit()\n"); } } console.log(term.exitCode); } finally { await term.close(); } ``` Pass `command: ["python3", "-i"]` for a REPL. `term.resize` / `term.kill` as needed. **Embedding a terminal in your own product.** Authenticate with your `INIS_API_KEY` server-side and proxy frames to the browser — never put the key in client code (browsers also cannot set `Authorization` on `WebSocket`). --- ## Vercel AI SDK URL: https://inis.run/docs/integrations/ai-sdk Vercel's [AI SDK](https://sdk.vercel.ai) does not ship a first-party inis plugin — and it does not need one. The pattern (same as E2B) is a small helper package that exports `tool()` definitions wired to the inis SDK. **Beta.** Supported AI SDK range: `ai@^5.0.0` — tested against v5. Newer majors exist and are not yet validated. ## Install ```bash npm install @inis-run/ai-sdk @inis-run/sdk ai zod ``` ## Usage ```typescript import { anthropic } from "@ai-sdk/anthropic"; import { generateText, stepCountIs } from "ai"; import { Client } from "@inis-run/sdk"; import { inisTools } from "@inis-run/ai-sdk"; // Create a persistent session first — tools do not auto-create one const client = new Client({ token: process.env.INIS_API_KEY }); const session = await client.sessions.create({ egress: { mode: "deny" } }); try { const result = await generateText({ model: anthropic("claude-sonnet-4-20250514"), system: "You are a data analyst. Run Python in the sandbox instead of guessing.", messages, tools: inisTools({ sessionId: session.sessionId }), stopWhen: stepCountIs(5), }); console.log(result.text); } finally { await session.destroy(); // this app owns the session } ``` To reuse the same sandbox across turns/requests, persist `session.sessionId` yourself and pass it back into `inisTools({ sessionId })` on the next request — there is no shared mutable ref object to pass around instead. ## What `inisTools()` exports | Tool | Description | |------|-------------| | `execute_python` | Run Python in the sandbox. Throws on non-zero exit. | | `execute_shell` | Run an arbitrary shell command. Throws on non-zero exit. | | `read_file` / `write_file` | File I/O under `/workspace` | | `list_files` | List a directory (defaults to `/workspace`) | This is deliberately the smallest execution/file surface. `sessionId` is required — `inisTools()` only ever attaches to a session your app created, never creates or destroys one itself. Session administration (`pause`, `resume`, `checkpoint`, `restore`, `expose_port`, `capture_artifacts`) and unbounded stateless-execution sandbox creation (`execute_once`) are opt-in from `@inis-run/ai-sdk/lifecycle` — add them only if your app wants the model to have that control. If you want the tools package to create the session for you, use `createOwnedInisTools()`, which returns the tools plus the new session's ID and a `cleanup()` that destroys it. ## MCP alternative If your stack already uses remote MCP, connect to [`https://mcp.inis.run/sse`](/docs/integrations/mcp) via the AI SDK MCP client — no tool definitions in your app code. Use `@inis-run/ai-sdk` when you want in-process tools in a Next.js or Node service. --- ## Pydantic AI URL: https://inis.run/docs/integrations/pydantic-ai [Pydantic AI](https://ai.pydantic.dev) is the recommended Python agent framework for new projects. The inis integration wraps the [Python SDK](/docs/integrations/python) as a ready-made toolset — persistent session, shell, files, and code execution. **Beta.** Supported Pydantic AI range: `>=1.71,<3` (1.71 is the first release with the `capabilities` API). CI tests against the newest match, currently 2.x; earlier 1.x is supported but not exercised in CI. ## Install ```bash pip install inis-pydantic-ai ``` ## Usage ```python import asyncio from inis import AsyncClient from inis_pydantic_ai import inis_toolset from pydantic_ai import Agent async def main() -> None: # Create a persistent session first — the toolset never creates one client = AsyncClient() session = await client.sessions.create(egress_default="deny") toolset = inis_toolset(session_id=session.session_id) agent = Agent( "openai:gpt-4o", toolsets=[toolset], system_prompt="Run Python in the sandbox instead of guessing.", ) try: result = await agent.run("Plot a histogram of [1, 2, 2, 3, 3, 3, 4] with matplotlib") print(result.output) finally: await toolset.aclose() await session.destroy() # this app owns the session asyncio.run(main()) ``` ## What `inis_toolset()` provides | Tool | Description | |------|-------------| | `execute_python` | Run Python in the sandbox. Raises on non-zero exit. | | `execute_shell` | Run a shell command in the persistent session. Raises on non-zero exit. | | `read_file` / `write_file` | File I/O under `/workspace` | | `list_files` | List a directory (defaults to `/workspace`) | The toolset holds a **persistent session** for the whole conversation — multiple tool calls, and multiple `agent.run()` calls, share state. `session_id` is required; the toolset only ever attaches, never creates or destroys a session. This is deliberately the smallest execution/file surface. Session administration (`pause`, `resume`, `checkpoint`, `restore`, `expose_port`, `capture_artifacts`) and unbounded stateless-execution sandbox creation (`execute_once`) are opt-in from `inis_pydantic_ai.lifecycle` — add them to `toolsets=[...]` only if your app wants the model to have that control. For a capability-based alternative that follows the current pydantic-ai-harness sandbox contract (`run_command`, `read_file`, `write_file`, `list_directory`), see `InisSandbox` in `inis_pydantic_ai.sandbox` — same attach-only session rule, registered via `Agent(capabilities=[...])` instead of `toolsets=[...]`. ## Configuration ```python inis_toolset( session_id="9hmquuxiz7qyqdqiwfvep", # required api_key="inis_...", # or $INIS_API_KEY base_url="https://api.inis.run", ) ``` ## vs LangChain | Pydantic AI | LangChain | |-------------|-----------| | Typed tools, minimal boilerplate | Larger ecosystem, LangGraph for graphs | | Best for new Python agent apps | Best if you are already on LangChain | Both wrap the same Python SDK. Pick one — or use [remote MCP](/docs/integrations/mcp) and skip framework glue entirely. --- ## LangChain URL: https://inis.run/docs/integrations/langchain `langchain-inis` is a native backend for [LangChain Deep Agents](https://docs.langchain.com/oss/python/deepagents/overview) — it implements `deepagents.backends.sandbox.BaseSandbox` directly, so `create_deep_agent(backend=...)` is the whole integration. For teams not using Deep Agents, the same package ships a lower-level LangGraph recipe. **Beta.** Verified against `deepagents==0.7.1` — pin `langchain-inis` and re-check before assuming it tracks a later `deepagents` major without changes. ## Install ```bash pip install langchain-inis deepagents ``` ## Usage ```python from inis import Client from deepagents import create_deep_agent from langchain_inis import InisSandboxBackend backend = InisSandboxBackend.create() # owned: this app destroys it try: agent = create_deep_agent(model="anthropic:claude-sonnet-5", backend=backend) result = agent.invoke({"messages": [{"role": "user", "content": "List /workspace, then write hello.txt"}]}) print(result["messages"][-1].content) finally: backend.destroy() ``` No custom lifecycle tools in the model prompt — passing `backend=backend` is the whole integration. Deep Agents auto-registers `ls`/`read_file`/`write_file`/`edit_file`/`glob`/`grep` and `execute` against it, all bounded to the sandbox. ## Owned vs. attached - **`InisSandboxBackend.create(...)`** — a brand-new session this app owns and must `backend.destroy()` when done. - **`InisSandboxBackend.attach(session_id, ...)`** — binds to a session this app does not own. Never destroys it; call `backend.close()` when done, which only releases the backend's local HTTP transport. ```python backend = InisSandboxBackend.attach(existing_session_id) try: agent = create_deep_agent(model=..., backend=backend) ... finally: backend.close() # local transport only — the session is not this app's to destroy ``` One agent thread/conversation should map to one session — resolve `session_id` per thread using whatever key your app already tracks conversations by. ## What it does - `execute`/`aexecute` (shell) - `upload_files`/`download_files` (+ async) — base64 for binary - Every derived file op (`ls`/`read`/`write`/`edit`/`grep`/`glob`/`delete`) — `BaseSandbox`'s own defaults, unmodified - Owned/attached lifetime split — see above - Structured error mapping — `InisError.code` mapped onto `FileOperationError` literals where it matches ## Notes True remote cancellation of an in-flight `execute()` is not implemented — `BaseSandbox.execute(command, timeout=...)` is timeout-only, with no abort hook. A `timeout` still ends the call. Streaming output is not implemented either. `enable_capture_offload` is forced `False`: Deep Agents' automatic eviction of oversized tool results needs to write to a directory outside `/workspace`, which a non-root inis.run session can't do. Nothing is silently dropped — the practical ceiling is inis.run's own guest-side capture cap (up to 4 MiB per stream). Bound noisy commands yourself (`head -c`/`tail -c`, or write to a file and read back a slice). `ExecuteResponse.truncated` is set directly from inis.run's own per-stream truncation signal. ## LangGraph recipe (lower-level, secondary path) For teams not using Deep Agents, [`examples/langgraph_recipe.py`](https://github.com/inis-run/sdk/blob/main/langchain-inis/examples/langgraph_recipe.py) is a complete, runnable example using plain LangGraph primitives (`@tool`, `ToolNode`, `StateGraph`): one session per graph thread ID, a bounded tool surface, and a small file-backed session store demonstrating a session ID surviving a process restart. ```bash python examples/langgraph_recipe.py # creates (or reattaches to) demo-thread-1 python examples/langgraph_recipe.py --end # ... and cleans it up ``` ## TypeScript / LangChain.js No dedicated `langchain-inis` JS package — use the [TypeScript SDK](/docs/integrations/typescript) directly, or the [AI SDK helper](/docs/integrations/ai-sdk) if the app already runs on Vercel AI SDK. The surface is thin enough to inline as a LangChain.js `Tool`. ## vs Pydantic AI | LangChain / Deep Agents | Pydantic AI | |--------------------------|--------------| | Larger ecosystem, LangGraph for lower-level graphs | Typed tools, minimal boilerplate | | Best if you're already on LangChain/Deep Agents | Best for new Python agent apps | Both wrap the same Python SDK. Pick one — or use [remote MCP](/docs/integrations/mcp) and skip framework glue entirely. --- ## OpenAI Agents SDK URL: https://inis.run/docs/integrations/openai-agents Native inis.run sandbox providers for the OpenAI Agents SDK's `SandboxAgent` path — [`agents.sandbox`](https://openai.github.io/openai-agents-python/) in Python, [`@openai/agents-core/sandbox`](https://openai.github.io/openai-agents-js/) in TypeScript. **Beta, upstream and here.** The Agents SDK documents its own sandbox surface as beta. Verified against `openai-agents==0.19.1` (Python) and `@openai/agents-core==0.14.1`/`@openai/agents==0.14.1` (TypeScript). ## Install ```bash pip install inis-openai-agents # Python npm install @inis-run/openai-agents # TypeScript / Node ``` ## Quickstart: attached (recommended) One inis.run session for the whole conversation, owned by your app. ```python from inis import AsyncClient from agents import Runner, RunConfig from agents.run_config import SandboxRunConfig from agents.sandbox import SandboxAgent from inis_openai_agents import InisSandboxSession client = AsyncClient() inis_session = await client.sessions.create(egress_default="deny") sandbox_session = InisSandboxSession.wrap(inis_session) agent = SandboxAgent(name="assistant", model="gpt-5.1") run_config = RunConfig(sandbox=SandboxRunConfig(session=sandbox_session)) try: result = await Runner.run(agent, "list files in /workspace", run_config=run_config) result2 = await Runner.run(agent, "now write hello.txt", run_config=run_config) finally: await inis_session.destroy() # this app owns the session; the SDK never will ``` ```typescript import { Client } from "@inis-run/sdk"; import { run } from "@openai/agents"; import { SandboxAgent } from "@openai/agents-core/sandbox"; import { InisSandboxSession } from "@inis-run/openai-agents"; const client = new Client(); const inisSession = await client.sessions.create({ egress: { mode: "deny" } }); const sandboxSession = InisSandboxSession.wrap(inisSession); const agent = new SandboxAgent({ name: "assistant", model: "gpt-5.1" }); try { const result = await run(agent, "list files in /workspace", { sandbox: { session: sandboxSession }, }); } finally { await inisSession.destroy(); // this app owns the session; the SDK never will } ``` The Agents SDK's own sandbox runtime never destroys a session passed via `sandbox.session` — that lifecycle stays entirely host-controlled: one persistent session across a whole conversation, not one sandbox per model turn. ## Owned: one run at a time The SDK can also create and destroy a fresh session for a single `Runner.run()`/`run()` call: ```python from agents.run_config import SandboxRunConfig from inis_openai_agents import InisSandboxClient, InisSandboxClientOptions run_config = RunConfig( sandbox=SandboxRunConfig( client=InisSandboxClient(), options=InisSandboxClientOptions(egress_default="deny"), ) ) result = await Runner.run(agent, "...", run_config=run_config) ``` To resume a conversation in a later process, pass `result._sandbox_resume_state` back in — the SDK creates a *new* session and restores the workspace from a tar snapshot; it does not reattach to the original session ID. Prefer the attached path above for a real multi-turn agent. ```typescript import { InisSandboxClient, InisSandboxClientOptions } from "@inis-run/openai-agents"; const result = await run(agent, "...", { sandbox: { client: new InisSandboxClient(), options: { egressDefault: "deny" } satisfies InisSandboxClientOptions, }, }); ``` `InisSandboxClientOptions` also accepts `connections` — inline [Connections](/docs/networking) to create alongside the session. ## What it does - `exec`/`execCommand` (shell), with a real interactive PTY (`tty: true`) and `writeStdin` for a running session - File read/write, symlink-safe path validation (Python); `readFile` and plain `file`/`dir` manifest entries (TypeScript) - Exposed ports, via `session.expose()` - Owned/attached lifetime split — see above - Snapshot persist/hydrate (owned path's resume) — tar+base64 over `exec()` ## Notes Docker-volume-mount manifests are not implemented (`supports_docker_volume_mounts()` stays `False` in Python; nested `Dir`/`local_file`/`local_dir`/`git_repo` manifest entries throw in TypeScript). True remote cancellation of an in-flight command is not implemented in either language — the sandbox contract is timeout-only, with no abort handle to route through. `InisSandboxSession.exec()` returns a result type extending upstream's own with one added field, `truncated` — set directly from inis.run's own per-stream capture-limit signal (never derived from stream content, so it can't be spoofed by a guest command printing fake marker text). ## Fallback: plain function tools Not using `SandboxAgent`? Use an ordinary `Agent` with function tools against the [Python](/docs/integrations/python) or [TypeScript](/docs/integrations/typescript) SDK directly. --- ## Strands Agents URL: https://inis.run/docs/integrations/strands-agents Native inis.run sandbox providers for [Strands Agents](https://strandsagents.com)' `Sandbox` surface — gives Strands its standard `sandbox_bash` and `sandbox_file_editor` tools backed by a real, isolated inis.run session instead of the local host. Verified against `strands-agents==1.50.2` (Python) and `@strands-agents/sdk==1.11.2` (TypeScript). ## Install ```bash pip install inis-strands-agents # Python npm install @inis-run/strands-agents @strands-agents/sdk @inis-run/sdk # TypeScript / Node ``` ## Quickstart: attached (recommended) One inis.run session for the whole conversation, owned by your app. ```python from inis import AsyncClient from strands import Agent from inis_strands_agents import InisSandbox client = AsyncClient() session = await client.sessions.create(egress_default="deny") sandbox = InisSandbox.wrap(session) agent = Agent(model="...", sandbox=sandbox) await agent.invoke_async("list files in /workspace") await agent.invoke_async("now write hello.txt") await session.destroy() # this app owns the session; the adapter never will ``` ```typescript import { Client } from "@inis-run/sdk"; import { Agent } from "@strands-agents/sdk"; import { InisSandbox } from "@inis-run/strands-agents"; const client = new Client(); const session = await client.sessions.create({ egress: { mode: "deny" } }); const sandbox = InisSandbox.wrap(session); const agent = new Agent({ model, sandbox }); await agent.invoke("list files in /workspace"); await agent.invoke("now write hello.txt"); await session.destroy(); // this app owns the session; the adapter never will ``` ## Owned: the adapter creates and destroys the session for you ```python from strands import Agent from inis_strands_agents import InisSandbox async with await InisSandbox.create(egress_default="deny") as sandbox: agent = Agent(model="...", sandbox=sandbox) await agent.invoke_async("...") # session destroyed on exit ``` ```typescript import { Agent } from "@strands-agents/sdk"; import { InisSandbox } from "@inis-run/strands-agents"; const sandbox = await InisSandbox.create(undefined, { egress: { mode: "deny" } }); try { const agent = new Agent({ model, sandbox }); await agent.invoke("..."); } finally { await sandbox.close(); } ``` `InisSandbox.create()`'s options also accept `connections` — inline [Connections](/docs/networking) to create alongside the session. Either way, `Agent({ sandbox })` registers `sandbox_bash` and `sandbox_file_editor` automatically — no separate tool wiring needed. Session create/destroy, egress, pause/resume, and fork stay host-controlled. ## What it does - Streaming shell execution — distinct stdout/stderr chunks, then a final result - Binary-safe file read/write/remove/list, routed to inis.run's native `/files` endpoints - Per-call `timeout` — genuinely kills the remote process on expiry - Per-call `env` — via a validated shell-export prefix (inis.run's exec API fixes env at session creation) - Cancellation: Python `asyncio` task cancellation preempts a running command outright; TypeScript `AbortSignal` can only preempt at a chunk boundary (`Session.execStream` has no cancellation parameter of its own) — a real, tested asymmetry between the two packages, not a bug in one of them. ## Notes PTY isn't implemented in either language: the `Sandbox`/`PosixShellSandbox` shell/file contract has no PTY concept to hook into. Output-file collection is always empty, same as every other shell-based `Sandbox` — read a produced file back explicitly instead. --- ## Mastra URL: https://inis.run/docs/integrations/mastra `@inis-run/mastra` is a native sandbox provider for [Mastra](https://mastra.ai) `Workspace` — it implements the `WorkspaceSandbox` contract from `@mastra/core/workspace`, backed by a real, isolated inis.run session instead of a local process. **Beta.** Verified against `@mastra/core==1.55.0`. ## Install ```bash npm install @inis-run/mastra @mastra/core @inis-run/sdk ``` ## Quickstart: attached (recommended) One inis.run session for a whole conversation, owned by your app: ```typescript import { Client } from "@inis-run/sdk"; import { Workspace } from "@mastra/core/workspace"; import { InisSandbox } from "@inis-run/mastra"; const client = new Client(); const session = await client.sessions.create({ egress: { mode: "deny" } }); const workspace = new Workspace({ sandbox: new InisSandbox({ session }) }); try { const result = await workspace.sandbox?.executeCommand?.("ls /workspace"); } finally { await session.destroy(); // this app owns the session; InisSandbox never will } ``` `InisSandbox` never destroys, pauses, or resumes a session passed this way. Reattach later with the session ID: ```typescript const sandbox = new InisSandbox({ session: existingSessionId, client }); ``` ## Owned: the sandbox manages its own session ```typescript const workspace = new Workspace({ sandbox: new InisSandbox({ egressDefault: "deny" }), }); await workspace.sandbox?.executeCommand?.("ls /workspace"); // creates the session lazily await workspace.destroy(); // destroys it ``` `stop()`/`start()` pause and resume the real session (VM, filesystem, and background processes freeze in place and thaw exactly where they left off) rather than recreating it. `clone()` builds an independent owned sibling. Owned-mode options also accept `connections` — inline [Connections](/docs/networking) to create alongside the session; `getInfo()` echoes each session's redacted connections (name, origin, state, allow rules — never the secret) under `metadata.connections`. ## What it does - `executeCommand` (foreground) - Background processes: `spawn`/`list`/`get`/`kill` - Remote cancellation (`abortSignal`, timeout) — genuine `SIGTERM`→`SIGKILL` server-side - Output streaming (`onStdout`/`onStderr`) — a live log follow, not polling - Bulk file write (`writeFiles`) - Exposed ports (`networking.getPortUrl`), via `session.expose()` - `session` accessor (pause/resume/fork/checkpoint/expose/files) — host-side only, never a model tool ## Notes `ProcessHandle.sendStdin` is not implemented — no stdin-write endpoint for a named background process. `mount`/`unmount` are not supported: both throw `MountNotSupportedError` rather than silently no-op'ing; inis.run has no FUSE-style mount primitive. One known platform-level rough edge, not papered over by this adapter: `killProcess` can report `true` for a process that was already exiting on its own. --- ## Google ADK URL: https://inis.run/docs/integrations/google-adk `inis-google-adk` is a native inis.run environment provider for [Google Agent Development Kit (ADK)](https://google.github.io/adk-docs/)'s `BaseEnvironment`/`EnvironmentToolset` surface — gives ADK's `Execute`/`ReadFile`/`EditFile`/`WriteFile` tools a real, isolated inis.run session instead of a local subprocess. **Experimental, upstream.** `BaseEnvironment`/`EnvironmentToolset` are decorated `@experimental` in ADK's own source — ADK ships two other in-tree providers against the same contract. Verified against `google-adk==2.6.0`. Neither class is re-exported from the `google.adk` top level; import from `google.adk.environment` / `google.adk.tools.environment` directly. ## Install ```bash pip install inis-google-adk ``` ## Quickstart: attached (recommended) One inis.run session for the whole conversation, owned by your app: ```python from inis import AsyncClient from google.adk.agents import Agent from google.adk.tools.environment import EnvironmentToolset from inis_google_adk import InisEnvironment client = AsyncClient() session = await client.sessions.create(egress_default="deny") environment = InisEnvironment.wrap(session) agent = Agent(model="...", tools=[EnvironmentToolset(environment=environment)]) ... await session.destroy() # this app owns the session; the environment never will ``` Reconnect a later process to the same session (and its persistent `/workspace` filesystem) by session ID alone: ```python environment = InisEnvironment.attach("9hmquuxiz7qyqdqiwfvep") ``` ## Owned: the environment creates and destroys the session for you ```python from inis_google_adk import InisEnvironment environment = InisEnvironment(egress_default="deny") toolset = EnvironmentToolset(environment=environment) try: agent = Agent(model="...", tools=[toolset]) ... finally: await toolset.close() # calls environment.close(), which destroys the session ``` ## Explicit fallback: plain function tools If you'd rather not depend on ADK's experimental surface at all, `inis_adk_tools()` returns ordinary `FunctionTool`s wrapping the same session directly — a smaller, stable surface (`execute`, `read_file`, `write_file`, `list_files`; nothing that creates, destroys, or administers the session): ```python from google.adk.agents import Agent from inis_google_adk import inis_adk_tools agent = Agent(model="...", tools=inis_adk_tools(session)) ``` ## What it does - `execute` (shell) — real stdout/stderr/exit_code/timed_out - `read_file`/`write_file` — a missing file raises `FileNotFoundError` - `EditFile` — built entirely on `read_file`/`write_file` - Owned/attached lifecycle split — `InisEnvironment()` owns; `.wrap()`/`.attach()` never do - `close()` idempotency — safe to call more than once in either mode - Non-experimental fallback (`inis_adk_tools()`) ## Notes TypeScript, Java, and Go support isn't claimed: this package wraps the Python `inis` SDK and Python `google-adk` only. True remote cancellation of an in-flight `execute()` call is not implemented — timeout-only; a timeout still ends the call. `InisEnvironment.execute()` returns a result type with one field added over upstream's own, `truncated` — set directly from inis.run's own per-stream capture-limit signal. `inis_adk_tools()`'s `execute` returns one plain string with no structured result to carry the same field, so truncation there stays an inline `[inis: output truncated by the sandbox's own capture limit]` marker instead. --- ## Microsoft Agent Framework URL: https://inis.run/docs/integrations/agent-framework `inis-agent-framework` is a native inis.run CodeAct provider for [Microsoft Agent Framework](https://github.com/microsoft/agent-framework) (`agent_framework.ContextProvider`) — gives an `Agent` a real, isolated `execute_code` tool backed by inis.run's persistent Python interpreter. **CodeAct providers are a young, beta convention upstream.** `agent-framework-core` itself is stable; Microsoft's own first-party CodeAct backends (`agent-framework-monty`, `agent-framework-hyperlight`) are each beta. Verified against `agent-framework-core==1.13.0`. Python only — no .NET package. ## Install ```bash pip install inis-agent-framework ``` ## Quickstart: attached (recommended) One inis.run session for the whole conversation, owned by your app: ```python from inis import AsyncClient from agent_framework import Agent from inis_agent_framework import InisCodeActProvider client = AsyncClient() session = await client.sessions.create(egress_default="deny") codeact = InisCodeActProvider.wrap(session) agent = Agent(client=chat_client, name="assistant", context_providers=[codeact]) await agent.run("Use execute_code to compute 6 * 7.") await session.destroy() # this app owns the session; the provider never will ``` Reconnect a later process to the same persistent interpreter context by session ID alone — no snapshot, no workspace round-trip: ```python codeact = InisCodeActProvider.attach("9hmquuxiz7qyqdqiwfvep") agent = Agent(client=chat_client, context_providers=[codeact]) await agent.run("What was x again?") # sees state from the earlier process ``` ## Owned: the provider creates and destroys the session for you ```python from inis_agent_framework import InisCodeActProvider codeact = await InisCodeActProvider.create(egress_default="deny") try: agent = Agent(client=chat_client, context_providers=[codeact]) await agent.run("...") finally: await codeact.aclose() # destroys the session ``` Either way, only `execute_code` is model-visible. ## Persistent interpreter state, not a fresh one per call `execute_code` runs through a real persistent Python process inside the session: a variable set in one call is still there in the next one, across separate tool calls *and* separate `agent.run()` invocations against the same session, until `restart_context()` is called or the session is torn down. ## What it does - `execute_code` (persistent Python interpreter) — text/image/table/json/error results mapped to `agent_framework.Content` - Interpreter state across calls and `agent.run()` invocations — `.attach()` resumes the same context - `restart_context()` — discards the interpreter context without touching the session's filesystem or lifecycle - Owned/attached lifecycle split — `.create()` owns and destroys; `.wrap()`/`.attach()` never do ## Notes `call_tool` bridging to host-registered tools is not implemented, deliberately: inis.run's `execute_code` runs in a real remote VM with no channel for the guest to call an arbitrary host function mid-cell — that would let sandboxed code call any tool the agent has, unbounded. Host-directory binding (`workspace_root`/`file_mounts`) is not implemented either — an inis.run session runs on separate hardware; use `session.read_file()`/`write_file()` directly instead. True remote cancellation of an in-flight `execute_code` call is not implemented — timeout-only; a timeout still ends the call and the interpreter context stays usable afterward. --- ## API overview URL: https://inis.run/docs/api/overview The execution API is versioned under `/v1`. All endpoints accept JSON and require [bearer authentication](/docs/authentication). **Base URL:** `https://api.inis.run` Each endpoint in the reference shows the HTTP method, path, request body, and response shape. For interactive exploration, use the [OpenAPI spec](/docs/openapi.yaml) or the [CLI](/docs/integrations/cli). ## Endpoints | Method | Path | Description | |--------|------|-------------| | POST | `/v1/sessions/exec` | Stateless run in a throwaway session | | GET | `/v1/sessions` | List sessions | | POST | `/v1/sessions` | Create session | | GET | `/v1/sessions/{id}` | Get session | | DELETE | `/v1/sessions/{id}` | Destroy session | | POST | `/v1/sessions/{id}/exec` | Run command | | POST | `/v1/sessions/{id}/processes` | Start a named background process | | GET | `/v1/sessions/{id}/processes` | List named background processes | | GET/DELETE | `/v1/sessions/{id}/processes/{name}` | Get / kill a named background process | | GET | `/v1/sessions/{id}/processes/{name}/logs` | Process output — buffered, or `?follow=true` for SSE | | GET | `/v1/sessions/{id}/files` | Read a file, list a directory, or `?op=find`/`?op=grep` | | PUT | `/v1/sessions/{id}/files` | Write a file | | PUT | `/v1/sessions/{id}/files/batch` | Write several small files in one call | | GET | `/v1/sessions/{id}/pty` | Interactive terminal (WebSocket) | | GET | `/v1/sessions/{id}/tunnel` | SSH tunnel (WebSocket) | | POST | `/v1/sessions/{id}/expose` | Preview URL | | POST | `/v1/sessions/{id}/unexpose` | Remove exposed port | | GET/POST | `/v1/sessions/{id}/egress` | Read / set the egress policy | | POST | `/v1/sessions/{id}/fork` | Fork into N children | | POST | `/v1/sessions/{id}/pause` | Pause session | | POST | `/v1/sessions/{id}/resume` | Resume session | | POST / GET | `/v1/sessions/{id}/checkpoints` | Create / list checkpoints | | POST | `/v1/sessions/{id}/restore` | Roll back to a checkpoint in place | | POST / GET | `/v1/sessions/{id}/artifacts` | Capture / list artifacts | | GET | `/v1/templates` | List available templates | | POST | `/v1/sessions/{id}/templates` | Save a session as a template | | POST | `/v1/sessions/batch/exec` | Fan-out command | | GET | `/v1/org` | Account capacity and limits | | GET | `/v1/healthz` | Node health (no auth) | Detail: [Stateless execution](/docs/api/execute) · [Sessions](/docs/api/sessions) · [Organisation](/docs/api/org) · [Errors](/docs/api/errors) · [Networking & egress](/docs/networking) · [Execution log](/docs/execution-log) · [Artifacts](/docs/artifacts) · [Templates](/docs/templates) Account management (API keys, usage, billing) lives on the control plane at **`https://app.inis.run/v1/*`** — separate from execution. That's also where `GET /v1/audit/events` lives — see [Execution log](/docs/execution-log). ## Session sizes Set the size on session create with three fields: | Field | Range | Default | |---|---|---| | `vcpus` | `1`, `2`, `4`, `8` | required with `mem_mb` | | `mem_mb` | 1 to 4 GB per vCPU, in 1 GB steps, at most 32 GB (`32768`) | required with `vcpus` | | `disk_gb` | 8 to 256; needs `vcpus` and `mem_mb`; not allowed with `volume_id` | 16 | Billing is exact, with no size buckets: €0.002 per vCPU-hour and €0.0065 per GB-hour of RAM while awake, and, for a session without a volume, €0.04 per GB-month of `disk_gb` for the session's whole life, awake or paused. A session with a volume bills the volume instead. Omitting `vcpus`, `mem_mb` and `disk_gb` creates the server's default fixed size, which bills storage differently: paused storage at €0.03 per GiB-month of stored bytes, and the live workspace at the volume rate. Examples and a calculator are on [pricing](https://inis.run/pricing). A fork of a flexible-size session returns `409` for now. The older `size` field is a deprecated alias; new code should not use it. ## OpenAPI The full schema is available as [openapi.yaml](/docs/openapi.yaml). New to the primitives? Start with [Concepts](/docs/concepts). --- ## Sessions URL: https://inis.run/docs/api/sessions Sessions are the primary primitive for agents. Create once, call exec/files/expose many times, destroy when done. All requests require `Authorization: Bearer inis_...` and `Content-Type: application/json`. Path parameter `{id}` is the session ID. Prefer the [CLI](/docs/integrations/cli) (`inis sessions`, `inis exec --session`) or an [SDK](/docs/integrations/python) for day-to-day use. ## Create Optionally set an `Idempotency-Key` header to make the create retry-safe — see [Idempotent retries](#idempotent-retries) below. **Request body** ```json { "vcpus": 2, "mem_mb": 4096, "disk_gb": 16, "max_lifetime_ms": 3600000, "idle_timeout_ms": 300000, "on_pty_detach": "pause", "paused_ttl_ms": 86400000, "egress": { "mode": "deny", "allow": ["api.openai.com"] } } ``` | Field | Required | Description | |-------|----------|-------------| | `vcpus` | no | `1`, `2`, `4` or `8`. Send with `mem_mb`; one without the other is a `400`. Billed per vCPU-hour. See [Session sizes](/docs/api/overview#session-sizes) | | `mem_mb` | no | RAM in whole GB (multiples of 1024), from 1 GB to 4 GB per vCPU, at most `32768`. Send with `vcpus`. Billed per GB-hour | | `disk_gb` | no | Provisioned disk, `8` to `256`; default `16` when `vcpus` and `mem_mb` are sent. Needs `vcpus` and `mem_mb` (alone it is a `400`), and is not allowed with `volume_id` (the volume is the disk). Billed per GB-month from create to delete, awake or paused | | `size` | no | Deprecated alias for a fixed `vcpus` / `mem_mb` bundle. Use `vcpus`, `mem_mb` and `disk_gb` instead. Cannot be combined with them. Omitting `size`, `vcpus`, `mem_mb` and `disk_gb` creates the server's default fixed size | | `volume_id` | no | Attach a persistent volume you already created via `POST /v1/volumes`. Naming an id you don't own, or one that doesn't exist, is a `404`. See [Volumes](/docs/volumes) | | `max_lifetime_ms` | no | Hard cap on session age. Omit for no cap of your own — every session still force-pauses after 24 hours continuously live regardless, as a fleet backstop (see [Session lifecycle](/docs/session-lifecycle#limits)). Reaching your own `max_lifetime_ms` auto-pauses the session **permanently** — it cannot resume again after this. Capped at 24 hours; cannot be combined with a negative `paused_ttl_ms` (rejected `400`) | | `idle_timeout_ms` | no | Auto-pause after idle period. Omit for no auto-pause. Capped at 1 hour | | `name` | no | Caller-assigned label for the session | | `labels` | no | Arbitrary key/value metadata | | `external_id` | no | Caller-owned index key (e.g. your own user/workflow/thread id) to look this session up later without maintaining your own mapping table. See [Index by your own id](#index-by-your-own-id) below | | `template` | no | Base environment to start from. Empty or `base` uses the default `base` template; `name@version` pins a specific version. See [Templates](/docs/templates) | | `egress` | no | Outbound allowlist — `{ "mode": "allow" \| "deny", "allow": [...] }`. Omitted keeps full public egress. See [Networking & egress](/docs/networking) | | `no_sudo` | no | Run in hardened mode for untrusted code — the default user loses passwordless sudo. Omitted leaves sudo available | | `on_pty_detach` | no | What the server does when the last terminal (PTY) client detaches: `pause` (default), `keep_live`, or `destroy`. No effect for API-only sessions | | `paused_ttl_ms` | no | Auto-destroy a paused session after this long. Omit, `0` or negative for never (the default). With `max_lifetime_ms`, omit/`0` means 30 days and a negative value is rejected (`400`) — that pause is permanent, so "never expire" would leave it paused and billed forever | | `destroy_on_completion` | no | Skip persistence and tear the session down as soon as the first command completes | | `artifacts` | no | `{ "paths": [...] }` to auto-capture on teardown. See [Artifacts](/docs/artifacts) | | `project_id` | no | Attribute the session to this project instead of the credential's default. A project-scoped key must omit this or match its own project (403 otherwise) | | `command_capture` | no | Command metadata retained in the execution log: `hash`, `executable` (default), or `full` (explicit content-capture opt-in) | | `env` | no | Plain, non-sensitive environment variables (config/flags), set for every process this session's exec/PTY spawns. See [Environment and secrets](#environment-and-secrets) | | `secrets` | no | Sensitive environment variables — encrypted at rest, never echoed back. See [Environment and secrets](#environment-and-secrets) | | `connections` | no | Bind the session to specific external API origins, injecting a credential you supply on the way out — code calls the provider's real hostname unmodified. See [Connections](/docs/connections) | For sessions created before November 2026 without a `paused_ttl_ms`, see [Session lifecycle](/docs/session-lifecycle#timers). **Response `200`** ```json { "session_id": "2476b0a6-722e-4bd9-9f25-771ccbdd53bd", "state": "creating", "created_at": "2026-06-22T13:46:00Z" } ``` Most creates return `state: "creating"` immediately and finish provisioning in the background. Poll `GET /v1/sessions/{id}` until `live` (or `failed`). SDKs that wait on create hide this; raw HTTP clients should not assume `live` on the create response. When present, `status_detail` / `status_reason` explain provisioning progress or failure. ### Environment and secrets Both `env` and `secrets` are maps of string to string, set once at create and injected into every process this session's exec/PTY spawns: ```json { "env": { "LOG_LEVEL": "debug" }, "secrets": { "API_KEY": "sk-..." } } ``` ```python session = client.sessions.create( env={"LOG_LEVEL": "debug"}, secrets={"API_KEY": "sk-..."}, ) ``` ```typescript const session = await client.sessions.create({ env: { LOG_LEVEL: "debug" }, secrets: { API_KEY: "sk-..." }, }); ``` `env` is plain config — stored as-is and echoed back on `GET /v1/sessions/{id}`. `secrets` is for anything sensitive: encrypted at rest immediately on create, never logged, and decrypted only in memory at the moment a guest request is sent. A secret is never echoed back — `GET` a session to see only the configured secret *names* (`secret_names`), never values. Creating a session with `secrets` on a server without a secret-encryption key configured fails with `503`. Pairing `secrets` with a [deny-by-default egress policy](/docs/networking) means the code can use the key but can't send it to an arbitrary destination. **Secrets and saved state.** This protects the value in storage and in transit, not inside the running session. Once a secret is set in a process's environment, pausing or checkpointing that session saves its memory, which can include the secret's plaintext for any process that was holding it. That saved state is stored on the exec node and, if cold archiving is enabled for your plan, uploaded to object storage — currently under the storage provider's default at-rest encryption, not a key of ours tied to your secret. Deleting a secret does not retroactively scrub state already saved. Treat any secret injected into a session as retrievable for as long as saved state containing it exists. ### Index by your own id `external_id` stamps a session with a caller-owned key — a user id, workflow id, or thread id from your own system — so you can find it later without maintaining a separate `external_id -> session_id` mapping table on your side: ```json { "external_id": "workflow-42" } ``` ```python session = client.sessions.create(external_id="workflow-42") sessions, _ = client.sessions.list(external_id="workflow-42") ``` ```typescript const session = await client.sessions.create({ externalId: "workflow-42" }); const { sessions } = await client.sessions.list({ externalId: "workflow-42" }); ``` It's echoed back on every session read (`GET /v1/sessions/{id}`, list, create) and filterable via `GET /v1/sessions?external_id=...`. **Not unique** — unlike `name`, multiple sessions may share one `external_id` (e.g. every session a long-running workflow spins up), so a filtered list can return more than one result. Capped at 256 characters; must be valid UTF-8 with no control characters. ### Idempotent retries Set an `Idempotency-Key` header on `POST /v1/sessions` to make a create safe to retry — the case where your process crashes, times out, or loses the response after the request already reached the server, and you don't know whether the session was actually created: ``` Idempotency-Key: order-42-session-create ``` ```python session = client.sessions.create(idempotency_key="order-42-session-create") ``` ```typescript const session = await client.sessions.create({ idempotencyKey: "order-42-session-create" }); ``` A retry with the **same key, the same account, and the same request body**, within 24 hours, returns the **original session** (`200`, with an `Idempotent-Replayed: true` response header) instead of creating a second one or 409ing on a name clash. A concurrent duplicate request for a key that's still mid-create gets `409 idempotency_key_in_progress` (retryable — respect the `Retry-After` header) rather than racing a second session into existence; it resolves to the same session once the in-flight request finishes. Omit the header for an ordinary, non-idempotent create. Max 255 characters; letters, digits, and `` _.:=+/- `` only. **Flexible sizes.** An out-of-range value is a `400`. A size over your account's limits is a `403`, or a `429` when your other awake sessions already use the room (pause one and retry). A fork of a flexible-size session, or a new session from its checkpoint, returns `409` for now; restoring a checkpoint into a session of the same size works. Rates: [pricing](https://inis.run/pricing). **Reusing a key with a different request body is an error, not a silent replay.** If a key is reused with a different `name`, `template`, `size`, or any other create field, the request is rejected with `409 conflict` rather than returning the first request's session — the same contract Stripe and most idempotent-write APIs use. Use a new key for a genuinely different request; only retry with the same key when the body is byte-for-byte the same logical request. ## Get **Response `200`** — session metadata: `session_id`, `state`, `volume_id`, `created_at`, `last_active_at`, `size`, `vcpus`, `mem_mb`, `template`, `no_sudo`, `on_pty_detach`, `paused_ttl_ms`, `egress`, `exposed_previews`, `archive`, `snapshot_tier` (paused sessions only), `env`, `secret_names` (configured secret names only — never values), `external_id` (if set at create — see [Index by your own id](#index-by-your-own-id)). See the [OpenAPI spec](/docs/openapi.yaml) for the full shape. ## List List your sessions, newest first. Filter with `?state=` (`live`, `paused`, `creating`, or `ended`) and `?external_id=` (exact match — see [Index by your own id](#index-by-your-own-id); not unique, so this can return more than one session). `?limit=` caps every state. `?cursor=` only pages `state=ended` (see below) — a `live`/`paused`/unfiltered list is a flat query capped at `limit`, with no cursor to page the rest with; narrow the filter or raise `limit` instead. See [Pagination](/docs/production#pagination-only-stateended-history-actually-pages) for the difference in practice. `state=ended` returns the **history** of destroyed sessions — terminal rows that carry `ended_at` and `end_reason` (`client_destroy`, `shell_exit`, `on_detach_destroy`, `max_lifetime`, `paused_ttl`, or `error`). History is metadata only; the saved snapshot is deleted when the session is destroyed, or 30 days after it ended if the machine it ran on was lost or that deletion failed. `state: "unavailable"` identifies a resident session held because its network backend cannot serve requests. It remains listed (also with `state=unavailable`), counts toward running concurrency limits, and is not billed for held compute time. Operations, including destroy, return `503 network_backend_unavailable` until backend recovery or operator repair permits safe lease teardown. See [Session lifecycle](/docs/session-lifecycle). ## Destroy Optionally pass `?reason=` (`client_destroy` — the default — or `shell_exit`) to record why the session ended on its history row. **Response `204`** — empty body. ## Exec **Request body** ```json { "command": ["python3", "-c", "print(42)"], "cwd": "/workspace", "timeout_ms": 30000 } ``` **Response `200`** ```json { "stdout": "42\n", "stderr": "", "exit_code": 0, "duration_ms": 41, "timed_out": false } ``` ### Streaming exec Same request body as above. Instead of one buffered response, the connection stays open and streams the command's stdout/stderr as it's produced, as Server-Sent Events — for a long build, a test run, or anything else where you want output as it happens instead of after the fact: ``` event: stdout data: event: stderr data: event: exit data: {"exit_code":0,"timed_out":false,"duration_ms":1042} ``` `stdout`/`stderr` payloads are base64 (output is arbitrary bytes, not necessarily UTF-8) and arrive chunk-by-chunk with no total-output cap, unlike the buffered mode's 4 MiB truncation. The stream always ends in exactly one of `event: exit` (the command ran to completion or its timeout fired — `data` is the same shape as the buffered response minus stdout/stderr) or `event: error` (a guest-side failure). Disconnecting before either arrives kills the command — it does not keep running in the background the way a [named background process](#background-processes) does. ```python for chunk in session.exec_stream(["python3", "-u", "train.py"]): if chunk.stream == "stdout": print(chunk.data, end="") # already a str elif chunk.stream == "exit": print(f"exit code: {chunk.exit_code}") ``` ```typescript for await (const chunk of session.execStream(["python3", "-u", "train.py"])) { if (chunk.stream === "stdout") process.stdout.write(chunk.data); else if (chunk.stream === "exit") console.log(`exit code: ${chunk.exitCode}`); } ``` ## Files Reading, listing, finding, and searching are all a single `GET` with query parameters; writing is a `PUT` with a body (or `PUT .../files/batch` for several small files at once). Query params: `path` (required for `read`; defaults to `/workspace` for `list`/`find`/`grep`), `op` (`read` default, `list`, `find`, `grep`), and `encoding` (`read` only — `text` default, or `base64` for binary files). **Read** — `GET /v1/sessions/{id}/files?path=/workspace/out.txt` Response includes `"content": "hello"`. **Read binary** — `GET /v1/sessions/{id}/files?path=/workspace/logo.png&encoding=base64` Response's `content` is base64; `encoding` echoes back `"base64"` so the caller knows how to decode it. **List** — `GET /v1/sessions/{id}/files?path=/workspace&op=list` Response includes `"entries": ["out.txt", "data.csv"]`. **Write** ```json { "path": "/workspace/out.txt", "content": "hello", "encoding": "text" } ``` `encoding` is `text` (default, content written as-is) or `base64` (decoded first, for binary files). ```python session.write_file("/workspace/out.txt", "hello") session.write_file("/workspace/logo.png", png_bytes) # bytes auto-base64-encoded ``` ```typescript await session.writeFile("/workspace/out.txt", "hello"); await session.writeFile("/workspace/logo.png", pngBytes); // Uint8Array auto-base64-encoded ``` ### Batch write Scaffold several small files in one call instead of one `PUT` each. Capped at 64 files / 8 MiB total content — for one large file (a dataset, a binary), stream it in with `session.upload_file` / `session.uploadFile` instead (`PUT /v1/sessions/{id}/files/stream`, no batch cap); for a whole directory, zip it and upload the archive — see [bulk file transfer](/docs/production#bulk-file-transfer-zip-upload-extract). Not fail-fast: the response carries a `{path, ok, error?}` result per file, so one bad path doesn't sink the rest of the batch. ```json { "files": [ { "path": "/workspace/a.py", "content": "print('a')" }, { "path": "/workspace/b.py", "content": "print('b')" } ] } ``` ```python results = session.write_files([ {"path": "/workspace/a.py", "content": "print('a')"}, {"path": "/workspace/b.py", "content": "print('b')"}, ]) ``` ```typescript const results = await session.writeFiles([ { path: "/workspace/a.py", content: "print('a')" }, { path: "/workspace/b.py", content: "print('b')" }, ]); ``` ### Find and grep `GET /v1/sessions/{id}/files` also takes `op=find` (glob match on paths) and `op=grep` (regex match on file contents). **Find** — `?path=/workspace&op=find&pattern=*.py` `pattern` is a glob: an exact path, `*`/`?`/`[...]`, or a trailing `/**` for recursive. Response includes `"paths": [...]` and `"truncated"` — set (not an error) when `max_results` caps the match set. **Grep** — `?path=/workspace&op=grep&pattern=TODO&file_pattern=*.go&context_lines=1` `pattern` is a regular expression (Go RE2 syntax — no PCRE lookaround/backreferences) matched against each line. Optional params: `file_pattern` (restrict by base name glob), `case_sensitive` (default false), `context_lines`, `exclude_dirs` (comma-separated), `max_results` (caps matching *files*, not match lines). Response includes `"matches": [{ "path", "line_number", "line", "before"?, "after"? }]`, `"files_searched"`, and `"truncated"`. Both `find` and `grep` enforce internal scan budgets (10,000 files; `grep` also caps at 256 MiB read) so a pattern that matches nothing still returns promptly, with `truncated: true`, instead of scanning the whole workspace. ```python found = session.find_files("*.py", path="/workspace") hits = session.grep_files("TODO", path="/workspace", file_pattern="*.go", context_lines=1) ``` ```typescript const found = await session.findFiles("*.py", { path: "/workspace" }); const hits = await session.grepFiles("TODO", { path: "/workspace", filePattern: "*.go", contextLines: 1 }); ``` ## Background processes Named, detached commands that keep running — and keep producing output — after the call returns and after the caller disconnects, independent of any one HTTP request. **Request body** ```json { "name": "web", "command": ["python3", "-m", "http.server", "8080"], "cwd": "/workspace", "keep_alive": false } ``` `name` is caller-chosen (lowercase alphanumerics and hyphens) and must be free — starting a second process under a name still in use by a running process is rejected, but a name whose process has already exited may be reused. A session holds at most 32 named processes (running, or exited but not yet reused) at once; one more is rejected with a clear error. `keep_alive: true` suppresses the session's idle timer for as long as the process runs, the same mechanism an attached PTY uses; default `false` means the process runs detached but doesn't by itself keep an otherwise-idle session live. **Response `200`** ```json { "name": "web", "pid": 4213, "command": ["python3", "-m", "http.server", "8080"], "state": "running", "keep_alive": false, "started_at": "2026-07-17T10:00:00Z" } ``` List every named process in the session, running and exited (an exited entry is kept until its name is reused or the session is torn down). Kill sends `SIGTERM`, then `SIGKILL` after a grace period if the process hasn't exited. Killing an already-exited process is a no-op that just reports its final state. Without `?follow=true`, returns the process's captured stdout/stderr so far as one JSON body — each stream capped at 4 MiB from the tail (the underlying on-disk log is itself capped at 10 MiB per stream; once exceeded, older output is dropped so a long-lived, verbose process can't grow its log or fill the guest's disk without bound). With `?follow=true`, upgrades to a Server-Sent Events stream instead: `event: stdout` / `event: stderr` frames (base64-encoded, since output is arbitrary bytes), ending with `event: eof` once the process exits and its output is fully drained, or `event: error` on a guest-side failure. ```python proc = session.start_process("web", ["python3", "-m", "http.server", "8080"], keep_alive=True) for p in session.list_processes(): print(p.name, p.state) for event in session.stream_process_logs("web"): if event.event in ("stdout", "stderr"): print(event.data, end="") elif event.event in ("eof", "error"): break session.kill_process("web") ``` ```typescript const proc = await session.startProcess("web", ["python3", "-m", "http.server", "8080"], { keepAlive: true }); for (const p of await session.listProcesses()) console.log(p.name, p.state); for await (const event of session.streamProcessLogs("web")) { if (event.event === "stdout" || event.event === "stderr") process.stdout.write(event.data); if (event.event === "eof" || event.event === "error") break; } await session.killProcess("web"); ``` ## Expose Ensure an HTTPS preview URL is running for a port inside the guest. The process must bind to `0.0.0.0`, not `127.0.0.1`. **Request body** ```json { "port": 8080, "visibility": "token", "auth": "bearer" } ``` `auth` controls access to the preview URL: `none` (default) leaves it open, `bearer` requires every inbound request to carry an `Authorization: Bearer ` header. **Response `200`** ```json { "session_id": "2476b0a6-722e-4bd9-9f25-771ccbdd53bd", "port": 8080, "preview_url": "https://8080-2476b0a6-722e-4bd9-9f25-771ccbdd53bd.ams1.sb.inis.run", "guest_ip": "10.42.3.2", "auth": "bearer", "auth_token": "qN3kf2...", "result": "created" } ``` When `auth` is `bearer`, inbound requests without a matching `Authorization: Bearer` header are rejected with `401`. The active mode shows up as `auth` on each entry in `exposed_previews` from a session fetch; the token itself is only ever returned from this endpoint. Preview URLs follow `https://{port}-{session_id}.{node-domain}`. ### Expose is idempotent Calling expose again for a port that is already exposed with the same `visibility`, `auth` and `login_url` returns the preview URL and token it already handed out. It does not mint new ones, and it does not wake a paused session. That matters because a preview URL is a credential someone else may be holding — a webhook you registered with an external service, a link in a browser, a URL stored in your own database. Rotating it silently breaks the holder with no error and no event, so a retry, or a loop that re-asserts the state it wants, is safe here by default. `result` says what the call actually did: | `result` | meaning | | --- | --- | | `created` | the port was not exposed; a route and its credentials were minted | | `unchanged` | already exposed exactly as asked — nothing minted, no wake, `preview_url` is the URL an earlier call returned | | `updated` | a route existed and this call rewrote it, because the settings differed or `rotate` was set | On an `updated` call the ingress token is kept wherever the new settings leave room for it — changing `login_url`, or turning `auth: "bearer"` **on**, does not invalidate a URL in use. Three things move it: `visibility` (`public` has no token to keep, and coming back to `token` mints a new one), `rotate`, and turning `auth: "bearer"` **off**. Turning bearer auth **off** mints a fresh ingress token, and the previous preview URL stops working — on a `token` route. It has to: `auth` defaults to `"none"`, so omitting it on a route that is currently `bearer` *is* the downgrade — and if the URL survived that, everyone already holding it (a log line, a CI artifact, a pasted link) would go from `401` to unauthenticated access without anyone asking. Send `auth: "bearer"` on every convergence pass if you mean to keep it. A `public` route is the exception, and it cuts the other way. Its URL carries no token, so there is nothing to rotate: dropping bearer leaves the **same** hostname reachable with no auth at all, and every holder of that URL gains access rather than losing it. There is no way to revoke a public route's URL — that is what `public` means. If the gate matters, use `visibility: "token"`. Two things are converged on every call whatever the result: the route's backend, so a session that came back on a new guest IP is repointed rather than left aiming at a dead one, and its expiry lease. ### Rotating a token deliberately ```json { "port": 8080, "rotate": true } ``` `rotate: true` mints a fresh ingress token (and a fresh bearer token when `auth` is `bearer`) even if the port is already exposed exactly as requested. Every URL carrying the old token stops working the moment it returns — that is the point of it, so send it only when you mean it. On the CLI it is `inis sessions expose --port 8080 --rotate`. ## Pause and resume Pause stops billing for compute; storage for the paused state continues. Any exec/files call on a paused session wakes it automatically, as does attaching with `inis ssh`. Expose wakes it too when it has actual work to do — creating a route, or changing one — but an expose that is already satisfied answers from the existing route and leaves the session asleep. Pause also happens on its own: when the last client detaches (if the session's `on_pty_detach` is `pause`, the default) and after the `idle_timeout_ms` window. A paused session is auto-destroyed once it sits past its `paused_ttl_ms`, if it has one. ## Fork Clone a live session into N independent children — useful for parallel eval or RL rollouts. Forks keep the parent's `paused_ttl_ms`. **Request body** ```json { "count": 10 } ``` **Response `200`** ```json { "parent_session_id": "2476b0a6-722e-4bd9-9f25-771ccbdd53bd", "children": ["...", "..."] } ``` ## Checkpoints A checkpoint is a named, retained save-point of a live session. It survives the session's destruction and is deleted only when you ask. See [Concepts](/docs/concepts#checkpoints) for checkpoint vs fork vs pause. Capture a checkpoint. The source session keeps running. **Request body** ```json { "name": "clean" } ``` **Response `200`** ```json { "checkpoint_id": "ckpt_3f9a...", "parent_session_id": "...", "name": "clean", "size_bytes": 268435456, "created_at": "2026-06-23T10:00:00Z" } ``` List checkpoints captured from a session. Fetch a checkpoint's metadata. Delete a checkpoint and free its disk. ### Restore in place Roll a session back to a checkpoint, reusing the same session ID. The "run untrusted code, then roll back to clean" flow. **Request body** ```json { "checkpoint_id": "ckpt_3f9a..." } ``` ### New session from a checkpoint Start a fresh, independent session from a checkpoint (the template path). Via the CLI: `inis checkpoints create-session `. ## Lifecycle ``` creating → live ⇄ paused → destroyed → (ended history) ↑ ↓ wake-on-op auto-pause on detach / idle ``` `live → paused` happens on detach (`on_pty_detach: pause`) or idle timeout; `paused → live` on any operation or attach. A session reaches `destroyed` explicitly, at `max_lifetime`, or when a paused session passes its `paused_ttl` — and leaves an `ended` history row behind either way. Full walkthrough of timers, wake-on-op, billing, and recipes: [Session lifecycle](/docs/session-lifecycle). For when to use sessions vs stateless execute, see [Concepts](/docs/concepts). ### Limits Default caps on the managed cloud today — talk to us if one of these doesn't fit your workload: | Limit | Default | Notes | |-------|---------|-------| | Concurrent live sessions per account | 10 | Across all API keys on the account. Exceeding it returns `account_concurrency_exceeded` (429, retryable) | | Requests per second | No fixed limit on the execution API | The concurrency cap above is what bounds usage. Auth endpoints (sign-in code, CLI pairing, OAuth, passkey, 2FA) are separately rate-limited per IP/email against brute-force and abuse | | `idle_timeout_ms` | Off by default; 1 hour max if you set one | — | | `max_lifetime_ms` | Off by default (no cap); 24 hours max if you set one | Every session also force-pauses after 24 hours continuously live regardless of this setting — a fleet-wide backstop, not something you opt out of | | `paused_ttl_ms` | Never (30 days with `max_lifetime_ms`) | Set per session | | `timeout_ms` (a single exec) | 30 seconds; 1 hour max | — | A new account (trial, no card on file) is more limited while unverified: 1 concurrent session, 15 minutes of runtime per day, and 24 GB of cumulative disk across live/paused sessions. Paid accounts get 10 concurrent sessions and 512 GB cumulative disk by default. Sessions created with `vcpus` / `mem_mb` / `disk_gb` have their own limits. Trial: up to 1 vCPU and 2 GB per session, 2 live sessions, 16 GB of provisioned disk in total (the default `disk_gb`, so one session at the default fills it). Funded: up to 8 vCPU and 16 GB across awake sessions, 200 GB of provisioned disk. Ask us to raise them. --- ## One-shot exec URL: https://inis.run/docs/api/execute A session is the only primitive. When you just want to run one command and get the output back, `/v1/sessions/exec` collapses create, run, and destroy into a single call — no session to track, no teardown to remember. Reach for it for batch jobs, simple tools, and playground runs. For multi-step work where state carries between calls, use [sessions](/docs/api/sessions) instead. All requests require `Authorization: Bearer inis_...` and `Content-Type: application/json`. See [Authentication](/docs/authentication). Prefer the [CLI](/docs/integrations/cli) or an [SDK](/docs/integrations/python) for day-to-day use — the reference below is for custom integrations. ## Run code Run Python or Node source in a fresh sandbox that is destroyed when the run completes. **Request body** ```json { "language": "python", "code": "print(6)", "dependencies": ["pandas"], "timeout_ms": 30000 } ``` | Field | Required | Description | |-------|----------|-------------| | `language` | yes | `python`, `node`, or `bun` | | `code` | yes | Source to run | | `dependencies` | no | pip/npm packages installed before run | | `volume_id` | no | Attach a persistent volume you already created via `POST /v1/volumes`. Naming an id you don't own, or one that doesn't exist, is a `404`. See [Volumes](/docs/volumes) | | `timeout_ms` | no | Wall-clock cap (default 30s) | | `size` | no | Deprecated alias for a fixed size bundle. Omitted uses the server's default. For a chosen size, create a session with `vcpus`, `mem_mb` and `disk_gb` instead — see [Sessions](/docs/api/sessions#create) | | `template` | no | Base environment to start from. Empty or `base` uses the default `base` template. See [Templates](/docs/templates) | | `no_sudo` | no | Run in hardened mode for untrusted code — the default user loses passwordless sudo | | `project_id` | no | Attribute the run to this project instead of the credential's default | | `command_capture` | no | Command metadata retained in the execution log: `hash`, `executable` (default), or `full` | **Response `200`** ```json { "session_id": "2476b0a6-722e-4bd9-9f25-771ccbdd53bd", "stdout": "6\n", "stderr": "", "exit_code": 0, "duration_ms": 842, "install_ms": 0, "restore_ms": 0, "phase": "run", "timed_out": false } ``` `session_id` is the throwaway session used for the run (useful for audit/history). `restore_ms` is set when the run woke from a paused baseline. ## When to use stateless execution vs sessions | Stateless execution (`/v1/sessions/exec`) | Sessions | |--------------------------------|----------| | Run and return, nothing to track | Multi-step workflows | | No state across calls | Warm wake; state persists | | Simplest integration | Files, ports, fork, pause | A stateless-execution call is the same session primitive with `destroy_on_completion` set — you can pass that flag to [`POST /v1/sessions`](/docs/api/sessions) yourself if you want to run the create and exec steps separately while still skipping persistence. See [Concepts](/docs/concepts) for the full comparison. --- ## Organisation URL: https://inis.run/docs/api/org A small read-only endpoint for seeing how much of your capacity is in use. All requests require `Authorization: Bearer inis_...`. ## Capacity Returns live session counts for your account, your per-account limits, and how many more sessions of each size can be placed right now. **Response `200`** ```json { "capacity": { "running": 3, "warm": 10, "limits": { "running": 20, "warm": 50, "account_live_sessions": 10 }, "headroom": { "tiny": 40, "small": 20, "medium": 10, "large": 5, "xlarge": 0 }, "headroom_measured_at": "2026-10-18T09:00:00Z" } } ``` - `running`: live sessions, including ones still starting up. - `warm`: paused sessions, ready to resume. - `limits`: the ceilings for your account. `account_live_sessions` is the live-session limit, and a create past it is refused with `429`. It is omitted when your account has no limit. - `headroom`: how many more sessions of each fixed size bundle you could create right now, with one key per bundle (the keys are the deprecated `size` aliases). It counts free memory, CPU and disk across the fleet, and it is capped by your remaining `account_live_sessions`. Paused sessions use disk but no memory, so they count against disk only. A size that reads `0` cannot be placed now. - `headroom_measured_at`: when the oldest node reading behind `headroom` was taken. It is omitted when no node could be read, and every size is then `0`. `headroom` is a snapshot, not a reservation: a create can still be refused between your read and your request. If `headroom_measured_at` is missing or more than a minute or two old, treat the numbers as `0`. The CLI surfaces the same view with `inis org`. --- ## Errors URL: https://inis.run/docs/api/errors Every non-2xx response carries the same JSON envelope: ```json { "error": "session is not live", "code": "session_not_live" } ``` - `error` — a human-readable message. Don't match on its text; it can be reworded. - `code` — a stable, machine-readable string. Branch on this instead. New codes can appear over time — treat one you don't recognize as a generic failure of the class implied by the HTTP status, not as an error in itself. ## Codes Prefer the primary code when present. "Also seen as" columns are older, equivalent strings that still appear on some paths for historical reasons — treat every column as valid for client branching. {/* BEGIN GENERATED ERROR TABLE (scripts/gen/docs_manifest.py — do not hand-edit) */} | Code | Also seen as | HTTP | Retryable | Meaning and corrective action | |------|--------------|------|-----------|--------------------------------| | `validation` | `bad_request` | 400 | No | Malformed or invalid request — fix the request body/params, don't retry unmodified. | | `payload_too_large` | | 400 | No | Request content exceeds a transport limit. Deterministic in the content — retrying identically fails identically; shrink the payload instead. | | `unauthenticated` | `unauthorized` | 401 | No | Missing, invalid, or expired credential — refresh it, then retry. | | `payment_required` | | 402 | No | Prepaid balance exhausted, a spend cap was reached, or the balance check was explicitly rejected — top up or raise the cap, then retry. | | `forbidden` | | 403 | No | Valid credential, not allowed to do this — suspended account, reserved name, or cross-tenant access. | | `not_found` | | 404 | No | Missing, or missing for this caller. Cross-tenant lookups deliberately look identical to a genuine miss. | | `method_not_allowed` | | 405 | No | Wrong HTTP method for this path. A well-behaved client should never construct this request — check the API reference rather than retrying. | | `conflict` | | 409 | No | Well-formed request, current resource state refuses it — re-read the resource's state before retrying. | | `session_not_live` | | 409 | Yes | A live-only operation (exec, files, fork, ...) against a session that's paused, ending, or not yet ready. Refetch session state and retry once it transitions. | | `org_has_other_members` | | 409 | No | Account closure was refused because the organisation still has members besides the requesting owner. Remove the other members, then request closure again. | | `no_restore_point` | | 409 | No | A `POST /v1/sessions/{id}/recover` was refused because the session has no completed cold snapshot in object storage, or the storage object was missing — do not retry without a usable snapshot. | | `snapshot_not_resizable` | | 409 | No | A start was refused because its snapshot can never be brought to the size asked for: its guest has no memory hotplug driver, its hotplug region is not the recorded one, or the size does not fit it. Pick another size or template; retrying the identical request fails the same way. | | `idempotency_key_in_progress` | | 409 | Yes | A POST /v1/sessions with this `Idempotency-Key` is already being processed by another request for the same key + customer — retry shortly and it resolves to the same session once that request finishes. Respect the `Retry-After` header. | | `session_ended` | | 410 | No | The session has definitively ended past recall — start a new one. When the cause is a session past its own max_lifetime_ms, `GET /v1/sessions/{id}` reports this ahead of time via state: "lifetime_expired" instead of only surfacing it once a resume attempt fails. | | `session_node_lost` | | 410 | No | The session's home node was declared permanently dead. Call `POST /v1/sessions/{id}/recover` to bring it back under the same id from its last cold snapshot, if one survives — GET reports whether it does. Otherwise recreate the session from its template, or restore from your last checkpoint; work since that snapshot is gone. GET still reports the state, DELETE still destroys the session, and `POST .../recover` attempts recovery — every other operation returns this code. | | `rate_limited` | `concurrency_limit_exceeded`, `rate_limit_exceeded` | 429 | Yes | Rate or concurrency limit exceeded — back off and retry. Respect a `Retry-After` header if the response includes one. | | `account_concurrency_exceeded` | | 429 | Yes | The caller's account is already at its concurrent live-session ceiling — back off and retry. Respect the `Retry-After` header. | | `key_concurrency_exceeded` | | 429 | Yes | The caller's API key is already at its concurrent live-session ceiling — back off and retry. Respect the `Retry-After` header. | | `bad_gateway` | | 502 | Yes | Upstream node unreachable or failing — retry with backoff; the router may resolve it on the next attempt. | | `session_unavailable` | | 503 | Yes | The session is live but its VM is wedged or unreachable — retry. | | `session_node_unavailable` | | 503 | Yes | The session's home node is unreachable — retry; the response usually sets `Retry-After`. | | `template_version_unavailable` | | 502/503 | Yes | A pinned template version could not be materialized on this node — retry. Never silently falls back to a different cached version of the same template. | | `archive_unavailable` | | 503 | No | No working cold tier available to durably pause this session to. Needs a node/placement configuration change — retrying the identical pause will not succeed; the session itself was left running untouched. | | `archive_unrecoverable` | | 410 | No | An archive retry was refused because part of the paused session's local snapshot is missing from its node, so that pause can never be uploaded from there; its upload status is now `unrecoverable`. The session itself still exists — this is not `session_ended`. Do not retry. | | `session_quarantined` | | 409 | No | The paused session cannot be resumed, forked, checkpointed or uploaded: an earlier resume failed after it started running, and its disks could not be put back to match its memory snapshot. The session and its data still exist. Do not retry; contact support to have it repaired. | | `size_unavailable` | | 503 | No | The requested size cannot fit on any node in the fleet today. Pick a smaller size instead of retrying. | | `node_disk_pressure` | | 503 | Yes | The node is too full to take this work right now — a create, fork, restore, one-shot run, resume or cold adopt refused by its disk gate. Back off and retry; respect the `Retry-After` header. A refused wake also raises a `session.wake_refused` event on the org event stream (and a refused create, `session.create_refused`), so a tenant that was not the caller still hears about it. | | `unavailable` | `service_unavailable` | 502/503 | Yes | A dependency is temporarily unreachable — retry. | | `internal` | `internal_error` | 500 | No | Unexpected server-side failure. The message is intentionally generic; if it persists, share the request ID with support. | | `error` | | any | No | Fallback used only when no more specific code applies. | {/* END GENERATED ERROR TABLE */} The [console](https://app.inis.run) dual-maps several of these. SDKs surface the `code` string from the envelope — branch on it, not on `error` text. ---