An open-source, faster Devin alternative
TypeScript
docs: make agent sessions onboarding app-first
Igor Zalutski97e9e472fc23
diff --git a/docs/agent-sessions/agents.mdx b/docs/agent-sessions/agents.mdxindex 5e9f251a..1eb022ae 100644--- a/docs/agent-sessions/agents.mdx+++ b/docs/agent-sessions/agents.mdx@@ -5,15 +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.-```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", "key": "sk-ant-…" }'+```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,+ }),+});```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>+## Pinned snapshotWhen a session is created it **freezes** the agent's `prompt`, `model`, `runtime`, and `revision` (a number that bumps on every edit) into the session — and pins the resolved credential too. Editing the named agent afterwards never changes a running or resumed session — its behavior is pinned for its whole life. Update an agent freely: existing sessions keep what they started with, new sessions pick up the change. (Rotating a credential's **key value** is the exception — that flows to running sessions, so a compromised key can be replaced; see [authentication](/agent-sessions/authentication#model-credentials).)diff --git a/docs/agent-sessions/authentication.mdx b/docs/agent-sessions/authentication.mdxindex 79182aaa..4d7d4987 100644--- a/docs/agent-sessions/authentication.mdx+++ b/docs/agent-sessions/authentication.mdx@@ -5,13 +5,23 @@ 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.-```bash-curl https://api.opencomputer.dev/v3/sessions \- -H "Authorization: Bearer $OPENCOMPUTER_API_KEY" -d '{ … }'+```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());```<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>@@ -22,10 +32,11 @@ A **session-scoped, short-lived** token with `read` + `steer` scope — safe toYou 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 }'+```ts+const token = await oc(`/sessions/${sessionId}/client-tokens`, {+ method: "POST",+ body: JSON.stringify({ 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.@@ -46,16 +57,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:-```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 '{ "credential": "cred_…" }'+```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 }),+});```**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 c12b8d4c..ffd5aaa1 100644--- a/docs/agent-sessions/messaging.mdx+++ b/docs/agent-sessions/messaging.mdx@@ -9,10 +9,26 @@ 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:-```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" }'+```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();+}```Pass `idempotency_key` so retries (flaky network, double-click) are de-duplicated — applied at most once **per session**, so the same key is safe to reuse across different sessions.diff --git a/docs/agent-sessions/overview.mdx b/docs/agent-sessions/overview.mdxindex e8d51fc1..8be01739 100644--- a/docs/agent-sessions/overview.mdx+++ b/docs/agent-sessions/overview.mdx@@ -31,14 +31,14 @@ Give an agent a prompt and a task; OpenComputer runs it on a managed runtime and## Get started<Steps>- <Step title="Define an agent (with your key)">- A reusable `{ name, model, prompt, runtime }` — `POST /v3/agents`. Pass your Anthropic `key` inline; it's stored as a [credential](/agent-sessions/authentication#model-credentials). ([Agents](/agent-sessions/agents))+ <Step title="Define an agent">+ Create a reusable `{ name, model, prompt, runtime }` from your backend. Pass your Anthropic `key` inline, or reference a saved [credential](/agent-sessions/authentication#model-credentials). ([Agents](/agent-sessions/agents))</Step><Step title="Start a session">- `POST /v3/sessions { agent, input }` — the agent starts immediately; you get the session and a browser-safe `client_token`.+ Start a session with `{ agent, input }`. The agent starts immediately and returns a browser-safe `client_token`.</Step><Step title="Watch, steer, get notified">- Stream `GET …/events?stream=sse` ([resume](/agent-sessions/events) from any cursor), `POST …/messages` to [steer](/agent-sessions/messaging), and register a [webhook](/agent-sessions/webhooks) for push.+ Stream events with `EventSource`, [steer](/agent-sessions/messaging) with the client token, and register a [webhook](/agent-sessions/webhooks) when your backend needs push delivery.</Step></Steps>@@ -58,7 +58,10 @@ 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">- Start a session, stream it, and steer it in a few minutes.+ Build a streaming TypeScript UI with a server-side helper and client token.+ </Card>+ <Card title="Prompting" icon="file-lines" href="/agent-sessions/prompting">+ Start from a prompt template designed for useful event streams and final results.</Card><Card title="How sessions work" icon="book" href="/agent-sessions/sessions">How a session works — lifecycle and events.diff --git a/docs/agent-sessions/prompting.mdx b/docs/agent-sessions/prompting.mdxnew file mode 100644index 00000000..be23d3ff--- /dev/null+++ b/docs/agent-sessions/prompting.mdx@@ -0,0 +1,128 @@+---+title: "Prompting agents"+description: "Write Claude runtime prompts that produce reliable sessions"+---++In Durable Agent Sessions, the prompt is part of your application contract. It shapes the event stream your UI renders, when the agent asks for help, what it treats as done, and how easy failures are to debug.++Use a prompt that tells the agent how to work in the sandbox, how to communicate progress, and how to end each turn.++## A good starting prompt++This 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 = `+You 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.+Use only the provided tools for side effects:+- bash: run commands in the sandbox+- read: inspect files+- write: create or edit files+- ls: list directories+- say: send concise progress updates and final results to the user+- ask: request a decision only when you are genuinely blocked++Operating rules:+- Work in /workspace unless the user gives a different path.+- Prefer small, verifiable changes over large rewrites.+- Run the relevant tests or commands before saying the work is done.+- Keep commands idempotent where possible. A turn may be retried after a crash.+- Do not hide failures. If a command fails, inspect the output, fix the issue, and retry.+- If you need a decision, ask one clear question and stop. Otherwise choose a reasonable default and continue.++Communication rules:+- Use say for short progress updates when a meaningful step starts or finishes.+- Do not narrate private chain-of-thought. Report observable work: files changed, commands run, results found.+- End each successful turn with a final say that includes what changed and how to verify it.+- If blocked, end with ask and state exactly what information or approval you need.++Task:+{{TASK}}+`.trim();+```++## App-builder variant++For a Lovable-style builder, add a clear build target and preview convention:++```ts+export const APP_BUILDER_PROMPT = `+You 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:+- Work in /workspace.+- For a new app, scaffold a small React app with Vite.+- Install dependencies, implement the request, and keep the app runnable.+- Run the dev server on 0.0.0.0:3000 when the app is ready.+- Keep each follow-up change small, then verify the app still starts.++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>++## Pass structured context++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",+ },+ },+ }),+});+```++Then include a rule in the prompt:++```txt+If refs.repo, refs.branch, refs.commit, refs.issue, or refs.pr are present, treat them as authoritative task context. Do not infer those values from prose.+```++## Make outputs easy to render++Design your prompt around the UI you want:++| UI surface | Prompt instruction |+| --- | --- |+| Chat bubble | "Use `say` for user-facing answers and final results." |+| Activity feed | "Say short progress updates only at meaningful milestones." |+| Debug console | "Run commands with clear working directories and concise output." |+| Approval flow | "Use `ask` only when blocked by a user decision." |+| Result page | "End with a final `say` summarizing result, verification, and next action." |++Your renderer should still switch on [event `type`](/agent-sessions/events#event-shape), not on the prompt's wording.++## Avoid these prompt mistakes++- Do not say "ask me if anything is unclear" without also saying when to proceed. That causes avoidable pauses.+- Do not request verbose narration. It makes `progress` streams noisy.+- Do not tell the agent to use local machine paths. Its tools operate in the sandbox.+- Do not rely on unstructured final prose as your only completion signal. Await `turn.completed`.+- Do not assume side effects run once. Use idempotency keys in your app and ask the agent to make external actions idempotent.++## Where to go next++<CardGroup cols={2}>+ <Card title="Runtime tools" icon="toolbox" href="/agent-sessions/runtime-tools">+ The exact tools the Claude runtime can use.+ </Card>+ <Card title="Events" icon="timeline" href="/agent-sessions/events">+ How progress updates, tool calls, results, and errors appear in the log.+ </Card>+</CardGroup>diff --git a/docs/agent-sessions/quickstart.mdx b/docs/agent-sessions/quickstart.mdxindex 8e77e5b8..11816761 100644--- a/docs/agent-sessions/quickstart.mdx+++ b/docs/agent-sessions/quickstart.mdx@@ -1,93 +1,271 @@---title: "Quickstart"-description: "Start a session, stream it live, and steer it"+description: "Build a streaming agent UI in TypeScript"---+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`.++<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.+ </Card>+ <Card title="Prompt template" icon="file-lines" href="/agent-sessions/prompting">+ A production-minded Claude runtime prompt you can adapt.+ </Card>+</CardGroup>+## Prerequisites+Set two server-side environment variables:+```bash-export OPENCOMPUTER_API_KEY=your-api-key+OPENCOMPUTER_API_KEY=osb_...+ANTHROPIC_API_KEY=sk-ant-...```-<Tip>Grab your API key from [app.opencomputer.dev](https://app.opencomputer.dev).</Tip>+<Tip>Grab your OpenComputer API key from [app.opencomputer.dev](https://app.opencomputer.dev). Sessions run the model on your Anthropic key.</Tip>-## 1. Create an agent (with your Anthropic key)+## 1. Add the server helper-An [agent](/agent-sessions/agents) is the reusable "what" — a name, a prompt, and a model. Sessions run the model on **your** Anthropic key, so pass it inline with `key`. It's held in OpenComputer's [secret store](/sandboxes/secrets) (encrypted, write-only); the **real key never enters the sandbox** — it's sealed, and a host proxy reveals it only on the outbound call to Anthropic, so it's never exposed to the model or the agent's code.+Keep all management calls server-side. This helper creates the reusable agent, starts sessions, and mints fresh browser tokens.-```bash-curl https://api.opencomputer.dev/v3/agents \- -H "Authorization: Bearer $OPENCOMPUTER_API_KEY" \- -d '{ "name": "coder", "prompt": "You are a coding assistant.",- "model": "anthropic/claude-opus-4-8", "key": "sk-ant-…" }'-# → { "id": "agt_…", "name": "coder", … }-```+```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;-<Tip>Reusing one key across agents? Add it once via [`POST /credentials`](/agent-sessions/authentication#model-credentials), set it as your default, and skip `key` here.</Tip>+const PROMPT = `+You are a coding agent working in an OpenComputer sandbox.-## 2. Start a session+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();-Start a session on the agent with a task. Add an optional `webhook` to receive every event from the start.+export async function oc<T>(path: string, init: RequestInit = {}): Promise<T> {+ if (!ORG_KEY) throw new Error("OPENCOMPUTER_API_KEY is not set");-```bash-curl https://api.opencomputer.dev/v3/sessions \- -H "Authorization: Bearer $OPENCOMPUTER_API_KEY" \- -d '{ "agent": "agt_…",- "input": "Write a Python script that prints the first 20 primes, run it, and report the output.",- "webhook": "https://your.app/oc-webhook" }'+ const res = await fetch(`${OC}/v3${path}`, {+ ...init,+ headers: {+ Authorization: `Bearer ${ORG_KEY}`,+ "Content-Type": "application/json",+ ...init.headers,+ },+ });++ if (!res.ok) {+ throw new Error(`OpenComputer ${res.status}: ${await res.text()}`);+ }++ return res.json() as Promise<T>;+}++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;+}++export async function startSession(input: string) {+ const agent = await ensureAgent();++ return oc<{+ session: { id: string; status: string; head: number };+ client_token: string;+ }>("/sessions", {+ method: "POST",+ body: JSON.stringify({ agent, input }),+ });+}++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 }),+ },+ );+}```-```jsonc-{- "session": { "id": "sess_abc", "status": "queued", "head": 1, "input_cursor": 0 },- "client_token": "ct_…" // session-scoped; safe to hand to a browser (read + steer)+## 2. Start a session from your backend++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";++export async function POST(req: Request) {+ const { input } = await req.json();++ if (typeof input !== "string" || !input.trim()) {+ return Response.json({ error: "input is required" }, { status: 400 });+ }++ try {+ return Response.json(await startSession(input));+ } catch (err) {+ return Response.json({ error: (err as Error).message }, { status: 502 });+ }}```-<Note>Reuse the agent across as many sessions as you like. To bound a run, pass `limits: { tokens?, turn_seconds?, turns? }` on the agent or the session.</Note>+## 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.++```tsx+const OC = process.env.NEXT_PUBLIC_OC_API_URL ?? "https://api.opencomputer.dev";-## 3. Stream it live+type SessionEvent = {+ id: string;+ seq: number;+ type: string;+ level: "user" | "progress" | "internal";+ body?: Record<string, unknown>;+};-Open an `EventSource` with the `client_token` from the create call. It rides the query string — browsers can't set headers on `EventSource`, so the scoped client token goes in the URL (never your API key). `level=user` shows only what an end user should see (see [levels](/agent-sessions/events#levels)).+async function createSession(input: string) {+ const res = await fetch("/api/sessions", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ input }),+ });-```js-const es = new EventSource(- `https://api.opencomputer.dev/v3/sessions/${id}/events?stream=sse&level=user&token=${clientToken}`-);-es.onmessage = (e) => render(JSON.parse(e.data)); // each event: { seq, actor, type, level, body, … }+ if (!res.ok) throw new Error(await res.text());+ return res.json() as Promise<{+ session: { id: string };+ client_token: string;+ }>;+}++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();+}```-**Resume is automatic.** Each event carries its `seq` as the SSE event `id`, so on a dropped connection `EventSource` reconnects and resends `Last-Event-ID` — you pick up exactly where you left off, no bookkeeping. (Pass `after=<seq>` on the URL to start from a specific point.)+## 4. Render by event type-## 4. Steer it+The stable discriminator is `type`. Do not parse prose to decide whether a turn finished or failed.-Send a follow-up at any time. The session wakes and continues with its prior context.+```tsx+function EventRow({ event }: { event: SessionEvent }) {+ const body = event.body ?? {};-```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" }'+ switch (event.type) {+ case "agent.message":+ return <p>{String(body.text ?? "")}</p>;++ case "tool.call":+ return <code>$ {String(body.args_summary ?? body.tool ?? "tool")}</code>;++ case "exec.completed":+ return (+ <pre>+ exit {String(body.exit_code)}+ {"\n"}+ {String(body.summary ?? "")}+ </pre>+ );++ 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>;+ }++ default:+ return body.text || body.summary ? <p>{String(body.text ?? body.summary)}</p> : null;+ }+}```-## 5. Manage destinations (optional)+## 5. Steer the session-You already passed a `webhook` at create. Add or manage more destinations later — each receives events from when it's created (earlier events aren't backfilled yet).+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.-```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" }'+```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();+}```-Deliveries are signed ([Standard Webhooks](https://www.standardwebhooks.com)) and retried; dedupe by `webhook-id`. See [Webhooks](/agent-sessions/webhooks) to verify the signature and inspect deliveries.+## Production checklist++- 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`.+- 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.+- Register a [webhook](/agent-sessions/webhooks) when your backend needs push delivery after the tab closes.## Next steps<CardGroup cols={2}>- <Card title="Sessions" icon="book" href="/agent-sessions/sessions">- How a session works — lifecycle and events.+ <Card title="Events" icon="timeline" href="/agent-sessions/events">+ Event shape, levels, cursors, and resume behavior.+ </Card>+ <Card title="Prompting" icon="file-lines" href="/agent-sessions/prompting">+ Write prompts that produce usable event streams and final results.+ </Card>+ <Card title="Example app" icon="github" href="https://github.com/diggerhq/oc-sessions-demos">+ Fork a complete app-builder implementation.</Card>- <Card title="Webhooks" icon="bell" href="/agent-sessions/webhooks">- Deliver output reliably, and control deliveries.+ <Card title="API reference" icon="code" href="/agent-sessions/api-reference">+ Endpoint details and response shapes.</Card></CardGroup>diff --git a/docs/agent-sessions/runtime-tools.mdx b/docs/agent-sessions/runtime-tools.mdxindex cff3eb86..d309880e 100644--- a/docs/agent-sessions/runtime-tools.mdx+++ b/docs/agent-sessions/runtime-tools.mdx@@ -38,3 +38,5 @@ These map to events you can stream: a `bash` run surfaces as an [`exec.completed- To work on a repo, point it at a **public** one (`use_repo`, or `bash` + `git clone`); pass the target in [`input.refs`](/agent-sessions/messaging) (`repo`, `branch`, `commit`) rather than burying it in prose. (Private-repo connections are coming soon.)- Have it `say` a clear final result — that's what `GET /sessions/:id/result` returns.- Have it `ask` only when it genuinely needs a decision; otherwise it should proceed.++For a complete starting point, use the [prompt template](/agent-sessions/prompting). It includes operating rules for progress updates, verification, idempotency, and final results.diff --git a/docs/agent-sessions/runtimes.mdx b/docs/agent-sessions/runtimes.mdxindex 78f03d0d..a97194cd 100644--- a/docs/agent-sessions/runtimes.mdx+++ b/docs/agent-sessions/runtimes.mdx@@ -9,11 +9,19 @@ 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).-```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" }'+<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_...",+ }),+});```### How it's structureddiff --git a/docs/agent-sessions/sessions.mdx b/docs/agent-sessions/sessions.mdxindex 580e4ace..8f6ecb8a 100644--- a/docs/agent-sessions/sessions.mdx+++ b/docs/agent-sessions/sessions.mdx@@ -31,11 +31,19 @@ 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:-```bash-curl https://api.opencomputer.dev/v3/sessions/$ID/result \- -H "Authorization: Bearer $OPENCOMPUTER_API_KEY"-# → { "last_turn": { "id": "trn_…", "state": "ok", "yield_reason": "completed", "result_event_id": "evt_…" },-# "result": { "type": "agent.message", "level": "user", "body": { "text": "…" } } }+<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}`);+}```## Limitsdiff --git a/docs/agent-sessions/webhooks.mdx b/docs/agent-sessions/webhooks.mdxindex d5c94a08..ff702efd 100644--- a/docs/agent-sessions/webhooks.mdx+++ b/docs/agent-sessions/webhooks.mdx@@ -7,13 +7,18 @@ Register a **destination** and a session's [events](/agent-sessions/events) are## Destinations-```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",- "include_raw": false }'+<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,+ }),+});````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"]`.diff --git a/docs/docs.json b/docs/docs.jsonindex 643846ef..a8a7ff68 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -64,6 +64,7 @@"pages": ["agent-sessions/overview","agent-sessions/quickstart",+ "agent-sessions/prompting","agent-sessions/agents","agent-sessions/sessions","agent-sessions/events",diff --git a/docs/guides/build-a-lovable-clone.mdx b/docs/guides/build-a-lovable-clone.mdxindex 24adce0e..c4b9f535 100644--- a/docs/guides/build-a-lovable-clone.mdx+++ b/docs/guides/build-a-lovable-clone.mdx@@ -5,10 +5,17 @@ description: "Build an open-source AI app builder using OpenComputer sandboxes"In this guide you'll build a fully functional **Lovable clone** — an AI-powered web app builder where users describe an app in plain English and get a live, running React application in seconds. The entire project is open-source and uses OpenComputer sandboxes as the execution engine.+<Note>+For new app-builder projects, start with [Durable Agent Sessions](/agent-sessions/quickstart) and the [app-builder example](https://github.com/diggerhq/oc-sessions-demos). This guide shows the older raw-sandbox orchestration pattern, which is still useful when you want to own the agent loop yourself.+</Note>+<CardGroup cols={2}><Card title="GitHub Repository" icon="github" href="https://github.com/diggerhq/osslovable">Source code for the complete project.</Card>+ <Card title="Durable sessions example" icon="github" href="https://github.com/diggerhq/oc-sessions-demos">+ The recommended app-builder architecture for new projects.+ </Card><Card title="Live Demo" icon="globe" href="https://openlovable.cc">Try the running app at openlovable.cc.</Card>