Skip to content

An open-source, faster Devin alternative

TypeScript

docs: clarify application lifecycle and retry guarantees

Igor Zalutskie6c312255fff
diff --git a/docs/agents/api.mdx b/docs/agents/api.mdx
index 7272dacf..520bbd59 100644
--- a/docs/agents/api.mdx
+++ b/docs/agents/api.mdx
@@ -18,6 +18,10 @@ an organization and reaches every project, agent and session in it. Keep it
on the server; the [React integration](/agents/react) shows how a browser
attaches through your own routes without seeing the key.
+Your server must authenticate callers and enforce which projects,
+environments, agents and sessions they may access. A list filter or session
+label is not an authorization boundary.
+
Request and response bodies are JSON. Paths below are relative to the base
URL; `<p>` is a project ID and `<r>` a memory resource ID. The
[TypeScript client](/reference/typescript-sdk/agents) on
@@ -143,9 +147,7 @@ curl 'https://app.opencomputer.dev/api/managed-agents/sessions?project=<project-
| `limit` | Rows per page, 1 to 100; default 50 |
| `cursor` | The `nextCursor` of the previous page |
-Any other parameter is `400 invalid_query`, as is a malformed value. A
-project-scoped key lists its own project; naming another is
-`403 project_scope_violation`.
+Any other parameter is `400 invalid_query`, as is a malformed value.
A row is `id`, `projectId`, `agentId`, `deploymentId`, `environment` (`null`
when the session has none), `source`, `status`, `labels`, `createdAt`,
@@ -155,12 +157,16 @@ how many turns wait behind it, and the most recently finished turn as
`{ id, status, at }` or `null`. Rows carry no `turns` and no `memory`; read
`GET /sessions/<id>` for those.
-Rows are ordered by `createdAt`, newest first, then by `id`, and the order
-never changes: a session that is updated does not move, so a traversal with
-`cursor` sees every row exactly once even while sessions are running. To show
-recent activity first, sort the page you hold by `updatedAt`. `nextCursor` is
-`null` on the last page. A session appears in the list as soon as its create
-call has returned.
+Rows are ordered by `createdAt`, newest first, then by `id`. Updates do not
+move rows. Keep the same filters while following `nextCursor`; `null` means
+there are no more matches after that cursor.
+
+Pagination is not a snapshot: each request applies the filters to the
+current rows. New sessions and sessions that newly match a status or label
+filter can fall before your cursor. Refresh from the first page to see
+them. Sorting fetched rows by `updatedAt` orders only those rows, not all
+matching sessions. A successful create response confirms the session is
+listed.
### Labels
@@ -194,28 +200,39 @@ and repeating the patch is safe because each key takes the last write.
### End and interrupt
`POST /sessions/<id>/end` ends the session. Queued and running turns are
-cancelled and memory write access is revoked; do not send further turns to
-it. `503 session_end_unconfirmed` means the session is ended but the memory
-revocation was not acknowledged; retry, or
-[freeze the document](/agents/document-memory#disable-agent-writes). Ending an
-ended session returns it unchanged.
+marked `cancelled` with reason `session_ended`, and no further turns are
+accepted. A `200` confirms memory write access is revoked.
+`503 session_end_unconfirmed` means the session ended but memory revocation
+was not acknowledged; retry the same end request, or
+[freeze the document](/agents/document-memory#disable-agent-writes).
+Repeating end confirms any pending memory revocation without ending the
+session again.
+
+The `session.ended` event is recorded before memory revocation is confirmed.
+Neither that event nor the end response waits for commands to stop; remote
+cleanup continues in the background. Interrupt provides command-settlement
+confirmation for the current turn, subject to the compatibility note below;
+it leaves queued turns available to run.
`POST /sessions/<id>/interrupt` stops the running turn without spending a
-model turn. The response shows the session as `stopping` with the turn still
-`running`: the model loop is stopped, and every command the turn had started
-on its computer is stopped before the turn settles. The turn then settles as
-`cancelled` with reason `interrupted`, the session returns to `idle` and the
-next queued turn starts. A command that cannot be confirmed stopped is
-resolved by replacing the computer, and the turn settles once the
-replacement is confirmed; the turn's `turn.cancelled` event records how the
-stop settled ([Session events](/agents/events#turns)). An idle session is
-returned unchanged.
-
-A session whose `executionMode` (reported when it is created) is `microvm`
-still cancels immediately: the response shows it `idle` with the turn
-already `cancelled`, the commands the turn started are not waited for, and
-its `turn.cancelled` event carries `reason` alone, none of the settlement
-fields, until sessions in that mode settle the same way.
+model turn. The response acknowledges the stop request; it does not wait
+for completion. While stopping, the session is `stopping` and the turn
+remains `running`. Once the model loop and its commands have stopped, the
+turn becomes `cancelled` with reason `interrupted`, the session becomes
+`idle`, and the next queued turn can start.
+
+If a command cannot be confirmed stopped, OpenComputer terminates its
+computer before settling the turn. The next command uses a fresh computer
+with the session's workspace. The cancellation event records the
+[settlement details](/agents/events#turns). An idle session is returned
+unchanged. Stopping does not undo files already written or external effects.
+
+<Note>
+ Sessions created with `executionMode: "microvm"` cancel immediately on
+ interrupt, without waiting for their commands to stop. They do not enter
+ `stopping`, and their cancellation events have no settlement fields.
+ Check the creation response when this guarantee matters to your app.
+</Note>
## Turns
@@ -242,7 +259,7 @@ are present they must be equal, else `400 invalid_turn`.
| --- | --- |
| `input` | The user text for this turn. Required, not empty. |
| `idempotencyKey` | Optional. The key in body form, for a proxied browser send; equal to the header when both are present. |
-| `mode` | `queue` (default): run after earlier turns. `steer`: deliver into the running turn when the runtime supports it, otherwise queue. `interrupt`: cancel running turns and run next. |
+| `mode` | `queue` (default): run after earlier turns. `steer`: deliver into the running turn when the runtime supports it, otherwise queue. `interrupt`: interrupt running turns and run next, with the [same settlement behavior](#end-and-interrupt) as the interrupt route. |
| `payload` | Optional. A JSON value for the agent, at most 32 KB encoded. It reaches the agent as [`useInput().payload`](/agents/inputs) with `source: "user"`, next to the text, and is recorded on the turn's `message.received` event. The text stays the message; the payload is structured context the agent reads. |
The response is `202 { turnId, status, duplicate }` for a new turn and
diff --git a/docs/agents/document-memory.mdx b/docs/agents/document-memory.mdx
index 14d5eadb..65f6e6c0 100644
--- a/docs/agents/document-memory.mdx
+++ b/docs/agents/document-memory.mdx
@@ -92,9 +92,9 @@ The [management API](/agents/api#create) page has the full rules.
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.
+neither is created as a side effect of the other. The SDK and CLI can create
+the document and then the session in one call. These are separate requests;
+the document remains if session creation fails.
```ts
import { OpenComputer } from "@opencomputer/sdk/agents";
@@ -121,6 +121,12 @@ const { document, session } = await oc.sessions.startOnDocument({
fails with code `idempotency_key_reused`. `access` (default `read-write`),
`memory` for further bindings and `source` are passed through.
+The helper resolves the agent's environment alias on each attempt. A
+redeploy can therefore make a retry conflict even if the first attempt
+created the session. Do not change the key to recover a lost response: that
+would create another session. For retries across redeploys, use separate
+document and session calls with a retained deployment ID, as described below.
+
The CLI does the same for a Development session:
```bash
@@ -135,9 +141,11 @@ 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. The call's
-parameters and errors are in the
+/api/managed-agents/sessions` with the document binding, a retained
+`deploymentId`, `environment` and `Idempotency-Key`; `201` created the
+session, `200` returned the one that key had already created. Keep that
+envelope unchanged for retries. See [session creation](/agents/api#create)
+for the body and the
[Serverless Agents client reference](/reference/typescript-sdk/agents#start-a-session-on-a-memory-document).
## Reading
diff --git a/docs/agents/events.mdx b/docs/agents/events.mdx
index 003f8102..cca1f07e 100644
--- a/docs/agents/events.mdx
+++ b/docs/agents/events.mdx
@@ -44,17 +44,18 @@ unknown type as informational and keep reading.
| --- | --- | --- |
| `session.created` | The session exists. Always the first event. | `agentId`, `deploymentId` |
| `session.status_changed` | The session moved between `new`, `connecting`, `idle`, `running`, `stopping`, `waiting_runtime`, `suspending`, `suspended`, `resuming`, `failed` and `ended` | `from`, `to` |
-| `session.ended` | The owner ended the session. Queued and running turns were cancelled and memory writes revoked. | none |
+| `session.ended` | The session accepts no more turns; queued and running turns were marked cancelled. Memory revocation and remote cleanup may still be pending. | none |
| `session.failed` | The session cannot continue | `code`, `message`: a [public failure](#public-failures) |
`stopping` follows an [interrupt](/agents/api#end-and-interrupt) or an
interrupt-mode turn: the session stays there until the stopped turn's
-commands are confirmed stopped or its computer is replaced, then `idle`
-follows and the next turn starts. A session whose `executionMode` is
-`microvm` does not pass through `stopping`: an interrupt cancels its turn
-immediately, without waiting for the turn's commands, and the
-`turn.cancelled` event carries `reason` alone, none of the settlement
-fields, until sessions in that mode settle the same way.
+commands are confirmed stopped or its computer is terminated, then `idle`
+follows and the next turn can start. See the API's compatibility note for
+sessions that cancel immediately instead.
+
+`session.ended` is not a command-settlement or memory-revocation receipt.
+The [end response](/agents/api#end-and-interrupt) confirms memory revocation;
+remote cleanup continues in the background.
### Turns
@@ -63,11 +64,18 @@ fields, until sessions in that mode settle the same way.
| `message.received` | A turn was accepted; its input is recorded before anything runs | `input`: the user text; `mode`: `queue`, `steer` or `interrupt`; `payload`: the structured value the turn was sent with, when there was one |
| `turn.queued` | The turn waits for earlier turns | `mode` |
| `turn.steered` | The input was delivered into the running turn | `activeTurnId` |
-| `turn.interrupted` | This turn cancelled the turns that were running | `interruptedTurnIds` |
+| `turn.interrupted` | This turn requested interruption of the running turns | `interruptedTurnIds` |
| `turn.started` | The runtime began the turn | none |
| `turn.completed` | The turn finished and the session is idle again | none |
| `turn.failed` | The turn stopped with an error | `code`, `message`, and `model` or `tool` when named: a [public failure](#public-failures) |
-| `turn.cancelled` | The turn was stopped by an interrupt, once the work it had started was stopped | `reason`: `interrupted`; `replacementTurnId` when an interrupt-mode turn replaced it; `settledAfterMs`: how long after the interrupt the turn settled; `operationsSettled`: how many commands were stopped; `computerTerminated`: `true` when a command could not be confirmed stopped and the computer was replaced |
+| `turn.cancelled` | The turn was cancelled by an interrupt or session end | `reason`: `interrupted` or `session_ended`; optional `replacementTurnId`, `settledAfterMs`, `operationsSettled`, `computerTerminated` |
+
+For an interrupt that waits for commands, `settledAfterMs` records the wait,
+`operationsSettled` counts the settled commands, and `computerTerminated`
+says whether stopping required terminating the computer. Cancellation with
+`reason: "session_ended"` has no settlement fields: it records the session's
+decision to end, before remote cleanup finishes. Immediate-cancellation
+sessions also omit these fields; see [End and interrupt](/agents/api#end-and-interrupt).
#### Public failures
@@ -116,7 +124,7 @@ tool; the save itself is reported separately.
`input` and `output` are JSON values, never JSON text: an object comes as an
object, and a consumer reads it without parsing. Tool events recorded before
these fields were introduced keep the shape they were recorded with, so the
-React hook's [`turns`](/agents/react#activity) shows those calls unnamed and
+React hook's [`turns`](/agents/react#hook-reference) shows those calls unnamed and
without output; `messages` is unaffected.
A successful call of the agent's [result tool](/agents/tools#the-session-result)
@@ -133,6 +141,8 @@ write, with `settledBy` naming the terminal event (`turn.completed`,
`turn.failed` or `turn.cancelled`) and a `message` saying the turn ended
first. A consumer therefore never sees a settled turn with a running call;
one that keys rows on `callId` needs no rule of its own for the turn's end.
+This settles the call in the log; it does not strengthen the command-stop
+guarantees of the terminal turn event.
### Memory
@@ -168,11 +178,15 @@ reconnecting and completing work. See
| Type | When | `data` |
| --- | --- | --- |
| `runtime.connected` | An agent runtime attached to the session | none |
-| `runtime.disconnected` | The runtime went away; a running turn is queued again and resumes on the next runtime | none |
+| `runtime.disconnected` | The runtime connection closed; running turns return to the queue to await a runtime | none |
| `runtime.suspended` | The runtime was suspended between turns | none |
| `runtime.resumed` | The runtime was resumed | none |
| `runtime.log` | A line of runtime output or a platform milestone | `level`, `stream`, `message` for output; `phase` and `message` for milestones such as the runtime starting |
+A runtime disconnect does not prove that a command stopped or that its
+effects were undone. Follow the subsequent turn events to learn whether
+work continued or failed; see [Durability and recovery](/agents/sessions#durability-and-recovery).
+
### Agent renders
| Type | When | `data` |
diff --git a/docs/agents/github.mdx b/docs/agents/github.mdx
index b2e7cc17..e02c9ef1 100644
--- a/docs/agents/github.mdx
+++ b/docs/agents/github.mdx
@@ -9,8 +9,8 @@ installation.
## Declare access
-Declare the maximum permissions this agent needs, then select the connection
-with `useConnection()`:
+Declare the permissions the agent needs and reference the connection from its
+agent function:
```tsx
import {
@@ -39,15 +39,16 @@ The supported permissions are `actions`, `checks`, `contents`, `issues`,
`metadata`, and `pull_requests`. `metadata` is read-only. Request only what the
agent needs.
-`useConnection(github)` activates the declared connection for the agent. At
-session startup, OpenComputer sends the declaration's exact `permissions`
-object when it asks GitHub to mint the installation token. GitHub does not let
-that token exceed the permissions granted to the App installation.
+GitHub access applies to the session, not to an individual render. OpenComputer
+mints a token with the combined permissions of the deployment's declared
+GitHub connections; if one declares read access and another write access for the
+same permission, the token requests write access. Omitting or conditionally
+calling `useConnection(github)` does not withhold or revoke that token.
Effective authority is therefore the intersection of:
- the managed OpenComputer GitHub App's permission ceiling;
-- the permissions declared in `githubApp({ permissions })`; and
+- the combined permissions declared in `githubApp({ permissions })`; and
- the repositories selected in the attached GitHub installation.
## Install the App
@@ -78,7 +79,7 @@ current selection from the connection rather than holding a GitHub credential
of its own:
```text
-GET /projects/<p>/github/repositories?environment=<env>&cursor=&limit=
+GET /projects/<project-id>/github/repositories?environment=development&limit=100
```
`environment` is `development` or `production` and is required. `limit` is at
@@ -102,7 +103,7 @@ most 100, the default; `cursor` is the `nextCursor` of the previous page.
The list is read live from GitHub each time, with a token minted for that read
that can see repository metadata and nothing else. OpenComputer keeps no copy:
change the selection in GitHub's installation settings and the next read shows
-it. It is available to the organization's API key, not to project tokens.
+it. Call this route from your server with an organization API key.
| Status | Code | Meaning |
| --- | --- | --- |
@@ -124,17 +125,17 @@ gh pr create --repo acme/service --fill
gh api repos/acme/service/pulls
```
-OpenComputer mints a GitHub installation token whose permissions are limited
-to those declared by the deployed agent. GitHub installation tokens expire
-after about one hour; the agent does not manage that. Before a command is
-dispatched, the token is renewed if it would expire before the command's
-allowed duration is up, so a `git push` or `gh pr create` late in a long
-session, or on a computer that has been running for most of an hour, uses a
-token that outlives the command. Git and `gh` both pick up the renewed token
-without any change to how the agent calls them. Renewal never widens what the
-token can do: it carries the same declared permissions against the
+GitHub installation tokens expire after about one hour. Before dispatching a
+command, OpenComputer attempts renewal if the held token would expire within
+the command's allowed duration. Git and `gh` pick up a renewed token without
+changes to the command. Renewal uses the same declared permissions and the
installation's current repository selection.
+If renewal fails, the command still runs with the held token and its GitHub
+requests may fail authentication. Detaching the connection prevents new
+tokens from being issued; it does not immediately revoke a token already on
+the computer. That token can remain usable until GitHub expires or revokes it.
+
### Understand GitHub permission responses
Installation tokens do not have OAuth scopes. That does not mean they are
@@ -162,8 +163,8 @@ and
[listing repositories accessible to an installation](https://docs.github.com/en/rest/apps/installations#list-repositories-accessible-to-the-app-installation).
<Warning>
- The short-lived token is available inside the eligible agent's sandbox as
- `GH_TOKEN` and `GITHUB_TOKEN` for the operation. Code running in that sandbox
+ The short-lived token is available inside the agent's sandbox as
+ `GH_TOKEN` and `GITHUB_TOKEN`. Code running in that sandbox
can read it. Do not print it, write it into source, add it to a Git remote,
include it in a checkpoint, or send it to logs. Install the App only on
repositories you are comfortable granting to the agent.
diff --git a/docs/agents/mental-model.mdx b/docs/agents/mental-model.mdx
index 25a58a9d..265a7c90 100644
--- a/docs/agents/mental-model.mdx
+++ b/docs/agents/mental-model.mdx
@@ -128,7 +128,11 @@ result. See [Agent capabilities](/agents/capabilities) for the full comparison.
## Deployment registers; rendering selects
A deployment packages the agents and resources that are allowed to exist. A
-render selects which of those resources are available for one model step.
+render selects the tools, instructions and other resources for one model step.
+
+[Managed GitHub access](/agents/github#declare-access) is session-wide: its
+token carries the deployment's declared GitHub permissions. Conditional
+`useConnection()` calls do not change that token's authority.
```mermaid
flowchart LR
diff --git a/docs/agents/overview.mdx b/docs/agents/overview.mdx
index 4b03cd7d..0ccd73bf 100644
--- a/docs/agents/overview.mdx
+++ b/docs/agents/overview.mdx
@@ -40,6 +40,9 @@ by the model through memory tools, and owned by you.
<Card title="Sessions" icon="comments" href="/agents/sessions">
Stream responses and inspect durable conversations.
</Card>
+ <Card title="Build an application" icon="window" href="/agents/react">
+ Create sessions on your server and attach a React interface.
+ </Card>
<Card title="Capabilities" icon="shapes" href="/agents/capabilities">
Choose between tools, MCP servers, skills, and subagents.
</Card>
@@ -58,12 +61,14 @@ npx @opencomputer/cli init my-agent
cd my-agent
npm install
npx --package @opencomputer/cli opencomputer login
+npx --package @opencomputer/cli opencomputer link --create-project "my-agent"
npm run deploy -- --watch
```
-The initializer creates one hello-world agent. The first watched deployment
-lets you create a cloud project or select an existing one, prints its dashboard
-URL, and syncs every configured agent to `development`.
+The initializer creates one hello-world agent. `link` connects the directory
+to a cloud project; [link by ID or slug](/agents/projects#create-or-select-the-cloud-project)
+to use an existing one. The watcher prints the dashboard URL and syncs every
+configured agent to `development`.
<Note>
There is no local agent server. Agent code runs in OpenComputer's managed
diff --git a/docs/agents/react.mdx b/docs/agents/react.mdx
index 0ba5e698..d699f8ac 100644
--- a/docs/agents/react.mdx
+++ b/docs/agents/react.mdx
@@ -1,81 +1,67 @@
---
title: "React integration"
-description: "Attach a React application to agent sessions with useAgent"
+description: "Create sessions on your server; attach, submit work and reopen them with useAgent"
---
-`@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.
+`@opencomputer/react` provides `useAgent`: a session's conversation, turn
+activity and input controls. Your server creates sessions and checks access;
+the hook reads their event log and sends turns through your routes. The API
+key stays on the server.
```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 on your 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. `oc.sessions.startOnDocument` on the
-[management client](/reference/typescript-sdk/agents) 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)):
+Use the [management client](/reference/typescript-sdk/agents) from trusted
+code. Resolve an allowed deployment when composing the submission, then
+retain its ID and a creation key for retries:
```ts
import { OpenComputer } from "@opencomputer/sdk/agents";
const oc = new OpenComputer({ apiKey: process.env.OPENCOMPUTER_API_KEY! });
-const { session } = await oc.sessions.startOnDocument({
- projectId: process.env.OPENCOMPUTER_PROJECT_ID!,
- environment: "development",
- agent: "<agent-id>",
- resource: "notes",
- documentId: "workshop",
- document: { title: "Workshop notes" },
- idempotencyKey: `workshop/${user.id}`,
-});
-// Store session.id with the workshop; the browser attaches to it.
+const { session } = await oc.sessions.create(
+ { deploymentId, environment: "development", labels: { request: taskId } },
+ { idempotencyKey: taskId },
+);
+// Return session.id to the browser; use it when reopening this conversation.
```
-Without memory, `oc.sessions.create({ agentId: "<agent-id>@development" })`
-returns `{ session: { id } }`. Both are [management API](/agents/api#sessions)
-calls.
+Here `deploymentId` and `taskId` belong to one submission. Validate the
+requested deployment against the user's permitted project, environment and
+agent. Retry an uncertain create with the same parameters and key; resolving
+an alias again could select a newer deployment. Creating a session and
+sending its first turn are separate calls with separate keys.
-### 2. Proxy three routes
+## Expose three routes
-The hook needs exactly these [management API](/agents/api) routes, relative
-to its `basePath`:
+The hook needs these [management API](/agents/api) routes, 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, payload? }` |
-| `POST /sessions/<id>/interrupt` | Stop the running turn |
+| `GET /sessions/<id>/events?after=<seq>` | Read conversation history and new events |
+| `POST /sessions/<id>/turns` | Submit `{ input, idempotencyKey, payload? }` |
+| `POST /sessions/<id>/interrupt` | Request Stop for 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:
+Authenticate each request and check access to the session before forwarding
+it with your organization API key. For example, a Next.js route handler:
```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 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
+ const user = await requireUser(request);
if (!allowed[request.method]?.includes(action) || !(await userOwnsSession(user, id))) {
return new Response(null, { status: 404 });
}
@@ -83,246 +69,278 @@ async function proxy(request: Request, { params }: { params: Promise<{ id: strin
`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" },
+ headers: {
+ "x-api-key": process.env.OPENCOMPUTER_API_KEY!,
+ "content-type": "application/json",
+ },
body: request.method === "POST" ? await request.text() : undefined,
+ redirect: "error",
},
);
- return new Response(upstream.body, { status: upstream.status, headers: { "content-type": "application/json" } });
+ 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 caller's when `send` was
-given one and otherwise one the hook generates for the request, 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 } }`.
+`requireUser` and `userOwnsSession` are your application's access checks.
+The latter must enforce the application's project, environment and agent
+scope as well as the user's access. Forward JSON bodies and response statuses
+unchanged: the hook supplies the turn key in the body and reads the admission
+receipt or error envelope from the response.
+
+## Attach and submit
-### 3. Attach in the browser
+Keep each submission's text and key until its receipt arrives. If the reply
+is lost, Retry sends the same submission; it must not generate a new key.
```tsx
import { useState } from "react";
import { useAgent } from "@opencomputer/react";
-export function WorkshopChat({ sessionId, onNotesChanged }: { sessionId: string; onNotesChanged: () => void }) {
- const { messages, send, stop, isReplaying, isRunning, error } = useAgent({
+type Submission = { text: string; idempotencyKey: string };
+
+export function Chat({ sessionId }: { sessionId: string }) {
+ const { messages, turns, send, stop, isReplaying, error } = useAgent({
sessionId,
basePath: "/api/agent",
- onMemorySaved: onNotesChanged,
});
const [draft, setDraft] = useState("");
+ const [pending, setPending] = useState<Submission | null>(null);
+ const [sending, setSending] = useState(false);
async function submit() {
- await send(draft); // rejects when no turn was admitted
- setDraft(""); // clear only once the platform has the input
+ const submission = pending ?? {
+ text: draft.trim(),
+ idempotencyKey: crypto.randomUUID(),
+ };
+ setPending(submission);
+ setSending(true);
+ try {
+ await send(submission.text, { idempotencyKey: submission.idempotencyKey });
+ setPending(null);
+ setDraft("");
+ } catch {
+ // The hook exposes the error. Keep this submission for retry.
+ } finally {
+ setSending(false);
+ }
}
return (
<section>
{isReplaying ? <p>Loading the conversation…</p> : null}
{messages.map((message) => (
- <p key={message.id}>
- <strong>{message.role}:</strong> {message.text}
- </p>
+ <p key={message.id}><strong>{message.role}:</strong> {message.text}</p>
))}
- <input value={draft} onChange={(event) => setDraft(event.target.value)} />
- <button onClick={() => submit().catch(() => undefined)}>Send</button>
- <button disabled={!isRunning} onClick={() => void stop()}>Stop</button>
+ <input
+ value={draft}
+ disabled={sending || pending !== null}
+ onChange={(event) => setDraft(event.target.value)}
+ />
+ <button disabled={sending || (!pending && !draft.trim())} onClick={() => void submit()}>
+ {sending ? "Sending…" : pending ? "Retry" : "Send"}
+ </button>
+ <button disabled={!turns.some((turn) => turn.status === "running")} 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; a `send`
-still in flight for the previous session settles for its caller but never
-changes what the new session shows.
+This example retains the submission for the life of the component. To retry
+across navigation or a reload, retain the same envelope there too. Include
+`payload` in it when sending structured input. An explicit rejection such as
+`session_ended` requires resolving that error; a new key starts new work and
+is not recovery of an uncertain request.
-`after` is a position, not a snapshot: the hook applies only events after
-it, so messages and running state from before that position are not
-reconstructed. Pass `after` to skip history you have already rendered from
-your own store, otherwise start at `0`.
+Turns sent while another runs are queued. `send` resolves on admission, not
+when the agent finishes. It returns `{ sessionId, turnId, status, duplicate }`:
-Turns sent while one is running are queued by the platform. `stop`
-interrupts the running turn without spending a model turn.
+- A new turn is `queued` or `running`.
+- A repeated key returns the existing turn and its current status, including
+ `completed`, `failed` or `cancelled`, with `duplicate: true`.
+- Keep both the text and payload unchanged when retrying a key.
-### What `send` takes and returns
+The input appears in `messages` after admission. Its event-log record
+confirms that message instead of adding a second one.
-`send(text, options?)` starts a turn with the text. The options:
+### Send options and errors
| Option | Purpose |
| --- | --- |
-| `idempotencyKey` | The turn's idempotency key. Generate one per submission and keep it for that submission's retries: a retried `send` with the same key returns the same turn instead of admitting a second one. Without a key the hook generates one for the request, and a retry is a new turn. |
-| `payload` | Structured JSON the agent reads as `useInput().payload` beside the text, for example the repository and ref a task is about. |
-
-Two composers that each generate their own keys produce two turns; one
-composer retrying with the key it kept produces one.
-
-`send` resolves once the platform has admitted the input as a turn, with a
-receipt `{ sessionId, turnId, status, duplicate }`. `status` is the turn's
-persisted status: `queued` or `running` for a new turn, and for a retried
-key the existing turn's status, `completed`, `failed` or `cancelled` once it
-has settled, with `duplicate` true. Nothing is mapped, so a retry after a
-lost reply learns what became of the turn, and a settled duplicate never
-sets `isRunning`. The input appears in `messages` at that point; the log's
-own record of it confirms that message rather than adding a second one.
-`isRunning` is true from admission until the log settles the turn, and a
-reply that arrives after the log has already shown the turn completed
-changes nothing.
-
-`send` rejects with a `SendError` when no turn was admitted, so a composer
-can keep the draft:
-
-| `code` | Cause | `status` |
-| --- | --- | --- |
-| The platform's error code, for example `session_ended`, `memory_admission_unconfirmed` or `insufficient_credits` | The request was answered with an error | The HTTP status |
-| `network_error` | The request was not answered | none |
-| `empty_input` | The text was blank; nothing was sent | none |
-| `busy` | Create mode only: a turn is already running | none |
-| `invalid_response` | The admission reply was not a turn receipt | none |
-
-The hook's `error` is set to the same message either way. A turn that fails
-after admission is not a rejection: the receipt was returned, the failure
-arrives through the log as a `turn.failed` event and sets `error`.
-
-The hook never suspends, resumes or ends an attached session. Its lifecycle
-belongs to the server that created it.
-
-### Refresh notes on save
+| `idempotencyKey` | One key per submission, reused on retries. Without it, **each call** generates a new key and can admit a new turn. |
+| `payload` | Structured JSON available to the agent as `useInput().payload`, beside the text |
-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.
+`send` rejects with a `SendError`. Rejection alone does **not** establish
+whether a turn was admitted:
-### Activity
+| `code` | Meaning | `status` |
+| --- | --- | --- |
+| The API's code, such as `session_ended`, `memory_admission_unconfirmed` or `insufficient_credits` | An error response; follow that code's [recovery contract](/agents/api#turns) | HTTP status |
+| `network_error` | Transport or response-reading failure; admission may have succeeded | none |
+| `invalid_response` | The response was not a turn receipt; admission may have succeeded | none |
+| `empty_input` | Blank text; nothing sent | none |
+| `busy` | Create mode only: a turn already runs; nothing sent | none |
-`turns` is the session's turns in log order, reduced from the same event log
-as `messages`, so a reopened page shows the same activity a live one did.
-Each turn is:
+The hook also puts the message in `error`. A turn that fails after admission
+is separate: `turn.failed` sets the turn's `failure` and the hook's `error`.
-| Field | Meaning |
-| --- | --- |
-| `id` | The turn id |
-| `status` | `queued`, `running`, `completed`, `failed` or `cancelled` |
-| `input` | The text the turn was admitted with |
-| `messages` | The turn's messages, the same objects as in `messages` |
-| `toolCalls` | `{ callId, tool, title, input?, output?, status }` in the order the calls started; `input` and `output` are JSON values; `status` is `running`, `completed`, `failed` or `cancelled` |
-| `result` | The decoded output of the agent's result tool, the same JSON value the session's `result.data` holds, when it reported one; a later call replaces it. An ordinary tool's output never becomes `result` |
-| `failure` | `{ code, message }` from `turn.failed` |
+## Display activity and results
-Tool calls are keyed on the runtime's `callId`, so a `tool.completed` updates
-the entry its `tool.started` created rather than adding one. A call its turn
-ended before it completed is `failed`: the log records a `tool.failed` for it
-with `settledBy` naming the turn's end ([Session events](/agents/events#tools)).
-Should a log carry no such record, the hook settles every call still
-`running` when the turn ends: `completed` when the turn completed, `failed`
-when it failed, `cancelled` when it was interrupted. A settled turn therefore
-never shows a running call. Tool events recorded before the current fields
-were introduced keep the shape they were recorded with, so `turns` shows
-those calls unnamed and without output; `messages` is unaffected. An
-activity timeline renders `turns` directly:
+`turns` comes from the same durable event log as `messages`. Use its statuses
+to distinguish queued work from running and settled turns:
```tsx
{turns.map((turn) => (
<section key={turn.id}>
- <h3>{turn.input}</h3>
+ <h3>{turn.input} — {turn.status}</h3>
{turn.toolCalls.map((call) => (
<p key={call.callId}>{call.title}: {call.status}</p>
))}
- {turn.result ? <pre>{JSON.stringify(turn.result, null, 2)}</pre> : null}
+ {turn.result !== undefined ? <pre>{JSON.stringify(turn.result, null, 2)}</pre> : null}
{turn.failure ? <p role="alert">{turn.failure.message}</p> : null}
</section>
))}
```
-Every event is also available through `onEvent`; the types and their data
-are listed on [Session events](/agents/events).
-
-## Create a session from the browser
+| Turn field | Meaning |
+| --- | --- |
+| `id`, `status`, `input` | Turn ID, lifecycle status and admitted text |
+| `messages` | This turn's messages, also present in the hook's `messages` |
+| `toolCalls` | `{ callId, tool, title, input?, output?, status }` in start order; values are decoded JSON |
+| `result` | This turn's latest committed [result-tool output](/agents/tools#the-session-result), if any; ordinary tool output does not become a result |
+| `failure` | `{ code, message }` from `turn.failed` |
-For a local application against Development, pass `agent-id@alias` and the
-first `send` creates the session through the development bridge:
+Reporting a result does not finish a turn. The session's latest result may
+also belong to an earlier turn; see [result provenance](/agents/sessions)
+before treating a session as ready for review.
+
+A tool call is `running`, `completed`, `failed` or `cancelled`. Calls still
+running when their turn settles are settled too. The hook exposes failure
+status but does not currently retain `tool.failed.message` or `settledBy` on
+`ToolCall`; those details remain in the [event log](/agents/events#tools),
+also available through `onEvent`. Older tool records may lack a name or
+output.
+
+`isRunning` is an activity hint, not the session's lifecycle status. It also
+includes this hook instance's unsettled admission receipts. After reopening,
+a queued turn is visible in `turns` but does not by itself set `isRunning`.
+Use `turns` for queued/running counts and the [session API](/agents/api#sessions)
+for session status.
+
+## Stop and reopen
+
+`stop()` requests an interrupt without spending a model turn. It returns
+`Promise<void>` and reports request failures through `error`; a resolved
+promise is **not** confirmation that execution has stopped. Watch the running
+turn settle in `turns`. Stop affects that turn, so the next queued turn can
+start afterwards. The [interrupt contract](/agents/api#end-and-interrupt)
+describes settlement and remote-command guarantees.
+
+The hook does not expose `stopping` or `ended` session status. Read the
+session through your server when your interface needs that lifecycle detail.
+It also never suspends, resumes or ends an attached session; those operations
+belong to the server that created it.
+
+Reopen by mounting the hook with the same `sessionId`. It reads history from
+`after` (default `0`), including work completed while the page was closed,
+then polls for new events. A failed poll sets `error`, backs off and resumes
+from the same cursor; a successful recovery clears that polling error.
+
+Changing `sessionId` replays the new session. A send still in flight for the
+previous session settles for its caller without changing the new session's
+view. Remount your composer for the new session, for example
+`<Chat key={sessionId} sessionId={sessionId} />`, so a retained submission
+cannot be retried into another session.
+
+`after` skips earlier events; it is not a snapshot. Start at `0` to reconstruct
+the conversation and turn activity. Use another cursor only when the earlier
+view is already retained elsewhere. See [Sessions and turns](/agents/sessions)
+for the distinction between reopening a conversation and recovering failed
+execution.
+
+## Bind memory
+
+Choose [memory bindings](/agents/memory) during server-side session creation;
+the browser cannot change them. To create a document and bind it in one
+helper call, see [`startOnDocument`](/reference/typescript-sdk/agents#start-a-session-on-a-memory-document)
+and its retry limits. For pinned session creation, use the explicit
+[document and session calls](/agents/document-memory#start-a-session-on-a-new-document).
+
+Pass `onMemorySaved` to refresh your document panel through an authenticated
+owner route:
```tsx
-import { useAgent } from "@opencomputer/react";
+const agent = useAgent({
+ sessionId,
+ basePath: "/api/agent",
+ onMemorySaved: () => refreshNotes(),
+});
+```
-export default function Chat() {
- const { messages, send, sessionId, isRunning, error } = useAgent(
- "hello-world@development",
- );
+`memorySaves` also contains those events, with `resource`, `documentId`,
+`revision` and `bytes`. Save events are best-effort; refresh on opening the
+panel too, because documents can change without an event in this session.
- return (
- <main>
- {messages.map((message) => (
- <p key={message.id}>
- <strong>{message.role}:</strong> {message.text}
- </p>
- ))}
- <button
- disabled={isRunning}
- onClick={() => send("Hello").catch(() => undefined)}
- >
- Send
- </button>
- {sessionId ? <small>Session: {sessionId}</small> : null}
- {error ? <p role="alert">{error}</p> : null}
- </main>
- );
-}
+## Local development
+
+For a local application, pass `agent-id@alias` instead of a session ID:
+
+```tsx
+const { messages, send, sessionId, isRunning, error } = useAgent(
+ "hello-world@development",
+);
```
-Each `send` resumes the session, streams one turn and suspends it again; the
-promise settles when the turn ends, with the same receipt and rejections as
-in attach mode. Sessions created this way have no memory bindings.
+The first `send` creates a session through the authenticated development
+bridge. Later calls resume that session; each call streams a turn and then
+suspends it. Unlike attach mode, it normally waits through the turn and suspension
+before resolving. Failures after admission appear through `error`; the
+returned receipt still describes admission, not successful completion. Created sessions
+have no memory bindings, and the hook does not recover their identity across
+a page reload. Use attach mode for an application users will reopen.
-Run the watched agent deployment and the web application separately:
+Run the watched agent deployment and web application separately:
```bash
npm run deploy -- --watch
npm run dev:web
```
-The first command deploys agent changes and provides the authenticated
-development bridge at the hook's default `basePath`. The second starts only
-the web application. Credentials are not bundled into browser code.
+The first provides the development bridge at the default `basePath`; the
+second starts the web application. Credentials are not bundled into browser
+code.
-## Hook result
+## Hook reference
| Value | Purpose |
| --- | --- |
-| `messages` | User and assistant messages, in log order |
-| `turns` | The session's turns with status, input, messages, tool calls, result and failure, in log order |
-| `send(text, options?)` | Starts a turn; resolves with `{ sessionId, turnId, status, duplicate }` or rejects with a `SendError`. `options` carries `idempotencyKey` and `payload`. 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` | A turn is admitted and not yet settled by the log |
-| `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
+| `messages` | User and assistant messages in log order |
+| `turns` | Turns with status, input, messages, tool calls, result and failure |
+| `send(text, options?)` | Submit a turn; resolve with a receipt or reject with `SendError` |
+| `stop()` | Request an interrupt; errors appear in `error`, settlement in `turns` |
+| `sessionId` | Attached session, or the created one after the first send |
+| `isRunning` | Running activity or this instance's unsettled admissions; not a session status |
+| `isReplaying` | Attach mode: existing history is still loading |
+| `error` | Latest reported request or turn error |
+| `memorySaves` | Observed `memory.saved` events |
+| `cursor` | Last applied event position |
| Option | Purpose |
| --- | --- |
-| `sessionId` | Attach to this session |
+| `sessionId` | Attach to an existing 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: apply only events after this position; earlier history is not reconstructed |
-| `pollIntervalMs` | Attach mode: interval between empty polls; default 1000, 500 while a turn runs |
+| `basePath` | Route prefix; default `/api/opencomputer/managed-agents` |
+| `fetch` | Custom fetch, for example to add a CSRF header |
+| `after` | Attach mode: skip events through this position; default `0` |
+| `pollIntervalMs` | Attach mode: empty-poll interval; default 1000 ms, 500 ms while running |
| `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).
+| `onMemorySaved` | Each observed `memory.saved` event |
+| `source` | Create mode: input source |
diff --git a/docs/agents/sessions.mdx b/docs/agents/sessions.mdx
index 26d5c8e8..a31a8d1a 100644
--- a/docs/agents/sessions.mdx
+++ b/docs/agents/sessions.mdx
@@ -37,6 +37,41 @@ rows with the session's status, its current turn activity and its latest
result; open a session for its turns and events. The query, the row shape and
the label bounds are on the [API reference](/agents/api#get-and-list).
+## Execution, labels and results
+
+These describe different parts of a session:
+
+| Field | What it answers |
+| --- | --- |
+| `status` and `activity` | Is work queued, running, stopping or finished? |
+| `labels` | How does your application organize the session? A ticket ID or `archived` label is your convention; changing it does not stop work. |
+| `result` | What did the agent last report? Its `data` is validated against the [result tool's](/agents/tools#the-session-result) output schema; `turnId` and `callId` identify the report. |
+
+A report does not finish a turn, and each report replaces the whole result.
+Later work can run, fail or be cancelled while an earlier result remains.
+For a review queue, check current activity, the last settled turn's status,
+and whether `result.turnId` matches that turn before treating the report as
+ready. Your application decides what the reported data means.
+
+## Durability and recovery
+
+Closing the browser or redeploying your application does not discard work
+the API has accepted. Reopen the session and resume reading its durable
+event log. If a submission's response was lost, retry with the same request
+key and body; see [Starting work from an application](/agents/api#start-work-from-an-application).
+
+Durable history does not make every command resumable. A lost computer can
+leave a command's outcome unknown; OpenComputer does not automatically
+replay that command or roll back its effects. The turn can continue with a
+tool error or fail. Inspect the recorded outcome and verify external
+effects before asking the agent to retry.
+
+[Interrupt](/agents/api#end-and-interrupt) stops the current turn while
+keeping the session available for more work. End closes the session and
+revokes its memory writes. Neither operation undoes completed writes;
+their different acknowledgement and cleanup guarantees are described in
+the API reference.
+
## CLI
Start a session against the development agent:
diff --git a/docs/agents/tools.mdx b/docs/agents/tools.mdx
index 5ff8fec1..3f157dcc 100644
--- a/docs/agents/tools.mdx
+++ b/docs/agents/tools.mdx
@@ -78,6 +78,7 @@ The `run` function receives:
| `input` | Arguments created for the tool call |
| `sessionId` | Current session ID |
| `messageId` | Message containing the tool call |
+| `toolCallId` | ID of this invocation, unique within the session |
| `agentId` | Agent executing the call |
| `signal` | Optional cancellation signal for abortable work |
| `reportProgress(metadata)` | Emits JSON-compatible progress metadata |
@@ -100,43 +101,47 @@ export const importCatalog = defineTool({
Tool results and progress metadata must be JSON-compatible values.
+For an external write, `${sessionId}:${toolCallId}` can identify the invocation
+in a downstream idempotency key. It stays the same when that invocation is
+retried. A new call from the model has a new ID, even if it requests the same
+action; use a business-level key when those calls must also converge.
+
## The session result
An agent may mark one tool as its result tool. Its latest committed output
is the session's `result`: the structured outcome an application reads
-instead of parsing the final message.
+instead of parsing the final message. This tool checks a URL itself rather
+than accepting a claimed status from the model:
```tsx
-export const report = defineTool({
- name: "report",
- description: "Report the branch and pull request as soon as each is known",
- input: {
- type: "object",
- properties: {
- branch: { type: "string" },
- pr: { type: "object", properties: { number: { type: "integer" }, url: { type: "string" } } },
- },
- required: ["branch"],
- additionalProperties: false,
+import { defineTool } from "@opencomputer/agent";
+
+const checkResult = {
+ type: "object",
+ properties: {
+ url: { type: "string" },
+ status: { type: "integer" },
},
- output: {
+ required: ["url", "status"],
+ additionalProperties: false,
+} as const;
+
+export const checkUrl = defineTool({
+ name: "check_url",
+ description: "Check an HTTPS URL and report its HTTP status",
+ input: {
type: "object",
- properties: {
- branch: { type: "string" },
- pr: {
- type: "object",
- properties: { number: { type: "integer" }, url: { type: "string" } },
- required: ["number", "url"],
- additionalProperties: false,
- },
- },
- required: ["branch"],
+ properties: { url: { type: "string" } },
+ required: ["url"],
additionalProperties: false,
},
+ output: checkResult,
result: true,
- async run({ input }) {
- // Verify what the model claims before it becomes the result.
- return { branch: String(input.branch), ...(input.pr ? { pr: input.pr } : {}) };
+ async run({ input, signal }) {
+ const url = new URL(String(input.url));
+ if (url.protocol !== "https:") throw new Error("Use an HTTPS URL");
+ const response = await fetch(url, { method: "HEAD", signal });
+ return { url: response.url, status: response.status };
},
});
```
@@ -147,43 +152,6 @@ a result tool declares `output`, and it runs with `run()` rather than
recorded with the deployment, and every value the tool returns is validated
against it.
-`output` can be written three ways, and `input` accepts the same forms: an
-object literal in the call; a `const` object literal in the same module,
-where `as const` keeps its literal types so one schema serves the tool, your
-own validation and the inferred type; or a named import of such a `const`
-from a module inside the agent directory. The build copies the schema as
-written into the deployment without running your code, so a value produced
-by a function, a `let`, a namespace member such as `schemas.report`, a
-package import or a re-export from another module is refused with a message
-that names it.
-
-```tsx
-// tools/report.ts
-import { defineTool } from "@opencomputer/agent";
-import { reportSchema } from "../schemas.js";
-
-export const report = defineTool({
- name: "report",
- description: "Report the branch and pull request",
- input: reportSchema,
- output: reportSchema,
- result: true,
- async run({ input }) {
- return input;
- },
-});
-```
-
-The build reads `name`, `result` and `output` from the `defineTool()` call
-itself, without running your code. A form it cannot read fails the build and
-the message names it: a spread (`...options`), a computed property name
-(`["result"]: true`), or a `result` that is not the literal `true` or `false`
-(a variable, a shorthand `result`). The rule exists because a `result: true`
-hidden behind a spread would deploy as an ordinary tool and its output would
-never become the session's result. When a deployment loads, the platform
-also checks each tool module's declared `result` against what the build
-recorded; a module that disagrees fails to load rather than run.
-
A call to the result tool succeeds only once its output is committed to
the session:
@@ -192,19 +160,50 @@ the session:
becomes `{ turnId, callId, reportedAt, data }`, and the call's
`tool.completed` event carries `result: true`
([Session events](/agents/events#tools)).
-- A value that does not match `output`, or exceeds 8 KB of JSON, fails the
+- A value that does not match `output`, or exceeds 8 KiB of JSON, fails the
call; the model sees the reason and can call again. The previous result
stands.
- A call from a turn that was interrupted or has ended, or from a runtime
the session no longer runs on, is refused the same way.
-- A later call replaces the result. A turn that fails or is cancelled never
- clears it, and the event log keeps every call.
+- A later call replaces the entire value. Reporting does not finish the turn.
+ A subsequent turn that fails or is cancelled does not clear the result, and
+ the event log keeps every call.
The result says what the agent reported, not that the work succeeded.
Verify claims inside `run()`, where a tool can check that a branch exists
or a pull request is open, and throw to reject them; let the application
check what the result references. Read it from
-[`GET /sessions/<id>`](/agents/api#get-and-list).
+[`GET /sessions/<id>`](/agents/api#get-and-list). For a review-ready UI, also
+check current activity and whether `result.turnId` belongs to the last settled
+turn. An existing result may describe earlier work.
+
+If the commit acknowledgement is lost, the tool can fail even though its
+result was saved. OpenComputer retries the commit for the same tool call;
+that deduplicates the saved result, not external writes inside `run()`. Prefer
+tools that verify and report existing work. Give any external write its own
+idempotency key.
+
+### Schema declarations
+
+The result tool's `output` is copied into the deployment without evaluating
+code. Use one of these forms:
+
+- An object literal in the `defineTool()` call.
+- A `const` object literal in the same module, as above.
+- A named import of such a `const` from a module inside the agent directory.
+
+Function calls, `let` bindings, namespace members such as `schemas.report`,
+package imports and re-exports are not supported for this `output` schema.
+The build error names the unsupported form. `input` may use these static
+forms or a schema constructed when the tool module loads; it is not subject
+to result-output extraction. Neither schema infers the TypeScript type of
+`run`'s `input`, which remains `Record<string, unknown>`. `as const` preserves
+the schema's literal types for your own typing and validation.
+
+Write `name`, `result` and `output` as ordinary properties on the
+`defineTool()` object. Spreads, computed property names, and a `result` value
+other than literal `true` or `false` fail the build. A tool module whose
+`result` declaration disagrees with its deployment fails to load.
## Conditional tools
@@ -231,10 +230,14 @@ runtime already provides that tool.
## Call external APIs safely
-Do not embed API keys in a tool or read them from the runtime environment.
-Declare an HTTP connection, store the value as an OpenComputer secret, and
-call the connection's `fetch()` method. See
-[Secrets and outbound requests](/agents/secrets) for a complete example.
+For authenticated HTTP APIs, declare a connection, store the key as an
+OpenComputer secret, and call the connection's `fetch()` method. This keeps
+the credential outside the agent runtime; see
+[Secrets and outbound requests](/agents/secrets).
+
+[Managed GitHub connections](/agents/github) are the exception: they supply
+short-lived environment credentials so Git and `gh` work directly. Never
+embed credentials in tool source or return them to the model.
## Wait for a person before writing
@@ -322,9 +325,10 @@ a schedule or a webhook, there is nobody to ask, and the call fails saying so.
## Computer commands
-Every session runs on its own computer, and the model runs commands on it
-through the built-in `shell` tool. A command runs in the session's workspace
-and takes `command` and an optional `timeoutSeconds`: 120 by default, at
+A session gets an isolated computer when it needs one; conversation alone
+does not require a computer. The model runs commands through the built-in
+`shell` tool. A command runs in the session's workspace and takes `command`
+and an optional `timeoutSeconds`: 120 by default, at
most 1800, and never more than the computer's remaining lifetime allows; a
value out of range fails the call before anything runs. A command is not
started on a computer that cannot host it for its full timeout; a fresh
@@ -337,18 +341,14 @@ and files the command wrote before it was stopped remain.
A command counts as stopped only once that is confirmed: every process it
started, detached ones included, is gone, or the computer itself was
-replaced. When the computer stops answering while a command runs, its
+terminated. When the computer stops answering while a command runs, its
outcome is unknown, and the call fails with that as the reason; the model
is never told a command was stopped when that was not confirmed. That
computer runs no further command until the unknown one is confirmed
stopped or the computer is replaced by a fresh one with the session's
-workspace, which the next command does on its own. The same rule settles
-an [interrupt](/agents/api#end-and-interrupt): the turn is cancelled only
-after its commands are confirmed stopped, and a stop that cannot be
-confirmed replaces the computer. A session whose `executionMode` is
-`microvm` still cancels immediately on interrupt, without waiting for its
-commands to be confirmed stopped, until sessions in that mode settle the
-same way.
+workspace, which the next command does on its own. See
+[End and interrupt](/agents/api#end-and-interrupt) for cancellation guarantees
+and the compatibility limit for sessions using the older runtime.
## Tools versus skills and MCP
diff --git a/docs/docs.json b/docs/docs.json
index 4b5c0e12..66d5718d 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -40,9 +40,6 @@
"pages": [
"agents/reactive-agents",
"agents/sessions",
- "agents/api",
- "agents/events",
- "agents/react",
"agents/memory",
"agents/schedules",
"agents/webhooks",
@@ -55,6 +52,15 @@
"agents/deployments"
]
},
+ {
+ "group": "Build an application",
+ "pages": [
+ "agents/react",
+ "reference/typescript-sdk/agents",
+ "agents/api",
+ "agents/events"
+ ]
+ },
{
"group": "Agent API",
"pages": [
@@ -189,8 +195,7 @@
"reference/typescript-sdk/pty",
"reference/typescript-sdk/image",
"reference/typescript-sdk/snapshots",
- "reference/typescript-sdk/secrets",
- "reference/typescript-sdk/agents"
+ "reference/typescript-sdk/secrets"
]
},
{
diff --git a/docs/reference/typescript-sdk/agents.mdx b/docs/reference/typescript-sdk/agents.mdx
index 1b0a2a82..4468f634 100644
--- a/docs/reference/typescript-sdk/agents.mdx
+++ b/docs/reference/typescript-sdk/agents.mdx
@@ -1,20 +1,18 @@
---
title: "Serverless Agents client"
-description: "The management API client on the portable @opencomputer/sdk/agents subpath"
+description: "Create sessions, submit work and read results from your application's server"
---
`@opencomputer/sdk/agents` is the TypeScript client for the
[management API](/agents/api): create sessions, send turns, read the event
log, list and label sessions, and manage a project's memory, webhooks, event
-subscriptions and GitHub repositories. It is the server-side leg of an
-application; the browser leg is [`@opencomputer/react`](/agents/react) and
-the authoring leg is `@opencomputer/agent`.
+subscriptions and GitHub repositories. Use it in your application's server;
+use [`@opencomputer/react`](/agents/react) in the browser and
+[`@opencomputer/agent`](/agents/hooks) to define agent behavior.
-The subpath is portable. Its module graph uses `fetch`, `URL`, `Headers` and
-Web Crypto and nothing else: no Node built-ins, nothing run at import. The
-same import serves a Cloudflare Worker without Node compatibility, a Vercel
-function, Deno and Node. The package root, `@opencomputer/sdk`, is the Node
-sandbox client and is separate on purpose.
+The client uses web-standard APIs and runs on Cloudflare Workers without
+Node compatibility, Vercel functions, Deno and Node. The package root,
+`@opencomputer/sdk`, provides the separate sandbox client.
```bash
npm install @opencomputer/sdk
@@ -28,6 +26,16 @@ const oc = new OpenComputer({ apiKey: process.env.OPENCOMPUTER_API_KEY! });
Use it from trusted server code. The key belongs to an organization and
reaches every project, agent and session in it; it must not reach a browser.
+Authenticate your users and check their access before forwarding requests.
+
+<Note>
+ This client requires SDK 2.0 or later. Version 2 removes the older session
+ client and moves `startSessionOnDocument`, memory types and event-subscription
+ types to `@opencomputer/sdk/agents`. See the
+ [migration notes](https://github.com/diggerhq/opencomputer/blob/main/sdks/typescript/CHANGELOG.md#200)
+ for changed imports and errors. Applications using the older session API
+ should remain on SDK 1.1.1 until migrated.
+</Note>
## `new OpenComputer(options)`
@@ -37,15 +45,14 @@ reaches every project, agent and session in it; it must not reach a browser.
| `baseUrl` | `https://app.opencomputer.dev/api/managed-agents` | The management API |
| `fetch` | the global `fetch` | A fetch implementation, for runtimes without a global or for tests |
-Every method takes its parameters first and an options object last with
-`signal` (an `AbortSignal`); `sessions.create` also takes `idempotencyKey`
-there. Methods return the object the route returns, unwrapped: a list route's
-array, a paged route's `{ rows, nextCursor }`, a session, a document. The
-field names are the API's own.
+Methods accept an `AbortSignal` in their options; `startOnDocument` takes
+`signal` in its params. Return shapes are listed below. Paged session lists
+return `{ sessions, nextCursor }`; repository lists return
+`{ repositories, nextCursor }`. Event reads return an array.
## Errors
-Every failed call throws `OpenComputerError` with `code`, `status` and
+HTTP failures throw `OpenComputerError` with `code`, `status` and
`message`. `code` is the API's stable code when the body carried one
(`idempotency_conflict`, `session_ended`, `insufficient_credits`,
`session_publication_unconfirmed`); when the body had only text, it is
@@ -54,36 +61,25 @@ derived from the status: `unauthorized`, `forbidden`, `not_found`,
otherwise. A `429` also carries `retryAfter` in seconds, and an error the
API tied to a session carries `sessionId`.
-```typescript
-try {
- await oc.sessions.create({ agentId: "worker@development" }, { idempotencyKey: taskId });
-} catch (error) {
- if (error instanceof OpenComputerError && error.code === "idempotency_conflict") {
- // this key already created a session with different inputs
- }
-}
-```
+Network failures, response-body read failures and cancellation propagate the
+underlying error, such as `TypeError` or `AbortError`. They do not prove that
+a write was rejected. A request can commit before its response is lost.
-The client does not retry. The API's idempotency keys make a retry safe, and
-the caller decides which calls to repeat and with which key. The one error
-that asks for a retry, `503 session_publication_unconfirmed` from
-`sessions.create` or `sessions.setLabels`, is thrown like any other: the
-session exists, or its labels are recorded, but its row in the list was not
-confirmed in time, and `error.sessionId` names it. Repeat the same call, with
-the same `idempotencyKey` and params on `create` or the same patch on
-`setLabels`, until it returns; a return means the list reflects the change
-([Management API](/agents/api#create)).
+The client does not retry automatically. Keep the same parameters and key
+for a submission's retries; use a new key only for new work. Use bounded
+backoff and an `AbortSignal`, and retain the submission if the retry budget
+expires. Aborting the HTTP request does not cancel admitted work.
-```typescript
-for (;;) {
- try {
- return await oc.sessions.create(params, { idempotencyKey: taskId });
- } catch (error) {
- if (!(error instanceof OpenComputerError) || error.code !== "session_publication_unconfirmed") throw error;
- await new Promise((resolve) => setTimeout(resolve, 500));
- }
-}
-```
+| Failure | How to recover |
+| --- | --- |
+| Lost response or `invalid_response` after a write | Treat the outcome as unconfirmed. Retry create/send with the same key and input; do not create a replacement submission. |
+| `503 session_publication_unconfirmed` | The session or labels were recorded, but list visibility was not confirmed. Repeat create with its original key and params, or repeat the same label patch. |
+| `503 memory_admission_unconfirmed` | Retry the same admission; see [memory admission](/agents/api#create). |
+| `503 session_end_unconfirmed` | Retry `sessions.end(id)` to confirm memory-write revocation. |
+| `409 idempotency_conflict` | The key names different inputs. Recover the original submission; do not silently replace its key. |
+
+A successful create or label update confirms publication to the list. See
+the [Management API](/agents/api) for each operation's errors and guarantees.
The client does not follow redirects. The API key is sent to `baseUrl` and
to no other origin: a redirect answer fails the call with code `redirected`
@@ -95,17 +91,19 @@ Two codes come from the client rather than the API:
| `code` | Meaning |
| --- | --- |
| `redirected` | The call was answered with a redirect; the client never follows one with the API key. `status` is the redirect's status. |
-| `invalid_response` | The call succeeded but its body is not JSON or does not match the documented shape of the route. `status` is the HTTP status; the message names the route and the first field that did not match. |
+| `invalid_response` | The HTTP response succeeded but its body is not JSON or fails the client's shape checks. `status` is the HTTP status; the message names the route and, for shape failures, the field. |
## Validation
-Every response is checked against the documented shape of its route before
-the method returns: the fields the [API reference](/agents/api) lists, with
-their types. A field the documentation does not list passes through as it
-came, so an addition to the API never fails a call. Application data, that
-is a session's `result.data`, a turn's `payload`, and a tool call's `input`
-and `output`, is checked only as a JSON value; what it contains is yours to
-validate.
+The client checks response envelopes and selected fields before returning;
+unknown fields pass through. Application-owned values such as
+`session.result.data` and turn payloads still need your application schema.
+
+Event reads check `seq`, `type` and that `data` is an object. They do not
+validate each known event type's payload; identity and timestamp fields are
+checked only when present. The exported event types describe the API contract,
+not complete runtime validation. Validate event data before using it where
+its contents affect application correctness or access.
## Sessions
@@ -132,10 +130,12 @@ after a lost reply learns what became of the turn. `list` takes `project`,
`environment`, `agent`, `status`, `labels` (up to three, sent as
`label.<key>=<value>`), `cursor` and `limit`.
-The way an application starts work is two calls under two keys: resolve the
-deployment once where the submission is composed, pin it, then create and
-admit with one key each. A lost reply at either step is retried with the same
-envelope; the first step returns the same session, the second the same turn.
+### Create and submit
+
+Create the session, then send its first turn. Resolve the deployment once
+when composing the submission and retain its ID, both keys and the inputs.
+Retrying either call then returns the same session or turn, even if the
+agent is redeployed between attempts.
```typescript
const { session } = await oc.sessions.create(
@@ -149,29 +149,38 @@ const receipt = await oc.sessions.turns.send(session.id, {
});
```
-Reading a log, from the start and then live:
+Send follow-ups to the same session with a fresh key per submission. To
+display work in a browser, [attach the React hook](/agents/react) through
+your authenticated application routes.
+
+### Read progress and results
+
+Read events from sequence `0`, then request only events after the last
+sequence processed:
```typescript
-let after = 0;
-for (;;) {
- const events = await oc.sessions.events.list(session.id, { after });
- for (const event of events) {
- after = event.seq;
- if (event.type === "tool.completed" && event.data.result) console.log(event.data.output);
- }
- if (events.length === 0) await new Promise((resolve) => setTimeout(resolve, 1000));
-}
+const events = await oc.sessions.events.list(session.id, { after: 0 });
+const cursor = events.at(-1)?.seq ?? 0;
+const next = await oc.sessions.events.list(session.id, { after: cursor });
```
-`SessionEvent` is a union discriminated on `type` with the `data` of each
-[event type](/agents/events); an unknown type keeps `data` as a record.
+Each read returns up to 500 events. Continue immediately while catching up;
+when a read is empty, wait before polling again. A cursor skips earlier
+events; it does not reconstruct state you have discarded. See
+[Session events](/agents/events) for payloads and replay.
+
+`sessions.get(id)` returns the latest typed result, if the agent has reported
+one. Results retain their turn provenance and can outlive later work; see
+[Sessions](/agents/sessions) before treating a result as ready for review.
### Start a session on a memory document
`sessions.startOnDocument` creates a [memory document](/agents/document-memory)
if it does not exist, then a session bound to it, and reports both ids and
-whether each already existed. The two objects stay separate on the API; the
-call does the two steps in order and makes the pair converge on retry.
+whether each already existed. These are two requests, not an atomic operation:
+the document remains if session creation fails. Retries reuse the document
+and converge on the session while the agent's deployment and bindings remain
+unchanged.
```typescript
const { document, session } = await oc.sessions.startOnDocument({
@@ -227,9 +236,13 @@ The result:
| `session.created` | `false` when the key had already created this session |
| `session.status`, `session.executionMode` | As the create response reported them |
-A retry with the same `idempotencyKey` after a redeploy fails with
-`idempotency_key_reused`: the deployment is part of the session's identity.
-Start the new session under a new key.
+The helper resolves the environment's agent alias on every call and cannot
+pin a deployment. If that alias changes between a successful create and its
+retry, the retry fails with `idempotency_key_reused`. A new key would create
+another session; it does not recover a lost response. When retries must
+survive redeploys, create/read the document separately and pass its binding
+to [`sessions.create`](#create-and-submit) with a retained `deploymentId`
+and key.
`startSessionOnDocument({ apiKey, baseUrl?, fetch?, ...params })`, exported
from the same subpath, is the standalone form of the call for code that
diff --git a/react/src/index.ts b/react/src/index.ts
index d516db67..e32e0bd3 100644
--- a/react/src/index.ts
+++ b/react/src/index.ts
@@ -134,15 +134,16 @@ export interface UseAgentResult {
turns: Turn[];
/**
* Starts a turn. Resolves with the admission receipt; rejects with a
- * `SendError` when no turn was admitted, so a draft can be kept. In create
- * mode the first call creates the session and the promise settles when the
- * turn ends.
+ * `SendError` on refusal or an unconfirmed response. A lost response may
+ * follow admission: retain the input and idempotency key for retries.
+ * In create mode the first call creates the session and the promise
+ * settles when the turn ends.
*/
send: (value: string, options?: SendOptions) => Promise<SendReceipt>;
- /** Interrupts the running turn. */
+ /** Requests an interrupt. Request failures set `error`; this promise does not confirm settlement. */
stop: () => Promise<void>;
sessionId: string | undefined;
- /** A turn is admitted and not yet settled by the log. */
+ /** A turn is running in the log, or a locally admitted turn has not settled. Queued replay alone is false. */
isRunning: boolean;
/** Attach mode: true until the existing history has been replayed. */
isReplaying: boolean;