An open-source, faster Devin alternative
TypeScript
docs: Durable Agent Sessions section (launch #1)
Igor Zalutskib03d04f565d9
diff --git a/docs/agent-sessions/api-reference.mdx b/docs/agent-sessions/api-reference.mdxnew file mode 100644index 00000000..ee197f65--- /dev/null+++ b/docs/agent-sessions/api-reference.mdx@@ -0,0 +1,81 @@+---+title: "API reference"+description: "Every endpoint in the Durable Agent Sessions API"+---++Base URL `https://api.opencomputer.dev/v3`. Management calls authenticate with your **org API key**; stream and steer also accept a **[client token](/agent-sessions/authentication#client-tokens)**.++## Sessions++| Method · Path | Purpose |+| --- | --- |+| `POST /sessions` | Start a run. Body: `agent?`, `prompt?`, `model?`, `runtime?`, `input`, `key?`, `webhook?`, `destinations?[]`. Returns `{ session, client_token }`. |+| `GET /sessions/:id` | Fetch a session. |+| `GET /sessions` | List sessions. |+| `POST /sessions/:id/archive` | Archive (close) a session. |+| `POST /sessions/:id/client-tokens` | Mint a client token. Body: `scopes?`, `ttl?`. |++Provide `agent` (a saved agent id) **or** inline `prompt` + `model`. `key` gives get-or-create (one session per key). `input` is the task — a string or a full [envelope](/agent-sessions/messaging#the-envelope).++```+Session = { id, status, head, cursor,+ agent_snapshot: { prompt_hash, model, runtime },+ last_turn: { state, result_event_id?, error? }, key?, created_at }+```++## Events++| Method · Path | Purpose |+| --- | --- |+| `GET /sessions/:id/events?after=<seq>&level=<lvl>&limit=<n>` | Read events since a cursor. |+| `GET /sessions/:id/events?after=<seq>&level=<lvl>&stream=sse` | Live SSE stream from a cursor. |++`after` resumes from a `seq`; `level` is the max [level](/agent-sessions/concepts#levels) to receive.++```+Event = { id, seq, ts, session, actor, kind, level, body, refs }+```++## Steer++| Method · Path | Purpose |+| --- | --- |+| `POST /sessions/:id/messages` | Append an input message; wakes the session. Body: `{ text, idempotency_key? }` or `{ envelope }`. Returns `{ seq }`. |++## Destinations (webhooks)++| Method · Path | Purpose |+| --- | --- |+| `POST /sessions/:id/destinations` | Register a webhook. Body: `url`, `secret?`, `level?` (`user`), `kinds?[]`, `include_raw?` (`false`). |+| `GET /sessions/:id/destinations` | List destinations. |+| `DELETE /sessions/:id/destinations/:id` | Remove a destination. |+| `GET /sessions/:id/destinations/:id/deliveries` | List deliveries (incl. dead-lettered). |+| `POST /sessions/:id/destinations/:id/deliveries/:id/retry` | Retry a dead-lettered delivery. |++See [Messaging & webhooks](/agent-sessions/messaging#delivery-contract) for the signing and delivery contract.++```+Destination = { id, url, level, kinds, include_raw, created_at }+Delivery = { id, status, attempts, last_error?, event_id }+```++## Agents++| Method · Path | Purpose |+| --- | --- |+| `POST /agents` | Create a reusable agent. Body: `name`, `prompt`, `model`, `runtime?` (`claude`). Idempotent by `(owner, name)`. |+| `GET /agents/:id` · `GET /agents` | Fetch / list. |+| `PATCH /agents/:id` | Update `prompt?` / `model?`. Never affects existing sessions (snapshots are pinned). |++## Credentials++| Method · Path | Purpose |+| --- | --- |+| `POST /credentials` | Add a provider key. Body: `provider`, `key`, `name?`. Key is write-only. |+| `GET /credentials` · `DELETE /credentials/:id` | List / remove. |+| `PUT /credentials/default` | Set the org default for a provider. Body: `provider`, `credential`. |++```+Credential = { id, provider, name?, last4, created_at }+ClientToken = { token, scopes, expires_at }+```diff --git a/docs/agent-sessions/authentication.mdx b/docs/agent-sessions/authentication.mdxnew file mode 100644index 00000000..b4ba5fa1--- /dev/null+++ b/docs/agent-sessions/authentication.mdx@@ -0,0 +1,57 @@+---+title: "Authentication"+description: "Org keys, browser-safe client tokens, and bring-your-own model keys"+---++Three credentials, each with a job.++## Org API key++Your account key. Use it server-side for all **management** calls — creating agents, starting sessions, registering webhooks, managing credentials.++```bash+curl https://api.opencomputer.dev/v3/sessions \+ -H "Authorization: Bearer $OPENCOMPUTER_API_KEY" -d '{ … }'+```++<Warning>Never ship the org API key to a browser or mobile client — it can do anything on your account. Use a client token instead.</Warning>++## Client tokens++A **session-scoped, short-lived** token with `read` + `steer` scope — safe to hand to a front-end. It can stream and steer **one** session and nothing else.++You get one back from `POST /v3/sessions`, and can mint more:++```bash+curl https://api.opencomputer.dev/v3/sessions/$ID/client-tokens \+ -H "Authorization: Bearer $OPENCOMPUTER_API_KEY" \+ -d '{ "scopes": ["read", "steer"], "ttl": 3600 }'+```++The pattern: your backend creates the session with the org key, then hands the `client_token` to the browser, which uses it directly for the SSE stream and steer calls.++```+browser ──(create task)──▶ your backend ──(org key)──▶ POST /v3/sessions+browser ◀──(client_token)── your backend+browser ──(client_token)──▶ GET …/events (SSE) · POST …/messages+```++## Model credentials (BYO key)++By default, runs are **platform-billed on Anthropic** — zero setup, metered to your org, capped per session. To run on **your own** provider key, add a credential once. It's stored in our secret store (encrypted, write-only, never returned) — you never manage a raw secret store yourself.++```bash+curl https://api.opencomputer.dev/v3/credentials \+ -H "Authorization: Bearer $OPENCOMPUTER_API_KEY" \+ -d '{ "provider": "anthropic", "key": "sk-ant-…", "name": "prod" }'+# → { "id": "cred_…", "provider": "anthropic", "last4": "…", … }++# make it the default for this provider+curl -X PUT https://api.opencomputer.dev/v3/credentials/default \+ -H "Authorization: Bearer $OPENCOMPUTER_API_KEY" \+ -d '{ "provider": "anthropic", "credential": "cred_…" }'+```++**Resolution** for each run: the agent's credential → your org default for the model's provider → platform billing.++<Note>Today only **Anthropic** (the `claude` runtime). Other providers and model hot-swap are [coming soon](/agent-sessions/runtimes) — the credentials shape is the same, so adding them won't break anything.</Note>diff --git a/docs/agent-sessions/concepts.mdx b/docs/agent-sessions/concepts.mdxnew file mode 100644index 00000000..41d1bf19--- /dev/null+++ b/docs/agent-sessions/concepts.mdx@@ -0,0 +1,70 @@+---+title: "Concepts"+description: "Agents, sessions, events, and the run loop"+---++## The run loop++1. You create a **session** from an **agent** (a prompt + model). The run starts.+2. The **runtime** executes the agent in a sandbox, **appending events** to the session log as it works.+3. When it has nothing to do, the session goes **idle** and the sandbox **hibernates**.+4. A **steer** message wakes it; it resumes with full prior context. Repeat.++## Agent++A first-class, reusable definition of *what* runs: `{ name, prompt, model, runtime }`. Create one and start many sessions from it, or inline `{ prompt, model }` at session-create for a one-off.++**Agent snapshot.** At create, the session **freezes** the agent's `{ prompt, model, runtime }`. Editing the named agent later never changes a running or resumed session — its behavior is pinned.++## Session++One durable run: an append-only **event log** plus the pinned snapshot and a lifecycle status.++| Status | Meaning |+| --- | --- |+| `running` | A turn is executing. |+| `idle` | Quiescent and steerable; the sandbox is hibernated. |+| `failed` | The run errored out. |+| `archived` | Closed; read-only. |++A session also carries `last_turn = { state: "ok" \| "error", result_event_id?, error? }`, so a one-off run tells you whether it finished and what it produced. By convention, the **final result is a `user`-level `message` event**.++## Event++Every step is an event, appended in order:++```json+{ "id": "evt_…", "seq": 12, "ts": "…", "session": "sess_…",+ "actor": { "id": "agent", "type": "agent" },+ "kind": "message", "level": "user",+ "body": { "text": "3 tests fail in auth.spec.ts" }, "refs": {} }+```++- **`kind`** — `message` (content), `status` (lifecycle), or `error`.+- **`actor`** — `{ id, display?, type: "human" | "agent" | "system" }`.+- **`level`** — see below.+- **`body` / `refs`** — payload and related ids.++Inbound and outbound messages share one [envelope](/agent-sessions/messaging#the-envelope) shape.++## seq / cursor / head {#cursors}++- **`seq`** — a monotonic id assigned to each event; the cursor space.+- **`head`** — the highest `seq` in the session.+- **`cursor`** — how far a reader (or the runtime) has consumed.++Read or stream with `after=<seq>` and you get everything since that point — this is how **resume** works: reconnect with the last `seq` you saw.++## Levels {#levels}++Every event has a visibility level; filter the stream and webhooks by it.++| Level | For |+| --- | --- |+| `internal` | The agent's own reasoning and tool detail. |+| `progress` | Step-by-step updates. |+| `user` | What an end user should see (default for delivery). |++## Runtime++The stateless engine that runs the agent loop. **`claude`** today; more [coming soon](/agent-sessions/runtimes). The runtime works in a sandbox that hibernates when idle — durability is the session's job, not the runtime's.diff --git a/docs/agent-sessions/durability.mdx b/docs/agent-sessions/durability.mdxnew file mode 100644index 00000000..d3b8fdc2--- /dev/null+++ b/docs/agent-sessions/durability.mdx@@ -0,0 +1,42 @@+---+title: "Durability & resume"+description: "What survives a disconnect, an idle period, or a crash — and what doesn't"+---++## The event log is the source of truth++Every step is appended to the session's log with a monotonic `seq`. The log is durable and ordered; reads and the live stream are served from it. Anything the agent has logged or delivered is safe.++## Stream resume++Disconnects lose nothing. Reconnect with `after=<last seq you saw>` and you get every event since, in order — no gaps, no duplicates.++```js+// reconnect loop+let cursor = lastSeqSeen;+const res = await fetch(+ `https://api.opencomputer.dev/v3/sessions/${id}/events?stream=sse&after=${cursor}`,+ { headers: { Authorization: `Bearer ${clientToken}` } }+);+```++## Hibernate & resume++When a session has nothing to do it goes **idle** and its sandbox **hibernates** — the VM is snapshotted and stopped. You pay storage-only while idle; **active seconds only** show up in usage. The next message (a steer, or the next turn) wakes it, typically sub-second, and it continues with prior context.++<Note>This mirrors [sandbox hibernation](/sandboxes/timeout): idle ≈ free, fast wake. Sessions manage it for you — you don't set a timeout per turn.</Note>++## Limits (be precise) {#limits}++What's guaranteed today, and what isn't:++| Failure | What happens |+| --- | --- |+| Client disconnects | Reconnect from your cursor; nothing lost. |+| Session idles | Sandbox hibernates; resumes on the next message. |+| Runtime crashes mid-turn | Auto re-wakes and continues from the hibernated sandbox state. |+| Sandbox is **lost** (not hibernated) | The session may re-run / re-clone. Only **logged or delivered** outputs are durable. |++<Warning>+ v1 does **not** do byte-exact recovery after an arbitrary sandbox or model failure — in-flight, unlogged work can be redone. Build idempotent side effects, and treat the event log (and delivered webhooks) as your durable record. Byte-exact resume is coming in a later release.+</Warning>diff --git a/docs/agent-sessions/messaging.mdx b/docs/agent-sessions/messaging.mdxnew file mode 100644index 00000000..8f7d3b01--- /dev/null+++ b/docs/agent-sessions/messaging.mdx@@ -0,0 +1,87 @@+---+title: "Messaging & webhooks"+description: "Steer a session, and receive its output reliably"+---++Messaging is two halves over one shape: **steer** sends a message in; **destinations** push messages out. Both use the same channel-agnostic envelope, so the channels we add later (Slack, GitHub, …) won't change it.++## Steer (inbound)++Send a message to a running or idle session; it wakes and continues with full context. Minimal form is just text:++```bash+curl https://api.opencomputer.dev/v3/sessions/$ID/messages \+ -H "Authorization: Bearer $TOKEN" \+ -d '{ "text": "also check the CI config", "idempotency_key": "nudge-1" }'+```++Pass `idempotency_key` so retries (flaky network, double-click) are de-duplicated — the same key is applied at most once.++## The envelope {#the-envelope}++Every inbound and outbound message normalizes to this shape. The core fields are fixed; anything source-specific lives under `raw`, which the platform never interprets.++```json+{+ "id": "webhook:abc123",+ "source": "webhook",+ "kind": "message",+ "actor": { "id": "client:user-7", "display": "Ada", "type": "human" },+ "conversation": { "source": "webhook", "ref": "ticket-42" },+ "text": "also check the CI config",+ "refs": {},+ "ts": "2026-06-18T12:00:00Z",+ "raw": {}+}+```++- **`id`** — unique; the idempotency key.+- **`actor`** — who sent it (`human` | `agent` | `system`), namespaced.+- **`conversation`** — an opaque reply/routing anchor.+- **`text`** — the content the agent reads (or that you receive).+- **`raw`** — untouched original payload; optional, never read by the core.++## Destinations (outbound webhooks)++Register a destination and the agent's messages are delivered to it. Filter what you receive so you're not spammed with internal chatter.++```bash+curl https://api.opencomputer.dev/v3/sessions/$ID/destinations \+ -H "Authorization: Bearer $OPENCOMPUTER_API_KEY" \+ -d '{ "url": "https://your.app/oc-webhook",+ "secret": "whsec_…",+ "level": "user", // user (default) | progress+ "kinds": ["message"], // optional allow-list; default all+ "include_raw": false }' // strip raw from the delivered envelope+```++### Delivery contract++- **HTTPS only.** Private, loopback, link-local, and cloud-metadata addresses are refused.+- **At-least-once, idempotent per (event × destination)**, with exponential backoff. After the max attempts a delivery is **dead-lettered** — inspect and retry it:++```bash+curl https://api.opencomputer.dev/v3/sessions/$ID/destinations/$DID/deliveries \+ -H "Authorization: Bearer $OPENCOMPUTER_API_KEY" # includes dead-lettered+curl -X POST .../deliveries/$DELIVERY_ID/retry -H "Authorization: Bearer $OPENCOMPUTER_API_KEY"+```++- **Signed.** Each request carries `X-OC-Signature` (HMAC-SHA256 over `timestamp + "." + body`, keyed by your `secret`) and `X-OC-Timestamp`. The `secret` is write-only — set once, never returned.+- A delivery succeeds on HTTP `2xx`.++### Verify a webhook++```js+import { createHmac, timingSafeEqual } from "node:crypto";++function verify(req, secret, body) {+ const ts = req.headers["x-oc-timestamp"];+ if (Math.abs(Date.now() / 1000 - Number(ts)) > 300) return false; // reject stale → replay guard+ const expected = createHmac("sha256", secret).update(`${ts}.${body}`).digest("hex");+ const got = req.headers["x-oc-signature"];+ return got.length === expected.length &&+ timingSafeEqual(Buffer.from(got), Buffer.from(expected));+}+```++<Note>v1 ships the **generic webhook** channel. Channel adapters (Slack, GitHub comments, Jira, email) — inbound and outbound — are coming soon and reuse this exact envelope and delivery contract.</Note>diff --git a/docs/agent-sessions/overview.mdx b/docs/agent-sessions/overview.mdxnew file mode 100644index 00000000..61a1ad84--- /dev/null+++ b/docs/agent-sessions/overview.mdx@@ -0,0 +1,61 @@+---+title: "Durable Agent Sessions"+description: "Resumable, steerable agent runs — start one in a single API call"+---++Give an agent a prompt and a task; OpenComputer runs it on a managed runtime in a sandbox and records **every step as a durable, streamable, resumable session**. Watch it work live, drop your connection and reconnect right where you left off, let it idle and the sandbox hibernates (≈ free), then steer it with a message or get notified by webhook.++```bash+curl https://api.opencomputer.dev/v3/sessions \+ -H "Authorization: Bearer $OPENCOMPUTER_API_KEY" \+ -d '{ "model": "anthropic/claude-opus-4-8",+ "prompt": "You are a coding assistant.",+ "input": "Clone github.com/acme/widget, run its tests, and summarize what fails." }'+# → { "session": { "id": "sess_…", "status": "running" }, "client_token": "…" }+```++## What you get++- **One call to start** — `POST /v3/sessions` with a prompt, model, and task; the run begins immediately.+- **A durable event log** — every message, action, and status is appended with a monotonic `seq`; nothing is lost.+- **Live streaming + resume** — tail the log over SSE; reconnect from any cursor and continue.+- **Hibernate on idle** — the sandbox sleeps between turns and wakes on the next message; you pay storage-only while it's idle.+- **Steer & notify** — send a follow-up message any time; register a webhook to get results pushed to you, reliably.+- **Browser-safe tokens** — issue a session-scoped token so a front-end can stream and steer without your API key.++## What "durable" means here++<Note>+ We're precise about this so you can build on it:+ - The **event log is the source of truth** and is always durable.+ - The **stream resumes** from any cursor — disconnects lose nothing.+ - A **hibernated sandbox resumes** with its state intact.++ It is **not** byte-exact recovery after arbitrary failure. If a sandbox is *lost* (not hibernated), the session may re-run or re-clone, and only **logged or delivered outputs are guaranteed durable**. Byte-exact resume is [coming soon](/agent-sessions/durability#limits).+</Note>++## When to use it++Reach for sessions when you want a long-running or interactive agent and don't want to build the plumbing — an event store, live streaming, resume, idle hibernation, and reliable delivery — yourself. For a one-shot command in a raw box, use a [sandbox](/sandboxes/overview) directly.++## Available today vs coming soon++| Today | Coming soon |+| --- | --- |+| Agents on the `claude` runtime | Other runtimes (`codex`, `opencode`, custom BYO image) |+| Create / run / stream / resume / hibernate / archive sessions | `ask` (blocking request-for-input) |+| Steer by session id | Inbound channels (Slack, GitHub, Jira, email) |+| Outbound webhook delivery (signed, retried, filtered) | Outbound channel delivery (post to Slack, GitHub, …) |+| Browser client tokens · BYO Anthropic key | Other providers · model hot-swap |+| Platform-billed Anthropic + per-session cap | Workspaces, scheduled triggers, byte-exact resume |++## Next steps++<CardGroup cols={2}>+ <Card title="Quickstart" icon="bolt" href="/agent-sessions/quickstart">+ Start a session, stream it, and steer it in a few minutes.+ </Card>+ <Card title="Concepts" icon="book" href="/agent-sessions/concepts">+ Agents, sessions, events, cursors, and statuses.+ </Card>+</CardGroup>diff --git a/docs/agent-sessions/quickstart.mdx b/docs/agent-sessions/quickstart.mdxnew file mode 100644index 00000000..e2c48922--- /dev/null+++ b/docs/agent-sessions/quickstart.mdx@@ -0,0 +1,85 @@+---+title: "Quickstart"+description: "Start a session, stream it live, and steer it"+---++## Prerequisites++```bash+export OPENCOMPUTER_API_KEY=your-api-key+```++<Tip>Grab your API key from [app.opencomputer.dev](https://app.opencomputer.dev).</Tip>++## 1. Start a session++One call starts the run. Pass a `model`, a `prompt` (the agent's instructions), and `input` (the task).++```bash+curl https://api.opencomputer.dev/v3/sessions \+ -H "Authorization: Bearer $OPENCOMPUTER_API_KEY" \+ -d '{ "model": "anthropic/claude-opus-4-8",+ "prompt": "You are a coding assistant.",+ "input": "Clone github.com/acme/widget, run its tests, and summarize what fails." }'+```++```json+{+ "session": { "id": "sess_abc", "status": "running", "head": 0, "cursor": 0 },+ "client_token": "ct_…" // session-scoped; safe to hand to a browser (read + steer)+}+```++<Note>Defining the agent inline like this is sugar for one-off runs. To reuse an agent across sessions, [create one](/agent-sessions/api-reference#agents) and start sessions with `{ "agent": "agt_…", "input": … }`.</Note>++## 2. Stream it live++Tail the event log over SSE from a cursor. Use the `client_token` from step 1 — no API key needed in the client. `level=user` shows only what an end user should see (see [levels](/agent-sessions/concepts#levels)).++```js+const res = await fetch(+ `https://api.opencomputer.dev/v3/sessions/${id}/events?stream=sse&after=0&level=user`,+ { headers: { Authorization: `Bearer ${clientToken}` } }+);+const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();+for (;;) {+ const { value, done } = await reader.read();+ if (done) break;+ console.log(value); // raw SSE chunk(s) — split on "\n\n", strip "data:", JSON.parse+}+```++To **resume** after a disconnect, reconnect with `after=<last seq you saw>` — you won't miss or duplicate events.++## 3. Steer it++Send a follow-up at any time. The session wakes and continues with full prior context.++```bash+curl https://api.opencomputer.dev/v3/sessions/$ID/messages \+ -H "Authorization: Bearer $CLIENT_TOKEN" \+ -d '{ "text": "also check the CI config", "idempotency_key": "nudge-1" }'+```++## 4. Get notified (optional)++Register a webhook and the agent's user-facing messages are delivered to it — signed, retried, and de-duplicated.++```bash+curl https://api.opencomputer.dev/v3/sessions/$ID/destinations \+ -H "Authorization: Bearer $OPENCOMPUTER_API_KEY" \+ -d '{ "url": "https://your.app/oc-webhook", "secret": "whsec_…", "level": "user" }'+```++See [Messaging & webhooks](/agent-sessions/messaging) to verify the signature.++## Next steps++<CardGroup cols={2}>+ <Card title="Concepts" icon="book" href="/agent-sessions/concepts">+ The session model: events, cursors, statuses.+ </Card>+ <Card title="Messaging & webhooks" icon="bell" href="/agent-sessions/messaging">+ The envelope, steering, and reliable delivery.+ </Card>+</CardGroup>diff --git a/docs/agent-sessions/runtimes.mdx b/docs/agent-sessions/runtimes.mdxnew file mode 100644index 00000000..cffe5c6e--- /dev/null+++ b/docs/agent-sessions/runtimes.mdx@@ -0,0 +1,36 @@+---+title: "Runtimes"+description: "The engine that runs your agent — claude today, more soon"+---++A **runtime** is the stateless engine that executes the agent loop. You pick one per agent via `runtime`; it defaults to `claude`.++## `claude` — available today++The managed Claude agent loop. It works in a sandbox through remote tools, streams its steps into the session as events, and runs on Anthropic models — platform-billed by default, or on your [own key](/agent-sessions/authentication#model-credentials-byo-key).++```bash+curl https://api.opencomputer.dev/v3/agents \+ -H "Authorization: Bearer $OPENCOMPUTER_API_KEY" \+ -d '{ "name": "reviewer", "model": "anthropic/claude-opus-4-8",+ "prompt": "You review code.", "runtime": "claude" }'+```++## Coming soon++<Note>The runtimes below are not yet callable. `runtime` is an open field, so adopting one later is just a new value — no breaking changes to the API you build against today.</Note>++- **`codex`, `opencode`** — prebuilt, multi-provider runtimes.+- **Custom (bring your own image)** — package any harness — your own, or a lab's — as a runtime.++### How custom runtimes will work++A runtime is a container image implementing the **runtime contract**. On wake it:++1. Reads the session's events from the cursor.+2. Drives its own agent loop.+3. **Streams events back** to the session over the authenticated events API.+4. Performs all side effects through the **remote sandbox tools** (no local disk or network).+5. Calls the model, and **exits 0 when it has nothing left to do** (yield, don't block).++It holds no durable state — the session is the durable record. You'll register it with `oc runtime push <image>` and select it with `runtime: "<name>"`. This is the extensibility seam: any agent harness becomes a runtime.diff --git a/docs/docs.json b/docs/docs.jsonindex 53e5546d..dd9cc008 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -58,6 +58,19 @@}]},+ {+ "group": "Durable Agent Sessions",+ "pages": [+ "agent-sessions/overview",+ "agent-sessions/quickstart",+ "agent-sessions/concepts",+ "agent-sessions/authentication",+ "agent-sessions/durability",+ "agent-sessions/messaging",+ "agent-sessions/runtimes",+ "agent-sessions/api-reference"+ ]+ },{"group": "Reserved Capacity","pages": [