An open-source, faster Devin alternative
TypeScript
docs: use concise REST examples for agent sessions
Igor Zalutskidd7345dddcd1
diff --git a/docs/agent-sessions/agents.mdx b/docs/agent-sessions/agents.mdxindex 1eb022ae..8928b069 100644--- a/docs/agent-sessions/agents.mdx+++ b/docs/agent-sessions/agents.mdx@@ -5,22 +5,23 @@ description: "The reusable definition of what runs"An **agent** is a first-class, reusable definition of *what* runs — a `name`, a `prompt` (its instructions), a `model`, and a [`runtime`](/agent-sessions/runtimes). Every [session](/agent-sessions/sessions) runs on an agent, so create one first, then start as many sessions on it as you like.-```ts-const agent = await oc("/agents", {- method: "POST",- body: JSON.stringify({- name: "reviewer",- runtime: "claude",- model: "anthropic/claude-opus-4-8",- prompt: "Review the target repo. Run tests, summarize risks, and say the final result.",- key: process.env.ANTHROPIC_API_KEY,- }),-});+```http+POST https://api.opencomputer.dev/v3/agents+Authorization: Bearer $OPENCOMPUTER_API_KEY+Content-Type: application/json++{+ "name": "reviewer",+ "runtime": "claude",+ "model": "anthropic/claude-opus-4-8",+ "prompt": "Review the target repo. Run tests, summarize risks, and say the final result.",+ "key": "sk-ant-..."+}```Pass your Anthropic `key` inline and it's stored as a [credential](/agent-sessions/authentication#model-credentials) and attached to the agent — sessions run the model on it. Already have a credential? Reference it with `credential: "cred_…"` instead, or omit both to use your org default. Optionally set default [`limits`](/agent-sessions/sessions#limits) (`tokens`/`turn_seconds`/`turns`) too; sessions inherit them.-<Tip>Use the server-side `oc()` helper from the [quickstart](/agent-sessions/quickstart#1-add-the-server-helper). Keep the org key and model key on your backend.</Tip>+<Tip>Keep the org key and model key on your backend. Only return session-scoped client tokens to browsers.</Tip>## Pinned snapshotdiff --git a/docs/agent-sessions/authentication.mdx b/docs/agent-sessions/authentication.mdxindex 4d7d4987..be0cf4a2 100644--- a/docs/agent-sessions/authentication.mdx+++ b/docs/agent-sessions/authentication.mdx@@ -5,23 +5,16 @@ description: "Org keys, browser-safe client tokens, and bring-your-own model keyThree credentials, each with a job.-<Tip>Examples that call `oc()` use the server-side helper from the [quickstart](/agent-sessions/quickstart#1-add-the-server-helper).</Tip>-## Org API keyYour account key. Use it server-side for all **management** calls — creating agents, starting sessions, registering webhooks, managing credentials.-```ts-const res = await fetch("https://api.opencomputer.dev/v3/sessions", {- method: "POST",- headers: {- Authorization: `Bearer ${process.env.OPENCOMPUTER_API_KEY}`,- "Content-Type": "application/json",- },- body: JSON.stringify({ agent, input }),-});--if (!res.ok) throw new Error(await res.text());+```http+POST https://api.opencomputer.dev/v3/sessions+Authorization: Bearer $OPENCOMPUTER_API_KEY+Content-Type: application/json++{ "agent": "agt_...", "input": "Run the tests and summarize failures." }```<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>@@ -32,11 +25,12 @@ A **session-scoped, short-lived** token with `read` + `steer` scope — safe toYou get one back from `POST /v3/sessions`, and can mint more:-```ts-const token = await oc(`/sessions/${sessionId}/client-tokens`, {- method: "POST",- body: JSON.stringify({ scopes: ["read", "steer"], ttl: 3600 }),-});+```http+POST https://api.opencomputer.dev/v3/sessions/sess_.../client-tokens+Authorization: Bearer $OPENCOMPUTER_API_KEY+Content-Type: application/json++{ "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.@@ -57,20 +51,20 @@ Sessions run the model on **your own Anthropic key**. It's held in OpenComputer'The easiest way to add one is inline when you [create an agent](/agent-sessions/agents) (`"key": "sk-ant-…"`). The standalone resource below is for reusing one key across agents, setting an org default, and rotating/removing keys:-```ts-const credential = await oc<{ id: string }>("/credentials", {- method: "POST",- body: JSON.stringify({- provider: "anthropic",- key: process.env.ANTHROPIC_API_KEY,- name: "prod",- }),-});--await oc("/credentials/default", {- method: "PUT",- body: JSON.stringify({ credential: credential.id }),-});+```http+POST https://api.opencomputer.dev/v3/credentials+Authorization: Bearer $OPENCOMPUTER_API_KEY+Content-Type: application/json++{ "provider": "anthropic", "key": "sk-ant-...", "name": "prod" }+```++```http+PUT https://api.opencomputer.dev/v3/credentials/default+Authorization: Bearer $OPENCOMPUTER_API_KEY+Content-Type: application/json++{ "credential": "cred_..." }```**Resolution** per session: the agent's credential → your org default for the provider. (No platform-billed fallback yet — bring a key.)diff --git a/docs/agent-sessions/messaging.mdx b/docs/agent-sessions/messaging.mdxindex ffd5aaa1..ed5b0c63 100644--- a/docs/agent-sessions/messaging.mdx+++ b/docs/agent-sessions/messaging.mdx@@ -9,25 +9,14 @@ description: "Steer a session, and the shared message envelope"Send a message to a running or idle session; it wakes and continues with its prior context. Minimal form is just text:-```ts-async function steer(sessionId: string, clientToken: string, text: string) {- const res = await fetch(- `https://api.opencomputer.dev/v3/sessions/${sessionId}/messages`,- {- method: "POST",- headers: {- Authorization: `Bearer ${clientToken}`,- "Content-Type": "application/json",- },- body: JSON.stringify({- text,- idempotency_key: crypto.randomUUID(),- }),- },- );-- if (!res.ok) throw new Error(await res.text());- return res.json();+```http+POST https://api.opencomputer.dev/v3/sessions/sess_.../messages+Authorization: Bearer $CLIENT_TOKEN+Content-Type: application/json++{+ "text": "also check the CI config",+ "idempotency_key": "msg_01"}```diff --git a/docs/agent-sessions/overview.mdx b/docs/agent-sessions/overview.mdxindex 8be01739..c2494513 100644--- a/docs/agent-sessions/overview.mdx+++ b/docs/agent-sessions/overview.mdx@@ -58,7 +58,7 @@ Reach for sessions when you want a long-running or interactive agent and don't w<CardGroup cols={2}><Card title="Quickstart" icon="bolt" href="/agent-sessions/quickstart">- Build a streaming TypeScript UI with a server-side helper and client token.+ Start a session, stream events, and steer it with concise REST examples.</Card><Card title="Prompting" icon="file-lines" href="/agent-sessions/prompting">Start from a prompt template designed for useful event streams and final results.diff --git a/docs/agent-sessions/prompting.mdx b/docs/agent-sessions/prompting.mdxindex be23d3ff..df2776d0 100644--- a/docs/agent-sessions/prompting.mdx+++ b/docs/agent-sessions/prompting.mdx@@ -11,8 +11,7 @@ Use a prompt that tells the agent how to work in the sandbox, how to communicateThis is a production-minded baseline for coding agents. Adapt the product-specific section, but keep the operating rules explicit.-```ts-export const CODING_AGENT_PROMPT = `+```txtYou are a coding agent running in an OpenComputer Durable Agent Session.You work in a remote Linux sandbox. You cannot access the user's machine.@@ -40,15 +39,13 @@ Communication rules:Task:{{TASK}}-`.trim();```## App-builder variantFor a Lovable-style builder, add a clear build target and preview convention:-```ts-export const APP_BUILDER_PROMPT = `+```txtYou are an app-building agent. Turn the user's request into a working web app in your sandbox, then keep improving it as they chat with you.Build rules:@@ -62,7 +59,6 @@ User communication:- Say what you are doing at useful milestones: scaffolding, installing, editing, running, verifying.- When the app is running, say what was built and what the user can ask for next.- Ask only when the request is ambiguous enough that proceeding would likely waste the user's time.-`.trim();```<Note>First-class preview artifacts are coming soon. Until then, treat preview instructions as a convention for your app and event renderer, not as a guaranteed platform event.</Note>@@ -71,21 +67,18 @@ User communication:Do not bury machine-readable context in prose. Pass it in the message envelope or session input so your prompt can tell the agent to rely on it.-```ts-await oc("/sessions", {- method: "POST",- body: JSON.stringify({- agent,- input: {- text: "Review this pull request and summarize risky changes.",- refs: {- repo: "https://github.com/acme/app",- branch: "feature/billing",- pr: "128",- },- },- }),-});+```json+{+ "agent": "agt_...",+ "input": {+ "text": "Review this pull request and summarize risky changes.",+ "refs": {+ "repo": "https://github.com/acme/app",+ "branch": "feature/billing",+ "pr": "128"+ }+ }+}```Then include a rule in the prompt:diff --git a/docs/agent-sessions/quickstart.mdx b/docs/agent-sessions/quickstart.mdxindex 11816761..d76571b0 100644--- a/docs/agent-sessions/quickstart.mdx+++ b/docs/agent-sessions/quickstart.mdx@@ -1,13 +1,13 @@---title: "Quickstart"-description: "Build a streaming agent UI in TypeScript"+description: "Start a session, stream it live, and steer it"----Build the smallest useful Durable Agent Sessions app: your backend starts a session with an org key, then your browser streams and steers that one session with a scoped `client_token`.+Build the smallest useful Durable Agent Sessions integration: define an agent, start a session, stream its event log, then send follow-up messages with a scoped client token.<CardGroup cols={2}><Card title="Complete example app" icon="github" href="https://github.com/diggerhq/oc-sessions-demos">- A Lovable-style app builder using the same pattern.+ A Lovable-style app builder using the same API calls.</Card><Card title="Prompt template" icon="file-lines" href="/agent-sessions/prompting">A production-minded Claude runtime prompt you can adapt.@@ -16,7 +16,7 @@ Build the smallest useful Durable Agent Sessions app: your backend starts a sess## Prerequisites-Set two server-side environment variables:+You need an OpenComputer API key and an Anthropic key:```bashOPENCOMPUTER_API_KEY=osb_...@@ -25,232 +25,131 @@ ANTHROPIC_API_KEY=sk-ant-...<Tip>Grab your OpenComputer API key from [app.opencomputer.dev](https://app.opencomputer.dev). Sessions run the model on your Anthropic key.</Tip>-## 1. Add the server helper+## 1. Create an agent-Keep all management calls server-side. This helper creates the reusable agent, starts sessions, and mints fresh browser tokens.+An agent is the reusable definition of what runs: name, runtime, model, prompt, and model credential.-```ts-// src/oc.ts-const OC = process.env.OC_API_URL ?? "https://api.opencomputer.dev";-const ORG_KEY = process.env.OPENCOMPUTER_API_KEY;-const ANTHROPIC_KEY = process.env.ANTHROPIC_API_KEY;+```http+POST https://api.opencomputer.dev/v3/agents+Authorization: Bearer $OPENCOMPUTER_API_KEY+Content-Type: application/json-const PROMPT = `-You are a coding agent working in an OpenComputer sandbox.--Use bash/read/write/ls for all filesystem and command work.-Emit short progress updates with say as you work.-Ask only when blocked. Otherwise make a reasonable choice and continue.-When done, say exactly what changed and how to verify it.-`.trim();--export async function oc<T>(path: string, init: RequestInit = {}): Promise<T> {- if (!ORG_KEY) throw new Error("OPENCOMPUTER_API_KEY is not set");+{+ "name": "quickstart-coder",+ "runtime": "claude",+ "model": "anthropic/claude-opus-4-8",+ "prompt": "You are a coding agent. Work in /workspace. Use bash/read/write/ls for all work. Use say for concise progress and final results. Ask only when blocked.",+ "key": "sk-ant-...",+ "limits": { "turns": 4, "turn_seconds": 600 }+}+```- const res = await fetch(`${OC}/v3${path}`, {- ...init,- headers: {- Authorization: `Bearer ${ORG_KEY}`,- "Content-Type": "application/json",- ...init.headers,- },- });+Response:- if (!res.ok) {- throw new Error(`OpenComputer ${res.status}: ${await res.text()}`);- }+```json+{ "id": "agt_...", "name": "quickstart-coder", "revision": 1 }+```- return res.json() as Promise<T>;-}+<Tip>`POST /agents` is idempotent by agent name, so it is fine to call this during application startup.</Tip>-let agentId: Promise<string> | undefined;--export function ensureAgent() {- if (!ANTHROPIC_KEY) throw new Error("ANTHROPIC_API_KEY is not set");-- agentId ??= oc<{ id: string }>("/agents", {- method: "POST",- body: JSON.stringify({- name: "quickstart-coder",- runtime: "claude",- model: "anthropic/claude-opus-4-8",- prompt: PROMPT,- key: ANTHROPIC_KEY,- limits: { turns: 4, turn_seconds: 600 },- }),- })- .then((agent) => agent.id)- .catch((err) => {- agentId = undefined;- throw err;- });-- return agentId;-}+## 2. Start a session-export async function startSession(input: string) {- const agent = await ensureAgent();+A session starts work immediately and returns a browser-safe `client_token` for that one session.- return oc<{- session: { id: string; status: string; head: number };- client_token: string;- }>("/sessions", {- method: "POST",- body: JSON.stringify({ agent, input }),- });-}+```http+POST https://api.opencomputer.dev/v3/sessions+Authorization: Bearer $OPENCOMPUTER_API_KEY+Content-Type: application/json-export async function mintClientToken(sessionId: string) {- return oc<{ client_token: string; expires_at: string }>(- `/sessions/${sessionId}/client-tokens`,- {- method: "POST",- body: JSON.stringify({ scopes: ["read", "steer"], ttl: 3600 }),- },- );+{+ "agent": "agt_...",+ "input": "Create a todo app with local storage and a clean dark UI."}```-## 2. Start a session from your backend+Response:-In a Next.js route, accept a user task and return only the session plus its scoped token. The org key never reaches the browser.--```ts-// app/api/sessions/route.ts-import { startSession } from "@/oc";+```json+{+ "session": { "id": "sess_...", "status": "queued", "head": 1 },+ "client_token": "ct_..."+}+```-export async function POST(req: Request) {- const { input } = await req.json();+## 3. Stream events- if (typeof input !== "string" || !input.trim()) {- return Response.json({ error: "input is required" }, { status: 400 });- }+Use the `client_token` in the browser. Ask for `progress` for a good activity feed, or `internal` for an operator/debug view.- try {- return Response.json(await startSession(input));- } catch (err) {- return Response.json({ error: (err as Error).message }, { status: 502 });- }-}+```http+GET https://api.opencomputer.dev/v3/sessions/sess_.../events?stream=sse&level=progress&token=ct_...```-## 3. Stream events in the browser--Use the `client_token` with native `EventSource`. Ask for `progress` when you want a good user-facing activity feed, or `internal` for a debugging console.+In a browser:-```tsx-const OC = process.env.NEXT_PUBLIC_OC_API_URL ?? "https://api.opencomputer.dev";+```js+const events = new EventSource(+ `${OC}/v3/sessions/${sessionId}/events?stream=sse&level=progress&token=${clientToken}`,+);-type SessionEvent = {- id: string;- seq: number;- type: string;- level: "user" | "progress" | "internal";- body?: Record<string, unknown>;+events.onmessage = (message) => {+ const event = JSON.parse(message.data);+ render(event);};+```-async function createSession(input: string) {- const res = await fetch("/api/sessions", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ input }),- });-- if (!res.ok) throw new Error(await res.text());- return res.json() as Promise<{- session: { id: string };- client_token: string;- }>;-}+Each event's `seq` is sent as the SSE `id`, so `EventSource` resumes automatically with `Last-Event-ID` after a dropped connection.-function streamSession(- sessionId: string,- clientToken: string,- onEvent: (event: SessionEvent) => void,-) {- const url = new URL(`${OC}/v3/sessions/${sessionId}/events`);- url.searchParams.set("stream", "sse");- url.searchParams.set("level", "progress");- url.searchParams.set("token", clientToken);-- const es = new EventSource(url.toString());- es.onmessage = (message) => onEvent(JSON.parse(message.data));- es.onerror = () => {- // EventSource reconnects automatically. Each event seq is sent as the SSE id,- // so the browser resumes with Last-Event-ID after a dropped connection.- };-- return () => es.close();-}-```+## 4. Render by `type`-## 4. Render by event type+Switch on the event `type`. Do not parse prose to decide whether work finished or failed.-The stable discriminator is `type`. Do not parse prose to decide whether a turn finished or failed.+```json+{ "type": "agent.message", "level": "user", "body": { "text": "Done. I built..." } }+{ "type": "tool.call", "level": "progress", "body": { "tool": "bash", "args_summary": "npm test" } }+{ "type": "exec.completed", "level": "progress", "body": { "exit_code": 0, "summary": "12 tests passed" } }+{ "type": "turn.completed", "level": "user", "body": { "yield_reason": "completed", "result_event_id": "evt_..." } }+```-```tsx-function EventRow({ event }: { event: SessionEvent }) {- const body = event.body ?? {};+Handle `turn.completed.body.yield_reason` explicitly:- switch (event.type) {- case "agent.message":- return <p>{String(body.text ?? "")}</p>;+| `yield_reason` | UI behavior |+| --- | --- |+| `completed` | Show the final result. |+| `needs_input` | Show the agent's question and enable reply. |+| `deadline_exceeded`, `budget_exceeded`, `max_turns` | Explain which limit stopped the turn. |+| `error`, `canceled` | Show a stopped/error state. |- case "tool.call":- return <code>$ {String(body.args_summary ?? body.tool ?? "tool")}</code>;+## 5. Steer the session- case "exec.completed":- return (- <pre>- exit {String(body.exit_code)}- {"\n"}- {String(body.summary ?? "")}- </pre>- );+Post follow-up messages with the same `client_token`. An idle session wakes and continues with its prior context.- case "turn.completed": {- const reason = String(body.yield_reason ?? "completed");- if (reason === "completed") return <p>Done</p>;- if (reason === "needs_input") return <p>Waiting for input</p>;- return <p>Stopped: {reason}</p>;- }+```http+POST https://api.opencomputer.dev/v3/sessions/sess_.../messages+Authorization: Bearer $CLIENT_TOKEN+Content-Type: application/json- default:- return body.text || body.summary ? <p>{String(body.text ?? body.summary)}</p> : null;- }+{+ "text": "Add a filter for completed tasks.",+ "idempotency_key": "msg_01"}```-## 5. Steer the session+Response:-Post follow-up messages directly from the browser with the same `client_token`. The session wakes if it was idle and continues with its prior context.--```ts-async function steer(sessionId: string, clientToken: string, text: string) {- const res = await fetch(`${OC}/v3/sessions/${sessionId}/messages`, {- method: "POST",- headers: {- Authorization: `Bearer ${clientToken}`,- "Content-Type": "application/json",- },- body: JSON.stringify({- text,- idempotency_key: crypto.randomUUID(),- }),- });-- if (!res.ok) throw new Error(await res.text());- return res.json();+```json+{+ "event": { "id": "evt_...", "seq": 14 },+ "session": { "id": "sess_...", "status": "queued", "head": 14 }}```## Production checklist+- Keep the org API key and Anthropic key server-side.- Add app auth before minting or returning a `client_token`.-- Set `limits` on the agent or session to bound tokens, wall-clock time, and auto-run count.-- Render every non-`completed` `yield_reason` explicitly, especially `error`, `deadline_exceeded`, `budget_exceeded`, and `canceled`.+- Set `limits` on the agent or session.- Use `idempotency_key` for every user action you might retry.-- Use `level=user` for customer-facing chat, `level=progress` for activity feeds, and `level=internal` only for operator/debug views.+- Use `level=user` for customer-facing chat, `level=progress` for activity feeds, and `level=internal` only for debugging.- Register a [webhook](/agent-sessions/webhooks) when your backend needs push delivery after the tab closes.## Next stepsdiff --git a/docs/agent-sessions/runtimes.mdx b/docs/agent-sessions/runtimes.mdxindex a97194cd..915d6447 100644--- a/docs/agent-sessions/runtimes.mdx+++ b/docs/agent-sessions/runtimes.mdx@@ -9,19 +9,18 @@ A **runtime** is the engine that executes the agent loop. You pick one per agentThe managed Claude agent loop. It works in a sandbox through remote tools, streams its steps into the session as events, and runs Claude models on your [Anthropic key](/agent-sessions/authentication#model-credentials).-<Tip>This example uses the server-side `oc()` helper from the [quickstart](/agent-sessions/quickstart#1-add-the-server-helper).</Tip>--```ts-await oc("/agents", {- method: "POST",- body: JSON.stringify({- name: "reviewer",- runtime: "claude",- model: "anthropic/claude-opus-4-8",- prompt: "Review code in the sandbox. Run tests, explain risks, and say the final result.",- credential: "cred_...",- }),-});+```http+POST https://api.opencomputer.dev/v3/agents+Authorization: Bearer $OPENCOMPUTER_API_KEY+Content-Type: application/json++{+ "name": "reviewer",+ "runtime": "claude",+ "model": "anthropic/claude-opus-4-8",+ "prompt": "Review code in the sandbox. Run tests, explain risks, and say the final result.",+ "credential": "cred_..."+}```### How it's structureddiff --git a/docs/agent-sessions/sessions.mdx b/docs/agent-sessions/sessions.mdxindex 8f6ecb8a..5614fec7 100644--- a/docs/agent-sessions/sessions.mdx+++ b/docs/agent-sessions/sessions.mdx@@ -31,18 +31,26 @@ A session also carries `last_turn = { id, state, yield_reason?, result_event_id?Don't sniff prose for "is it done." Await the **`turn.completed`** event (on the [stream](/agent-sessions/events) or a [webhook](/agent-sessions/webhooks)), then fetch the answer:-<Tip>This example uses the server-side `oc()` helper from the [quickstart](/agent-sessions/quickstart#1-add-the-server-helper).</Tip>--```ts-const result = await oc<{- last_turn: { yield_reason?: string };- result?: { body?: { text?: string } };-}>(`/sessions/${sessionId}/result`);--if (result.last_turn.yield_reason === "completed") {- console.log(result.result?.body?.text);-} else {- console.log(`turn ended: ${result.last_turn.yield_reason}`);+```http+GET https://api.opencomputer.dev/v3/sessions/sess_.../result+Authorization: Bearer $OPENCOMPUTER_API_KEY+```++Response:++```json+{+ "last_turn": {+ "id": "trn_...",+ "state": "ok",+ "yield_reason": "completed",+ "result_event_id": "evt_..."+ },+ "result": {+ "type": "agent.message",+ "level": "user",+ "body": { "text": "Done. I found..." }+ }}```diff --git a/docs/agent-sessions/webhooks.mdx b/docs/agent-sessions/webhooks.mdxindex ff702efd..b086e934 100644--- a/docs/agent-sessions/webhooks.mdx+++ b/docs/agent-sessions/webhooks.mdx@@ -7,18 +7,17 @@ Register a **destination** and a session's [events](/agent-sessions/events) are## Destinations-<Tip>This example uses the server-side `oc()` helper from the [quickstart](/agent-sessions/quickstart#1-add-the-server-helper).</Tip>--```ts-const destination = await oc<{ id: string }>(`/sessions/${sessionId}/destinations`, {- method: "POST",- body: JSON.stringify({- url: "https://your.app/oc-webhook",- secret: process.env.OC_WEBHOOK_SECRET,- level: "user",- include_raw: false,- }),-});+```http+POST https://api.opencomputer.dev/v3/sessions/sess_.../destinations+Authorization: Bearer $OPENCOMPUTER_API_KEY+Content-Type: application/json++{+ "url": "https://your.app/oc-webhook",+ "secret": "whsec_...",+ "level": "user",+ "include_raw": false+}````level` is the visibility threshold (`user` default, or `progress`); `types` is an optional event-type allow-list (default: all — which **includes the terminal `turn.completed`**); `include_raw: false` strips `body.raw` from the delivered Event. To get only completions, set `types: ["turn.completed"]`.