Skip to content

An open-source, faster Devin alternative

TypeScript

docs: attach useAgent to a server-created session; start a session on a new document

Igor Zalutski009108033e8b
diff --git a/docs/agents/document-memory.mdx b/docs/agents/document-memory.mdx
index ddc0c46b..b81c503c 100644
--- a/docs/agents/document-memory.mdx
+++ b/docs/agents/document-memory.mdx
@@ -87,6 +87,56 @@ for read-only bindings, frozen/deleted documents and ended sessions.
Reusing a session-create `Idempotency-Key` requires identical agent, deployment,
environment and bindings; incompatible inputs return `409 conflict`.
+### Start a session on a new document
+
+A document and a session are separate objects: the document is owner data
+with its own lifetime, the binding is that session's admission to it, and
+neither is created as a side effect of the other. Opening a topic in an
+application still means "these notes, this session", so the SDK and the CLI
+do the two steps in order and make the pair converge on retry.
+
+```ts
+import { startSessionOnDocument } from "@opencomputer/sdk";
+
+const { document, session } = await startSessionOnDocument({
+ apiKey: process.env.OPENCOMPUTER_API_KEY!,
+ projectId: "<project-id>",
+ environment: "development",
+ agent: "<agent-id>",
+ resource: "notes",
+ documentId: "workshop",
+ document: { title: "Workshop notes" },
+ idempotencyKey: "topic/workshop/1",
+});
+// document.created and session.created are false when they already existed.
+```
+
+- The document is created with `If-None-Match: *`. An existing document is
+ left as it is; `document` is ignored then. A deleted id is reserved and
+ fails before any session is created.
+- The session is created with an `Idempotency-Key` derived from
+ `idempotencyKey`. The same key with the same agent, deployment, environment
+ and bindings returns the existing session; anything else under that key is
+ a conflict error naming the cause. `access` (default `read-write`),
+ `memory` for further bindings and `source` are passed through.
+
+The CLI does the same for a Development session:
+
+```bash
+opencomputer session create --memory notes=workshop --create-document --idempotency-key topic/workshop/1
+```
+
+`--memory <resource>=<documentId>[:read|read-write]` binds a document
+(read-write by default); `--memory <resource>` binds a collection.
+`--create-document` creates each bound document that does not exist yet,
+titled after its id, and reports it as created or existing. Add a prompt to
+run the first turn at once, and `--json` for the ids.
+
+Over HTTP, send `PUT .../documents/<id>` with `If-None-Match: *`, treat `412`
+as "exists" (then `GET` it; `404` means the id was deleted), and `POST
+/api/managed-agents/sessions` with an `Idempotency-Key`; `201` created the
+session, `200` returned the one that key had already created.
+
## Reading
The hook is synchronous; pass the definition or its ID:
diff --git a/docs/agents/react.mdx b/docs/agents/react.mdx
index 28b9ad83..a0f5f247 100644
--- a/docs/agents/react.mdx
+++ b/docs/agents/react.mdx
@@ -1,11 +1,160 @@
---
title: "React integration"
-description: "Stream agent sessions from a React application with useAgent"
+description: "Attach a React application to agent sessions with useAgent"
---
-An independently developed React application can use `@opencomputer/react`.
-The package owns session creation, multi-turn reuse, and streamed assistant
-messages. React is not part of the default agent scaffold.
+`@opencomputer/react` provides one hook, `useAgent`. It renders a session's
+messages, streams new turns and sends input. The session comes from one of
+two places:
+
+- **Attach** to a session your server created. This is the pattern for any
+ application that keeps its API key on the server and chooses what a session
+ may do there, including every application that binds
+ [memory](/agents/memory).
+- **Create** a session from the browser during development, through the
+ authenticated development bridge.
+
+```bash
+npm install @opencomputer/react
+```
+
+## Attach to a server-created session
+
+Three pieces: your server creates the session, your server proxies three
+routes under its own authentication, and the browser attaches with the
+session id.
+
+### 1. Create the session on the server
+
+Create the session where the API key lives. With memory, that is also where
+the bindings are chosen; the browser can neither see the key nor change what
+the session may read or write. `startSessionOnDocument` from
+`@opencomputer/sdk` creates the document if it does not exist yet, then the
+session bound to it, both converging under one idempotency key
+([details](/agents/document-memory#start-a-session-on-a-new-document)):
+
+```ts
+import { startSessionOnDocument } from "@opencomputer/sdk";
+
+const { session } = await startSessionOnDocument({
+ apiKey: process.env.OPENCOMPUTER_API_KEY!,
+ projectId: process.env.OPENCOMPUTER_PROJECT_ID!,
+ environment: "development",
+ agent: "topic-worker",
+ resource: "topics",
+ documentId: topicId,
+ document: { title },
+ idempotencyKey: `topic/${topicId}/${user.id}`,
+});
+// Store session.id with the topic; the browser attaches to it.
+```
+
+Without memory, `POST /api/managed-agents/sessions` with `x-api-key` and
+`{ "agentId": "<agent-id>@development" }` returns `{ session: { id } }`.
+
+### 2. Proxy three routes
+
+The hook needs exactly these, relative to its `basePath`:
+
+| Route | Purpose |
+| --- | --- |
+| `GET /sessions/<id>/events?after=<seq>` | The durable event log from a cursor; history and live turns |
+| `POST /sessions/<id>/turns` | A new turn: `{ input, idempotencyKey }` |
+| `POST /sessions/<id>/interrupt` | Stop the running turn |
+
+Expose them under your own authentication, check that the signed-in user may
+use that session, and forward to OpenComputer with the API key. A Next.js
+route handler that serves all three:
+
+```ts
+// app/api/agent/sessions/[id]/[action]/route.ts
+const allowed: Record<string, string[]> = { GET: ["events"], POST: ["turns", "interrupt"] };
+
+async function proxy(request: Request, { params }: { params: Promise<{ id: string; action: string }> }) {
+ const { id, action } = await params;
+ const user = await requireUser(request); // your session cookie or token
+ if (!allowed[request.method]?.includes(action) || !(await userOwnsSession(user, id))) {
+ return new Response(null, { status: 404 });
+ }
+ const upstream = await fetch(
+ `https://app.opencomputer.dev/api/managed-agents/sessions/${encodeURIComponent(id)}/${action}${new URL(request.url).search}`,
+ {
+ method: request.method,
+ headers: { "x-api-key": process.env.OPENCOMPUTER_API_KEY!, "content-type": "application/json" },
+ body: request.method === "POST" ? await request.text() : undefined,
+ },
+ );
+ return new Response(upstream.body, { status: upstream.status, headers: { "content-type": "application/json" } });
+}
+
+export const GET = proxy;
+export const POST = proxy;
+```
+
+The turn body carries an `idempotencyKey` the hook generates per send, so a
+retried request does not start a second turn. Forward request bodies and
+responses unchanged; the hook reads `{ events }`, `{ turnId }` and the error
+envelope `{ error: { message } }`.
+
+### 3. Attach in the browser
+
+```tsx
+import { useAgent } from "@opencomputer/react";
+
+export function TopicChat({ sessionId, onNotesChanged }: { sessionId: string; onNotesChanged: () => void }) {
+ const { messages, send, stop, isReplaying, isRunning, error } = useAgent({
+ sessionId,
+ basePath: "/api/agent",
+ onMemorySaved: onNotesChanged,
+ });
+
+ return (
+ <section>
+ {isReplaying ? <p>Loading the conversation…</p> : null}
+ {messages.map((message) => (
+ <p key={message.id}>
+ <strong>{message.role}:</strong> {message.text}
+ </p>
+ ))}
+ <button disabled={isRunning} onClick={() => void send("Book the venue")}>Send</button>
+ <button disabled={!isRunning} onClick={() => void stop()}>Stop</button>
+ {error ? <p role="alert">{error}</p> : null}
+ </section>
+ );
+}
+```
+
+On mount the hook reads the whole event log from `after` (default `0`) and
+reduces it to messages, so a reopened page shows the conversation as it
+stands, including turns that ran while the tab was closed. It then keeps
+polling from its cursor. A failed poll sets `error`, backs off, and resumes
+from the same cursor; nothing is replayed twice, and `error` clears when the
+log answers again. Changing `sessionId` replays the new session.
+
+`send` starts a turn and shows the input at once; the log's own record of it
+confirms that message rather than adding a second one. Turns sent while one
+is running are queued by the platform. `stop` interrupts the running turn
+without spending a model turn.
+
+The hook never suspends, resumes or ends an attached session. Its lifecycle
+belongs to the server that created it.
+
+### Refresh notes on save
+
+Every `memory.saved` event the session records
+([document memory](/agents/document-memory#saving)) is appended to
+`memorySaves` and passed to `onMemorySaved` with its `resource`,
+`documentId`, `revision` and `bytes`. Re-read the document through your own
+owner route when one arrives. Saves are reported best-effort: a document
+can change without an event, so also refresh when the user opens the panel.
+
+Any other event is available through `onEvent`, for example tool activity for
+an activity view.
+
+## Create a session from the browser
+
+For a local application against Development, pass `agent-id@alias` and the
+first `send` creates the session through the development bridge:
```tsx
import { useAgent } from "@opencomputer/react";
@@ -35,36 +184,8 @@ export default function Chat() {
}
```
-## Hook result
-
-| Value | Purpose |
-| --- | --- |
-| `messages` | User and assistant messages accumulated by this hook instance |
-| `send(text)` | Starts or continues the session and streams the response |
-| `sessionId` | Current cloud session after the first message |
-| `isRunning` | Whether a turn is active |
-| `error` | Most recent request error |
-
-## Select the target
-
-Pass `agent-id@alias` to choose the agent and environment:
-
-```tsx
-useAgent("support@development");
-useAgent("support@production");
-```
-
-An options object can also set the input source, API base path, or fetch
-implementation:
-
-```tsx
-useAgent({
- agent: "support@development",
- source: "customer-portal",
-});
-```
-
-## Development
+Each `send` resumes the session, streams one turn and suspends it again.
+Sessions created this way have no memory bindings.
Run the watched agent deployment and the web application separately:
@@ -74,8 +195,35 @@ npm run dev:web
```
The first command deploys agent changes and provides the authenticated
-development bridge. The second starts only the web application. The web app
-can also be deployed through its own lifecycle; credentials are not bundled
-into browser code.
+development bridge at the hook's default `basePath`. The second starts only
+the web application. Credentials are not bundled into browser code.
+
+## Hook result
+
+| Value | Purpose |
+| --- | --- |
+| `messages` | User and assistant messages, in log order |
+| `send(text)` | Starts a turn; in create mode the first call creates the session |
+| `stop()` | Interrupts the running turn |
+| `sessionId` | The attached session, or the created one after the first send |
+| `isRunning` | Whether a turn is active |
+| `isReplaying` | Attach mode: true until the existing history has been read |
+| `error` | The most recent request or turn failure |
+| `memorySaves` | `memory.saved` events seen so far |
+| `cursor` | The last event position applied |
+
+## Options
+
+| Option | Purpose |
+| --- | --- |
+| `sessionId` | Attach to this session |
+| `agent` | Create mode: `agent-id@alias` |
+| `basePath` | Route prefix for the three routes; default `/api/opencomputer/managed-agents` |
+| `fetch` | A fetch implementation, for example one that adds a CSRF header |
+| `after` | Attach mode: replay from this cursor instead of the start |
+| `pollIntervalMs` | Attach mode: interval between empty polls; default 1000, 500 while a turn runs |
+| `onEvent` | Every applied event, including replayed history |
+| `onMemorySaved` | Each `memory.saved` event |
+| `source` | Create mode: the session's input source |
For the durable conversation model, see [Sessions and turns](/agents/sessions).
diff --git a/docs/agents/sessions.mdx b/docs/agents/sessions.mdx
index 539a1d20..0eca7c0d 100644
--- a/docs/agents/sessions.mdx
+++ b/docs/agents/sessions.mdx
@@ -56,6 +56,13 @@ npm run session -- send <session-id> "Continue"
npm run session -- end <session-id>
```
+Bind [memory](/agents/memory) documents when creating a session; add
+`--create-document` to create the ones that do not exist yet:
+
+```bash
+npm run session -- create --memory notes=workshop --create-document "Plan the workshop"
+```
+
Follow the durable event log directly. With `--json`, each event is one NDJSON
record suitable for a coding agent or log processor:
diff --git a/docs/docs.json b/docs/docs.json
index e5cffa58..22458231 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -40,6 +40,7 @@
"pages": [
"agents/reactive-agents",
"agents/sessions",
+ "agents/react",
"agents/memory",
"agents/schedules",
"agents/webhooks",
diff --git a/docs/llms.txt b/docs/llms.txt
index 3804af2d..daf01b43 100644
--- a/docs/llms.txt
+++ b/docs/llms.txt
@@ -11,6 +11,7 @@
- [Deployments and environments](https://docs.opencomputer.dev/agents/deployments.md): Understand development, production, immutable deployments, and aliases.
- [Reactive agents](https://docs.opencomputer.dev/agents/reactive-agents.md): Render instructions, models, tools, subagents, and MCP servers from code.
- [Sessions and turns](https://docs.opencomputer.dev/agents/sessions.md): Create and inspect durable conversations.
+- [React integration](https://docs.opencomputer.dev/agents/react.md): Attach a React application to server-created sessions with useAgent, proxying three routes under your own authentication.
- [Agent capabilities](https://docs.opencomputer.dev/agents/capabilities.md): Choose between tools, MCP servers, skills, subagents, and outbound connections.
- [Secrets and outbound requests](https://docs.opencomputer.dev/agents/secrets.md): Store scoped secrets and inject them only into declared outbound requests.
- [Agent hooks](https://docs.opencomputer.dev/agents/hooks.md): Compose agent capabilities with reactive hooks.