An open-source, faster Devin alternative
TypeScript
docs: the Serverless Agents client page; send options and activity in the React guide
Igor Zalutskicb2e08c5c31c
diff --git a/docs/agents/api.mdx b/docs/agents/api.mdxindex 30f95856..829f6ea6 100644--- a/docs/agents/api.mdx+++ b/docs/agents/api.mdx@@ -19,7 +19,9 @@ on the server; the [React integration](/agents/react) shows how a browserattaches through your own routes without seeing the key.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.+URL; `<p>` is a project ID and `<r>` a memory resource ID. The+[TypeScript client](/reference/typescript-sdk/managed-agents) on+`@opencomputer/sdk/managed-agents` mirrors these routes one to one.## Errors@@ -201,9 +203,9 @@ curl -X PUT 'https://app.opencomputer.dev/api/managed-agents/projects/<project-i-d '{ "title": "Workshop notes" }'```-`startSessionOnDocument` in the-[TypeScript SDK](/reference/typescript-sdk#serverless-agents-helpers) does-this create and the session create in one call.+`oc.sessions.startOnDocument` on the+[TypeScript client](/reference/typescript-sdk/managed-agents) does this+create and the session create in one call.## Webhooksdiff --git a/docs/agents/document-memory.mdx b/docs/agents/document-memory.mdxindex 8a64e3ad..c1024a41 100644--- a/docs/agents/document-memory.mdx+++ b/docs/agents/document-memory.mdx@@ -97,10 +97,10 @@ application still means "these notes, this session", so the SDK and the CLIdo the two steps in order and make the pair converge on retry.```ts-import { startSessionOnDocument } from "@opencomputer/sdk";+import { OpenComputer } from "@opencomputer/sdk/managed-agents";-const { document, session } = await startSessionOnDocument({- apiKey: process.env.OPENCOMPUTER_API_KEY!,+const oc = new OpenComputer({ apiKey: process.env.OPENCOMPUTER_API_KEY! });+const { document, session } = await oc.sessions.startOnDocument({projectId: "<project-id>",environment: "development",agent: "<agent-id>",@@ -117,8 +117,8 @@ const { document, session } = await startSessionOnDocument({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`),+ and bindings returns the existing session; anything else under that key+ fails with code `idempotency_key_reused`. `access` (default `read-write`),`memory` for further bindings and `source` are passed through.The CLI does the same for a Development session:@@ -136,9 +136,9 @@ 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 helper's-signature and errors are in the-[TypeScript SDK reference](/reference/typescript-sdk#serverless-agents-helpers).+session, `200` returned the one that key had already created. The call's+parameters and errors are in the+[Serverless Agents client reference](/reference/typescript-sdk/managed-agents#start-a-session-on-a-memory-document).## Readingdiff --git a/docs/agents/memory.mdx b/docs/agents/memory.mdxindex 55963b50..a9072593 100644--- a/docs/agents/memory.mdx+++ b/docs/agents/memory.mdx@@ -85,8 +85,8 @@ credentials nor permission to select another document. A[collection binding](/agents/document-memory#session-bindings) instead lets itbrowse documents with `memory_list` and `memory_read`.-The document must exist before the session binds it. `startSessionOnDocument`-in the [TypeScript SDK](/reference/typescript-sdk#serverless-agents-helpers)+The document must exist before the session binds it. `sessions.startOnDocument`+on the [TypeScript client](/reference/typescript-sdk/managed-agents)creates it if needed and then the session, and the CLI's`session create --memory notes=workshop --create-document` does the same.diff --git a/docs/agents/react.mdx b/docs/agents/react.mdxindex cb44cd8d..16f95374 100644--- a/docs/agents/react.mdx+++ b/docs/agents/react.mdx@@ -28,16 +28,17 @@ session id.Create the session where the API key lives. With memory, that is also wherethe 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+the session may read or write. `oc.sessions.startOnDocument` on the+[management client](/reference/typescript-sdk/managed-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)):```ts-import { startSessionOnDocument } from "@opencomputer/sdk";+import { OpenComputer } from "@opencomputer/sdk/managed-agents";-const { session } = await startSessionOnDocument({- apiKey: process.env.OPENCOMPUTER_API_KEY!,+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>",@@ -49,9 +50,9 @@ const { session } = await startSessionOnDocument({// Store session.id with the workshop; the browser attaches to it.```-Without memory, `POST /api/managed-agents/sessions` with `x-api-key` and-`{ "agentId": "<agent-id>@development" }` returns `{ session: { id } }`. Both-are [management API](/agents/api#sessions) calls.+Without memory, `oc.sessions.create({ agentId: "<agent-id>@development" })`+returns `{ session: { id } }`. Both are [management API](/agents/api#sessions)+calls.### 2. Proxy three routes@@ -61,7 +62,7 @@ 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>/turns` | A new turn: `{ input, idempotencyKey, payload? }` || `POST /sessions/<id>/interrupt` | Stop the running turn |Expose them under your own authentication, check that the signed-in user may@@ -93,10 +94,11 @@ 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 } }`.+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 } }`.### 3. Attach in the browser@@ -151,9 +153,19 @@ your own store, otherwise start at `0`.Turns sent while one is running are queued by the platform. `stop`interrupts the running turn without spending a model turn.-### What `send` returns+### What `send` takes and returns-`send(text)` resolves once the platform has admitted the input as a turn,+`send(text, options?)` starts a turn with the text. The options:++| 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 }` where `status` is `queued`or `running`. The input appears in `messages` at that point; the log's ownrecord of it confirms that message rather than adding a second one.@@ -187,8 +199,41 @@ Every `memory.saved` event the session recordsowner route when one arrives. Saves are reported best-effort: a documentcan change without an event, so also refresh when the user opens the panel.-Every event is available through `onEvent`, for example tool activity for an-activity view; the types are listed on [Session events](/agents/events).+### Activity++`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:++| 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; `status` is `running`, `completed` or `failed` |+| `result` | The output of the agent's result tool, when it reported one; a later call replaces it |+| `failure` | `{ code, message }` from `turn.failed` |++Tool calls are keyed on the runtime's `callId`, so a `tool.completed` updates+the entry its `tool.started` created rather than adding one. An activity+timeline renders `turns` directly:++```tsx+{turns.map((turn) => (+ <section key={turn.id}>+ <h3>{turn.input}</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.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@@ -243,7 +288,8 @@ the web application. Credentials are not bundled into browser code.| Value | Purpose || --- | --- || `messages` | User and assistant messages, in log order |-| `send(text)` | Starts a turn; resolves with `{ sessionId, turnId, status }` or rejects with a `SendError`. In create mode the first call creates the session |+| `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 }` 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 |diff --git a/docs/agents/sessions.mdx b/docs/agents/sessions.mdxindex d754c9e6..87becac4 100644--- a/docs/agents/sessions.mdx+++ b/docs/agents/sessions.mdx@@ -94,9 +94,10 @@ the command exits.Applications create sessions with the [management API](/agents/api): `POST/api/managed-agents/sessions` with an API key, then turns and the event log-under that session. `startSessionOnDocument` in the-[TypeScript SDK](/reference/typescript-sdk#serverless-agents-helpers) creates-a memory document and a session bound to it in one call. In the browser, the+under that session. The+[TypeScript client](/reference/typescript-sdk/managed-agents) wraps those+routes; its `sessions.startOnDocument` creates a memory document and a+session bound to it in one call. In the browser, the[`useAgent`](/agents/react) hook attaches to a session your server createdand renders its messages.diff --git a/docs/docs.json b/docs/docs.jsonindex ea720d82..b9b2694a 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -188,7 +188,8 @@"reference/typescript-sdk/pty","reference/typescript-sdk/image","reference/typescript-sdk/snapshots",- "reference/typescript-sdk/secrets"+ "reference/typescript-sdk/secrets",+ "reference/typescript-sdk/managed-agents"]},{diff --git a/docs/reference/typescript-sdk.mdx b/docs/reference/typescript-sdk.mdxindex 47d9d05d..fa9685eb 100644--- a/docs/reference/typescript-sdk.mdx+++ b/docs/reference/typescript-sdk.mdx@@ -878,138 +878,10 @@ const apiResult = await sandbox.commands.run(----## Serverless Agents helpers+## Serverless Agents client-`Sandbox` and the `OpenComputer` client wrap the sandbox API and the `/v3`-Durable Agent Sessions API. The helpers in this section are different: they-call the Serverless Agents [management API](/agents/api) under-`/api/managed-agents` with an OpenComputer API key. Use them from trusted-server code only; the key must not reach a browser.--```typescript-import { startSessionOnDocument, sessionIdempotencyKey } from "@opencomputer/sdk";-```--### `startSessionOnDocument(params): Promise<StartSessionOnDocumentResult>`--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; this helper does the two-calls in order and makes the pair converge on retry.--```typescript-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",-});-```--| Parameter | Type | Default | Description |-| --- | --- | --- | --- |-| `apiKey` | string | required | API key with access to the project |-| `projectId` | string | required | Project whose memory holds the document |-| `environment` | `"development"` \| `"production"` | required | Memory store and session environment |-| `agent` | string | required | Agent ID; the environment supplies the alias |-| `resource` | string | required | Declared memory resource ID |-| `documentId` | string | required | Document to bind |-| `document` | `{ title, text?, summary?, agentWrites? }` | required | What to create when the document does not exist; ignored when it does |-| `access` | `"read"` \| `"read-write"` | `"read-write"` | The binding's access |-| `memory` | `MemoryBindings` | none | Further bindings keyed by resource ID |-| `idempotencyKey` | string | required | One key for the whole operation |-| `source` | string | `"api"` | The session's `source` |-| `baseUrl` | string | `https://app.opencomputer.dev` | The management API origin |-| `fetch` | typeof fetch | global | Override for runtimes without a global `fetch`, or tests |-| `signal` | AbortSignal | none | Aborts both requests |--The steps, in order:--1. `PUT /projects/<projectId>/memory/<resource>/documents/<documentId>` with- `If-None-Match: *` and the `document` body. `201` means the document was- created. `412` means it exists; the helper reads it with `GET` and leaves- its content as it is. A `404` on that read means the ID was deleted and is- reserved, which is an error, since a binding to it would fail admission.-2. `POST /sessions` with `agentId: "<agent>@<environment>"`, `source`, and- `memory` set to your further bindings plus- `{ [resource]: { scope: "document", id: documentId, access } }`. The- `Idempotency-Key` header is `sessionIdempotencyKey(idempotencyKey)`.- `201` created the session; `200` means the key had already created it.--The result:--| Field | Description |-| --- | --- |-| `document.id` | The document |-| `document.created` | `false` when it already existed |-| `document.revision` | Current revision, for a later conditional owner write |-| `document.title` | Its title |-| `session.id` | The session |-| `session.created` | `false` when the key had already created this session |-| `session.status`, `session.executionMode` | As the create response reported them |--Errors:--| Error | When |-| --- | --- |-| `NotFoundError` with code `memory_document_deleted` | The document ID was deleted and is reserved; use a new ID |-| `ConflictError` with code `idempotency_key_reused` | The key already created a session with a different agent, deployment, environment or bindings; the document was left as it is. Use a new key |-| `AuthError` | `401` or `403` from the API |-| `RateLimitError` | `429`; `retryAfter` carries the wait in seconds |-| `OpenComputerError` | Any other failure; `status` and `code` carry the API's error envelope |-| `Error` | No global `fetch` and none passed |--A retry with the same `idempotencyKey` after a redeploy is a-`ConflictError`: the deployment is part of the session's identity. Start-the new session under a new key.--### `sessionIdempotencyKey(idempotencyKey): Promise<string>`--The `Idempotency-Key` the helper sends when creating the session: the-SHA-256 hex digest of `opencomputer.memory.session`, a NUL byte and your-key. Stable for a retry and distinct from any other use of the same caller-key. Use it to recognize the session-create key in your own requests or logs.--### Memory types--The package exports the shapes of the memory management routes as types, for-typing your own requests, the CLI's `--json` output and `opencomputer memory-export` files. They carry no behavior.--| Type | Shape |-| --- | --- |-| `MemoryEnvironment` | `"development" \| "production"` |-| `MemoryAccess` | `"read" \| "read-write"` |-| `MemoryAgentWrites` | `"enabled" \| "disabled"` |-| `MemoryBinding` | One session binding: `{ scope: "document", id, access? }` or `{ scope: "collection", access?: "read" }` |-| `MemoryBindings` | `Record<string, MemoryBinding>`, keyed by resource ID, at most eight |-| `SessionMemoryBinding` | One entry of a session's `memory` array, with `resource` and `writable` |-| `MemoryWriter` | `{ kind: "owner" }` or `{ kind: "agent", sessionId }` |-| `MemoryDocumentMeta` | A document without `text`, as the list route returns it |-| `MemoryDocument` | A full document, as read, create, replace and patch return it |-| `MemoryDocumentPage` | `{ documents, nextCursor }` |-| `MemoryResource`, `MemoryResourceInventory` | One entry, and the whole, of `GET /projects/<id>/memory` |-| `CreateMemoryDocumentBody`, `ReplaceMemoryDocumentBody`, `PatchMemoryDocumentBody` | Bodies of `PUT` with `If-None-Match`, `PUT` with `If-Match`, and `PATCH` |-| `MemorySavedEvent` | The `data` of a `memory.saved` [session event](/agents/events) |-| `MemoryErrorCode` | The codes the memory routes return in `{ error: { code, message } }` |-| `StartSessionOnDocumentParams`, `StartSessionOnDocumentResult` | The helper's parameters and result |--### Event subscription types--The shapes of the [event subscription](/agents/api#event-subscriptions)-routes and of the input they deliver, as types only.--| Type | Shape |-| --- | --- |-| `OutcomeEventType` | `"turn.completed" \| "turn.failed" \| "turn.cancelled"` |-| `SessionDestination` | `{ type: "session", sessionId }` |-| `CreateEventSubscriptionBody` | Body of `POST /projects/<id>/event-subscriptions`: `agentId?`, `events`, `destination`, `environment?` |-| `EventSubscription` | A subscription as the routes return it |-| `OutcomeEvent` | The delivered outcome: `id`, `type`, `sessionId`, `turnId`, `agentId`, `occurredAt`, `reason?`, `error?`, `result?` |-| `EventInput` | `{ source: "event", text?, event }`, what the receiving agent's `useInput()` returns |-| `TurnOutcomeDelivery` | One entry of a turn's `deliveries` on `GET /sessions/<id>` |-| `EventSubscriptionErrorCode` | The codes the subscription routes return in `{ error: { code, message } }` |+The management API client for Serverless Agents is a separate, portable+subpath of the same package, `@opencomputer/sdk/managed-agents`, with the+memory and event subscription types and `startSessionOnDocument`. It is+documented on its own page:+[Serverless Agents client](/reference/typescript-sdk/managed-agents).diff --git a/docs/reference/typescript-sdk/managed-agents.mdx b/docs/reference/typescript-sdk/managed-agents.mdxnew file mode 100644index 00000000..15119d46--- /dev/null+++ b/docs/reference/typescript-sdk/managed-agents.mdx@@ -0,0 +1,270 @@+---+title: "Serverless Agents client"+description: "The management API client on the portable @opencomputer/sdk/managed-agents subpath"+---++`@opencomputer/sdk/managed-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`.++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.++```bash+npm install @opencomputer/sdk+```++```typescript+import { OpenComputer, OpenComputerError } from "@opencomputer/sdk/managed-agents";++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.++## `new OpenComputer(options)`++| Option | Default | Description |+| --- | --- | --- |+| `apiKey` | required | An OpenComputer API key |+| `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.++## Errors++Every failed call throws `OpenComputerError` with `code`, `status` and+`message`. `code` is the API's stable code when the body carried one+(`idempotency_conflict`, `session_ended`, `insufficient_credits`); when the+body had only text, it is derived from the status: `unauthorized`,+`forbidden`, `not_found`, `conflict`, `rate_limited`, `unavailable` for `5xx`,+`request_failed` otherwise. A `429` also carries `retryAfter` in seconds.++```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+ }+}+```++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.++## Sessions++| Method | Route | Returns |+| --- | --- | --- |+| `sessions.create(params, { idempotencyKey? })` | `POST /sessions` | `{ session, deployment, created }`; `created` is `false` when the key had already created the session |+| `sessions.get(id)` | `GET /sessions/<id>` | The session with its `turns` and `memory` |+| `sessions.list(query?)` | `GET /sessions` | `{ sessions, nextCursor }` |+| `sessions.end(id)` | `POST /sessions/<id>/end` | The ended session |+| `sessions.interrupt(id)` | `POST /sessions/<id>/interrupt` | The session |+| `sessions.setLabels(id, { set?, unset? })` | `PATCH /sessions/<id>/labels` | The session |+| `sessions.turns.send(id, params)` | `POST /sessions/<id>/turns` | `{ turnId, status, duplicate }` |+| `sessions.events.list(id, { after? })` | `GET /sessions/<id>/events` | The events with `seq` greater than `after`, up to 500 |+| `sessions.startOnDocument(params)` | `PUT` the document, then `POST /sessions` | `{ document, session }` with `created` on each |++`create` takes `agentId`, `deploymentId`, `environment`, `memory`, `source`+and `labels` as [documented](/agents/api#create). `turns.send` takes `input`,+`idempotencyKey`, `mode` and `payload`. `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.++```typescript+const { session } = await oc.sessions.create(+ { deploymentId, environment: "development", labels: { request: taskId } },+ { idempotencyKey: taskId },+);+const receipt = await oc.sessions.turns.send(session.id, {+ input: text,+ idempotencyKey: `${taskId}/start`,+ payload: { repo, ref },+});+```++Reading a log, from the start and then live:++```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));+}+```++`SessionEvent` is a union discriminated on `type` with the `data` of each+[event type](/agents/events); an unknown type keeps `data` as a record.++### 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.++```typescript+const { document, session } = await oc.sessions.startOnDocument({+ projectId: "<project-id>",+ environment: "development",+ agent: "<agent-id>",+ resource: "notes",+ documentId: "workshop",+ document: { title: "Workshop notes" },+ idempotencyKey: "topic/workshop/1",+});+```++| Parameter | Type | Default | Description |+| --- | --- | --- | --- |+| `projectId` | string | required | Project whose memory holds the document |+| `environment` | `"development"` \| `"production"` | required | Memory store and session environment |+| `agent` | string | required | Agent ID; the environment supplies the alias |+| `resource` | string | required | Declared memory resource ID |+| `documentId` | string | required | Document to bind |+| `document` | `{ title, text?, summary?, agentWrites? }` | required | What to create when the document does not exist; ignored when it does |+| `access` | `"read"` \| `"read-write"` | `"read-write"` | The binding's access |+| `memory` | `MemoryBindings` | none | Further bindings keyed by resource ID |+| `idempotencyKey` | string | required | One key for the whole operation |+| `source` | string | `"api"` | The session's `source` |+| `signal` | AbortSignal | none | Aborts both requests |++The steps, in order:++1. `PUT /projects/<projectId>/memory/<resource>/documents/<documentId>` with+ `If-None-Match: *` and the `document` body. `201` means the document was+ created. `412` means it exists; the call reads it with `GET` and leaves+ its content as it is. A `404` on that read means the ID was deleted and is+ reserved, which fails with code `memory_document_deleted`, since a binding+ to it would fail admission.+2. `POST /sessions` with `agentId: "<agent>@<environment>"`, `source`, and+ `memory` set to your further bindings plus+ `{ [resource]: { scope: "document", id: documentId, access } }`. The+ `Idempotency-Key` header is `sessionIdempotencyKey(idempotencyKey)`, the+ SHA-256 hex digest of `opencomputer.memory.session`, a NUL byte and your+ key. `201` created the session; `200` means the key had already created it.+ Anything else under that key fails with code `idempotency_key_reused`; the+ document was left as it is.++The result:++| Field | Description |+| --- | --- |+| `document.id`, `document.title` | The document |+| `document.created` | `false` when it already existed |+| `document.revision` | Current revision, for a later conditional owner write |+| `session.id` | The session |+| `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.++`startSessionOnDocument({ apiKey, baseUrl?, fetch?, ...params })`, exported+from the same subpath, is the standalone form of the call for code that+holds a key and no client, and `sessionIdempotencyKey(key)` derives the+session-create key.++## Projects++| Method | Route | Returns |+| --- | --- | --- |+| `projects.list()` | `GET /projects` | The projects |+| `projects.get(id)` | `GET /projects/<p>` | `{ project, deployments, sessions, connections, channels, schedules }` |+| `projects.create({ name, slug? })` | `POST /projects` | The project |++### Memory++Every call takes `{ environment }` last; conditional writes also take the+`revision` the write is conditional on, sent as `If-Match`.++| Method | Route |+| --- | --- |+| `projects.memory.resources(p, { environment })` | `GET /projects/<p>/memory` |+| `projects.memory.documents.list(p, r, { environment, cursor? })` | `GET /projects/<p>/memory/<r>/documents` |+| `projects.memory.documents.get(p, r, id, { environment })` | `GET /projects/<p>/memory/<r>/documents/<id>` |+| `projects.memory.documents.create(p, r, id, body, { environment })` | `PUT` with `If-None-Match: *` |+| `projects.memory.documents.replace(p, r, id, body, { environment, revision })` | `PUT` with `If-Match` |+| `projects.memory.documents.patch(p, r, id, body, { environment, revision })` | `PATCH` with `If-Match` |+| `projects.memory.documents.delete(p, r, id, { environment, revision })` | `DELETE` with `If-Match` |++Bodies, the document object and the error codes are on+[Document memory](/agents/document-memory#management-api).++### Webhooks++| Method | Route |+| --- | --- |+| `projects.webhooks.list(p, { environment?, agentId? })` | `GET /projects/<p>/webhooks` |+| `projects.webhooks.create(p, { name, agentId, environment, identity? })` | `POST /projects/<p>/webhooks` |+| `projects.webhooks.update(p, id, { name?, enabled?, identity? })` | `PATCH /projects/<p>/webhooks/<id>` |+| `projects.webhooks.rotateToken(p, id)` | `POST /projects/<p>/webhooks/<id>/rotate-token` |+| `projects.webhooks.delete(p, id)` | `DELETE /projects/<p>/webhooks/<id>` |+| `projects.webhooks.requests(p, id)` | `GET /projects/<p>/webhooks/<id>/requests` |++`create` and `rotateToken` return the webhook with its `token` and full+`invocationUrl` once; see [Agent webhooks](/agents/webhooks).++### Event subscriptions++| Method | Route |+| --- | --- |+| `projects.eventSubscriptions.create(p, { agentId?, events, destination, environment? })` | `POST /projects/<p>/event-subscriptions` |+| `projects.eventSubscriptions.list(p)` | `GET /projects/<p>/event-subscriptions` |+| `projects.eventSubscriptions.get(p, id)` | `GET /projects/<p>/event-subscriptions/<id>` |+| `projects.eventSubscriptions.delete(p, id)` | `DELETE /projects/<p>/event-subscriptions/<id>` |++The shapes are on [Event subscriptions](/agents/api#event-subscriptions).++### GitHub repositories++`projects.github.repositories(p, { environment, cursor?, limit? })` calls+`GET /projects/<p>/github/repositories` and returns+`{ repositories, nextCursor }`, each repository `{ id, fullName, private,+defaultBranch, archived }` as the environment's GitHub installation covers+them.++## Agents and deployments++| Method | Route | Returns |+| --- | --- | --- |+| `agents.list()` | `GET /agents` | `id`, `name`, `activeAlias`, `activeDeploymentId`, `deploymentCount` per agent |+| `deployments.list({ agentId })` | `GET /deployments?agentId=` | The agent's deployments |+| `deployments.get(id)` | `GET /deployments/<id>` | `id`, `agentId`, `alias`, `memory` declarations, `createdAt` |++## Types++The subpath exports the types of every object above: `Session`,+`SessionSummary`, `SessionCreated`, `Turn`, `TurnReceipt`, `SessionEvent`,+`Project`, `AgentSummary`, `Deployment`, `Webhook`, `Repository`, the+`Create…Params` and `List…Query` shapes, and `DataValue` for JSON payloads+and results. The memory types (`MemoryDocument`, `MemoryBindings`,+`SessionMemoryBinding`, `MemoryResourceInventory`, the document bodies,+`MemorySavedEvent`, `MemoryErrorCode`) and the event subscription types+(`EventSubscription`, `CreateEventSubscriptionBody`, `OutcomeEvent`,+`EventInput`, `TurnOutcomeDelivery`, `EventSubscriptionErrorCode`) are+exported from the same place.diff --git a/docs/reference/typescript-sdk/overview.mdx b/docs/reference/typescript-sdk/overview.mdxindex 3d4f91a9..cc0b4adb 100644--- a/docs/reference/typescript-sdk/overview.mdx+++ b/docs/reference/typescript-sdk/overview.mdx@@ -54,7 +54,7 @@ import { Image, Snapshots } from "@opencomputer/sdk/node";<Card title="Secret Stores" icon="key" href="/reference/typescript-sdk/secrets">Manage secrets and egress control</Card>- <Card title="Serverless Agents helpers" icon="robot" href="/reference/typescript-sdk#serverless-agents-helpers">- Start a session on a memory document; memory types for the management API+ <Card title="Serverless Agents client" icon="robot" href="/reference/typescript-sdk/managed-agents">+ The management API client on the portable `@opencomputer/sdk/managed-agents` subpath</Card></CardGroup>